diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 013f2fa..212e069 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,5 +1,5 @@ idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp" - "effects_util.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp" + "effects_util.cpp" "ws_client.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp" PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip INCLUDE_DIRS "." diff --git a/main/ddp.cpp b/main/ddp.cpp index 342b547..5bfe15f 100644 --- a/main/ddp.cpp +++ b/main/ddp.cpp @@ -9,9 +9,17 @@ #include "freertos/task.h" #include "lwip/sockets.h" #include "patterns.h" +#include "settings.h" static const char *TAG = "ddp"; +static volatile bool s_enabled = true; + +void ddp_set_enabled(bool on) +{ + s_enabled = on; +} + // Header: flags, sequence, data type, destination, data offset (4), data length (2); with the timecode // flag, 4 more bytes follow. Version 1 is flags bits 6-7 = 01. #define DDP_FLAG_VER1 0x40 @@ -52,7 +60,12 @@ static void ddp_task(void *arg) uint8_t buf[1500]; while (true) { - int n = recv(sock, buf, sizeof(buf), 0); + struct sockaddr_in src = {}; + socklen_t srclen = sizeof(src); + int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&src, &srclen); + if (!s_enabled) { + continue; + } if (n < DDP_HEADER) { continue; } @@ -73,12 +86,59 @@ static void ddp_task(void *arg) if (len > (size_t)n - hdr) { len = (size_t)n - hdr; } - patterns_ddp_write(offset, buf + hdr, len, (flags & 0x01) != 0); + bool push = (flags & 0x01) != 0; + patterns_ddp_write(offset, buf + hdr, len, push); + if (push) { + // Ack the completed frame to its sender ("LAK1" + the DDP seq). The sender broadcasts the + // sync only after this, so the frame is already held when the sync arrives. + uint8_t ack[5] = { 'L', 'A', 'K', '1', buf[1] }; + sendto(sock, ack, sizeof(ack), 0, (struct sockaddr *)&src, srclen); + } + } +} + +// Sync broadcasts: a frame that arrived by DDP is shown when the next sync arrives (see patterns.cpp). +static void ddp_sync_task(void *arg) +{ + (void)arg; + int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); + if (sock < 0) { + ESP_LOGE(TAG, "sync socket failed"); + vTaskDelete(NULL); + return; + } + struct sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_port = htons(DDP_SYNC_PORT); + addr.sin_addr.s_addr = htonl(INADDR_ANY); + if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + ESP_LOGE(TAG, "bind to sync port %d failed", DDP_SYNC_PORT); + close(sock); + vTaskDelete(NULL); + return; + } + ESP_LOGI(TAG, "sync listening on UDP port %d", DDP_SYNC_PORT); + + uint8_t buf[64]; + while (true) { + int n = recv(sock, buf, sizeof(buf), 0); + if (!s_enabled || n < 8 || memcmp(buf, "LSY1", 4) != 0) { + continue; + } + patterns_ddp_sync(be32(buf + 4)); } } esp_err_t ddp_start(void) { + net_cfg_t net; + if (settings_load_net(&net) == ESP_OK) { + s_enabled = net.ddp_enabled; + } BaseType_t ok = xTaskCreate(ddp_task, "ddp", 4096, NULL, 4, NULL); + if (ok != pdPASS) { + return ESP_ERR_NO_MEM; + } + ok = xTaskCreate(ddp_sync_task, "ddp_sync", 3072, NULL, 4, NULL); return ok == pdPASS ? ESP_OK : ESP_ERR_NO_MEM; } diff --git a/main/ddp.h b/main/ddp.h index 3a692a6..0dd1875 100644 --- a/main/ddp.h +++ b/main/ddp.h @@ -9,6 +9,10 @@ #include "esp_err.h" #define DDP_PORT 4048 +#define DDP_SYNC_PORT 4049 // UDP broadcast sync: "LSY1" + seq (u32, big endian) -/** @brief Start listening for DDP packets. */ +/** @brief Start listening for DDP packets and sync broadcasts. Off if the saved setting is off. */ esp_err_t ddp_start(void); + +/** @brief Turn DDP pixels and sync reception on or off. Packets are ignored while off. */ +void ddp_set_enabled(bool on); diff --git a/main/effects_a.cpp b/main/effects_a.cpp index eb37506..bd79cb2 100644 --- a/main/effects_a.cpp +++ b/main/effects_a.cpp @@ -296,8 +296,10 @@ bool fx_chase(fx_t &f, st_t &s) rgb color1 = ab(nc > 1 ? c[1] : c[0], b); int n1 = nz(f.pr->n[1], 1); int n2 = nz(f.pr->n[2], 1); - int n3 = sgn(f, f.pr->n[3]); - int n4 = sgn(f, f.pr->n[4]); + // Always move forward: a negative n3/n4 would otherwise make the dot bounce back. + // sgn() still applies the preset's reverse flag. + int n3 = sgn(f, abs(f.pr->n[3])); + int n4 = sgn(f, abs(f.pr->n[4])); int seg = n1 + n2; int max_pos = nled + seg; auto position = [&](int sc) { diff --git a/main/net.cpp b/main/net.cpp index fd3cc2a..e2dea9d 100644 --- a/main/net.cpp +++ b/main/net.cpp @@ -26,6 +26,17 @@ static volatile bool s_sta_up; static esp_ip4_addr_t s_sta_ip; static int s_retries; +// The access point. It can be turned off in settings, as long as the client is connected. If the client +// then stays down for about a minute (AP_FALLBACK_RETRIES reconnect attempts), the access point comes back. +#define AP_FALLBACK_RETRIES 6 +static volatile bool s_ap_on; +static bool s_ap_want; // the state ap_timer switches to +static esp_timer_handle_t s_ap_timer; + +// A saved network change reconnects the client a moment later, so the reply to the request still gets out +static esp_timer_handle_t s_reconnect_timer; +static net_cfg_t s_pending_net; + // Set the STA config from credentials. Empty password means an open network. static void apply_sta_config(const wifi_creds_t *c) { @@ -36,6 +47,58 @@ static void apply_sta_config(const wifi_creds_t *c) esp_wifi_set_config(WIFI_IF_STA, &cfg); } +// Turn the access point on (with its led-XXXXXX name, open) or off. The client keeps running either way. +static void apply_ap(bool on) +{ + if (on) { + char ssid[16]; + net_ap_ssid(ssid, sizeof(ssid)); + wifi_config_t ap = {}; + strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1); + ap.ap.ssid_len = strlen(ssid); + ap.ap.channel = AP_CHANNEL; + ap.ap.max_connection = AP_MAX_CLIENTS; + ap.ap.authmode = WIFI_AUTH_OPEN; + esp_wifi_set_config(WIFI_IF_AP, &ap); + esp_wifi_set_mode(WIFI_MODE_APSTA); + ESP_LOGI(TAG, "Access point %s on", ssid); + } else { + esp_wifi_set_mode(WIFI_MODE_STA); + ESP_LOGI(TAG, "Access point off"); + } + s_ap_on = on; +} + +// Switch the access point later, from a timer task (not inside a Wi-Fi event) +static void ap_timer_cb(void *arg) +{ + (void)arg; + if (s_ap_want != s_ap_on) { + apply_ap(s_ap_want); + } +} + +static esp_err_t apply_client_ip(const net_cfg_t *c); + +static void reconnect_cb(void *arg) +{ + (void)arg; + esp_timer_stop(s_retry_timer); + esp_wifi_disconnect(); + s_retries = 0; + if (apply_client_ip(&s_pending_net) != ESP_OK) { + ESP_LOGW(TAG, "Client address could not be applied"); + } + esp_wifi_connect(); +} + +static void ap_switch_later(bool on, uint64_t delay_us) +{ + s_ap_want = on; + esp_timer_stop(s_ap_timer); // not running is fine + esp_timer_start_once(s_ap_timer, delay_us); +} + // Client address: DHCP, or the static address from settings. Called before the client connects. static esp_err_t apply_client_ip(const net_cfg_t *c) { @@ -99,6 +162,9 @@ static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *da s_retries++; esp_timer_stop(s_retry_timer); esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000); + if (!s_ap_on && s_retries >= AP_FALLBACK_RETRIES) { + ap_switch_later(true, 1000000); // the client keeps failing: bring the access point back + } break; } default: @@ -146,31 +212,39 @@ esp_err_t net_start(void) }; ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer)); - ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA)); + const esp_timer_create_args_t ap_args = { + .callback = ap_timer_cb, + .arg = NULL, + .dispatch_method = ESP_TIMER_TASK, + .name = "ap_switch", + .skip_unhandled_events = false, + }; + ESP_ERROR_CHECK(esp_timer_create(&ap_args, &s_ap_timer)); - // Open access point named led-XXXXXX - char ssid[16]; - net_ap_ssid(ssid, sizeof(ssid)); - wifi_config_t ap = {}; - strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1); - ap.ap.ssid_len = strlen(ssid); - ap.ap.channel = AP_CHANNEL; - ap.ap.max_connection = AP_MAX_CLIENTS; - ap.ap.authmode = WIFI_AUTH_OPEN; - ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap)); + const esp_timer_create_args_t reconnect_args = { + .callback = reconnect_cb, + .arg = NULL, + .dispatch_method = ESP_TIMER_TASK, + .name = "wifi_reconnect", + .skip_unhandled_events = false, + }; + ESP_ERROR_CHECK(esp_timer_create(&reconnect_args, &s_reconnect_timer)); - // Client credentials, if any were saved + // The access point is on unless turned off. With no client Wi-Fi saved it stays on, so the device + // can always be reached and set up. + net_cfg_t n; + settings_load_net(&n); wifi_creds_t c; - if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) { + const bool has_creds = settings_load_wifi(&c) == ESP_OK && c.ssid[0]; + apply_ap(n.ap_enabled || !has_creds); + + if (has_creds) { apply_sta_config(&c); } ESP_ERROR_CHECK(esp_wifi_start()); - ESP_LOGI(TAG, "AP %s started", ssid); // mDNS: .local, with an HTTP service on port 80 - net_cfg_t n; - settings_load_net(&n); ESP_ERROR_CHECK(mdns_init()); ESP_ERROR_CHECK(mdns_hostname_set(n.hostname)); ESP_ERROR_CHECK(mdns_instance_name_set("LED controller")); @@ -208,6 +282,12 @@ esp_err_t net_sta_connect(const wifi_creds_t *c) esp_err_t net_save_network(const net_cfg_t *c) { + // Turning the access point off needs a connected client, or the device could not be reached again + net_cfg_t old; + settings_load_net(&old); + if (!c->ap_enabled && old.ap_enabled && !s_sta_up) { + return ESP_ERR_INVALID_STATE; + } esp_err_t err = settings_save_net(c); if (err != ESP_OK) { return err; @@ -216,19 +296,19 @@ esp_err_t net_save_network(const net_cfg_t *c) if (err != ESP_OK) { return err; } - // Reconnect with the new address settings if a client is configured + if (c->ap_enabled != s_ap_on) { + // After the reply has gone out, so the page that asked still gets it + ap_switch_later(c->ap_enabled, c->ap_enabled ? 1000000 : 1500000); + } + // Reconnect with the new address settings if a client is configured (after the reply, see reconnect_cb) wifi_creds_t w; if (settings_load_wifi(&w) != ESP_OK || !w.ssid[0]) { return ESP_OK; } - esp_timer_stop(s_retry_timer); - esp_wifi_disconnect(); - s_retries = 0; - err = apply_client_ip(c); - if (err != ESP_OK) { - return err; - } - return esp_wifi_connect(); + s_pending_net = *c; + esp_timer_stop(s_reconnect_timer); + esp_timer_start_once(s_reconnect_timer, 1000000); + return ESP_OK; } esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count) diff --git a/main/patterns.cpp b/main/patterns.cpp index e28b037..f18cb95 100644 --- a/main/patterns.cpp +++ b/main/patterns.cpp @@ -94,8 +94,18 @@ static uint32_t s_ddp_packets; static uint32_t s_ddp_frames; // frames completed (PUSH seen) static uint32_t s_ddp_sum; // checksum of the last completed frame static uint32_t s_ddp_log_ms; // last serial summary +// Frame sync: while syncs keep arriving, a completed DDP frame waits for the next sync before it is shown +#define DDP_SYNC_TIMEOUT_MS 2000 +static uint8_t s_ddp_show[FX_LEDS_MAX * 3]; // the frame the strip shows +static uint8_t s_ddp_held[FX_LEDS_MAX * 3]; // a completed frame waiting for a sync +static bool s_ddp_held_ok; +static uint32_t s_sync_last_ms; // 0: never +static uint32_t s_sync_seq; // seq of the last sync +static uint32_t s_sync_count; +static uint32_t s_ddp_shown; // frames shown static uint8_t s_max_brightness = 255; static uint8_t s_global = 255; +static uint8_t s_master = 255; static uint32_t s_fade_t0; static uint32_t s_fade_ms; @@ -190,6 +200,21 @@ uint8_t patterns_get_global(void) return v; } +void patterns_set_master(uint8_t level) +{ + xSemaphoreTake(s_lock, portMAX_DELAY); + s_master = level; + xSemaphoreGive(s_lock); +} + +uint8_t patterns_get_master(void) +{ + xSemaphoreTake(s_lock, portMAX_DELAY); + uint8_t v = s_master; + xSemaphoreGive(s_lock); + return v; +} + void patterns_get(preset_t *out) { xSemaphoreTake(s_lock, portMAX_DELAY); @@ -203,9 +228,11 @@ static uint32_t now_ms(void) } // Show the shadow frame, crossfading from the previous frame while a fade runs -static void output(uint32_t now) +static void output(uint32_t now, bool full_brightness) { - int s_scale = s_global * s_max_brightness / 255; // global brightness under the ceiling + // device brightness x master scale, under the max brightness ceiling. DDP frames are shown at + // full brightness: the sender sets the colours. + int s_scale = full_brightness ? 255 : s_global * s_master / 255 * s_max_brightness / 255; int k = -1; if (s_fading) { uint32_t el = now - s_fade_t0; @@ -342,14 +369,14 @@ static void patterns_task(void *arg) s_fx.t = now - g_st.t0; if (ddp_on) { for (int i = 0; i < s_fx.n; i++) { - s_fx.px[i] = { s_ddp[3 * i], s_ddp[3 * i + 1], s_ddp[3 * i + 2] }; + s_fx.px[i] = { s_ddp_show[3 * i], s_ddp_show[3 * i + 1], s_ddp_show[3 * i + 2] }; } } else if (!g_st.done) { if (kPatterns[s_run.pattern].fn(s_fx, g_st)) { g_st.done = true; } } - output(now); + output(now, ddp_on); xSemaphoreGive(s_lock); vTaskDelay(pdMS_TO_TICKS(FRAME_MS)); } @@ -378,6 +405,7 @@ void patterns_start(const hw_cfg_t &hw) s_fx.n = n; s_max_brightness = hw.max_brightness; s_global = hw.global_brightness; + s_master = hw.master_brightness; s_strip = new WS2812((gpio_num_t)hw.pin, n); s_strip->setOrder(hw.order); s_strip->setBrightness(255); // brightness is applied per colour by the patterns @@ -411,6 +439,27 @@ esp_err_t patterns_set_hardware(const hw_cfg_t &hw) // ---- DDP --------------------------------------------------------------------------------------- +// Make a completed frame the one the strip shows, and log it. Caller holds s_lock. +static void ddp_show(const uint8_t *frame, uint32_t now) +{ + size_t cap = (size_t)s_fx.n * 3; + memcpy(s_ddp_show, frame, cap); + s_ddp_shown++; + uint32_t sum = 0; + for (size_t i = 0; i < cap; i++) { + sum += frame[i]; + } + s_ddp_sum = sum; + // Summary on the serial log, at most twice a second, so the test can check what was shown + if (now - s_ddp_log_ms >= 500) { + s_ddp_log_ms = now; + ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u", + (unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum, + frame[0], frame[1], frame[2], + frame[cap - 3], frame[cap - 2], frame[cap - 1]); + } +} + void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push) { xSemaphoreTake(s_lock, portMAX_DELAY); @@ -426,23 +475,34 @@ void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool p s_ddp_packets++; if (push) { s_ddp_frames++; - uint32_t sum = 0; - for (size_t i = 0; i < cap; i++) { - sum += s_ddp[i]; - } - s_ddp_sum = sum; - // Summary on the serial log, at most twice a second, so the test can check what was shown - if (now - s_ddp_log_ms >= 500) { - s_ddp_log_ms = now; - ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u", - (unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum, - s_ddp[0], s_ddp[1], s_ddp[2], - s_ddp[cap - 3], s_ddp[cap - 2], s_ddp[cap - 1]); + bool syncing = s_sync_last_ms != 0 && now - s_sync_last_ms < DDP_SYNC_TIMEOUT_MS; + if (syncing) { + // Syncs are arriving: hold the frame until the next one. The sender acks each frame before it + // sends the sync, so the frame is always here when its sync arrives. + memcpy(s_ddp_held, s_ddp, cap); + s_ddp_held_ok = true; + } else { + s_ddp_held_ok = false; + ddp_show(s_ddp, now); } } xSemaphoreGive(s_lock); } +void patterns_ddp_sync(uint32_t seq) +{ + xSemaphoreTake(s_lock, portMAX_DELAY); + uint32_t now = now_ms(); + s_sync_last_ms = now | 1; // never 0 + s_sync_seq = seq; + s_sync_count++; + if (s_ddp_held_ok) { + s_ddp_held_ok = false; + ddp_show(s_ddp_held, now); + } + xSemaphoreGive(s_lock); +} + void patterns_ddp_status(bool *active, uint32_t *packets) { xSemaphoreTake(s_lock, portMAX_DELAY); @@ -451,6 +511,19 @@ void patterns_ddp_status(bool *active, uint32_t *packets) xSemaphoreGive(s_lock); } +void patterns_ddp_debug(patterns_ddp_debug_t *out) +{ + xSemaphoreTake(s_lock, portMAX_DELAY); + uint32_t now = now_ms(); + out->syncs = s_sync_count; + out->sync_seq = s_sync_seq; + out->sync_age_ms = s_sync_last_ms != 0 ? now - s_sync_last_ms : UINT32_MAX; + out->frames = s_ddp_frames; + out->shown = s_ddp_shown; + out->held = s_ddp_held_ok; + xSemaphoreGive(s_lock); +} + void patterns_shown_pixel(int i, uint8_t out[3]) { xSemaphoreTake(s_lock, portMAX_DELAY); diff --git a/main/patterns.h b/main/patterns.h index 364b96c..207b57b 100644 --- a/main/patterns.h +++ b/main/patterns.h @@ -41,10 +41,22 @@ void patterns_select(const preset_t &p); /** @brief DDP pixel data for the strip: byte offset into the RGB buffer, data, length. Replaces the pattern. */ void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push); +void patterns_ddp_sync(uint32_t seq); /** @brief Whether DDP pixels are arriving, and how many packets have come in. */ void patterns_ddp_status(bool *active, uint32_t *packets); +/** @brief Frame sync counters, for diagnosing the sync test. */ +typedef struct { + uint32_t syncs; // sync packets received + uint32_t sync_seq; // seq of the last sync + uint32_t sync_age_ms; // ms since the last sync (UINT32_MAX: never) + uint32_t frames; // DDP frames completed (PUSH) + uint32_t shown; // frames shown on the strip + bool held; // a frame is waiting for the next sync +} patterns_ddp_debug_t; +void patterns_ddp_debug(patterns_ddp_debug_t *out); + /** @brief The colour last shown on LED i, as RGB. */ void patterns_shown_pixel(int i, uint8_t out[3]); @@ -52,6 +64,10 @@ void patterns_shown_pixel(int i, uint8_t out[3]); void patterns_set_global(uint8_t level); uint8_t patterns_get_global(void); +/** @brief Master scale for this device, 0-255: multiplies the device brightness (under the max brightness ceiling). */ +void patterns_set_master(uint8_t level); +uint8_t patterns_get_master(void); + /** @brief Copy of the preset being shown. */ void patterns_get(preset_t *out); diff --git a/main/settings.cpp b/main/settings.cpp index 2383d57..b6c6e7d 100644 --- a/main/settings.cpp +++ b/main/settings.cpp @@ -50,6 +50,7 @@ esp_err_t settings_load_hw(hw_cfg_t *c) c->num_leds = 119; c->pin = 10; c->global_brightness = 255; + c->master_brightness = 255; nvs_handle_t h; if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) { return ESP_OK; @@ -72,6 +73,9 @@ esp_err_t settings_load_hw(hw_cfg_t *c) if (nvs_get_u8(h, "global_bright", &mb) == ESP_OK) { c->global_brightness = mb; } + if (nvs_get_u8(h, "master_bright", &mb) == ESP_OK) { + c->master_brightness = mb; + } nvs_close(h); return ESP_OK; } @@ -88,6 +92,7 @@ esp_err_t settings_save_hw(const hw_cfg_t *c) if (err == ESP_OK) err = nvs_set_i32(h, "num_leds", c->num_leds); if (err == ESP_OK) err = nvs_set_i32(h, "pin", c->pin); if (err == ESP_OK) err = nvs_set_u8(h, "global_bright", c->global_brightness); + if (err == ESP_OK) err = nvs_set_u8(h, "master_bright", c->master_brightness); if (err == ESP_OK) err = nvs_commit(h); nvs_close(h); return err; @@ -106,6 +111,8 @@ static void get_str(nvs_handle_t h, const char *key, char *buf, size_t len, cons esp_err_t settings_load_net(net_cfg_t *c) { memset(c, 0, sizeof(*c)); + c->ap_enabled = true; + c->ddp_enabled = true; nvs_handle_t h; esp_err_t err = nvs_open(NS, NVS_READONLY, &h); if (err == ESP_ERR_NVS_NOT_FOUND) { @@ -124,6 +131,12 @@ esp_err_t settings_load_net(net_cfg_t *c) get_str(h, "netmask", c->netmask, sizeof(c->netmask), ""); get_str(h, "gateway", c->gateway, sizeof(c->gateway), ""); get_str(h, "dns", c->dns, sizeof(c->dns), ""); + char ap[8]; + get_str(h, "ap", ap, sizeof(ap), "on"); + c->ap_enabled = strcmp(ap, "off") != 0; + char ddp[8]; + get_str(h, "ddp", ddp, sizeof(ddp), "on"); + c->ddp_enabled = strcmp(ddp, "off") != 0; nvs_close(h); return ESP_OK; } @@ -141,6 +154,8 @@ esp_err_t settings_save_net(const net_cfg_t *c) if (err == ESP_OK) err = nvs_set_str(h, "netmask", c->netmask); if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway); if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns); + if (err == ESP_OK) err = nvs_set_str(h, "ap", c->ap_enabled ? "on" : "off"); + if (err == ESP_OK) err = nvs_set_str(h, "ddp", c->ddp_enabled ? "on" : "off"); if (err == ESP_OK) err = nvs_commit(h); nvs_close(h); return err; diff --git a/main/settings.h b/main/settings.h index e5ccfb9..ff5e677 100644 --- a/main/settings.h +++ b/main/settings.h @@ -19,6 +19,8 @@ struct net_cfg_t { char netmask[16]; char gateway[16]; char dns[16]; // optional; empty uses the gateway + bool ap_enabled; // the access point (led-XXXXXX) is on; default on + bool ddp_enabled; // DDP pixels and frame sync are received; default on }; /** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */ @@ -32,7 +34,8 @@ struct hw_cfg_t { uint8_t max_brightness; // ceiling for every output colour, 0-255 int num_leds; // 1-512 int pin; // GPIO for the data line - uint8_t global_brightness; // live brightness for all patterns, 0-255 (under max_brightness) + uint8_t global_brightness; // this device's own brightness, 0-255 (under max_brightness) + uint8_t master_brightness; // master scale for this device, 0-255, set from "All devices" }; /** @brief Read the LED strip settings. Missing keys get their defaults (grb, 255, 119). */ diff --git a/main/web.cpp b/main/web.cpp index 945dca7..d75995c 100644 --- a/main/web.cpp +++ b/main/web.cpp @@ -11,6 +11,9 @@ #include "esp_http_server.h" #include "esp_log.h" #include "esp_netif.h" +#include "esp_timer.h" +#include +#include #include "esp_wifi.h" #include "net.h" #include "ota.h" @@ -20,6 +23,7 @@ #include "presets.h" #include "settings.h" #include "web.h" +#include "ws_client.h" static const char *TAG = "web"; @@ -122,38 +126,74 @@ void web_allow_lan_origin(httpd_req_t *req) httpd_resp_set_hdr(req, "Vary", "Origin"); } -static esp_err_t send_json(httpd_req_t *req, cJSON *obj) +// One API call, from an HTTP request or from a WebSocket message. Handlers use only the helpers +// below, so the same handler serves both. +typedef struct { + httpd_req_t *http; // the HTTP request, or NULL for a WebSocket call + const char *body; // WebSocket call: the request body text + const char *query; // WebSocket call: the query string after '?', or "" + char *out; // WebSocket call: the reply text is written here + size_t out_cap; + int status; // WebSocket call: the reply's status code +} api_req_t; + +typedef esp_err_t (*api_fn_t)(api_req_t *req); + +// Send a JSON reply. status is a status line such as "200 OK". +static esp_err_t send_text(api_req_t *req, const char *status, const char *text) +{ + if (req->http) { + web_allow_lan_origin(req->http); + httpd_resp_set_status(req->http, status); + httpd_resp_set_type(req->http, "application/json"); + return httpd_resp_sendstr(req->http, text); + } + req->status = atoi(status); + snprintf(req->out, req->out_cap, "%s", text); + return ESP_OK; +} + +static esp_err_t send_json(api_req_t *req, cJSON *obj) { char *s = cJSON_PrintUnformatted(obj); cJSON_Delete(obj); - web_allow_lan_origin(req); if (!s) { - return httpd_resp_send_500(req); + return send_text(req, "500 Internal Server Error", "{\"error\":\"out of memory\"}"); } - httpd_resp_set_type(req, "application/json"); - esp_err_t err = httpd_resp_sendstr(req, s); + esp_err_t err = send_text(req, "200 OK", s); cJSON_free(s); return err; } -static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg) +static esp_err_t send_error(api_req_t *req, const char *status, const char *msg) { - httpd_resp_set_status(req, status); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "error", msg); - return send_json(req, o); + char *s = cJSON_PrintUnformatted(o); + cJSON_Delete(o); + esp_err_t err = send_text(req, status, s ? s : "{}"); + cJSON_free(s); + return err; } // Read the request body into buf (NUL-terminated). False if missing, too big or unreadable. -static bool read_body(httpd_req_t *req, char *buf, size_t cap) +static bool read_body(api_req_t *req, char *buf, size_t cap) { - int len = req->content_len; + if (!req->http) { + size_t n = req->body ? strlen(req->body) : 0; + if (n == 0 || n >= cap) { + return false; + } + memcpy(buf, req->body, n + 1); + return true; + } + int len = req->http->content_len; if (len <= 0 || (size_t)len >= cap) { return false; } int got = 0; while (got < len) { - int r = httpd_req_recv(req, buf + got, len - got); + int r = httpd_req_recv(req->http, buf + got, len - got); if (r <= 0) { return false; } @@ -164,7 +204,7 @@ static bool read_body(httpd_req_t *req, char *buf, size_t cap) } // Read a JSON body; NULL (no reply sent) if missing, too big or not JSON. Caller frees with cJSON_Delete. -static cJSON *read_json(httpd_req_t *req) +static cJSON *read_json(api_req_t *req) { char body[MAX_BODY]; if (!read_body(req, body, sizeof(body))) { @@ -190,7 +230,7 @@ static esp_err_t style_css_get(httpd_req_t *req) } // GET /api/status : the running preset (same fields as a preset), plus device and network state -static esp_err_t status_get(httpd_req_t *req) +static esp_err_t status_get(api_req_t *req) { preset_t p; patterns_get(&p); @@ -207,6 +247,7 @@ static esp_err_t status_get(httpd_req_t *req) cJSON_AddStringToObject(o, "sta_ip", ip); cJSON_AddStringToObject(o, "selected", presets_selected()); cJSON_AddNumberToObject(o, "global_brightness", patterns_get_global()); + cJSON_AddNumberToObject(o, "master_brightness", patterns_get_master()); cJSON *modes = cJSON_AddArrayToObject(o, "patterns"); for (int i = 0; i < patterns_count(); i++) { cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_name(i))); @@ -215,7 +256,7 @@ static esp_err_t status_get(httpd_req_t *req) } // POST /api/pattern : change the running settings. Fields missing from the body keep their value. -static esp_err_t pattern_post(httpd_req_t *req) +static esp_err_t pattern_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { @@ -233,7 +274,7 @@ static esp_err_t pattern_post(httpd_req_t *req) } // GET /api/wifi : saved client SSID and connection state -static esp_err_t wifi_get(httpd_req_t *req) +static esp_err_t wifi_get(api_req_t *req) { wifi_creds_t c = {}; settings_load_wifi(&c); @@ -247,7 +288,7 @@ static esp_err_t wifi_get(httpd_req_t *req) } // POST /api/wifi {"ssid","password"} : save and connect -static esp_err_t wifi_post(httpd_req_t *req) +static esp_err_t wifi_post(api_req_t *req) { char body[MAX_BODY]; if (!read_body(req, body, sizeof(body))) { @@ -285,7 +326,7 @@ static esp_err_t wifi_post(httpd_req_t *req) } // GET /api/wifi/scan : visible networks -static esp_err_t wifi_scan_get(httpd_req_t *req) +static esp_err_t wifi_scan_get(api_req_t *req) { static wifi_ap_record_t recs[MAX_SCAN]; uint16_t count = MAX_SCAN; @@ -330,7 +371,7 @@ static bool valid_ipv4(const char *s) } // GET /api/network : mDNS name and client address settings, with the current address -static esp_err_t network_get(httpd_req_t *req) +static esp_err_t network_get(api_req_t *req) { net_cfg_t n; settings_load_net(&n); @@ -345,12 +386,14 @@ static esp_err_t network_get(httpd_req_t *req) cJSON_AddStringToObject(o, "dns", n.dns); cJSON_AddBoolToObject(o, "connected", up); cJSON_AddStringToObject(o, "current_ip", ip); + cJSON_AddBoolToObject(o, "ap_enabled", n.ap_enabled); + cJSON_AddBoolToObject(o, "ddp_enabled", n.ddp_enabled); return send_json(req, o); } // POST /api/network {"hostname","mode":"dhcp"|"static","ip","netmask","gateway","dns"} // Missing fields keep their current value. Saves, applies and reconnects the client. -static esp_err_t network_post(httpd_req_t *req) +static esp_err_t network_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { @@ -399,6 +442,15 @@ static esp_err_t network_post(httpd_req_t *req) f.dst[f.len - 1] = '\0'; } } + cJSON *ap = cJSON_GetObjectItem(in, "ap_enabled"); + if (cJSON_IsBool(ap)) { + n.ap_enabled = cJSON_IsTrue(ap); + } + cJSON *ddp = cJSON_GetObjectItem(in, "ddp_enabled"); + if (cJSON_IsBool(ddp)) { + n.ddp_enabled = cJSON_IsTrue(ddp); + ddp_set_enabled(n.ddp_enabled); + } cJSON_Delete(in); if (n.use_static) { @@ -411,6 +463,9 @@ static esp_err_t network_post(httpd_req_t *req) } esp_err_t err = net_save_network(&n); + if (err == ESP_ERR_INVALID_STATE) { + return send_error(req, "400 Bad Request", "connect to a Wi-Fi network before turning the access point off"); + } if (err != ESP_OK) { ESP_LOGW(TAG, "Network apply failed: %s", esp_err_to_name(err)); return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); @@ -451,7 +506,7 @@ static bool valid_pin(int pin) } // GET /api/hardware : LED strip settings -static esp_err_t hardware_get(httpd_req_t *req) +static esp_err_t hardware_get(api_req_t *req) { hw_cfg_t hw; settings_load_hw(&hw); @@ -464,7 +519,7 @@ static esp_err_t hardware_get(httpd_req_t *req) } // POST /api/hardware {"rgb_order","max_brightness":0-255,"num_leds":1-512}. Missing fields keep their value. -static esp_err_t hardware_post(httpd_req_t *req) +static esp_err_t hardware_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { @@ -523,18 +578,21 @@ static esp_err_t hardware_post(httpd_req_t *req) } // GET /api/ddp[?led=N] : DDP receiver state, and the colour shown on LED N (for checks) -static esp_err_t ddp_get(httpd_req_t *req) +static esp_err_t ddp_get(api_req_t *req) { bool active; uint32_t packets; patterns_ddp_status(&active, &packets); int led = 0; - char q[32]; - if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) { - char v[8]; - if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) { - led = atoi(v); - } + char q[32] = ""; + if (req->http) { + httpd_req_get_url_query_str(req->http, q, sizeof(q)); + } else { + snprintf(q, sizeof(q), "%s", req->query); + } + char v[8]; + if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) { + led = atoi(v); } uint8_t px[3]; patterns_shown_pixel(led, px); @@ -542,6 +600,16 @@ static esp_err_t ddp_get(httpd_req_t *req) cJSON_AddBoolToObject(o, "active", active); cJSON_AddNumberToObject(o, "packets", packets); cJSON_AddNumberToObject(o, "port", DDP_PORT); + patterns_ddp_debug_t dbg; + patterns_ddp_debug(&dbg); + cJSON *sy = cJSON_AddObjectToObject(o, "sync"); + cJSON_AddNumberToObject(sy, "port", DDP_SYNC_PORT); + cJSON_AddNumberToObject(sy, "syncs", dbg.syncs); + cJSON_AddNumberToObject(sy, "seq", dbg.sync_seq); + cJSON_AddNumberToObject(sy, "age_ms", dbg.sync_age_ms == UINT32_MAX ? -1 : (double)dbg.sync_age_ms); + cJSON_AddNumberToObject(sy, "frames", dbg.frames); + cJSON_AddNumberToObject(sy, "shown", dbg.shown); + cJSON_AddBoolToObject(sy, "held", dbg.held); cJSON_AddNumberToObject(o, "led", led); cJSON *px_arr = cJSON_AddArrayToObject(o, "rgb"); for (int i = 0; i < 3; i++) { @@ -551,7 +619,7 @@ static esp_err_t ddp_get(httpd_req_t *req) } // POST /api/presets/order {"names":[...]} : the presets' order on the front page -static esp_err_t presets_order_post(httpd_req_t *req) +static esp_err_t presets_order_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { @@ -578,7 +646,7 @@ static esp_err_t presets_order_post(httpd_req_t *req) } // POST /api/presets/defaults : add the default presets that are missing -static esp_err_t presets_defaults_post(httpd_req_t *req) +static esp_err_t presets_defaults_post(api_req_t *req) { cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "added", presets_add_defaults()); @@ -586,7 +654,7 @@ static esp_err_t presets_defaults_post(httpd_req_t *req) } // GET /api/presets -static esp_err_t presets_get(httpd_req_t *req) +static esp_err_t presets_get(api_req_t *req) { cJSON *o = cJSON_CreateObject(); cJSON *arr = cJSON_AddArrayToObject(o, "presets"); @@ -599,32 +667,52 @@ static esp_err_t presets_get(httpd_req_t *req) return send_json(req, o); } -// POST /api/brightness {"brightness":0-255} : live brightness for every pattern, saved -static esp_err_t brightness_post(httpd_req_t *req) +// POST /api/brightness {"brightness":0-255} sets this device's level; {"master":0-255} sets its +// master scale (sent to every device by "All devices"). Either or both, saved. +// Returns NULL when applied, or the error message. +static const char *brightness_apply(const cJSON *in) +{ + const cJSON *v = cJSON_GetObjectItem(in, "brightness"); + const cJSON *m = cJSON_GetObjectItem(in, "master"); + if (!v && !m) { + return "send brightness and/or master"; + } + if ((v && (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255)) || + (m && (!cJSON_IsNumber(m) || m->valueint < 0 || m->valueint > 255))) { + return "brightness and master must be 0-255"; + } + hw_cfg_t hw; + settings_load_hw(&hw); + if (v) { + hw.global_brightness = (uint8_t)v->valueint; + patterns_set_global(hw.global_brightness); + } + if (m) { + hw.master_brightness = (uint8_t)m->valueint; + patterns_set_master(hw.master_brightness); + } + settings_save_hw(&hw); + return NULL; +} + +static esp_err_t brightness_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } - cJSON *v = cJSON_GetObjectItem(in, "brightness"); - if (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255) { - cJSON_Delete(in); - return send_error(req, "400 Bad Request", "brightness must be 0-255"); - } - uint8_t level = (uint8_t)v->valueint; + const char *err = brightness_apply(in); cJSON_Delete(in); - patterns_set_global(level); - hw_cfg_t hw; - settings_load_hw(&hw); - hw.global_brightness = level; - settings_save_hw(&hw); + if (err) { + return send_error(req, "400 Bad Request", err); + } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved"); return send_json(req, o); } // POST /api/presets : create or update by name. Missing fields take the running settings. -static esp_err_t presets_post(httpd_req_t *req) +static esp_err_t presets_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { @@ -656,7 +744,7 @@ static esp_err_t presets_post(httpd_req_t *req) } // Shared body for select, delete and startup: {"name"} -static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg) +static esp_err_t preset_name_action(api_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg) { cJSON *in = read_json(req); if (!in) { @@ -684,24 +772,25 @@ static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const return send_json(req, o); } -static esp_err_t select_post(httpd_req_t *req) +static esp_err_t select_post(api_req_t *req) { return preset_name_action(req, presets_select, "selected"); } -static esp_err_t delete_post(httpd_req_t *req) +static esp_err_t delete_post(api_req_t *req) { return preset_name_action(req, presets_delete, "deleted"); } -static esp_err_t startup_post(httpd_req_t *req) +static esp_err_t startup_post(api_req_t *req) { return preset_name_action(req, presets_set_startup, "startup set"); } static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *)) { - httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL }; + httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL, + .is_websocket = false, .handle_ws_control_frames = false, .supported_subprotocol = NULL }; httpd_register_uri_handler(srv, &u); } @@ -734,90 +823,240 @@ static bool relay_path_ok(const char *p) return strstr(p, "..") == NULL && strchr(p, ' ') == NULL && strchr(p, '\r') == NULL && strchr(p, '\n') == NULL; } +// Relay connections are kept open per peer, so a relayed request does not pay for a new TCP connection. +// The HTTP server runs one task, so relay calls never overlap and the slots need no lock. +#define RELAY_SLOTS 4 +#define RELAY_TIMEOUT_MS 4000 +struct relay_slot_t { + char host[80]; + esp_http_client_handle_t cl; +}; +static relay_slot_t s_relay[RELAY_SLOTS]; + +// The kept-open client for this host, pointed at url. A new slot evicts the oldest one. +static esp_http_client_handle_t relay_client(const char *host, const char *url) +{ + int slot = -1; + for (int i = 0; i < RELAY_SLOTS; i++) { + if (s_relay[i].cl && strcmp(s_relay[i].host, host) == 0) { + slot = i; + break; + } + } + if (slot < 0) { + slot = 0; + for (int i = 0; i < RELAY_SLOTS; i++) { + if (!s_relay[i].cl) { + slot = i; + break; + } + } + if (s_relay[slot].cl) { + esp_http_client_cleanup(s_relay[slot].cl); + } + esp_http_client_config_t cfg = {}; + cfg.url = url; + cfg.timeout_ms = RELAY_TIMEOUT_MS; + cfg.keep_alive_enable = true; + s_relay[slot].cl = esp_http_client_init(&cfg); + snprintf(s_relay[slot].host, sizeof(s_relay[slot].host), "%s", host); + return s_relay[slot].cl; + } + esp_http_client_set_url(s_relay[slot].cl, url); + return s_relay[slot].cl; +} + +// One request to a peer over its kept-open connection. A dead connection is dropped and retried once. +static esp_err_t relay_do(const char *host, const char *url, bool is_post, const char *body, int body_len, + int *status, char *out, int cap, int *got) +{ + for (int attempt = 0; attempt < 2; attempt++) { + const int64_t t0 = esp_timer_get_time(); + esp_http_client_handle_t cl = relay_client(host, url); + const int64_t t_client = esp_timer_get_time(); + if (!cl) { + return ESP_ERR_NO_MEM; + } + esp_http_client_set_method(cl, is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET); + esp_http_client_set_header(cl, "Content-Type", "text/plain"); + esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0); + const int64_t t_open = esp_timer_get_time(); + if (err == ESP_OK && is_post && body_len > 0 && esp_http_client_write(cl, body, body_len) != body_len) { + err = ESP_FAIL; + } + const int64_t t_write = esp_timer_get_time(); + *got = 0; + bool full = false; + int fetch_rc = -1; + if (err == ESP_OK) { + fetch_rc = esp_http_client_fetch_headers(cl); + } + const int64_t t_headers = esp_timer_get_time(); + ESP_LOGI(TAG, "relay %s attempt %d: client %lld us, open %lld us, write %lld us, headers %lld us (rc %d, err %d)", + host, attempt, (long long)(t_client - t0), (long long)(t_open - t_client), + (long long)(t_write - t_open), (long long)(t_headers - t_write), fetch_rc, (int)err); + if (err == ESP_OK && fetch_rc >= 0) { + *status = esp_http_client_get_status_code(cl); + int r; + while (*got < cap && (r = esp_http_client_read(cl, out + *got, cap - *got)) > 0) { + *got += r; + } + ESP_LOGI(TAG, "relay %s body %d bytes read in %lld us", host, *got, + (long long)(esp_timer_get_time() - t_headers)); + full = *got >= cap; // more body than fits: keep what fits, and drop the connection + if (!full) { + return ESP_OK; + } + esp_http_client_close(cl); + return ESP_OK; + } + // Failed before the answer: drop this connection and try once more + esp_http_client_close(cl); + } + return ESP_FAIL; +} + +// Calls to a peer go over a kept-open WebSocket (its /ws), not a new HTTP request each time. +#define WS_SLOTS 4 +struct ws_slot_t { + char host[80]; // empty when the slot is free + int fd; +}; +static ws_slot_t s_ws[WS_SLOTS]; + +static void ws_slot_drop(ws_slot_t *slot) +{ + ws_client_close(slot->fd); + slot->fd = -1; + slot->host[0] = '\0'; +} + +// Send msg to host's /ws and read the reply into reply. Reconnects once if the connection is dead. +static bool ws_fast_call(const char *host, const char *msg, char *reply, size_t cap) +{ + for (int attempt = 0; attempt < 2; attempt++) { + ws_slot_t *slot = NULL; + for (int i = 0; i < WS_SLOTS; i++) { + if (s_ws[i].host[0] && strcmp(s_ws[i].host, host) == 0) { + slot = &s_ws[i]; + break; + } + } + if (!slot) { + for (int i = 0; i < WS_SLOTS && !slot; i++) { + if (!s_ws[i].host[0]) { + slot = &s_ws[i]; + } + } + if (!slot) { + slot = &s_ws[0]; + ws_slot_drop(slot); + } + slot->fd = ws_client_connect(host, "/ws"); + if (slot->fd < 0) { + slot->host[0] = '\0'; + return false; + } + snprintf(slot->host, sizeof(slot->host), "%s", host); + } + if (ws_client_send_text(slot->fd, msg, strlen(msg)) == ESP_OK && ws_client_recv_text(slot->fd, reply, cap) >= 0) { + return true; + } + ws_slot_drop(slot); + } + return false; +} + +// The reply to a relayed or WebSocket call: {"status": n, "body": "..."} +static void envelope(char *out, size_t cap, int status, const char *body_text) +{ + cJSON *env = cJSON_CreateObject(); + cJSON_AddNumberToObject(env, "status", status); + cJSON_AddStringToObject(env, "body", body_text); + char *s = cJSON_PrintUnformatted(env); + snprintf(out, cap, "%s", s ? s : "{}"); + cJSON_free(s); + cJSON_Delete(env); +} + +// Call another driver's API. The peer's WebSocket is tried first (kept open, so it is fast); the HTTP +// call is the fallback. out gets the envelope {"status": n, "body": "..."}. +static void relay_forward(const char *host, const char *method, const char *path, const char *body, + char *out, size_t cap) +{ + if (!relay_host_ok(host) || !relay_path_ok(path) || (strcmp(method, "GET") != 0 && strcmp(method, "POST") != 0)) { + envelope(out, cap, 400, "{\"error\":\"need host, method GET or POST, and a path under /api/\"}"); + return; + } + const bool is_post = strcmp(method, "POST") == 0; + const char *b = is_post ? body : ""; + + cJSON *m = cJSON_CreateObject(); + cJSON_AddStringToObject(m, "method", method); + cJSON_AddStringToObject(m, "path", path); + cJSON_AddStringToObject(m, "body", b); + char *msg = cJSON_PrintUnformatted(m); + cJSON_Delete(m); + bool ok = msg && ws_fast_call(host, msg, out, cap); // the peer's reply is already an envelope + cJSON_free(msg); + if (ok) { + return; + } + + char *buf = (char *)malloc(4096); + if (!buf) { + envelope(out, cap, 503, "{\"error\":\"out of memory\"}"); + return; + } + char url[200]; + snprintf(url, sizeof(url), "http://%s%s", host, path); + int got = 0; + int status = 0; + if (relay_do(host, url, is_post, b, (int)strlen(b), &status, buf, 4095, &got) != ESP_OK) { + envelope(out, cap, 502, "{\"error\":\"could not reach that device\"}"); + } else { + buf[got] = '\0'; + envelope(out, cap, status, buf); + } + free(buf); +} + // POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."} -// Calls another driver from here and answers {"status": n, "body": "..."}. A page on this driver only -// talks to this driver, so the browser never has to reach the other device itself. -static esp_err_t relay_post(httpd_req_t *req) +// Kept for HTTP callers; the page itself sends relayed calls over the WebSocket. +static esp_err_t relay_post(api_req_t *req) { - // Heap buffers: the HTTP server task has an 8 KB stack char *in = (char *)malloc(2048); - char *out = (char *)malloc(4096); + char *out = (char *)malloc(8192); if (!in || !out) { free(in); free(out); return send_error(req, "503 Service Unavailable", "out of memory"); } - esp_err_t result = ESP_FAIL; + esp_err_t result; if (!read_body(req, in, 2048)) { result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); - goto done; } else { cJSON *top = cJSON_Parse(in); const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL; const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL; const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL; const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL; - if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp) || !relay_host_ok(jh->valuestring) - || !relay_path_ok(jp->valuestring) || (strcmp(jm->valuestring, "GET") != 0 && strcmp(jm->valuestring, "POST") != 0)) { + if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp)) { cJSON_Delete(top); - result = send_error(req, "400 Bad Request", "need host, method GET or POST, and a path under /api/"); - goto done; - } - const bool is_post = strcmp(jm->valuestring, "POST") == 0; - const char *body = (is_post && cJSON_IsString(jb)) ? jb->valuestring : ""; - const int body_len = (int)strlen(body); - char url[200]; - snprintf(url, sizeof(url), "http://%s%s", jh->valuestring, jp->valuestring); - esp_http_client_config_t ccfg = {}; - ccfg.url = url; - ccfg.method = is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET; - ccfg.timeout_ms = 4000; - esp_http_client_handle_t cl = esp_http_client_init(&ccfg); - if (!cl) { - cJSON_Delete(top); - result = send_error(req, "502 Bad Gateway", "could not start the request"); - goto done; - } - esp_http_client_set_header(cl, "Content-Type", "text/plain"); - esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0); - if (err == ESP_OK && is_post && body_len > 0) { - if (esp_http_client_write(cl, body, body_len) != body_len) { - err = ESP_FAIL; - } - } - int got = 0; - int status = 0; - if (err == ESP_OK && esp_http_client_fetch_headers(cl) >= 0) { - status = esp_http_client_get_status_code(cl); - int r; - while (got < 4095 && (r = esp_http_client_read(cl, out + got, 4095 - got)) > 0) { - got += r; - } + result = send_error(req, "400 Bad Request", "need host, method and path"); } else { - err = ESP_FAIL; + relay_forward(jh->valuestring, jm->valuestring, jp->valuestring, + cJSON_IsString(jb) ? jb->valuestring : "", out, 8192); + cJSON_Delete(top); + result = send_text(req, "200 OK", out); } - esp_http_client_close(cl); - esp_http_client_cleanup(cl); - cJSON_Delete(top); - if (err != ESP_OK) { - result = send_error(req, "502 Bad Gateway", "could not reach that device"); - goto done; - } - out[got] = '\0'; - cJSON *o = cJSON_CreateObject(); - cJSON_AddNumberToObject(o, "status", status); - cJSON_AddStringToObject(o, "body", out); - result = send_json(req, o); } -done: free(in); free(out); return result; } -// GET /api/devices: the LED drivers on this network, found by mDNS (they advertise app=led-strip). -// Includes this driver; the page leaves it out, since "This device" is already in the list. -static esp_err_t devices_get(httpd_req_t *req) +static esp_err_t devices_get(api_req_t *req) { cJSON *arr = cJSON_CreateArray(); mdns_result_t *res = NULL; @@ -873,6 +1112,184 @@ static esp_err_t devices_get(httpd_req_t *req) return send_json(req, top); } +// The server sends each response header as its own small write. With Nagle on, every write after the +// first waits for the client's delayed ACK (hundreds of ms), so turn Nagle off on each new connection. +static esp_err_t open_nodelay(httpd_handle_t hd, int sockfd) +{ + (void)hd; + int one = 1; + setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + return ESP_OK; +} + +// The JSON API. Each route answers an HTTP request and a WebSocket message alike. +typedef struct { + const char *path; + httpd_method_t method; + api_fn_t fn; +} api_route_t; + +static const api_route_t s_api[] = { + {"/api/status", HTTP_GET, status_get}, + {"/api/pattern", HTTP_POST, pattern_post}, + {"/api/wifi", HTTP_GET, wifi_get}, + {"/api/wifi", HTTP_POST, wifi_post}, + {"/api/wifi/scan", HTTP_GET, wifi_scan_get}, + {"/api/network", HTTP_GET, network_get}, + {"/api/network", HTTP_POST, network_post}, + {"/api/ddp", HTTP_GET, ddp_get}, + {"/api/hardware", HTTP_GET, hardware_get}, + {"/api/hardware", HTTP_POST, hardware_post}, + {"/api/presets", HTTP_GET, presets_get}, + {"/api/presets", HTTP_POST, presets_post}, + {"/api/presets/select", HTTP_POST, select_post}, + {"/api/presets/delete", HTTP_POST, delete_post}, + {"/api/presets/startup", HTTP_POST, startup_post}, + {"/api/presets/defaults", HTTP_POST, presets_defaults_post}, + {"/api/presets/order", HTTP_POST, presets_order_post}, + {"/api/brightness", HTTP_POST, brightness_post}, + {"/api/devices", HTTP_GET, devices_get}, + {"/api/relay", HTTP_POST, relay_post}, +}; + +// An HTTP request for a route: the route's function is kept in the URI's user_ctx. +static esp_err_t api_http_entry(httpd_req_t *req) +{ + api_req_t a = {}; + a.http = req; + return reinterpret_cast(req->user_ctx)(&a); +} + +#define WS_MSG_MAX 2048 // a request message +#define WS_REPLY_MAX 8192 // a reply envelope + +// Run an API route on this driver: target is the path, optionally with a query string. +static void ws_local(const char *method, const char *target, const char *body, char *out, size_t cap) +{ + char path[64]; + const char *q = strchr(target, '?'); + size_t n = q ? (size_t)(q - target) : strlen(target); + if (n >= sizeof(path)) { + envelope(out, cap, 404, "{\"error\":\"no such API path\"}"); + return; + } + memcpy(path, target, n); + path[n] = '\0'; + for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) { + const bool is_get = s_api[i].method == HTTP_GET; + if (strcmp(s_api[i].path, path) == 0 && strcmp(method, is_get ? "GET" : "POST") == 0) { + char *reply = (char *)malloc(WS_REPLY_MAX); + if (!reply) { + envelope(out, cap, 503, "{\"error\":\"out of memory\"}"); + return; + } + reply[0] = '\0'; + api_req_t a = {}; + a.body = body; + a.query = q ? q + 1 : ""; + a.out = reply; + a.out_cap = WS_REPLY_MAX; + a.status = 200; + s_api[i].fn(&a); + if (reply[0] == '\0') { + snprintf(reply, WS_REPLY_MAX, "{}"); + } + envelope(out, cap, a.status, reply); + free(reply); + return; + } + } + envelope(out, cap, 404, "{\"error\":\"no such API path\"}"); +} + +// A WebSocket request: {"method": "GET" or "POST", "path": "/api/...", "body": ""}, plus +// "host" to have this driver relay it to that driver. The reply is the envelope {"status": n, "body": "..."}. +static void ws_dispatch(const char *msg, char *out, size_t cap) +{ + cJSON *top = cJSON_Parse(msg); + const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL; + const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL; + const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL; + const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL; + if (!cJSON_IsString(jp)) { + envelope(out, cap, 400, "{\"error\":\"need a path\"}"); + cJSON_Delete(top); + return; + } + const char *method = cJSON_IsString(jm) ? jm->valuestring : "GET"; + char *owned = NULL; // body printed from a JSON object (a string is used as it is) + const char *body = ""; + if (cJSON_IsString(jb)) { + body = jb->valuestring; + } else if (jb) { + owned = cJSON_PrintUnformatted(jb); + body = owned ? owned : ""; + } + if (cJSON_IsString(jh) && jh->valuestring[0] != '\0') { + relay_forward(jh->valuestring, method, jp->valuestring, body, out, cap); + } else { + ws_local(method, jp->valuestring, body, out, cap); + } + cJSON_free(owned); + cJSON_Delete(top); +} + +// WebSocket handler: one text frame in, one text frame out +// Another site's page must not drive this driver. A browser sends its Origin with the WebSocket +// handshake, and only a page from the LAN (or this device) may open the socket. ESP-IDF has no hook +// before the handshake reply, so the check runs right after it: a refused socket is closed before any +// frame is read, so its messages are never dispatched. +static esp_err_t ws_origin_check(httpd_req_t *req) +{ + size_t origin_len = httpd_req_get_hdr_value_len(req, "Origin"); + if (origin_len == 0) { + return ESP_OK; // not a browser (no Origin): the device's own client, or a tool + } + char origin[128]; + if (origin_len >= sizeof(origin) || httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK + || !origin_is_lan(origin)) { + return ESP_FAIL; + } + return ESP_OK; +} + +static esp_err_t ws_handler(httpd_req_t *req) +{ + if (req->method == HTTP_GET) { + return ws_origin_check(req); // the handshake is done + } + httpd_ws_frame_t frame = {}; + frame.type = HTTPD_WS_TYPE_TEXT; + esp_err_t err = httpd_ws_recv_frame(req, &frame, 0); + if (err != ESP_OK) { + return err; + } + if (frame.len == 0 || frame.len > WS_MSG_MAX) { + return ESP_FAIL; + } + uint8_t *buf = (uint8_t *)malloc(frame.len + 1); + char *reply = (char *)malloc(WS_REPLY_MAX); + if (!buf || !reply) { + free(buf); + free(reply); + return ESP_ERR_NO_MEM; + } + frame.payload = buf; + err = httpd_ws_recv_frame(req, &frame, frame.len); + if (err == ESP_OK) { + buf[frame.len] = '\0'; + ws_dispatch((const char *)buf, reply, WS_REPLY_MAX); + httpd_ws_frame_t out = {}; + out.type = HTTPD_WS_TYPE_TEXT; + out.payload = (uint8_t *)reply; + out.len = strlen(reply); + err = httpd_ws_send_frame(req, &out); + } + free(buf); + free(reply); + return err; +} + esp_err_t web_start(void) { httpd_config_t cfg = HTTPD_DEFAULT_CONFIG(); @@ -881,6 +1298,7 @@ esp_err_t web_start(void) cfg.lru_purge_enable = true; cfg.max_open_sockets = 7; cfg.backlog_conn = 10; + cfg.open_fn = open_nodelay; esp_err_t err = httpd_start(&s_server, &cfg); if (err != ESP_OK) { ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err)); @@ -889,26 +1307,18 @@ esp_err_t web_start(void) add_uri(s_server, "/", HTTP_GET, index_get); add_uri(s_server, "/app.js", HTTP_GET, app_js_get); add_uri(s_server, "/style.css", HTTP_GET, style_css_get); - add_uri(s_server, "/api/status", HTTP_GET, status_get); - add_uri(s_server, "/api/pattern", HTTP_POST, pattern_post); - add_uri(s_server, "/api/wifi", HTTP_GET, wifi_get); - add_uri(s_server, "/api/wifi", HTTP_POST, wifi_post); - add_uri(s_server, "/api/wifi/scan", HTTP_GET, wifi_scan_get); - add_uri(s_server, "/api/network", HTTP_GET, network_get); - add_uri(s_server, "/api/network", HTTP_POST, network_post); - add_uri(s_server, "/api/ddp", HTTP_GET, ddp_get); - add_uri(s_server, "/api/hardware", HTTP_GET, hardware_get); - add_uri(s_server, "/api/hardware", HTTP_POST, hardware_post); - add_uri(s_server, "/api/presets", HTTP_GET, presets_get); - add_uri(s_server, "/api/presets", HTTP_POST, presets_post); - add_uri(s_server, "/api/presets/select", HTTP_POST, select_post); - add_uri(s_server, "/api/presets/delete", HTTP_POST, delete_post); - add_uri(s_server, "/api/presets/startup", HTTP_POST, startup_post); - add_uri(s_server, "/api/presets/defaults", HTTP_POST, presets_defaults_post); - add_uri(s_server, "/api/presets/order", HTTP_POST, presets_order_post); - add_uri(s_server, "/api/brightness", HTTP_POST, brightness_post); - add_uri(s_server, "/api/relay", HTTP_POST, relay_post); - add_uri(s_server, "/api/devices", HTTP_GET, devices_get); + for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) { + httpd_uri_t u = {}; + u.uri = s_api[i].path; + u.method = s_api[i].method; + u.handler = api_http_entry; + u.user_ctx = reinterpret_cast(s_api[i].fn); + httpd_register_uri_handler(s_server, &u); + } + static const httpd_uri_t ws_uri = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, + .user_ctx = NULL, .is_websocket = true, .handle_ws_control_frames = false, + .supported_subprotocol = NULL }; + httpd_register_uri_handler(s_server, &ws_uri); ota_register(s_server); ESP_LOGI(TAG, "Web UI on port 80"); return ESP_OK; diff --git a/main/ws_client.cpp b/main/ws_client.cpp new file mode 100644 index 0000000..38b1eee --- /dev/null +++ b/main/ws_client.cpp @@ -0,0 +1,173 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include "ws_client.h" + +#include +#include +#include + +#include "esp_log.h" +#include "esp_random.h" +#include "lwip/netdb.h" +#include "lwip/sockets.h" + +static const char *TAG = "ws_client"; +#define WS_TIMEOUT_MS 2000 + +// Read until the buffer holds the end of the handshake reply. Returns the bytes read, or -1. +static int read_handshake(int fd, char *buf, size_t cap) +{ + size_t got = 0; + while (got < cap - 1) { + int r = recv(fd, buf + got, cap - 1 - got, 0); + if (r <= 0) { + return -1; + } + got += r; + buf[got] = '\0'; + if (strstr(buf, "\r\n\r\n")) { + return (int)got; + } + } + return -1; +} + +int ws_client_connect(const char *host, const char *path) +{ + struct addrinfo hints = {}; + struct addrinfo *res = NULL; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo(host, "80", &hints, &res) != 0 || !res) { + ESP_LOGW(TAG, "cannot resolve %s", host); + return -1; + } + int fd = socket(res->ai_family, res->ai_socktype, 0); + if (fd < 0) { + freeaddrinfo(res); + return -1; + } + struct timeval tv = { .tv_sec = WS_TIMEOUT_MS / 1000, .tv_usec = (WS_TIMEOUT_MS % 1000) * 1000 }; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + int one = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); // one frame, one segment + if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) { + freeaddrinfo(res); + close(fd); + return -1; + } + freeaddrinfo(res); + + char req[256]; + int n = snprintf(req, sizeof(req), + "GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n", + path, host); + if (n <= 0 || send(fd, req, n, 0) != n) { + close(fd); + return -1; + } + char reply[256]; + if (read_handshake(fd, reply, sizeof(reply)) < 0 || strncmp(reply, "HTTP/1.1 101", 12) != 0) { + ESP_LOGW(TAG, "handshake with %s failed", host); + close(fd); + return -1; + } + return fd; +} + +// Client frames are masked (RFC 6455). The mask only has to vary, not be secret. +esp_err_t ws_client_send_text(int fd, const char *data, size_t len) +{ + if (len > 2048) { + return ESP_ERR_INVALID_SIZE; + } + size_t hdr = len < 126 ? 2 : 4; // 2-byte or 16-bit length + size_t total = hdr + 4 + len; + uint8_t *frame = (uint8_t *)malloc(total); + if (!frame) { + return ESP_ERR_NO_MEM; + } + uint8_t mask[4]; + esp_fill_random(mask, sizeof(mask)); + frame[0] = 0x81; // FIN, text + if (len < 126) { + frame[1] = 0x80 | (uint8_t)len; + } else { + frame[1] = 0x80 | 126; + frame[2] = (uint8_t)(len >> 8); + frame[3] = (uint8_t)len; + } + memcpy(&frame[hdr], mask, 4); + for (size_t i = 0; i < len; i++) { + frame[hdr + 4 + i] = (uint8_t)data[i] ^ mask[i & 3]; + } + esp_err_t err = send(fd, frame, total, 0) == (ssize_t)total ? ESP_OK : ESP_FAIL; + free(frame); + return err; +} + +// Read exactly n bytes +static bool read_n(int fd, uint8_t *dst, size_t n) +{ + size_t got = 0; + while (got < n) { + int r = recv(fd, dst + got, n - got, 0); + if (r <= 0) { + return false; + } + got += r; + } + return true; +} + +// Server frames are not masked. Only text frames are returned; other opcodes are skipped. +int ws_client_recv_text(int fd, char *buf, size_t cap) +{ + for (;;) { + uint8_t h[2]; + if (!read_n(fd, h, 2)) { + return -1; + } + size_t len = h[1] & 0x7F; + if (len == 126) { + uint8_t ext[2]; + if (!read_n(fd, ext, 2)) { + return -1; + } + len = (ext[0] << 8) | ext[1]; + } else if (len == 127) { + return -1; // larger than this client accepts + } + bool masked = (h[1] & 0x80) != 0; + uint8_t mask[4] = {}; + if (masked && !read_n(fd, mask, 4)) { + return -1; + } + if (len >= cap) { + return -1; + } + if (!read_n(fd, (uint8_t *)buf, len)) { + return -1; + } + for (size_t i = 0; masked && i < len; i++) { + buf[i] ^= mask[i & 3]; + } + if ((h[0] & 0x0F) == 0x1) { // text + buf[len] = '\0'; + return (int)len; + } + if ((h[0] & 0x0F) == 0x8) { // close + return -1; + } + } +} + +void ws_client_close(int fd) +{ + if (fd >= 0) { + close(fd); + } +} diff --git a/main/ws_client.h b/main/ws_client.h new file mode 100644 index 0000000..d080fa4 --- /dev/null +++ b/main/ws_client.h @@ -0,0 +1,22 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Minimal WebSocket client for talking to another driver. One connection is kept open per peer. + */ +#pragma once + +#include + +#include "esp_err.h" + +/** @brief Open (or reuse) a WebSocket to host:/ws. Returns the socket, or -1. */ +int ws_client_connect(const char *host, const char *path); + +/** @brief Send one text frame. */ +esp_err_t ws_client_send_text(int fd, const char *data, size_t len); + +/** @brief Receive one text frame into buf (NUL-terminated). Returns the length, or -1 on error. */ +int ws_client_recv_text(int fd, char *buf, size_t cap); + +/** @brief Close a socket from ws_client_connect. */ +void ws_client_close(int fd); diff --git a/managed_components/espressif__cjson/.component_hash b/managed_components/espressif__cjson/.component_hash new file mode 100644 index 0000000..974a7f1 --- /dev/null +++ b/managed_components/espressif__cjson/.component_hash @@ -0,0 +1 @@ +e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469 \ No newline at end of file diff --git a/managed_components/espressif__cjson/CHECKSUMS.json b/managed_components/espressif__cjson/CHECKSUMS.json new file mode 100644 index 0000000..d649eb8 --- /dev/null +++ b/managed_components/espressif__cjson/CHECKSUMS.json @@ -0,0 +1 @@ +{"version":"1.0","algorithm":"sha256","created_at":"2026-03-30T15:24:33.754457+00:00","files":[{"path":"CMakeLists.txt","size":299,"hash":"ed52bedef7b81ab94f0229eb17680e1c90de6776110e2d24a1ff12fd4b4a4d8d"},{"path":"Kconfig","size":763,"hash":"b6b494bf761d2a358abc941fcba2b9a2bd961ccf4dd6a5cedaf7cde19830003c"},{"path":"LICENSE","size":1084,"hash":"a36dda207c36db5818729c54e7ad4e8b0c6fba847491ba64f372c1a2037b6d5c"},{"path":"README.md","size":27630,"hash":"a3947fea0e24b4069f93a5379e2fb3103b48c339c1dd4368f714469fa8da4904"},{"path":"idf_component.yml","size":331,"hash":"8cf02081bf037b8d0b89e613f5803d463d4a93d2eab892c4bbe20020cdbd4396"},{"path":"sbom_cJSON.yml","size":313,"hash":"a47df162c2671b1f4bc79a84875ba5e2cc2021c5cb73a60150951c1c16265e3d"},{"path":"cJSON/.editorconfig","size":428,"hash":"b2b78dbe3b29690f9ac605b0c6d998ca25e89d578198d3cba935cd66c94dede1"},{"path":"cJSON/.git","size":39,"hash":"2af511596d328b1e545b079746663861fe439d64f4f7bac297cbd22dce46a4f4"},{"path":"cJSON/.gitattributes","size":340,"hash":"51901378d0408db37a541af075c3673f919feb8c50dc4fb077e31d086fcf3f3b"},{"path":"cJSON/.gitignore","size":171,"hash":"c894dad853994898d6328bfee88fb6e4a01ad15ec587c66d149841acdeb7716d"},{"path":"cJSON/.travis.yml","size":602,"hash":"5e0eb8ed93a5e590ce7e72a6fe26db8df20804e872ea253254f46dfe29ac5fe2"},{"path":"cJSON/CHANGELOG.md","size":25980,"hash":"adec9eeee3c855842a770e75f2b4538a3bb21cc998d832395fff361dbd21d316"},{"path":"cJSON/CMakeLists.txt","size":10205,"hash":"160c8e123cdc5fa89edbb3866eeaa17a7a40503985b26f8ffc6d3f92ab6c4763"},{"path":"cJSON/CONTRIBUTORS.md","size":4131,"hash":"48b3c704097b40d9ef908db883001041bafd051b4d2787957438f2a71f7fb63c"},{"path":"cJSON/LICENSE","size":1084,"hash":"a36dda207c36db5818729c54e7ad4e8b0c6fba847491ba64f372c1a2037b6d5c"},{"path":"cJSON/Makefile","size":4650,"hash":"410bdeb55e6b8ecd49a6d34f61ce53e2e7643136c8aebe148ba1baa28c505b94"},{"path":"cJSON/README.md","size":27630,"hash":"a3947fea0e24b4069f93a5379e2fb3103b48c339c1dd4368f714469fa8da4904"},{"path":"cJSON/SECURITY.md","size":713,"hash":"213c3a4c10fb81ba6b431ab259513c262023685191d6a6be2cca0b39ce6fd1e0"},{"path":"cJSON/appveyor.yml","size":2284,"hash":"48e9f4f585df68114d2213b6f9113d7d32ec3626689a90dfb63a2450d72b7509"},{"path":"cJSON/cJSON.c","size":80692,"hash":"607e756460fa0de37d20a7a9181f2de29c97bfb7ce5a0e6c2f548243836cd852"},{"path":"cJSON/cJSON.h","size":16394,"hash":"25b0145150d500498e4d209cec69c18c42cf818bffcc54690be3b895a2a16dee"},{"path":"cJSON/cJSON_Utils.c","size":40736,"hash":"bf3092696763a9a446c39365d7c35f23e5acfdca1bd1da33ef66c1161f9243e9"},{"path":"cJSON/cJSON_Utils.h","size":3938,"hash":"1050a7cce8ffe352c509e0c1faad505b9b8a09cac3a1c45c544447868e05f3b5"},{"path":"cJSON/test.c","size":7711,"hash":"9073e70d626d83f202768c3a486aa5496ac33277b7f265fdba200888fc93941e"},{"path":"cJSON/valgrind.supp","size":61,"hash":"5f721f7cff3acb7712af9836cdec19b7f352b851d73829b8e37e994e6f513ec1"},{"path":"cJSON/fuzzing/.gitignore","size":10,"hash":"95b6e450406b13395e5e449b105b785a42c1c67d439762d5ba1b8fbd8dad9419"},{"path":"cJSON/fuzzing/CMakeLists.txt","size":1169,"hash":"80a356c8ad968c1f88498d89e263a20f46765b8fb343f2b82c290e2fbf8f7065"},{"path":"cJSON/fuzzing/afl-prepare-linux.sh","size":153,"hash":"c86a6dfee8758becb7e44e184a429225f1e99ea705b28fcf37a24f7327a06170"},{"path":"cJSON/fuzzing/afl.c","size":4192,"hash":"179261ee7e9a55e1bd1609bbe9f1995f17e6a5e1611378abed85b4eddb1cdd31"},{"path":"cJSON/fuzzing/afl.sh","size":192,"hash":"9614b91989583e8fe2e1961b56b47e660ff053dfccb9b28ecf221320c207b3b5"},{"path":"cJSON/fuzzing/cjson_read_fuzzer.c","size":1695,"hash":"a8e9443438bfb323dcaed5af86dfc3fae7dfbc970a992b0af569a58e1b8c9376"},{"path":"cJSON/fuzzing/fuzz_main.c","size":992,"hash":"880426b8d17e75f41157f0b06d26716d99801b3f9578245183cd4bf718c8c882"},{"path":"cJSON/fuzzing/json.dict","size":914,"hash":"715638fc7ae17e2fad98c7f5db17e5834f134e9aa03fe7e89d6c9816646ff12e"},{"path":"cJSON/fuzzing/ossfuzz.sh","size":529,"hash":"a832e5c52839fa54637b052d3cfd9f63da8deb66f3ea6890af3adf4ff6557927"},{"path":"cJSON/library_config/cJSONConfig.cmake.in","size":802,"hash":"ce9b592eae998427aad7b506e4a7661db303ef038c524f2fcc7ba56319a26c65"},{"path":"cJSON/library_config/cJSONConfigVersion.cmake.in","size":379,"hash":"8a8e1a78f45a121db7732cd81800530b82fc5ace4cd410aa401ade6aa49315af"},{"path":"cJSON/library_config/libcjson.pc.in","size":304,"hash":"051388ae79065c08400dae18cfedf32abbaa34b6a4db9cf547d8db2ff5b04b9b"},{"path":"cJSON/library_config/libcjson_utils.pc.in","size":351,"hash":"9df4bd96583141c2b735b3215d0fb66c0d28364b39278de41ef676c0b27beb68"},{"path":"cJSON/library_config/uninstall.cmake","size":726,"hash":"3b0cf68d1babfb6a72ea673ef24276795c062432c785a0de77fb69ff11145124"},{"path":"cJSON/tests/CMakeLists.txt","size":4530,"hash":"4f98fd9f350148ca49e7f0c3a41875288ed67ae63694add225b01144fd40856d"},{"path":"cJSON/tests/cjson_add.c","size":12774,"hash":"4b9bf117c07e2be9d1ce5db32a63f57e479369516f97a91b5f4d6c8aaccff30e"},{"path":"cJSON/tests/common.h","size":4166,"hash":"c1f106726a5865965aad9597687df8c7ba43b587a495fa5e17c23231a99ddaa2"},{"path":"cJSON/tests/compare_tests.c","size":8588,"hash":"c7d38712a8346763b40e836d9a1c6519e3e2c3ee1510c7493597308594ca1198"},{"path":"cJSON/tests/json_patch_tests.c","size":6776,"hash":"348555d7a3ff837e43f47688e25a542cca1c551b0e557229293d15737aa49d63"},{"path":"cJSON/tests/minify_tests.c","size":5456,"hash":"23b0f6af10660fc7b7a9da1e8d7083644513525263f56ff8f43fcd2e045ba7e7"},{"path":"cJSON/tests/misc_tests.c","size":32086,"hash":"077a0704f3118311597c58c14a5ca323a369e07f0e03d78dfa8d911c32fab8ca"},{"path":"cJSON/tests/misc_utils_tests.c","size":3386,"hash":"0a3874130b4f320a3a0f02f1045df5407d0df0633e355bbf30bd718915920e31"},{"path":"cJSON/tests/old_utils_tests.c","size":7766,"hash":"2df8a031f08b2ed95c92bf5850022cac89fdc9c2e24fb47d10db57a202343d1f"},{"path":"cJSON/tests/parse_array.c","size":5068,"hash":"d9ff0f6b59708f341e3ff1ea8d3915c4e4104c70021e306f9e4e1c2afc8cceee"},{"path":"cJSON/tests/parse_examples.c","size":8699,"hash":"e1d1e69d69377eb01050cc85f4f10218cd7c0cef9e63418c21c39abced5dc373"},{"path":"cJSON/tests/parse_hex4.c","size":3434,"hash":"308710a6a164cce203e950d64c0acda8a20cc21f0ee19572d7d5c404c73e65ad"},{"path":"cJSON/tests/parse_number.c","size":4673,"hash":"dc55d81687735f7d2f3986bf90f4d3ef9f183d73f79ac178e71b123c56d13de2"},{"path":"cJSON/tests/parse_object.c","size":5568,"hash":"87a58dd9a3505e13cee37aaedf9ef6e2f458979f201f7d2d596fdf31bcc2d6ea"},{"path":"cJSON/tests/parse_string.c","size":4679,"hash":"d665ea70b7cb94eb2e370268355bbdb9ab19a7d7e8a4f66c761d36dd134773d1"},{"path":"cJSON/tests/parse_value.c","size":3302,"hash":"7c675a2840915d5bda6cb70bf8ea793ae2969c83a6450c21acaa45470d854c8d"},{"path":"cJSON/tests/parse_with_opts.c","size":4168,"hash":"a38e8a2a6986c886c3d44ba2f6d0f549fc00c00c294dd35078afdf5bdb8a4f36"},{"path":"cJSON/tests/print_array.c","size":3818,"hash":"2de8a850c1a9df40e105d49cd724ae0f527a8e6dedd54e5c4faad76b2f73ed9f"},{"path":"cJSON/tests/print_number.c","size":4447,"hash":"e548a3d5010c5325a451148af05b7ab7b663800e06914cd0547b0e6b1308cd38"},{"path":"cJSON/tests/print_object.c","size":4223,"hash":"af397c6fc869ebdc68a913b64fff53219a765a5788db13fa2908602742b16028"},{"path":"cJSON/tests/print_string.c","size":2822,"hash":"0f495b80145aca503ffcdc5ff0d18eff87cc33a06a7e398ce251c56407bfb7cf"},{"path":"cJSON/tests/print_value.c","size":3189,"hash":"40a7db740adc05df72d9e98d23147b8de3d9736a237d11168b651eb09b7a177d"},{"path":"cJSON/tests/readme_examples.c","size":6854,"hash":"506fa8132eff2c50a4a80087201aa4c67550f72d3b253ef2defa9087c500ed90"},{"path":"cJSON/tests/unity_setup.c","size":121,"hash":"5f00ce6ea0455d5b898b5da3abc483e616f7d1f37fd2f8cc0ca84b09ff23e067"},{"path":"cJSON/tests/inputs/test1","size":583,"hash":"b03c70f84fecd61f88de1d480a6b151157db38d1459d79fcb08046189946e6ae"},{"path":"cJSON/tests/inputs/test1.expected","size":474,"hash":"01cc16b9a569a5b5a5fa3b42703d95fb90c3adf152283e6d102ea216b62007f0"},{"path":"cJSON/tests/inputs/test10","size":79,"hash":"8cb1309e2c70a9737a690ab6d0da386db20150e50eaf1aedb3c822f2cdf8b887"},{"path":"cJSON/tests/inputs/test10.expected","size":78,"hash":"18b7b68090fa1ba3858cbf8d54128b0ca7d4402bc9b457c6734ec5e40aab59bd"},{"path":"cJSON/tests/inputs/test11","size":149,"hash":"323abb1689f7030df78c587b4d4622341fc155ac8b4fe3c477568eb653ec624e"},{"path":"cJSON/tests/inputs/test11.expected","size":147,"hash":"d24e688e245600ebe2d69ee831993eb8fd1e80857f038f6166bc1721e06c360d"},{"path":"cJSON/tests/inputs/test2","size":242,"hash":"bcf0193107b78a8835fe4bbbee161caa6d803d709cff043f2a1191a49d117c7b"},{"path":"cJSON/tests/inputs/test2.expected","size":268,"hash":"5640449d7438834c6771f2ab5b10773241877b059578a28c38bcce1903ddab87"},{"path":"cJSON/tests/inputs/test3","size":603,"hash":"06fc27d33b348407fe50b34a4c4397e33cb7acae094cbeb232daad07e7715f60"},{"path":"cJSON/tests/inputs/test3.expected","size":505,"hash":"d4495f02b4c3879f5707c681f5e62bfbc01eae07b464533c33aa70e9d5190886"},{"path":"cJSON/tests/inputs/test4","size":3464,"hash":"a01e18f77d08bdef9a872d9c3d2b5f58b86c3ed6db1f9bf68db969357b0743e4"},{"path":"cJSON/tests/inputs/test4.expected","size":3285,"hash":"21c53d49a9c3c5070d3b98c2c9525ec52cdefb42a8858add687c0f2b50458c48"},{"path":"cJSON/tests/inputs/test5","size":873,"hash":"c13f3e1957ddb0aaec77173a0aaae9838f910f8d0b4d6cd0bbdb37e8b49f5bd9"},{"path":"cJSON/tests/inputs/test5.expected","size":900,"hash":"7cdd2bf7e176bdf18db4b0edd61343c55292f427e1b34be2081747d9aee4ca11"},{"path":"cJSON/tests/inputs/test6","size":484,"hash":"bbb2d49cf5e36d7f09e3e23843022c61f8226afbb8b33ec859668ab57173e206"},{"path":"cJSON/tests/inputs/test7","size":399,"hash":"800ee3dbe3b5ac0eb3c84d3c408594837d25cb017cfe461f11afe6b5d895466d"},{"path":"cJSON/tests/inputs/test7.expected","size":347,"hash":"58a05d06ab633aad6c15c63f5054f0da76907dba2223a7c5914fcaa7fe9982e5"},{"path":"cJSON/tests/inputs/test8","size":247,"hash":"8f12cafffed5858bcf1db7add4f96e7ddf302ce0920b4262f925720dfe756aea"},{"path":"cJSON/tests/inputs/test8.expected","size":228,"hash":"cf91affe773c43b3301e666b01bbcf96b7cfe24e607a5cdd5807454e25c19bb0"},{"path":"cJSON/tests/inputs/test9","size":50,"hash":"99956a0476bef0fa482b71764091dc9ad46851f91ddac1e62e9b69abffb3135d"},{"path":"cJSON/tests/inputs/test9.expected","size":34,"hash":"dc09889048190fe3ed20d5d92186337e5fd3ad34cd000dc711fd17c102fb1b8f"},{"path":"cJSON/tests/json-patch-tests/.editorconfig","size":183,"hash":"1e48756cfcaf64d49bafb685261bb990308219e32d1c835653bfd93b7c627f7c"},{"path":"cJSON/tests/json-patch-tests/.gitignore","size":34,"hash":"26d17285e59ae0df0e84ccc5ac8a8e29252afcae79c8ee449e231d8072ea4d1e"},{"path":"cJSON/tests/json-patch-tests/.npmignore","size":25,"hash":"67ee5983a254b254a70464d1700d3e9c5bfc182f84d326129c7826cc7cd5c366"},{"path":"cJSON/tests/json-patch-tests/README.md","size":2306,"hash":"f995d6a6e1babf653444b40783b21420a3840962889cf1c1024a70549e603828"},{"path":"cJSON/tests/json-patch-tests/cjson-utils-tests.json","size":2659,"hash":"7903cc19a66ba441cd8808d09490c58749132f5d3fefcca8633c7b180d270059"},{"path":"cJSON/tests/json-patch-tests/package.json","size":393,"hash":"7c808769bf7b0d72976d21273afb43ed44df71dd3e3c31b1cd33430b4ff2f493"},{"path":"cJSON/tests/json-patch-tests/spec_tests.json","size":4031,"hash":"a26b050292207033e5cccc5d6102b7bd6f8add7db0d0680e5d46a7ecf40a8c7b"},{"path":"cJSON/tests/json-patch-tests/tests.json","size":17205,"hash":"c7c42a57d29a8029d60160eba8efa6daec560912dca07772d0e86e64589117b0"},{"path":"cJSON/tests/unity/.gitattributes","size":573,"hash":"84a5202c7923a8a8108cd15637834c1f35bf76a4f54865074e15d6c5d695b663"},{"path":"cJSON/tests/unity/.gitignore","size":212,"hash":"85c167144d06769a736731ba29a89cb7ecb15283455fad681387e773b817ee15"},{"path":"cJSON/tests/unity/.travis.yml","size":852,"hash":"155c12a48818cbc16bb7afc3b67f70ecbb32c42a7fd1bcac3c7663e189b23071"},{"path":"cJSON/tests/unity/README.md","size":7806,"hash":"c8922237978b31ecfeb41ea90c93946310cccd60068d1c8772726266fc3e0a2f"},{"path":"cJSON/tests/unity/auto/colour_prompt.rb","size":3462,"hash":"b25f12cab00233838cc1ec2478b78868d8cb380aff93479db855cfc73a6a5d6f"},{"path":"cJSON/tests/unity/auto/colour_reporter.rb","size":1178,"hash":"825b4b4bfc28449c6b24c804d9ffc2d1f1f5855a6655f6101debbeb69d461e64"},{"path":"cJSON/tests/unity/auto/generate_config.yml","size":1273,"hash":"85c5702a168e366148e8ec89df416eae888278a526c79459162c0f37641a02fe"},{"path":"cJSON/tests/unity/auto/generate_module.rb","size":11086,"hash":"40a016ee8a8c53f1bbaa8b47026318e14fec1e3742ef55e0eb1b81c11250c4b1"},{"path":"cJSON/tests/unity/auto/generate_test_runner.rb","size":18170,"hash":"ec7f43dddfc24648e34871f5babefe07f4b427e8ebd2abf16d51dbaa179e1f54"},{"path":"cJSON/tests/unity/auto/parse_output.rb","size":6995,"hash":"9af7bb80491c7d01998fbd6b17ef58fd212dbba89d6d714b1f668d1f879743d4"},{"path":"cJSON/tests/unity/auto/stylize_as_junit.rb","size":7698,"hash":"8350efa8dac6ea49c460dd0125c979bd011b992528571e640ae8d03fce703a2b"},{"path":"cJSON/tests/unity/auto/test_file_filter.rb","size":766,"hash":"3797fd7cfcc40c643f0b66555e751fbba36ba0c7517c01e3537ffc659af4ea37"},{"path":"cJSON/tests/unity/auto/type_sanitizer.rb","size":201,"hash":"ecc5677ac9820f343aca50893463602fca940c24daf07a4784b4e9e0801c3f4b"},{"path":"cJSON/tests/unity/auto/unity_test_summary.py","size":5173,"hash":"8912c5cacee70c5be95e35ff4c48746e5ecdc31819ff528f076f6fd64a32dd69"},{"path":"cJSON/tests/unity/auto/unity_test_summary.rb","size":4143,"hash":"ba1e76115ebc4d4221a919c682fb3faae6d0e375a1d7910c199f2abff9caa736"},{"path":"cJSON/tests/unity/auto/unity_to_junit.py","size":5939,"hash":"0743f26b5ae67af204981293337f9cc9a8cb46c90aaa3f46f31fd9658ab65990"},{"path":"cJSON/tests/unity/docs/ThrowTheSwitchCodingStandard.md","size":8092,"hash":"a1838b8c9e20ac3c15bf96742b716b6621c0607c9273ae0f92a6769e3aa45f41"},{"path":"cJSON/tests/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf","size":144467,"hash":"251fcb21ea66444941a34f8b932a3baf0c47aed4c7827215e027006f06013bea"},{"path":"cJSON/tests/unity/docs/UnityAssertionsReference.md","size":28588,"hash":"2d72b94d517b22ff743245145ed8bb0ab0a6b72c37a5314810d7ff3cabb7af37"},{"path":"cJSON/tests/unity/docs/UnityConfigurationGuide.md","size":18107,"hash":"7f014f736a317d36d807bc4bded65d89919e1a9a88fa39cdbfd93202b88c43b1"},{"path":"cJSON/tests/unity/docs/UnityGettingStartedGuide.md","size":8248,"hash":"f1845c8483f193271e13e309cb644d8fa20c2fca30f5a15cbcd2778379178dbe"},{"path":"cJSON/tests/unity/docs/UnityHelperScriptsGuide.md","size":9332,"hash":"57136398257546b59443eaec9469166e17664a3df68112adbc3765422b90c783"},{"path":"cJSON/tests/unity/docs/license.txt","size":1123,"hash":"3ed9b51da86f52c729c96cc99fdde6444b2297c788a9cf4ad1d3649dc34c4985"},{"path":"cJSON/tests/unity/examples/unity_config.h","size":12322,"hash":"c3d7d8f48c9dfb38a4cbaabc2d30a0a5335d2bdd8b454fd70326876e90133299"},{"path":"cJSON/tests/unity/release/build.info","size":5,"hash":"d068d6cff7b4f86fea550f0c3a9d37b227c5c18c20da61d2f73553906484999f"},{"path":"cJSON/tests/unity/release/version.info","size":7,"hash":"86328f4d3186c9624da589a8ee8238f55e9518d4c5d8edd5f3a99a944a41aec6"},{"path":"cJSON/tests/unity/src/unity.c","size":49463,"hash":"b9dc88ba266f4140ade6cb8b6b74869d9d0927fdc1bf791ef51ae306d4c8f965"},{"path":"cJSON/tests/unity/src/unity.h","size":66485,"hash":"2d356dcffe0f8d887ece0ad8d5cd0d388aeef5482800a7b8fea6d415be8bcf1f"},{"path":"cJSON/tests/unity/src/unity_internals.h","size":69552,"hash":"874c2af0bcebead08d0f609f77e2306a735ba55205b7776d937120cb616d4304"},{"path":"cJSON/tests/unity/test/.rubocop.yml","size":1386,"hash":"8d80c9a0ad12c1b02ef92151523a27e8c7219de7303899f134e69f327ecc4583"},{"path":"cJSON/tests/unity/test/Makefile","size":2665,"hash":"6eb94e8d682068fd80d7155c83486cdebabd2ff0ca218d5c2ca643f9e8c61e2b"},{"path":"cJSON/tests/unity/test/rakefile","size":3095,"hash":"bcf952c92696d59e0a5b01f1e44f54f798bb16d5e6364714a2c5bdea0a51357e"},{"path":"cJSON/tests/unity/test/rakefile_helper.rb","size":8988,"hash":"5423a66a42384ddce1b9fb9cfa690f8fea3e3e062ae3d66910356d011147646a"},{"path":"cJSON/tests/unity/test/expectdata/testsample_cmd.c","size":1427,"hash":"832ec9c8c30fd374adea6620dd38c19c689047bdad0513984066e525eefc0723"},{"path":"cJSON/tests/unity/test/expectdata/testsample_def.c","size":1271,"hash":"246d3d9bc73ccef28f7a70b8748d95cd31eb85b9874e6972d30be1f74000fb8c"},{"path":"cJSON/tests/unity/test/expectdata/testsample_head1.c","size":1242,"hash":"ed31f2c63e4bb7ba015a5388429b34287ecefa098551e55ae5864b883c3cdad4"},{"path":"cJSON/tests/unity/test/expectdata/testsample_head1.h","size":333,"hash":"fc279a298e45f70a559d05132ae888973c8f5aad913c0b2d6d8425ccbde5c998"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_cmd.c","size":1649,"hash":"b826f44458088555058b6c3b9c7ef15c2a5528c8efe01034d0f1debee06a739e"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_def.c","size":1493,"hash":"1016f1162a3ea3be49dffd824e529493d2845860d1139cb44cc32f0fe0a0701f"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_head1.c","size":1489,"hash":"cb7b253cefa315d7b4edaa386bffb63a728f3b33c869bf55ecfcd53d1e47eaaf"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_head1.h","size":267,"hash":"9cb779d98b40e5dfcf70db57f7d3deae6310cac80547140c972ecde585f56c18"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_new1.c","size":1831,"hash":"4e5d73972dce4276dc688016eeb310e93ef96ea7beee0e6839092f0459798856"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_new2.c","size":1705,"hash":"74418cfefe544ac366a043972648c31742b2a4652155507c93a1a2a38471a5eb"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_param.c","size":1591,"hash":"6a8edda1c9b5a56d38e705d2d0341232ca9a55f1fb7383171475cb972c9b6c18"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_run1.c","size":1831,"hash":"4e5d73972dce4276dc688016eeb310e93ef96ea7beee0e6839092f0459798856"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_run2.c","size":1705,"hash":"74418cfefe544ac366a043972648c31742b2a4652155507c93a1a2a38471a5eb"},{"path":"cJSON/tests/unity/test/expectdata/testsample_mock_yaml.c","size":1798,"hash":"763d37bc5a5edc7566bf6625dd38878aed8cc94a5cec8f6e23aee16e30bdaad6"},{"path":"cJSON/tests/unity/test/expectdata/testsample_new1.c","size":1532,"hash":"983abee21894ba9fb5d667a69b046558867f9f16eaf546d259671f54dd4be626"},{"path":"cJSON/tests/unity/test/expectdata/testsample_new2.c","size":1483,"hash":"9726bdaec7a5c8e99b4e6bbfc41b91c8687665bbafdb617be4514eadc30b023c"},{"path":"cJSON/tests/unity/test/expectdata/testsample_param.c","size":1405,"hash":"7ab6834f8376908625b9999a4c5dad32ad65c8f3fd852e78b6d9c3bc871fc639"},{"path":"cJSON/tests/unity/test/expectdata/testsample_run1.c","size":1532,"hash":"983abee21894ba9fb5d667a69b046558867f9f16eaf546d259671f54dd4be626"},{"path":"cJSON/tests/unity/test/expectdata/testsample_run2.c","size":1483,"hash":"9726bdaec7a5c8e99b4e6bbfc41b91c8687665bbafdb617be4514eadc30b023c"},{"path":"cJSON/tests/unity/test/expectdata/testsample_yaml.c","size":1576,"hash":"17714f87e28c7723608fdc832189965482404e3540e3f3ec55afa7f07054e0a7"},{"path":"cJSON/tests/unity/test/spec/generate_module_existing_file_spec.rb","size":4386,"hash":"41d0b6bf8255f97e4fbf6c4f5fb2dcc61d846d2ddaf2cad763c1f500b8a68727"},{"path":"cJSON/tests/unity/test/targets/clang_file.yml","size":1552,"hash":"afbb70db8cc433aca8e6ea3d04d2f5142cc8bd1a8f6e421006038c9601222d32"},{"path":"cJSON/tests/unity/test/targets/clang_strict.yml","size":1552,"hash":"336cc5344beccd0c3a6c83227b764c8945193b464600ba56ade14c3c44c98b27"},{"path":"cJSON/tests/unity/test/targets/gcc_32.yml","size":917,"hash":"734debdb4392b83942cdccfb31ca724a43b923617a8b45d86bf6a1fefa86a7e6"},{"path":"cJSON/tests/unity/test/targets/gcc_64.yml","size":942,"hash":"530851623a24956399add9f0c0fe18719eb6dc428c1bec03ae6b255a9d0ae972"},{"path":"cJSON/tests/unity/test/targets/gcc_auto_limits.yml","size":856,"hash":"fbd96dc8a94c4de70dae87ff378312b3ee07cb8219d6290af17d36e3b34d0f6e"},{"path":"cJSON/tests/unity/test/targets/gcc_auto_stdint.yml","size":1139,"hash":"c9ec9f61987603d059d4509f4befe0744f5fa99a137d95be359ddd2c71443281"},{"path":"cJSON/tests/unity/test/targets/gcc_manual_math.yml","size":854,"hash":"3bd8b0d4eb9fa693f4cf74fdaf61e31183b85351c4e957577bc8497cdc8f15a0"},{"path":"cJSON/tests/unity/test/targets/hitech_picc18.yml","size":2960,"hash":"7b2a4ea56f3125fd75bb7d8e9baf1f26706b206f98c6f88e4d4b4091361fc546"},{"path":"cJSON/tests/unity/test/targets/iar_arm_v4.yml","size":2060,"hash":"3df93ad02fd4e1cc17d28a63f824881eee4f73e1db54e43ff36909dd2f5eabaf"},{"path":"cJSON/tests/unity/test/targets/iar_arm_v5.yml","size":1886,"hash":"bb6f961bbf3cf2c4651a33bf415818726b4d609c05cb9fdeabe6dc7a94d47e6b"},{"path":"cJSON/tests/unity/test/targets/iar_arm_v5_3.yml","size":1886,"hash":"bb6f961bbf3cf2c4651a33bf415818726b4d609c05cb9fdeabe6dc7a94d47e6b"},{"path":"cJSON/tests/unity/test/targets/iar_armcortex_LM3S9B92_v5_4.yml","size":2274,"hash":"8835f98e84e75b920fb9e27c0ebcc9c11f14bff768b382441099a01cbf7a129d"},{"path":"cJSON/tests/unity/test/targets/iar_cortexm3_v5.yml","size":1898,"hash":"70ba518b050162526cf5cfd3cdc90a00a6aad0d0ef65558612d384c855513d52"},{"path":"cJSON/tests/unity/test/targets/iar_msp430.yml","size":2244,"hash":"527ef25ba8d5056a8b44fce38302895a1a8ed342331edeed69db067b831c8e7b"},{"path":"cJSON/tests/unity/test/targets/iar_sh2a_v6.yml","size":2052,"hash":"b99162afd271d76014220cabda53ff3951aae6595b198520eba36ef095e57746"},{"path":"cJSON/tests/unity/test/testdata/CException.h","size":221,"hash":"3d791048e28a3a83580dc5cb7a03d918323247128bde97b055e1037924a4a3a0"},{"path":"cJSON/tests/unity/test/testdata/Defs.h","size":96,"hash":"309f8524e59399b7e9e5f2a02ab7a1a4e21d6f808bdb05730ad41366412b72ea"},{"path":"cJSON/tests/unity/test/testdata/cmock.h","size":452,"hash":"f600e74488bfc56862df2daedce1a3525eaad43ed72c6706817f6629b180a1ec"},{"path":"cJSON/tests/unity/test/testdata/mockMock.h","size":291,"hash":"f198c43bad6e541c08b5e32c204d894be499ff005032c3ffa25e7ed7ba176001"},{"path":"cJSON/tests/unity/test/testdata/testRunnerGenerator.c","size":5137,"hash":"019b92525eaf472f608028dd6a68d3921ea39032d7973a3aabfaf0776f7bac64"},{"path":"cJSON/tests/unity/test/testdata/testRunnerGeneratorSmall.c","size":1356,"hash":"84391f905960812afd4640f92aae9c34c4e391f3a944d8bc93cc6db14f89d952"},{"path":"cJSON/tests/unity/test/testdata/testRunnerGeneratorWithMocks.c","size":5844,"hash":"5771f02d8a44f71d3abebe2509e83c3d53e228e16b3791a1621e440994670c8a"},{"path":"cJSON/tests/unity/test/tests/test_generate_test_runner.rb","size":47428,"hash":"bbcfbcd8c45d6c8dcd05fc2400914805d965e378297d536a63276cb2760deda3"},{"path":"cJSON/tests/unity/test/tests/testparameterized.c","size":3442,"hash":"baed74f82c4b452063bb0b33ad488acbb6df0cf2362a5209bc53a396b946bcea"},{"path":"cJSON/tests/unity/test/tests/testunity.c","size":123592,"hash":"89c5ac06926074a73ff5fcb89bddd923d9040aa3e5cd3108d733315714c9c71b"},{"path":"cJSON/tests/unity/extras/eclipse/error_parsers.txt","size":1139,"hash":"72204789cf143e044ed448e826a7d1eb1cc9c74b580e36902fbaec98bca02582"},{"path":"cJSON/tests/unity/extras/fixture/rakefile.rb","size":1109,"hash":"52800d045e67262e1bd53f9867417b6fc1f56eb7cf446bcbaa20dba0c41f10a8"},{"path":"cJSON/tests/unity/extras/fixture/rakefile_helper.rb","size":6621,"hash":"3e9ccb2a4370fbc68d1228a115e5a6a5d6ab689db1805266206a261cdc04f58c"},{"path":"cJSON/tests/unity/extras/fixture/readme.txt","size":515,"hash":"5692862a5fbc1910978be7ea4751899bafb6b913ce34cffa5517c0eba1fe40e3"},{"path":"cJSON/tests/unity/extras/fixture/src/unity_fixture.c","size":10386,"hash":"cf55816ca47f37c29ee446468ca076c96860ca506d47c6832e81cb1d82b48c4c"},{"path":"cJSON/tests/unity/extras/fixture/src/unity_fixture.h","size":3348,"hash":"d99045365d5fc89535b283b9608631883bf5aa35d41665889f25c9bfcb925b29"},{"path":"cJSON/tests/unity/extras/fixture/src/unity_fixture_internals.h","size":1518,"hash":"fbdafda4dd395e08ff7503180022c074947d622f4e83256256297ce05c154e73"},{"path":"cJSON/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h","size":1892,"hash":"446d4a58dd88ce0bceba6e095ac4f26a4c55898e67265d688450fa3aacc7741c"},{"path":"cJSON/tests/unity/extras/fixture/test/Makefile","size":2314,"hash":"665bba3afaf6ebd289432b039e40b03a24c7fee6f4dde8f82b1a7468fe82a7e7"},{"path":"cJSON/tests/unity/extras/fixture/test/template_fixture_tests.c","size":722,"hash":"3ca4c500397fc3dd7370b419e7d4f7abb3a8b05deacaf72a4e2ccb396669003a"},{"path":"cJSON/tests/unity/extras/fixture/test/unity_fixture_Test.c","size":14403,"hash":"d8d631a1e192b25ae24ea6ecf3bb53e86eff8f0615a1ad7095106d847b847d18"},{"path":"cJSON/tests/unity/extras/fixture/test/unity_fixture_TestRunner.c","size":2593,"hash":"e739cdf119f943d482fe99b6acec671aa88a78b9cb38bb2b459d946ab962a200"},{"path":"cJSON/tests/unity/extras/fixture/test/unity_output_Spy.c","size":1206,"hash":"efa0dfae695ba004c67a120c0b0e3d6f93f72cf7a992662bd4ab15d725c3ff45"},{"path":"cJSON/tests/unity/extras/fixture/test/unity_output_Spy.h","size":628,"hash":"b5adfe4f07d3c1c4b7cb0178344ccf608c60a08713d768c8b3e073c6f030dde5"},{"path":"cJSON/tests/unity/extras/fixture/test/main/AllTests.c","size":653,"hash":"1ec0a0e004f8a70d03dc76e28f38f09519bbaf7306d48d17d5bf0573d34c87c0"},{"path":"cJSON/tests/unity/examples/example_1/makefile","size":2237,"hash":"367e10ef968648ec5c531f144bb0ee257a619091a76fcc17516c220bf20539e6"},{"path":"cJSON/tests/unity/examples/example_1/readme.txt","size":139,"hash":"4d72d51f1a385cd4aeb594e4485ca2439d5b86247523cd2d2b89acc2173d8a24"},{"path":"cJSON/tests/unity/examples/example_2/makefile","size":1768,"hash":"9c925a4b80f11ce51cb65fef51f8e1279113dc67838c71b5bc8b0c31009e65bb"},{"path":"cJSON/tests/unity/examples/example_2/readme.txt","size":175,"hash":"a03bf4ac2d294a037189b42f7bf8fdff0bf50524857e3f8933eba76085f22f04"},{"path":"cJSON/tests/unity/examples/example_3/rakefile.rb","size":884,"hash":"7a1113adb71787b2ae7cd29fe9a5c7b50dec87c041aa6500aaa836ae2c4a0d4f"},{"path":"cJSON/tests/unity/examples/example_3/rakefile_helper.rb","size":8367,"hash":"a545c40149bdaeb2592322771b5e180bc103d67c783b23c74dcb8b0fb619a5aa"},{"path":"cJSON/tests/unity/examples/example_3/readme.txt","size":696,"hash":"2af5e731fb1db0ddf5c739f0b08fb2724e4acc7efb7ee0a02fe474a3e69d284a"},{"path":"cJSON/tests/unity/examples/example_3/target_gcc_32.yml","size":852,"hash":"d7ab74bbff3a1b2a50432636ffbd4d7d7e87df592bf5a5754de56275f44ca521"},{"path":"cJSON/tests/unity/examples/example_3/helper/UnityHelper.c","size":405,"hash":"091c2466d25deffd8958332ad03d393ca1ec1b1f6150c16626d57d5901eb1b21"},{"path":"cJSON/tests/unity/examples/example_3/helper/UnityHelper.h","size":483,"hash":"a95bb6d3704c51637bb0855787236b41229e3836601ba97e88768f95779f3d4d"},{"path":"cJSON/tests/unity/examples/example_3/src/ProductionCode.c","size":847,"hash":"75136eec7a43d0dbe980dea19ec46f6e16c0da92093686e59f6143d8ae8b5bb7"},{"path":"cJSON/tests/unity/examples/example_3/src/ProductionCode.h","size":96,"hash":"25cfcc42b79140f4c399363e0ef10a6e518a1831e10c61cc138d6d9a230425ce"},{"path":"cJSON/tests/unity/examples/example_3/src/ProductionCode2.c","size":331,"hash":"a929e7ef393ec5ccc53e3f885d663a1c8fbe5cc5f72a0fcad5c0d2f6cbc8b210"},{"path":"cJSON/tests/unity/examples/example_3/src/ProductionCode2.h","size":69,"hash":"d4db1a4eea2bee3d668a203d4953f415f23be64a826c5a73059ef221f61b3882"},{"path":"cJSON/tests/unity/examples/example_3/test/TestProductionCode.c","size":2357,"hash":"b0e815e2285b1730d7dcd24b400d15b4efccfe5e4776d96248a2165c2f0caec6"},{"path":"cJSON/tests/unity/examples/example_3/test/TestProductionCode2.c","size":565,"hash":"895f437abd40bd461fd86a3b8ed6bc02c5c283fc3926aafe53b473e477fa0a5a"},{"path":"cJSON/tests/unity/examples/example_2/src/ProductionCode.c","size":847,"hash":"75136eec7a43d0dbe980dea19ec46f6e16c0da92093686e59f6143d8ae8b5bb7"},{"path":"cJSON/tests/unity/examples/example_2/src/ProductionCode.h","size":96,"hash":"25cfcc42b79140f4c399363e0ef10a6e518a1831e10c61cc138d6d9a230425ce"},{"path":"cJSON/tests/unity/examples/example_2/src/ProductionCode2.c","size":331,"hash":"a929e7ef393ec5ccc53e3f885d663a1c8fbe5cc5f72a0fcad5c0d2f6cbc8b210"},{"path":"cJSON/tests/unity/examples/example_2/src/ProductionCode2.h","size":69,"hash":"d4db1a4eea2bee3d668a203d4953f415f23be64a826c5a73059ef221f61b3882"},{"path":"cJSON/tests/unity/examples/example_2/test/TestProductionCode.c","size":2453,"hash":"cae04759fdca5834d1c2f926c0bfdb222da048069470722361bbdfcc3017233c"},{"path":"cJSON/tests/unity/examples/example_2/test/TestProductionCode2.c","size":664,"hash":"332f23e940a9676504c84dc92d1a6cf72cd9204afe7f664c16b58ee7dbff312d"},{"path":"cJSON/tests/unity/examples/example_2/test/test_runners/TestProductionCode2_Runner.c","size":271,"hash":"14aef95de310f1e1381feaaf256ea94d0905a538311b5e3fdc944f927e75b287"},{"path":"cJSON/tests/unity/examples/example_2/test/test_runners/TestProductionCode_Runner.c","size":700,"hash":"a782491bcd8dd857b26a62df58e8671f1cb7641d6c0fe7f7853c079732ccd8e9"},{"path":"cJSON/tests/unity/examples/example_2/test/test_runners/all_tests.c","size":221,"hash":"fe5c0418201d70dc696b0db6acf60b2ea0069d74fa94fb96d7169b8752e00d17"},{"path":"cJSON/tests/unity/examples/example_1/src/ProductionCode.c","size":862,"hash":"29d42fce2d89d95fb2b14b649d3b2d7406d225a071e01e86d6ec0cdb04c7e614"},{"path":"cJSON/tests/unity/examples/example_1/src/ProductionCode.h","size":96,"hash":"25cfcc42b79140f4c399363e0ef10a6e518a1831e10c61cc138d6d9a230425ce"},{"path":"cJSON/tests/unity/examples/example_1/src/ProductionCode2.c","size":335,"hash":"c2cc0a76cb2ea145d3861bd9ccc467ac45ad3e8230d5075ed174ce3a5cd50a76"},{"path":"cJSON/tests/unity/examples/example_1/src/ProductionCode2.h","size":69,"hash":"d4db1a4eea2bee3d668a203d4953f415f23be64a826c5a73059ef221f61b3882"},{"path":"cJSON/tests/unity/examples/example_1/test/TestProductionCode.c","size":2393,"hash":"2cc1611df09a030abb8ec11569d200dc313645662577b6a6eb32065a193b4343"},{"path":"cJSON/tests/unity/examples/example_1/test/TestProductionCode2.c","size":567,"hash":"11387f2ecdc97ee3344c0df42123e73cae899702b348d5597e09e9760db267aa"},{"path":"cJSON/tests/unity/examples/example_1/test/test_runners/TestProductionCode2_Runner.c","size":1178,"hash":"2c84d6b954a6810a7c509dc861ee0c18a562dd23a5dd7747ea524f0c1467d9a4"},{"path":"cJSON/tests/unity/examples/example_1/test/test_runners/TestProductionCode_Runner.c","size":1998,"hash":"b6ec7bb984eddea80c178ecb30f6f772325a745ff9812a5e3f41f236c43e19e0"},{"path":"cJSON/fuzzing/inputs/test1","size":585,"hash":"575a805b8582fcafe96e4e49b9b0c8cf42a49759ed41afe1046a27656e126ea2"},{"path":"cJSON/fuzzing/inputs/test10","size":81,"hash":"0411a8d09c3329fee6fdd1cfcdaeb8ecc30cc7a150fea5226b8af787c22e6099"},{"path":"cJSON/fuzzing/inputs/test11","size":151,"hash":"e426feb8b6664ddaf3fab041829ce34439161371e6d1c9a3360c11d6b1bb3894"},{"path":"cJSON/fuzzing/inputs/test2","size":244,"hash":"2b3b1a75dca9ca58523f2bcc9066345220bff8fbe959daed1fa2647dba747450"},{"path":"cJSON/fuzzing/inputs/test3","size":603,"hash":"ef5c0435dcdea047bb105c44a5ea059772cd55ebb4e3db293849f8e7c3be6cc4"},{"path":"cJSON/fuzzing/inputs/test3.bu","size":603,"hash":"38e8f277565a0dd5194fc8bf1dc028469d70149eba3b75b730eb8802921c5b27"},{"path":"cJSON/fuzzing/inputs/test3.uf","size":603,"hash":"5f0911f8e7bd504fb9485d11f5097a666c323f6a26fc12b865c78c940effc595"},{"path":"cJSON/fuzzing/inputs/test3.uu","size":603,"hash":"7ab9252284ec773b973208aa60d48f199a2b72b1f8e1136248171362cbbebdfc"},{"path":"cJSON/fuzzing/inputs/test4","size":3465,"hash":"ddb6276d3aebc311a9b042459f544f80c1b3e1f11591e43926e29b519225530e"},{"path":"cJSON/fuzzing/inputs/test5","size":875,"hash":"6a9b241591ac80f24357f94d518487501984578411cb57657b79142a8c56f6bb"},{"path":"cJSON/fuzzing/inputs/test6","size":487,"hash":"bfe13f225816216354d11c3c147b75414ec69b669cc84dcd2c4b05ae29530986"},{"path":"cJSON/fuzzing/inputs/test7","size":401,"hash":"ff934c7141f8b6a5429b1a45250024187258c0b030b0eff236c467fb9440fb38"},{"path":"cJSON/fuzzing/inputs/test8","size":249,"hash":"03812794e39a3cec68aaf709d3ff1f890bdccae55f2ccc0c8b5287b79b795e7e"},{"path":"cJSON/fuzzing/inputs/test9","size":52,"hash":"2933710b91761580feafa16315e57281f24b1defa74687f38705a511ba05fe92"}]} \ No newline at end of file diff --git a/managed_components/espressif__cjson/CMakeLists.txt b/managed_components/espressif__cjson/CMakeLists.txt new file mode 100644 index 0000000..521cf8e --- /dev/null +++ b/managed_components/espressif__cjson/CMakeLists.txt @@ -0,0 +1,7 @@ +idf_component_register(SRCS "cJSON/cJSON.c" + "cJSON/cJSON_Utils.c" + INCLUDE_DIRS "cJSON") + +target_compile_definitions(${COMPONENT_LIB} PUBLIC + CJSON_NESTING_LIMIT=${CONFIG_CJSON_NESTING_LIMIT} + CJSON_CIRCULAR_LIMIT=${CONFIG_CJSON_CIRCULAR_LIMIT}) diff --git a/managed_components/espressif__cjson/Kconfig b/managed_components/espressif__cjson/Kconfig new file mode 100644 index 0000000..8628512 --- /dev/null +++ b/managed_components/espressif__cjson/Kconfig @@ -0,0 +1,20 @@ +menu "cJSON" + + config CJSON_NESTING_LIMIT + int "Maximum nesting depth for JSON parsing" + default 1000 + help + Limits how deeply nested arrays/objects can be before cJSON + rejects to parse them. This is to prevent stack overflows. + Lower values use less stack, higher values allow deeper nesting. + + config CJSON_CIRCULAR_LIMIT + int "Maximum depth for circular reference detection" + default 10000 + help + Limits the depth for circular reference detection during + printing/comparison operations. This prevents infinite loops + and stack overflows when processing JSON structures with + circular references. Lower values use less stack. + +endmenu diff --git a/managed_components/espressif__cjson/LICENSE b/managed_components/espressif__cjson/LICENSE new file mode 100644 index 0000000..78deb04 --- /dev/null +++ b/managed_components/espressif__cjson/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/managed_components/espressif__cjson/README.md b/managed_components/espressif__cjson/README.md new file mode 100644 index 0000000..9c7ed14 --- /dev/null +++ b/managed_components/espressif__cjson/README.md @@ -0,0 +1,590 @@ +# cJSON + +Ultralightweight JSON parser in ANSI C. + +## Table of contents +* [License](#license) +* [Usage](#usage) + * [Welcome to cJSON](#welcome-to-cjson) + * [Building](#building) + * [Copying the source](#copying-the-source) + * [CMake](#cmake) + * [Makefile](#makefile) + * [Meson](#meson) + * [Vcpkg](#Vcpkg) + * [Including cJSON](#including-cjson) + * [Data Structure](#data-structure) + * [Working with the data structure](#working-with-the-data-structure) + * [Basic types](#basic-types) + * [Arrays](#arrays) + * [Objects](#objects) + * [Parsing JSON](#parsing-json) + * [Printing JSON](#printing-json) + * [Example](#example) + * [Printing](#printing) + * [Parsing](#parsing) + * [Caveats](#caveats) + * [Zero Character](#zero-character) + * [Character Encoding](#character-encoding) + * [C Standard](#c-standard) + * [Floating Point Numbers](#floating-point-numbers) + * [Deep Nesting Of Arrays And Objects](#deep-nesting-of-arrays-and-objects) + * [Thread Safety](#thread-safety) + * [Case Sensitivity](#case-sensitivity) + * [Duplicate Object Members](#duplicate-object-members) + * [Enjoy cJSON!](#enjoy-cjson) + +## License + +MIT License + +> Copyright (c) 2009-2017 Dave Gamble and cJSON contributors +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +## Usage + +### Welcome to cJSON. + +cJSON aims to be the dumbest possible parser that you can get your job done with. +It's a single file of C, and a single header file. + +JSON is described best here: http://www.json.org/ +It's like XML, but fat-free. You use it to move data around, store things, or just +generally represent your program's state. + +As a library, cJSON exists to take away as much legwork as it can, but not get in your way. +As a point of pragmatism (i.e. ignoring the truth), I'm going to say that you can use it +in one of two modes: Auto and Manual. Let's have a quick run-through. + +I lifted some JSON from this page: http://www.json.org/fatfree.html +That page inspired me to write cJSON, which is a parser that tries to share the same +philosophy as JSON itself. Simple, dumb, out of the way. + +### Building + +There are several ways to incorporate cJSON into your project. + +#### copying the source + +Because the entire library is only one C file and one header file, you can just copy `cJSON.h` and `cJSON.c` to your projects source and start using it. + +cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible. + +#### CMake + +With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 3.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a `build` directory and run CMake inside it. + +``` +mkdir build +cd build +cmake .. +``` + +This will create a Makefile and a bunch of other files. You can then compile it: + +``` +make +``` + +And install it with `make install` if you want. By default it installs the headers `/usr/local/include/cjson` and the libraries to `/usr/local/lib`. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library. + +You can change the build process with a list of different options that you can pass to CMake. Turn them on with `On` and off with `Off`: + +* `-DENABLE_CJSON_TEST=On`: Enable building the tests. (on by default) +* `-DENABLE_CJSON_UTILS=On`: Enable building cJSON_Utils. (off by default) +* `-DENABLE_TARGET_EXPORT=On`: Enable the export of CMake targets. Turn off if it makes problems. (on by default) +* `-DENABLE_CUSTOM_COMPILER_FLAGS=On`: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default) +* `-DENABLE_VALGRIND=On`: Run tests with [valgrind](http://valgrind.org). (off by default) +* `-DENABLE_SANITIZERS=On`: Compile cJSON with [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) enabled (if possible). (off by default) +* `-DENABLE_SAFE_STACK`: Enable the [SafeStack](https://clang.llvm.org/docs/SafeStack.html) instrumentation pass. Currently only works with the Clang compiler. (off by default) +* `-DBUILD_SHARED_LIBS=On`: Build the shared libraries. (on by default) +* `-DBUILD_SHARED_AND_STATIC_LIBS=On`: Build both shared and static libraries. (off by default) +* `-DCMAKE_INSTALL_PREFIX=/usr`: Set a prefix for the installation. +* `-DENABLE_LOCALES=On`: Enable the usage of localeconv method. ( on by default ) +* `-DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On`: Enable overriding the value of `BUILD_SHARED_LIBS` with `-DCJSON_BUILD_SHARED_LIBS`. +* `-DENABLE_CJSON_VERSION_SO`: Enable cJSON so version. ( on by default ) + +If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example: +``` +mkdir build +cd build +cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr +make +make DESTDIR=$pkgdir install +``` + +On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows. + +#### Makefile + +**NOTE:** This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs. + +If you don't have CMake available, but still have GNU make. You can use the makefile to build cJSON: + +Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite). + +``` +make all +``` + +If you want, you can install the compiled library to your system using `make install`. By default it will install the headers in `/usr/local/include/cjson` and the libraries in `/usr/local/lib`. But you can change this behavior by setting the `PREFIX` and `DESTDIR` variables: `make PREFIX=/usr DESTDIR=temp install`. And uninstall them with: `make PREFIX=/usr DESTDIR=temp uninstall`. + +#### Meson + +To make cjson work in a project using meson, the libcjson dependency has to be included: + +```meson +project('c-json-example', 'c') + +cjson = dependency('libcjson') + +example = executable( + 'example', + 'example.c', + dependencies: [cjson], +) +``` + + +#### Vcpkg + +You can download and install cJSON using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: +``` +git clone https://github.com/Microsoft/vcpkg.git +cd vcpkg +./bootstrap-vcpkg.sh +./vcpkg integrate install +vcpkg install cjson +``` + +The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + +### Including cJSON + +If you installed it via CMake or the Makefile, you can include cJSON like this: + +```c +#include +``` + +### Data Structure + +cJSON represents JSON data using the `cJSON` struct data type: + +```c +/* The cJSON structure: */ +typedef struct cJSON +{ + struct cJSON *next; + struct cJSON *prev; + struct cJSON *child; + int type; + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + double valuedouble; + char *string; +} cJSON; +``` + +An item of this type represents a JSON value. The type is stored in `type` as a bit-flag (**this means that you cannot find out the type by just comparing the value of `type`**). + +To check the type of an item, use the corresponding `cJSON_Is...` function. It does a `NULL` check followed by a type check and returns a boolean value if the item is of this type. + +The type can be one of the following: + +* `cJSON_Invalid` (check with `cJSON_IsInvalid`): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes. +* `cJSON_False` (check with `cJSON_IsFalse`): Represents a `false` boolean value. You can also check for boolean values in general with `cJSON_IsBool`. +* `cJSON_True` (check with `cJSON_IsTrue`): Represents a `true` boolean value. You can also check for boolean values in general with `cJSON_IsBool`. +* `cJSON_NULL` (check with `cJSON_IsNull`): Represents a `null` value. +* `cJSON_Number` (check with `cJSON_IsNumber`): Represents a number value. The value is stored as a double in `valuedouble` and also in `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`. +* `cJSON_String` (check with `cJSON_IsString`): Represents a string value. It is stored in the form of a zero terminated string in `valuestring`. +* `cJSON_Array` (check with `cJSON_IsArray`): Represent an array value. This is implemented by pointing `child` to a linked list of `cJSON` items that represent the values in the array. The elements are linked together using `next` and `prev`, where the first element has `prev.next == NULL` and the last element `next == NULL`. +* `cJSON_Object` (check with `cJSON_IsObject`): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in `string`. +* `cJSON_Raw` (check with `cJSON_IsRaw`): Represents any kind of JSON that is stored as a zero terminated array of characters in `valuestring`. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn't check if it is valid JSON. + +Additionally there are the following two flags: + +* `cJSON_IsReference`: Specifies that the item that `child` points to and/or `valuestring` is not owned by this item, it is only a reference. So `cJSON_Delete` and other functions will only deallocate this item, not its `child`/`valuestring`. +* `cJSON_StringIsConst`: This means that `string` points to a constant string. This means that `cJSON_Delete` and other functions will not try to deallocate `string`. + +### Working with the data structure + +For every value type there is a `cJSON_Create...` function that can be used to create an item of that type. +All of these will allocate a `cJSON` struct that can later be deleted with `cJSON_Delete`. +Note that you have to delete them at some point, otherwise you will get a memory leak. +**Important**: If you have added an item to an array or an object already, you **mustn't** delete it with `cJSON_Delete`. Adding it to an array or object transfers its ownership so that when that array or object is deleted, +it gets deleted as well. You also could use `cJSON_SetValuestring` to change a `cJSON_String`'s `valuestring`, and you needn't to free the previous `valuestring` manually. + +#### Basic types + +* **null** is created with `cJSON_CreateNull` +* **booleans** are created with `cJSON_CreateTrue`, `cJSON_CreateFalse` or `cJSON_CreateBool` +* **numbers** are created with `cJSON_CreateNumber`. This will set both `valuedouble` and `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint` +* **strings** are created with `cJSON_CreateString` (copies the string) or with `cJSON_CreateStringReference` (directly points to the string. This means that `valuestring` won't be deleted by `cJSON_Delete` and you are responsible for its lifetime, useful for constants) + +#### Arrays + +You can create an empty array with `cJSON_CreateArray`. `cJSON_CreateArrayReference` can be used to create an array that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`. + +To add items to an array, use `cJSON_AddItemToArray` to append items to the end. +Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another item, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere. +To insert items in the middle, use `cJSON_InsertItemInArray`. It will insert an item at the given 0 based index and shift all the existing items to the right. + +If you want to take an item out of an array at a given index and continue using it, use `cJSON_DetachItemFromArray`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak. + +Deleting items is done with `cJSON_DeleteItemFromArray`. It works like `cJSON_DetachItemFromArray`, but deletes the detached item via `cJSON_Delete`. + +You can also replace an item in an array in place. Either with `cJSON_ReplaceItemInArray` using an index or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place. + +To get the size of an array, use `cJSON_GetArraySize`. Use `cJSON_GetArrayItem` to get an element at a given index. + +Because an array is stored as a linked list, iterating it via index is inefficient (`O(n²)`), so you can iterate over an array using the `cJSON_ArrayForEach` macro in `O(n)` time complexity. + +#### Objects + +You can create an empty object with `cJSON_CreateObject`. `cJSON_CreateObjectReference` can be used to create an object that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`. + +To add items to an object, use `cJSON_AddItemToObject`. Use `cJSON_AddItemToObjectCS` to add an item to an object with a name that is a constant or reference (key of the item, `string` in the `cJSON` struct), so that it doesn't get freed by `cJSON_Delete`. +Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another object, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere. + +If you want to take an item out of an object, use `cJSON_DetachItemFromObjectCaseSensitive`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak. + +Deleting items is done with `cJSON_DeleteItemFromObjectCaseSensitive`. It works like `cJSON_DetachItemFromObjectCaseSensitive` followed by `cJSON_Delete`. + +You can also replace an item in an object in place. Either with `cJSON_ReplaceItemInObjectCaseSensitive` using a key or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place. + +To get the size of an object, you can use `cJSON_GetArraySize`, this works because internally objects are stored as arrays. + +If you want to access an item in an object, use `cJSON_GetObjectItemCaseSensitive`. + +To iterate over an object, you can use the `cJSON_ArrayForEach` macro the same way as for arrays. + +cJSON also provides convenient helper functions for quickly creating a new item and adding it to an object, like `cJSON_AddNullToObject`. They return a pointer to the new item or `NULL` if they failed. + +### Parsing JSON + +Given some JSON in a zero terminated string, you can parse it with `cJSON_Parse`. + +```c +cJSON *json = cJSON_Parse(string); +``` + +Given some JSON in a string (whether zero terminated or not), you can parse it with `cJSON_ParseWithLength`. + +```c +cJSON *json = cJSON_ParseWithLength(string, buffer_length); +``` + +It will parse the JSON and allocate a tree of `cJSON` items that represents it. Once it returns, you are fully responsible for deallocating it after use with `cJSON_Delete`. + +The allocator used by `cJSON_Parse` is `malloc` and `free` by default but can be changed (globally) with `cJSON_InitHooks`. + +If an error occurs a pointer to the position of the error in the input string can be accessed using `cJSON_GetErrorPtr`. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use `cJSON_ParseWithOpts` with `return_parse_end`. +By default, characters in the input string that follow the parsed JSON will not be considered as an error. + +If you want more options, use `cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)`. +`return_parse_end` returns a pointer to the end of the JSON in the input string or the position that an error occurs at (thereby replacing `cJSON_GetErrorPtr` in a thread safe way). `require_null_terminated`, if set to `1` will make it an error if the input string contains data after the JSON. + +If you want more options giving buffer length, use `cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)`. + +### Printing JSON + +Given a tree of `cJSON` items, you can print them as a string using `cJSON_Print`. + +```c +char *string = cJSON_Print(json); +``` + +It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually `free`, depends on what has been set with `cJSON_InitHooks`). + +`cJSON_Print` will print with whitespace for formatting. If you want to print without formatting, use `cJSON_PrintUnformatted`. + +If you have a rough idea of how big your resulting string will be, you can use `cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)`. `fmt` is a boolean to turn formatting with whitespace on and off. `prebuffer` specifies the first buffer size to use for printing. `cJSON_Print` currently uses 256 bytes for its first buffer size. Once printing runs out of space, a new buffer is allocated and the old gets copied over before printing is continued. + +These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and its length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough. + +### Example + +In this example we want to build and parse the following JSON: + +```json +{ + "name": "Awesome 4K", + "resolutions": [ + { + "width": 1280, + "height": 720 + }, + { + "width": 1920, + "height": 1080 + }, + { + "width": 3840, + "height": 2160 + } + ] +} +``` + +#### Printing + +Let's build the above JSON and print it to a string: + +```c +//create a monitor with a list of supported resolutions +//NOTE: Returns a heap allocated string, you are required to free it after use. +char *create_monitor(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *name = NULL; + cJSON *resolutions = NULL; + cJSON *resolution = NULL; + cJSON *width = NULL; + cJSON *height = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + if (monitor == NULL) + { + goto end; + } + + name = cJSON_CreateString("Awesome 4K"); + if (name == NULL) + { + goto end; + } + /* after creation was successful, immediately add it to the monitor, + * thereby transferring ownership of the pointer to it */ + cJSON_AddItemToObject(monitor, "name", name); + + resolutions = cJSON_CreateArray(); + if (resolutions == NULL) + { + goto end; + } + cJSON_AddItemToObject(monitor, "resolutions", resolutions); + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + resolution = cJSON_CreateObject(); + if (resolution == NULL) + { + goto end; + } + cJSON_AddItemToArray(resolutions, resolution); + + width = cJSON_CreateNumber(resolution_numbers[index][0]); + if (width == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "width", width); + + height = cJSON_CreateNumber(resolution_numbers[index][1]); + if (height == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "height", height); + } + + string = cJSON_Print(monitor); + if (string == NULL) + { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} +``` + +Alternatively we can use the `cJSON_Add...ToObject` helper functions to make our lives a little easier: + +```c +//NOTE: Returns a heap allocated string, you are required to free it after use. +char *create_monitor_with_helpers(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *resolutions = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + + if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL) + { + goto end; + } + + resolutions = cJSON_AddArrayToObject(monitor, "resolutions"); + if (resolutions == NULL) + { + goto end; + } + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + cJSON *resolution = cJSON_CreateObject(); + + if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL) + { + goto end; + } + + if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL) + { + goto end; + } + + cJSON_AddItemToArray(resolutions, resolution); + } + + string = cJSON_Print(monitor); + if (string == NULL) + { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} +``` + +#### Parsing + +In this example we will parse a JSON in the above format and check if the monitor supports a Full HD resolution while printing some diagnostic output: + +```c +/* return 1 if the monitor supports full hd, 0 otherwise */ +int supports_full_hd(const char * const monitor) +{ + const cJSON *resolution = NULL; + const cJSON *resolutions = NULL; + const cJSON *name = NULL; + int status = 0; + cJSON *monitor_json = cJSON_Parse(monitor); + if (monitor_json == NULL) + { + const char *error_ptr = cJSON_GetErrorPtr(); + if (error_ptr != NULL) + { + fprintf(stderr, "Error before: %s\n", error_ptr); + } + status = 0; + goto end; + } + + name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name"); + if (cJSON_IsString(name) && (name->valuestring != NULL)) + { + printf("Checking monitor \"%s\"\n", name->valuestring); + } + + resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions"); + cJSON_ArrayForEach(resolution, resolutions) + { + cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width"); + cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height"); + + if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height)) + { + status = 0; + goto end; + } + + if ((width->valuedouble == 1920) && (height->valuedouble == 1080)) + { + status = 1; + goto end; + } + } + +end: + cJSON_Delete(monitor_json); + return status; +} +``` + +Note that there are no NULL checks except for the result of `cJSON_Parse` because `cJSON_GetObjectItemCaseSensitive` checks for `NULL` inputs already, so a `NULL` value is just propagated and `cJSON_IsNumber` and `cJSON_IsString` return `0` if the input is `NULL`. + +### Caveats + +#### Zero Character + +cJSON doesn't support strings that contain the zero character `'\0'` or `\u0000`. This is impossible with the current API because strings are zero terminated. + +#### Character Encoding + +cJSON only supports UTF-8 encoded input. In most cases it doesn't reject invalid UTF-8 as input though, it just propagates it through as is. As long as the input doesn't contain invalid UTF-8, the output will always be valid UTF-8. + +#### C Standard + +cJSON is written in ANSI C (or C89, C90). If your compiler or C library doesn't follow this standard, correct behavior is not guaranteed. + +NOTE: ANSI C is not C++ therefore it shouldn't be compiled with a C++ compiler. You can compile it with a C compiler and link it with your C++ code however. Although compiling with a C++ compiler might work, correct behavior is not guaranteed. + +#### Floating Point Numbers + +cJSON does not officially support any `double` implementations other than IEEE754 double precision floating point numbers. It might still work with other implementations but bugs with these will be considered invalid. + +The maximum length of a floating point literal that cJSON supports is currently 63 characters. + +#### Deep Nesting Of Arrays And Objects + +cJSON doesn't support arrays and objects that are nested too deeply because this would result in a stack overflow. To prevent this cJSON limits the depth to `CJSON_NESTING_LIMIT` which is 1000 by default but can be changed at compile time. + +#### Thread Safety + +In general cJSON is **not thread safe**. + +However it is thread safe under the following conditions: + +* `cJSON_GetErrorPtr` is never used (the `return_parse_end` parameter of `cJSON_ParseWithOpts` can be used instead) +* `cJSON_InitHooks` is only ever called before using cJSON in any threads. +* `setlocale` is never called before all calls to cJSON functions have returned. + +#### Case Sensitivity + +When cJSON was originally created, it didn't follow the JSON standard and didn't make a distinction between uppercase and lowercase letters. If you want the correct, standard compliant, behavior, you need to use the `CaseSensitive` functions where available. + +#### Duplicate Object Members + +cJSON supports parsing and printing JSON that contains objects that have multiple members with the same name. `cJSON_GetObjectItemCaseSensitive` however will always only return the first one. + +# Enjoy cJSON! + +- Dave Gamble (original author) +- Max Bruckner and Alan Wang (current maintainer) +- and the other [cJSON contributors](CONTRIBUTORS.md) diff --git a/managed_components/espressif__cjson/cJSON/.editorconfig b/managed_components/espressif__cjson/cJSON/.editorconfig new file mode 100644 index 0000000..befb2c2 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/.editorconfig @@ -0,0 +1,23 @@ +root = true + + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[Makefile] +indent_style = tab +indent_size = unset + +# ignore external repositories and test inputs +[tests/{unity,json-patch-tests,inputs}/*] +indent_style = unset +indent_size = unset +end_of_line = unset +charset = unset +trim_trailing_whitespace = unset +insert_final_newline = unset diff --git a/managed_components/espressif__cjson/cJSON/.gitattributes b/managed_components/espressif__cjson/cJSON/.gitattributes new file mode 100644 index 0000000..883895f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/.gitattributes @@ -0,0 +1,11 @@ +* text=auto +/tests/inputs/* text eol=lf + +.gitattributes export-ignore +.gitignore export-ignore +.github export-ignore +.editorconfig export-ignore +.travis.yml export-ignore + +# Linguist incorrectly identified the headers as C++, manually override this. +*.h linguist-language=C diff --git a/managed_components/espressif__cjson/cJSON/.gitignore b/managed_components/espressif__cjson/cJSON/.gitignore new file mode 100644 index 0000000..65fa89b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/.gitignore @@ -0,0 +1,20 @@ +.svn +test +*.o +*.a +*.so +*.swp +*.patch +tags +*.dylib* +build/ +cJSON_test +cJSON_test_utils +libcjson.so.* +libcjson_utils.so.* +*.orig +.vscode +.idea +cmake-build-debug +*.lst +*.lss diff --git a/managed_components/espressif__cjson/cJSON/.travis.yml b/managed_components/espressif__cjson/cJSON/.travis.yml new file mode 100644 index 0000000..e7ff744 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/.travis.yml @@ -0,0 +1,28 @@ +dist: trusty +sudo: false +language: c +env: + matrix: + - VALGRIND=On SANITIZERS=Off + - VALGRIND=Off SANITIZERS=Off + - VALGRIND=Off SANITIZERS=On +compiler: + - gcc + - clang +addons: + apt: + packages: + - valgrind + - libasan0 + - lib32asan0 + # currently not supported on travis: + # - libasan1 + # - libasan2 + # - libubsan0 + - llvm +script: + - mkdir build + - cd build + - cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_VALGRIND="${VALGRIND}" -DENABLE_SAFE_STACK="${VALGRIND}" -DENABLE_SANITIZERS="${SANITIZERS}" + - make + - make test CTEST_OUTPUT_ON_FAILURE=On diff --git a/managed_components/espressif__cjson/cJSON/CHANGELOG.md b/managed_components/espressif__cjson/cJSON/CHANGELOG.md new file mode 100644 index 0000000..2f046e3 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/CHANGELOG.md @@ -0,0 +1,476 @@ +1.7.19 (Sep 9, 2025) +====== +Fixes: +------ +* Fix indentation (should use spaces), see #814 +* Fix spelling errors found by CodeSpell, see #841 +* Check for NULL in cJSON_DetachItemViaPointer, fixes #882, see #886 +* Fix #881, check overlap before calling strcpy in cJSON_SetValuestring, see #885 +* Fix #880 Max recursion depth for cJSON_Duplicate to prevent stack exhaustion, see #888 +* Allocate memory for the temporary buffer when paring numbers, see #939 +* fix the incorrect check in decode_array_index_from_pointer, see #957 + +1.7.18 (May 13, 2024) +====== +Fixes: +------ +* Add NULL check to cJSON_SetValuestring()(CVE-2024-31755), see #839 and #840 +* Remove non-functional list handling of compiler flags, see #851 +* Fix heap buffer overflow, see #852 +* remove misused optimization flag -01, see #854 +* Set free'd pointers to NULL whenever they are not reassigned immediately after, see #855 and #833 + +1.7.17 (Dec 26, 2023) +====== +Fixes: +------ +* Fix null reference in cJSON_SetValuestring(CVE-2023-50472), see #809 +* Fix null reference in cJSON_InsertItemInArray(CVE-2023-50471), see #809 and #810 + +1.7.16 (Jul 5, 2023) +====== +Features: +------ +* Add an option for ENABLE_CJSON_VERSION_SO in CMakeLists.txt, see #534 +* Add cmake_policy to CMakeLists.txt, see #163 +* Add cJSON_SetBoolValue, see #639 +* Add meson documentation, see #761 + +Fixes: +------ +* Fix memory leak in merge_patch, see #611 +* Fix conflicting target names 'uninstall', see #617 +* Bump cmake version to 3.0 and use new version syntax, see #587 +* Print int without decimal places, see #630 +* Fix 'cjson_utils-static' target not exist, see #625 +* Add allocate check for replace_item_in_object, see #675 +* Fix a null pointer crash in cJSON_ReplaceItemViaPointer, see #726 + +1.7.15 (Aug 25, 2021) +====== +Fixes: +------ +* Fix potential core dumped for strrchr, see [#546](https://github.com/DaveGamble/cJSON/pull/546) +* Fix null pointer crash in cJSON_CreateXxArray, see [#538](https://github.com/DaveGamble/cJSON/pull/538) +* Fix several null pointer problems on allocation failure, see [#526](https://github.com/DaveGamble/cJSON/pull/526) +* Fix a possible dereference of null pointer, see [#519](https://github.com/DaveGamble/cJSON/pull/519) +* Fix windows build failure about defining nan, see [#518](https://github.com/DaveGamble/cJSON/pull/518) + +1.7.14 (Sep 3, 2020) +====== +Fixes: +------ +* optimize the way to find tail node, see [#503](https://github.com/DaveGamble/cJSON/pull/503) +* Fix WError error on macosx because NAN is a float. Thanks @sappo, see [#484](https://github.com/DaveGamble/cJSON/pull/484) +* Fix some bugs in detach and replace. Thanks @miaoerduo, see [#456](https://github.com/DaveGamble/cJSON/pull/456) + +1.7.13 (Apr 2, 2020) +====== +Features: +--------- +* add new API of cJSON_ParseWithLength without breaking changes. Thanks @caglarivriz, see [#358](https://github.com/DaveGamble/cJSON/pull/358) +* add new API of cJSON_GetNumberValue. Thanks @Intuition, see[#385](https://github.com/DaveGamble/cJSON/pull/385) +* add uninstall target function for CMake. See [#402](https://github.com/DaveGamble/cJSON/pull/402) +* Improve performance of adding item to array. Thanks @xiaomianhehe, see [#430](https://github.com/DaveGamble/cJSON/pull/430), [#448](https://github.com/DaveGamble/cJSON/pull/448) +* add new API of cJSON_SetValuestring, for changing the valuestring safely. See [#451](https://github.com/DaveGamble/cJSON/pull/451) +* add return value for cJSON_AddItemTo... and cJSON_ReplaceItem... (check if the operation successful). See [#453](https://github.com/DaveGamble/cJSON/pull/453) + +Fixes: +------ +* Fix clang -Wfloat-equal warning. Thanks @paulmalovanyi, see [#368](https://github.com/DaveGamble/cJSON/pull/368) +* Fix make failed in mac os. See [#405](https://github.com/DaveGamble/cJSON/pull/405) +* Fix memory leak in cJSONUtils_FindPointerFromObjectTo. Thanks @andywolk for reporting, see [#414](https://github.com/DaveGamble/cJSON/issues/414) +* Fix bug in encode_string_as_pointer. Thanks @AIChangJiang for reporting, see [#439](https://github.com/DaveGamble/cJSON/issues/439) + +1.7.12 (May 17, 2019) +====== +Fixes: +------ +* Fix infinite loop in `cJSON_Minify` (potential Denial of Service). Thanks @Alanscut for reporting, see [#354](https://github.com/DaveGamble/cJSON/issues/354) +* Fix link error for Visual Studio. Thanks @tan-wei, see [#352](https://github.com/DaveGamble/cJSON/pull/352). +* Undefine `true` and `false` for `cJSON_Utils` before redefining them. Thanks @raiden00pl, see [#347](https://github.com/DaveGamble/cJSON/pull/347). + +1.7.11 (Apr 15, 2019) +====== +Fixes: +------ +* Fix a bug where cJSON_Minify could overflow it's buffer, both reading and writing. This is a security issue, see [#338](https://github.com/DaveGamble/cJSON/issues/338). Big thanks @bigric3 for reporting. +* Unset `true` and `false` macros before setting them if they exist. See [#339](https://github.com/DaveGamble/cJSON/issues/339), thanks @raiden00pl for reporting + +1.7.10 (Dec 21, 2018) +====== +Fixes: +------ +* Fix package config file for `libcjson`. Thanks @shiluotang for reporting [#321](https://github.com/DaveGamble/cJSON/issues/321) +* Correctly split lists in `cJSON_Utils`'s merge sort. Thanks @andysCaplin for the fix [#322](https://github.com/DaveGamble/cJSON/issues/322) + +1.7.9 (Dec 16, 2018) +===== +Fixes: +------ +* Fix a bug where `cJSON_GetObjectItemCaseSensitive` would pass a nullpointer to `strcmp` when called on an array, see [#315](https://github.com/DaveGamble/cJSON/issues/315). Thanks @yuweol for reporting. +* Fix error in `cJSON_Utils` where the case sensitivity was not respected, see [#317](https://github.com/DaveGamble/cJSON/pull/317). Thanks @yuta-oxo for fixing. +* Fix some warnings detected by the Visual Studio Static Analyzer, see [#307](https://github.com/DaveGamble/cJSON/pull/307). Thanks @bnason-nf + +1.7.8 (Sep 22, 2018) +====== +Fixes: +------ +* cJSON now works with the `__stdcall` calling convention on Windows, see [#295](https://github.com/DaveGamble/cJSON/pull/295), thanks @zhindes for contributing + +1.7.7 (May 22, 2018) +===== +Fixes: +------ +* Fix a memory leak when realloc fails, see [#267](https://github.com/DaveGamble/cJSON/issues/267), thanks @AlfieDeng for reporting +* Fix a typo in the header file, see [#266](https://github.com/DaveGamble/cJSON/pull/266), thanks @zhaozhixu + +1.7.6 (Apr 13, 2018) +===== +Fixes: +------ +* Add `SONAME` to the ELF files built by the Makefile, see [#252](https://github.com/DaveGamble/cJSON/issues/252), thanks @YanhaoMo for reporting +* Add include guards and `extern "C"` to `cJSON_Utils.h`, see [#256](https://github.com/DaveGamble/cJSON/issues/256), thanks @daschfg for reporting + +Other changes: +* Mark the Makefile as deprecated in the README. + +1.7.5 (Mar 23, 2018) +===== +Fixes: +------ +* Fix a bug in the JSON Patch implementation of `cJSON Utils`, see [#251](https://github.com/DaveGamble/cJSON/pull/251), thanks @bobkocisko. + +1.7.4 (Mar 3, 2018) +===== +Fixes: +------ +* Fix potential use after free if the `string` parameter to `cJSON_AddItemToObject` is an alias of the `string` property of the object that is added,see [#248](https://github.com/DaveGamble/cJSON/issues/248). Thanks @hhallen for reporting. + +1.7.3 (Feb 8, 2018) +===== +Fixes: +------ +* Fix potential double free, thanks @projectgus for reporting [#241](https://github.com/DaveGamble/cJSON/issues/241) + +1.7.2 (Feb 6, 2018) +===== +Fixes: +------ +* Fix the use of GNUInstallDirs variables and the pkgconfig file. Thanks @zeerd for reporting [#240](https://github.com/DaveGamble/cJSON/pull/240) + +1.7.1 (Jan 10, 2018) +===== +Fixes: +------ +* Fixed an Off-By-One error that could lead to an out of bounds write. Thanks @liuyunbin for reporting [#230](https://github.com/DaveGamble/cJSON/issues/230) +* Fixed two errors with buffered printing. Thanks @liuyunbin for reporting [#230](https://github.com/DaveGamble/cJSON/issues/230) + +1.7.0 (Dec 31, 2017) +===== +Features: +--------- +* Large rewrite of the documentation, see [#215](https://github.com/DaveGamble/cJSON/pull/215) +* Added the `cJSON_GetStringValue` function +* Added the `cJSON_CreateStringReference` function +* Added the `cJSON_CreateArrayReference` function +* Added the `cJSON_CreateObjectReference` function +* The `cJSON_Add...ToObject` macros are now functions that return a pointer to the added item, see [#226](https://github.com/DaveGamble/cJSON/pull/226) + +Fixes: +------ +* Fix a problem with `GNUInstallDirs` in the CMakeLists.txt, thanks @yangfl, see [#210](https://github.com/DaveGamble/cJSON/pull/210) +* Fix linking the tests when building as static library, see [#213](https://github.com/DaveGamble/cJSON/issues/213) +* New overrides for the CMake option `BUILD_SHARED_LIBS`, see [#207](https://github.com/DaveGamble/cJSON/issues/207) + +Other Changes: +-------------- +* Readme: Explain how to include cJSON, see [#211](https://github.com/DaveGamble/cJSON/pull/211) +* Removed some trailing spaces in the code, thanks @yangfl, see [#212](https://github.com/DaveGamble/cJSON/pull/212) +* Updated [Unity](https://github.com/ThrowTheSwitch/Unity) and [json-patch-tests](https://github.com/json-patch/json-patch-tests) + +1.6.0 (Oct 9, 2017) +===== +Features: +--------- +* You can now build cJSON as both shared and static library at once with CMake using `-DBUILD_SHARED_AND_STATIC_LIBS=On`, see [#178](https://github.com/DaveGamble/cJSON/issues/178) +* UTF-8 byte order marks are now ignored, see [#184](https://github.com/DaveGamble/cJSON/issues/184) +* Locales can now be disabled with the option `-DENABLE_LOCALES=Off`, see [#202](https://github.com/DaveGamble/cJSON/issues/202), thanks @Casperinous +* Better support for MSVC and Visual Studio + +Other Changes: +-------------- +* Add the new warnings `-Wswitch-enum`, `-Wused-but-makred-unused`, `-Wmissing-variable-declarations`, `-Wunused-macro` +* More number printing tests. +* Continuous integration testing with AppVeyor (semi automatic at this point), thanks @simon-p-r + +1.5.9 (Sep 8, 2017) +===== +Fixes: +------ +* Set the global error pointer even if `return_parse_end` is passed to `cJSON_ParseWithOpts`, see [#200](https://github.com/DaveGamble/cJSON/pull/200), thanks @rmallins + +1.5.8 (Aug 21, 2017) +===== +Fixes: +------ +* Fix `make test` in the Makefile, thanks @YanhaoMo for reporting this [#195](https://github.com/DaveGamble/cJSON/issues/195) + +1.5.7 (Jul 13, 2017) +===== +Fixes: +------ +* Fix a bug where realloc failing would return a pointer to an invalid memory address. This is a security issue as it could potentially be used by an attacker to write to arbitrary memory addresses, see [#189](https://github.com/DaveGamble/cJSON/issues/189), fixed in [954d61e](https://github.com/DaveGamble/cJSON/commit/954d61e5e7cb9dc6c480fc28ac1cdceca07dd5bd), big thanks @timothyjohncarney for reporting this issue +* Fix a spelling mistake in the AFL fuzzer dictionary, see [#185](https://github.com/DaveGamble/cJSON/pull/185), thanks @jwilk + +1.5.6 (Jun 28, 2017) +===== +Fixes: +------ +* Make cJSON a lot more tolerant about passing NULL pointers to its functions, it should now fail safely instead of dereferencing the pointer, see [#183](https://github.com/DaveGamble/cJSON/pull/183). Thanks @msichal for reporting [#182](https://github.com/DaveGamble/cJSON/issues/182) + +1.5.5 (Jun 15, 2017) +===== +Fixes: +------ +* Fix pointers to nested arrays in cJSON_Utils, see [9abe](https://github.com/DaveGamble/cJSON/commit/9abe75e072050f34732a7169740989a082b65134) +* Fix an error with case sensitivity handling in cJSON_Utils, see [b9cc911](https://github.com/DaveGamble/cJSON/commit/b9cc911831b0b3e1bb72f142389428e59f882b38) +* Fix cJSON_Compare for arrays that are prefixes of the other and objects that are a subset of the other, see [03ba72f](https://github.com/DaveGamble/cJSON/commit/03ba72faec115160d1f3aea5582d9b6af5d3e473) and [#180](https://github.com/DaveGamble/cJSON/issues/180), thanks @zhengqb for reporting + +1.5.4 (Jun 5, 2017) +====== +Fixes: +------ +* Fix build with GCC 7.1.1 and optimization level `-O2`, see [bfbd8fe](https://github.com/DaveGamble/cJSON/commit/bfbd8fe0d85f1dd21e508748fc10fc4c27cc51be) + +Other Changes: +-------------- +* Update [Unity](https://github.com/ThrowTheSwitch/Unity) to 3b69beaa58efc41bbbef70a32a46893cae02719d + +1.5.3 (May 23, 2017) +===== +Fixes: +------ +* Fix `cJSON_ReplaceItemInObject` not keeping the name of an item, see [#174](https://github.com/DaveGamble/cJSON/issues/174) + +1.5.2 (May 10, 2017) +===== +Fixes: +------ +* Fix a reading buffer overflow in `parse_string`, see [a167d9e](https://github.com/DaveGamble/cJSON/commit/a167d9e381e5c84bc03de4e261757b031c0c690d) +* Fix compiling with -Wcomma, see [186cce3](https://github.com/DaveGamble/cJSON/commit/186cce3ece6ce6dfcb58ac8b2a63f7846c3493ad) +* Remove leftover attribute from tests, see [b537ca7](https://github.com/DaveGamble/cJSON/commit/b537ca70a35680db66f1f5b8b437f7114daa699a) + +1.5.1 (May 6, 2017) +===== +Fixes: +------ +* Add gcc version guard to the Makefile, see [#164](https://github.com/DaveGamble/cJSON/pull/164), thanks @juvasquezg +* Fix incorrect free in `cJSON_Utils` if custom memory allocator is used, see [#166](https://github.com/DaveGamble/cJSON/pull/166), thanks @prefetchnta + +1.5.0 (May 2, 2017) +===== +Features: +* cJSON finally prints numbers without losing precision, see [#153](https://github.com/DaveGamble/cJSON/pull/153), thanks @DeboraG +* `cJSON_Compare` recursively checks if two cJSON items contain the same values, see [#148](https://github.com/DaveGamble/cJSON/pull/148) +* Provide case sensitive versions of every function where it matters, see [#158](https://github.com/DaveGamble/cJSON/pull/158) and [#159](https://github.com/DaveGamble/cJSON/pull/159) +* Added `cJSON_ReplaceItemViaPointer` and `cJSON_DetachItemViaPointer` +* Added `cJSON_free` and `cJSON_malloc` that expose the internal configured memory allocators. see [02a05ee](https://github.com/DaveGamble/cJSON/commit/02a05eea4e6ba41811f130b322660bea8918e1a0) + + +Enhancements: +------------- +* Parse into a buffer, this will allow parsing `\u0000` in the future (not quite yet though) +* General simplifications and readability improvements +* More unit tests +* Update [unity](https://github.com/ThrowTheSwitch/Unity) testing library to 2.4.1 +* Add the [json-patch-tests](https://github.com/json-patch/json-patch-tests) test suite to test cJSON_Utils. +* Move all tests from `test_utils.c` to unit tests with unity. + +Fixes: +------ +* Fix some warnings with the Microsoft compiler, see [#139](https://github.com/DaveGamble/cJSON/pull/139), thanks @PawelWMS +* Fix several bugs in cJSON_Utils, mostly found with [json-patch-tests](https://github.com/json-patch/json-patch-tests) +* Prevent a stack overflow by specifying a maximum nesting depth `CJSON_NESTING_LIMIT` + +Other Changes: +-------------- +* Move generated files in the `library_config` subdirectory. + +1.4.7 (Apr 19, 2017) +===== +Fixes: +------ +* Fix `cJSONUtils_ApplyPatches`, it was completely broken and apparently nobody noticed (or at least reported it), see [075a06f](https://github.com/DaveGamble/cJSON/commit/075a06f40bdc4f836c7dd7cad690d253a57cfc50) +* Fix inconsistent prototype for `cJSON_GetObjectItemCaseSensitive`, see [51d3df6](https://github.com/DaveGamble/cJSON/commit/51d3df6c9f7b56b860c8fb24abe7bab255cd4fa9), thanks @PawelWMS + +1.4.6 (Apr 9, 2017) +===== +Fixes: +------ +* Several corrections in the README +* Making clear that `valueint` should not be written to +* Fix overflow detection in `ensure`, see [2683d4d](https://github.com/DaveGamble/cJSON/commit/2683d4d9873df87c4bdccc523903ddd78d1ad250) +* Fix a potential null pointer dereference in cJSON_Utils, see [795c3ac](https://github.com/DaveGamble/cJSON/commit/795c3acabed25c9672006b2c0f40be8845064827) +* Replace incorrect `sizeof('\0')` with `sizeof("")`, see [84237ff](https://github.com/DaveGamble/cJSON/commit/84237ff48e69825c94261c624eb0376d0c328139) +* Add caveats section to the README, see [50b3c30](https://github.com/DaveGamble/cJSON/commit/50b3c30dfa89830f8f477ce33713500740ac3b79) +* Make cJSON locale independent, see [#146](https://github.com/DaveGamble/cJSON/pull/146), Thanks @peterh for reporting +* Fix compiling without CMake with MSVC, see [#147](https://github.com/DaveGamble/cJSON/pull/147), Thanks @dertuxmalwieder for reporting + +1.4.5 (Mar 28, 2017) +===== +Fixes: +------ +* Fix bug in `cJSON_SetNumberHelper`, thanks @mmkeeper, see [#138](https://github.com/DaveGamble/cJSON/issues/138) and [ef34500](https://github.com/DaveGamble/cJSON/commit/ef34500693e8c4a2849d41a4bd66fd19c9ec46c2) +* Workaround for internal compiler error in GCC 5.4.0 and 6.3.1 on x86 (2f65e80a3471d053fdc3f8aed23d01dd1782a5cb [GCC bugreport](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80097)) + +1.4.4 (Mar 24, 2017) +===== +Fixes: +------ +* Fix a theoretical integer overflow, (not sure if it is possible on actual hardware), see [e58f7ec](https://github.com/DaveGamble/cJSON/commit/e58f7ec027d00b7cdcbf63e518c1b5268b29b3da) +* Fix an off by one error, see [cc84a44](https://github.com/DaveGamble/cJSON/commit/cc84a446be20cc283bafdc4d94c050ba1111ac02), thanks @gatzka +* Double check the offset of the print buffer in `ensure`, see [1934059](https://github.com/DaveGamble/cJSON/commit/1934059554b9a0971e00f79e96900f422cfdd114) + +Improvements: +* Add a note in the header about required buffer size when using `cJSON_PrintPreallocated`, see [4bfb8800](https://github.com/DaveGamble/cJSON/commit/4bfb88009342fb568295a7f6dc4b7fee74fbf022) + +1.4.3 (Mar 19, 2017) +===== +Fixes: +------ +* Fix compilation of the tests on 32 bit PowerPC and potentially other systems, see [4ec6e76](https://github.com/DaveGamble/cJSON/commit/4ec6e76ea2eec16f54b58e8c95b4c734e59481e4) +* Fix compilation with old GCC compilers (4.3+ were tested), see [227d33](https://github.com/DaveGamble/cJSON/commit/227d3398d6b967879761ebe02c1b63dbd6ea6e0d), [466eb8e](https://github.com/DaveGamble/cJSON/commit/466eb8e3f8a65080f2b3ca4a79ab7b72bd539dba), see also [#126](https://github.com/DaveGamble/cJSON/issues/126) + +1.4.2 (Mar 16, 2017) +===== +Fixes: +------ +* Fix minimum required cmake version, see [30e1e7a](https://github.com/DaveGamble/cJSON/commit/30e1e7af7c63db9b55f5a3cda977a6c032f0b132) +* Fix detection of supported compiler flags, see [76e5296](https://github.com/DaveGamble/cJSON/commit/76e5296d0d05ceb3018a9901639e0e171b44a557) +* Run `cJSON_test` and `cJSON_test_utils` along with unity tests, see [c597601](https://github.com/DaveGamble/cJSON/commit/c597601cf151a757dcf800548f18034d4ddfe2cb) + +1.4.1 (Mar 16, 2017) +===== +Fixes: +------ +* Make `print_number` abort with a failure in out of memory situations, see [cf1842](https://github.com/DaveGamble/cJSON/commit/cf1842dc6f64c49451a022308b4415e4d468be0a) + +1.4.0 (Mar 4, 2017) +===== +Features +-------- +* Functions to check the type of an item, see [#120](https://github.com/DaveGamble/cJSON/pull/120) +* Use dllexport on windows and fvisibility on Unix systems for public functions, see [#116](https://github.com/DaveGamble/cJSON/pull/116), thanks @mjerris +* Remove trailing zeroes from printed numbers, see [#123](https://github.com/DaveGamble/cJSON/pull/123) +* Expose the internal boolean type `cJSON_bool` in the header, see [2d3520e](https://github.com/DaveGamble/cJSON/commit/2d3520e0b9d0eb870e8886e8a21c571eeddbb310) + +Fixes +* Fix handling of NULL pointers in `cJSON_ArrayForEach`, see [b47d0e3](https://github.com/DaveGamble/cJSON/commit/b47d0e34caaef298edfb7bd09a72cfff21d231ff) +* Make it compile with GCC 7 (fix -Wimplicit-fallthrough warning), see [9d07917](https://github.com/DaveGamble/cJSON/commit/9d07917feb1b613544a7513d19233d4c851ad7ad) + +Other Improvements +* internally use realloc if available ([#110](https://github.com/DaveGamble/cJSON/pull/110)) +* builtin support for fuzzing with [afl](http://lcamtuf.coredump.cx/afl/) ([#111](https://github.com/DaveGamble/cJSON/pull/111)) +* unit tests for the print functions ([#112](https://github.com/DaveGamble/cJSON/pull/112)) +* Always use buffered printing ([#113](https://github.com/DaveGamble/cJSON/pull/113)) +* simplify the print functions ([#114](https://github.com/DaveGamble/cJSON/pull/114)) +* Add the compiler flags `-Wdouble-conversion`, `-Wparentheses` and `-Wcomma` ([#122](https://github.com/DaveGamble/cJSON/pull/122)) + +1.3.2 (Mar 1, 2017) +===== +Fixes: +------ +* Don't build the unity library if testing is disabled, see [#121](https://github.com/DaveGamble/cJSON/pull/121). Thanks @ffontaine + +1.3.1 (Feb 27, 2017) +===== +Fixes: +------ +* Bugfix release that fixes an out of bounds read, see [#118](https://github.com/DaveGamble/cJSON/pull/118). This shouldn't have any security implications. + +1.3.0 (Feb 17, 2017) +===== +This release includes a lot of rework in the parser and includes the Cunity unit testing framework, as well as some fixes. I increased the minor version number because there were quite a lot of internal changes. + +Features: +* New type for cJSON structs: `cJSON_Invalid`, see [#108](https://github.com/DaveGamble/cJSON/pull/108) + +Fixes: +------ +* runtime checks for a lot of potential integer overflows +* fix incorrect return in cJSON_PrintBuffered [cf9d57d](https://github.com/DaveGamble/cJSON/commit/cf9d57d56cac21fc59465b8d26cf29bf6d2a87b3) +* fix several potential issues found by [Coverity](https://scan.coverity.com/projects/cjson) +* fix potentially undefined behavior when assigning big numbers to `valueint` ([41e2837](https://github.com/DaveGamble/cJSON/commit/41e2837df1b1091643aff073f2313f6ff3cc10f4)) + * Numbers exceeding `INT_MAX` or lower than `INT_MIN` will be explicitly assigned to `valueint` as `INT_MAX` and `INT_MIN` respectively (saturation on overflow). + * fix the `cJSON_SetNumberValue` macro ([87f7727](https://github.com/DaveGamble/cJSON/commit/87f77274de6b3af00fb9b9a7f3b900ef382296c2)), this slightly changes the behavior, see commit message + +Introduce unit tests +-------------------- + +* Started writing unit tests with the [Cunity](https://github.com/ThrowTheSwitch/Unity) testing framework. Currently this covers the parser functions. + +Also: +* Support for running the tests with [Valgrind](http://valgrind.org) +* Support for compiling the tests with [AddressSanitizer](https://github.com/google/sanitizers) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html). +* `travis.yml` file for running unit tests on travis. (not enabled for the repository yet though [#102](https://github.com/DaveGamble/cJSON/issues/102) + +Simplifications +--------------- + +After having unit tests for the parser function in place, I started refactoring the parser functions (as well as others) and making them easier to read and maintain. +* Use `strtod` from the standard library for parsing numbers ([0747669](https://github.com/DaveGamble/cJSON/commit/074766997246481dfc72bfa78f07898a2716473f)) +* Use goto-fail in several parser functions ([#100](https://github.com/DaveGamble/cJSON/pull/100)) +* Rewrite/restructure all of the parsing functions to be easier to understand and have less code paths doing the same as another. ([#109](https://github.com/DaveGamble/cJSON/pull/109)) +* Simplify the buffer allocation strategy to always doubling the needed amount ([9f6fa94](https://github.com/DaveGamble/cJSON/commit/9f6fa94c91a87b71e4c6868dbf2ce431a48517b0)) +* Combined `cJSON_AddItemToObject` and `cJSON_AddItemToObjectCS` to one function ([cf862d](https://github.com/DaveGamble/cJSON/commit/cf862d0fed7f9407e4b046d78d3d8050d2080d12)) + +Other changes +------------- +* Prevent the usage of incompatible C and header versions via preprocessor directive ([123bb1](https://github.com/DaveGamble/cJSON/commit/123bb1af7bfae41d805337fef4b41045ef6c7d25)) +* Let CMake automatically detect compiler flags +* Add new compiler flags (`-Wundef`, `-Wswitch-default`, `-Wconversion`, `-fstack-protector-strong`) ([#98](https://github.com/DaveGamble/cJSON/pull/98)) +* Change internal sizes from `int` to `size_t` ([ecd5678](https://github.com/DaveGamble/cJSON/commit/ecd5678527a6bc422da694e5be9e9979878fe6a0)) +* Change internal strings from `char*` to `unsigned char*` ([28b9ba4](https://github.com/DaveGamble/cJSON/commit/28b9ba4334e0f7309e867e874a31f395c0ac2474)) +* Add `const` in more places + +1.2.1 (Jan 31, 2017) +===== +Fixes: +------ +* Fixes a potential null pointer dereference in cJSON_Utils, discovered using clang's static analyzer by @bnason-nf, see [#96](https://github.com/DaveGamble/cJSON/issues/96) + +1.2.0 (Jan 9, 2017) +===== +Features: +--------- +* Add a new type of cJSON item for raw JSON and support printing it. Thanks @loigu, see [#65](https://github.com/DaveGamble/cJSON/pull/65), [#90](https://github.com/DaveGamble/cJSON/pull/90) + +Fixes: +------ +* Compiler warning if const is casted away, Thanks @gatzka, see [#83](https://github.com/DaveGamble/cJSON/pull/83) +* Fix compile error with strict-overflow on PowerPC, see [#85](https://github.com/DaveGamble/cJSON/issues/85) +* Fix typo in the README, thanks @MicroJoe, see [#88](https://github.com/DaveGamble/cJSON/pull/88) +* Add compile flag for compatibility with C++ compilers + +1.1.0 (Dec 6, 2016) +===== +* Add a function `cJSON_PrintPreallocated` to print to a preallocated buffer, thanks @ChisholmKyle, see [#72](https://github.com/DaveGamble/cJSON/pull/72) +* More compiler warnings when using Clang or GCC, thanks @gatzka, see [#75](https://github.com/DaveGamble/cJSON/pull/75), [#78](https://github.com/DaveGamble/cJSON/pull/78) +* fixed a memory leak in `cJSON_Duplicate`, thanks @alperakcan, see [#81](https://github.com/DaveGamble/cJSON/pull/81) +* fix the `ENABLE_CUSTOM_COMPILER_FLAGS` cmake option + +1.0.2 (Nov 25, 2016) +===== +* Rename internal boolean type, see [#71](https://github.com/DaveGamble/cJSON/issues/71). + +1.0.1 (Nov 20, 2016) +===== +Small bugfix release. +* Fixes a bug with the use of the cJSON structs type in cJSON_Utils, see [d47339e](https://github.com/DaveGamble/cJSON/commit/d47339e2740360e6e0994527d5e4752007480f3a) +* improve code readability +* initialize all variables + +1.0.0 (Nov 17, 2016) +===== +This is the first official versioned release of cJSON. It provides an API version for the shared library and improved Makefile and CMake build files. diff --git a/managed_components/espressif__cjson/cJSON/CMakeLists.txt b/managed_components/espressif__cjson/cJSON/CMakeLists.txt new file mode 100644 index 0000000..59e4af5 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/CMakeLists.txt @@ -0,0 +1,279 @@ +set(CMAKE_LEGACY_CYGWIN_WIN32 0) +cmake_minimum_required(VERSION 3.5) + +project(cJSON + VERSION 1.7.19 + LANGUAGES C) + +cmake_policy(SET CMP0054 NEW) # set CMP0054 policy + +include(GNUInstallDirs) + +set(CJSON_VERSION_SO 1) +set(CJSON_UTILS_VERSION_SO 1) + +set(custom_compiler_flags) + +include(CheckCCompilerFlag) +option(ENABLE_CUSTOM_COMPILER_FLAGS "Enables custom compiler flags" ON) +if (ENABLE_CUSTOM_COMPILER_FLAGS) + if (("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") OR ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")) + list(APPEND custom_compiler_flags + -std=c89 + -pedantic + -Wall + -Wextra + -Werror + -Wstrict-prototypes + -Wwrite-strings + -Wshadow + -Winit-self + -Wcast-align + -Wformat=2 + -Wmissing-prototypes + -Wstrict-overflow=2 + -Wcast-qual + -Wundef + -Wswitch-default + -Wconversion + -Wc++-compat + -fstack-protector-strong + -Wcomma + -Wdouble-promotion + -Wparentheses + -Wformat-overflow + -Wunused-macros + -Wmissing-variable-declarations + -Wused-but-marked-unused + -Wswitch-enum + ) + elseif("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC") + # Disable warning c4001 - nonstandard extension 'single line comment' was used + # Define _CRT_SECURE_NO_WARNINGS to disable deprecation warnings for "insecure" C library functions + list(APPEND custom_compiler_flags + /GS + /Za + /sdl + /W4 + /wd4001 + /D_CRT_SECURE_NO_WARNINGS + ) + endif() +endif() + +option(ENABLE_SANITIZERS "Enables AddressSanitizer and UndefinedBehaviorSanitizer." OFF) +if (ENABLE_SANITIZERS) + list(APPEND custom_compiler_flags + -fno-omit-frame-pointer + -fsanitize=address + -fsanitize=undefined + -fsanitize=float-cast-overflow + -fsanitize-address-use-after-scope + -fsanitize=integer + -fno-sanitize-recover + ) +endif() + +option(ENABLE_SAFE_STACK "Enables the SafeStack instrumentation pass by the Code Pointer Integrity Project" OFF) +if (ENABLE_SAFE_STACK) + if (ENABLE_SANITIZERS) + message(FATAL_ERROR "ENABLE_SAFE_STACK cannot be used in combination with ENABLE_SANITIZERS") + endif() + list(APPEND custom_compiler_flags + -fsanitize=safe-stack + ) +endif() + +option(ENABLE_PUBLIC_SYMBOLS "Export library symbols." On) +if (ENABLE_PUBLIC_SYMBOLS) + list(APPEND custom_compiler_flags -fvisibility=hidden) + add_definitions(-DCJSON_EXPORT_SYMBOLS -DCJSON_API_VISIBILITY) +endif() +option(ENABLE_HIDDEN_SYMBOLS "Hide library symbols." Off) +if (ENABLE_HIDDEN_SYMBOLS) + add_definitions(-DCJSON_HIDE_SYMBOLS -UCJSON_API_VISIBILITY) +endif() + +# apply custom compiler flags +foreach(compiler_flag ${custom_compiler_flags}) + #remove problematic characters + string(REGEX REPLACE "[^a-zA-Z0-9]" "" current_variable ${compiler_flag}) + + CHECK_C_COMPILER_FLAG(${compiler_flag} "FLAG_SUPPORTED_${current_variable}") + if (FLAG_SUPPORTED_${current_variable}) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${compiler_flag}") + endif() +endforeach() + +option(BUILD_SHARED_LIBS "Build shared libraries" ON) +option(ENABLE_TARGET_EXPORT "Enable exporting of CMake targets. Disable when it causes problems!" ON) + +#cJSON +set(CJSON_LIB cjson) + +file(GLOB HEADERS cJSON.h) +set(SOURCES cJSON.c) + +option(BUILD_SHARED_AND_STATIC_LIBS "Build both shared and static libraries" Off) +option(CJSON_OVERRIDE_BUILD_SHARED_LIBS "Override BUILD_SHARED_LIBS with CJSON_BUILD_SHARED_LIBS" OFF) +option(CJSON_BUILD_SHARED_LIBS "Overrides BUILD_SHARED_LIBS if CJSON_OVERRIDE_BUILD_SHARED_LIBS is enabled" ON) +option(ENABLE_CJSON_VERSION_SO "Enables cJSON so version" ON) + +if ((CJSON_OVERRIDE_BUILD_SHARED_LIBS AND CJSON_BUILD_SHARED_LIBS) OR ((NOT CJSON_OVERRIDE_BUILD_SHARED_LIBS) AND BUILD_SHARED_LIBS)) + set(CJSON_LIBRARY_TYPE SHARED) +else() + set(CJSON_LIBRARY_TYPE STATIC) +endif() + + +if (NOT BUILD_SHARED_AND_STATIC_LIBS) + add_library("${CJSON_LIB}" "${CJSON_LIBRARY_TYPE}" "${HEADERS}" "${SOURCES}") +else() + # See https://cmake.org/Wiki/CMake_FAQ#How_do_I_make_my_shared_and_static_libraries_have_the_same_root_name.2C_but_different_suffixes.3F + add_library("${CJSON_LIB}" SHARED "${HEADERS}" "${SOURCES}") + add_library("${CJSON_LIB}-static" STATIC "${HEADERS}" "${SOURCES}") + set_target_properties("${CJSON_LIB}-static" PROPERTIES OUTPUT_NAME "${CJSON_LIB}") + set_target_properties("${CJSON_LIB}-static" PROPERTIES PREFIX "lib") +endif() +if (NOT WIN32) + target_link_libraries("${CJSON_LIB}" m) +endif() + +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson.pc.in" + "${CMAKE_CURRENT_BINARY_DIR}/libcjson.pc" @ONLY) + +install(FILES cJSON.h DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/cjson") +install (FILES "${CMAKE_CURRENT_BINARY_DIR}/libcjson.pc" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig") +install(TARGETS "${CJSON_LIB}" + EXPORT "${CJSON_LIB}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}" +) +if (BUILD_SHARED_AND_STATIC_LIBS) + install(TARGETS "${CJSON_LIB}-static" + EXPORT "${CJSON_LIB}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}" +) +endif() +if(ENABLE_TARGET_EXPORT) + # export library information for CMake projects + install(EXPORT "${CJSON_LIB}" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON") +endif() + +if(ENABLE_CJSON_VERSION_SO) + set_target_properties("${CJSON_LIB}" + PROPERTIES + SOVERSION "${CJSON_VERSION_SO}" + VERSION "${PROJECT_VERSION}") +endif() + +#cJSON_Utils +option(ENABLE_CJSON_UTILS "Enable building the cJSON_Utils library." OFF) +if(ENABLE_CJSON_UTILS) + set(CJSON_UTILS_LIB cjson_utils) + + file(GLOB HEADERS_UTILS cJSON_Utils.h) + set(SOURCES_UTILS cJSON_Utils.c) + + if (NOT BUILD_SHARED_AND_STATIC_LIBS) + add_library("${CJSON_UTILS_LIB}" "${CJSON_LIBRARY_TYPE}" "${HEADERS_UTILS}" "${SOURCES_UTILS}") + target_link_libraries("${CJSON_UTILS_LIB}" "${CJSON_LIB}") + else() + add_library("${CJSON_UTILS_LIB}" SHARED "${HEADERS_UTILS}" "${SOURCES_UTILS}") + target_link_libraries("${CJSON_UTILS_LIB}" "${CJSON_LIB}") + add_library("${CJSON_UTILS_LIB}-static" STATIC "${HEADERS_UTILS}" "${SOURCES_UTILS}") + target_link_libraries("${CJSON_UTILS_LIB}-static" "${CJSON_LIB}-static") + set_target_properties("${CJSON_UTILS_LIB}-static" PROPERTIES OUTPUT_NAME "${CJSON_UTILS_LIB}") + set_target_properties("${CJSON_UTILS_LIB}-static" PROPERTIES PREFIX "lib") + endif() + + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson_utils.pc.in" + "${CMAKE_CURRENT_BINARY_DIR}/libcjson_utils.pc" @ONLY) + + install(TARGETS "${CJSON_UTILS_LIB}" + EXPORT "${CJSON_UTILS_LIB}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}" + ) + if (BUILD_SHARED_AND_STATIC_LIBS) + install(TARGETS "${CJSON_UTILS_LIB}-static" + EXPORT "${CJSON_UTILS_LIB}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}" + ) + endif() + install(FILES cJSON_Utils.h DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/cjson") + install (FILES "${CMAKE_CURRENT_BINARY_DIR}/libcjson_utils.pc" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig") + if(ENABLE_TARGET_EXPORT) + # export library information for CMake projects + install(EXPORT "${CJSON_UTILS_LIB}" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON") + endif() + + if(ENABLE_CJSON_VERSION_SO) + set_target_properties("${CJSON_UTILS_LIB}" + PROPERTIES + SOVERSION "${CJSON_UTILS_VERSION_SO}" + VERSION "${PROJECT_VERSION}") + endif() +endif() + +# create the other package config files +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfig.cmake.in" + ${PROJECT_BINARY_DIR}/cJSONConfig.cmake @ONLY) +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfigVersion.cmake.in" + ${PROJECT_BINARY_DIR}/cJSONConfigVersion.cmake @ONLY) + +if(ENABLE_TARGET_EXPORT) + # Install package config files + install(FILES ${PROJECT_BINARY_DIR}/cJSONConfig.cmake + ${PROJECT_BINARY_DIR}/cJSONConfigVersion.cmake + DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON") +endif() + +option(ENABLE_CJSON_TEST "Enable building cJSON test" ON) +if(ENABLE_CJSON_TEST) + enable_testing() + + set(TEST_CJSON cJSON_test) + add_executable("${TEST_CJSON}" test.c) + target_link_libraries("${TEST_CJSON}" "${CJSON_LIB}") + + add_test(NAME ${TEST_CJSON} COMMAND "${CMAKE_CURRENT_BINARY_DIR}/${TEST_CJSON}") + + # Disable -fsanitize=float-divide-by-zero for cJSON_test + if (FLAG_SUPPORTED_fsanitizefloatdividebyzero) + if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-sanitize=float-divide-by-zero") + else() + target_compile_options(${TEST_CJSON} PRIVATE "-fno-sanitize=float-divide-by-zero") + endif() + endif() + + #"check" target that automatically builds everything and runs the tests + add_custom_target(check + COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure + DEPENDS ${TEST_CJSON}) +endif() + +#Create the uninstall target +option(ENABLE_CJSON_UNINSTALL "Enable creating uninstall target" ON) +if(ENABLE_CJSON_UNINSTALL) + add_custom_target(uninstall "${CMAKE_COMMAND}" -P + "${PROJECT_SOURCE_DIR}/library_config/uninstall.cmake") +endif() + +# Enable the use of locales +option(ENABLE_LOCALES "Enable the use of locales" ON) +if(ENABLE_LOCALES) + add_definitions(-DENABLE_LOCALES) +endif() + +add_subdirectory(tests) +add_subdirectory(fuzzing) diff --git a/managed_components/espressif__cjson/cJSON/CONTRIBUTORS.md b/managed_components/espressif__cjson/cJSON/CONTRIBUTORS.md new file mode 100644 index 0000000..b9db178 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/CONTRIBUTORS.md @@ -0,0 +1,97 @@ +Contributors +============ + +Original Author: +- [Dave Gamble](https://github.com/DaveGamble) + +Current Maintainer: +- [Max Bruckner](https://github.com/FSMaxB) +- [Alan Wang](https://github.com/Alanscut) + +Contributors: +* [Ajay Bhargav](https://github.com/ajaybhargav) +* [AlexanderVasiljev](https://github.com/AlexanderVasiljev) +* [Alper Akcan](https://github.com/alperakcan) +* [Andrew Tang](https://github.com/singku) +* [Andy](https://github.com/mlh0101) +* [Anton Sergeev](https://github.com/anton-sergeev) +* [Benbuck Nason](https://github.com/bnason-nf) +* [Bernt Johan Damslora](https://github.com/bjda) +* [Bob Kocisko](https://github.com/bobkocisko) +* [Christian Schulze](https://github.com/ChristianSch) +* [Casperinous](https://github.com/Casperinous) +* [ChenYuan](https://github.com/zjuchenyuan) +* [Debora Grosse](https://github.com/DeboraG) +* [dieyushi](https://github.com/dieyushi) +* [Dōngwén Huáng (黄东文)](https://github.com/DongwenHuang) +* [Dominik](https://github.com/DL6ER) +* [Donough Liu](https://github.com/ldm0) +* [Erez Oxman](https://github.com/erez-o) +* Eswar Yaganti +* [Evan Todd](https://github.com/etodd) +* [Fabrice Fontaine](https://github.com/ffontaine) +* Ian Mobley +* Irwan Djadjadi +* [hopper-vul](https://github.com/hopper-vul) +* [HuKeping](https://github.com/HuKeping) +* [IvanVoid](https://github.com/npi3pak) +* [Jakub Wilk](https://github.com/jwilk) +* [Jiri Zouhar](https://github.com/loigu) +* [Jonathan Fether](https://github.com/jfether) +* [Joshua Arulsamy](https://github.com/jarulsamy) +* [Julian Ste](https://github.com/julian-st) +* [Julián Vásquez](https://github.com/juvasquezg) +* [Junbo Zheng](https://github.com/Junbo-Zheng) +* [Kevin Branigan](https://github.com/kbranigan) +* [Kevin Sapper](https://github.com/sappo) +* [Kyle Chisholm](https://github.com/ChisholmKyle) +* [Linus Wallgren](https://github.com/ecksun) +* [Luo Jin](https://github.com/Up-wind) +* [Max](https://github.com/maebex) +* [MaxBrandtner](https://github.com/MaxBrandtner) +* [Mateusz Szafoni](https://github.com/raiden00pl) +* Mike Pontillo +* [miaoerduo](https://github.com/miaoerduo) +* [mohawk2](https://github.com/mohawk2) +* [Mike Jerris](https://github.com/mjerris) +* [Mike Robinson](https://github.com/mhrobinson) +* [Moorthy](https://github.com/moorthy-bs) +* [myd7349](https://github.com/myd7349) +* [NancyLi1013](https://github.com/NancyLi1013) +* [Orri](https://github.com/sbvoxel) +* Paulo Antonio Alvarez +* [Paweł Malowany](https://github.com/PawelMalowany) +* [Pawel Winogrodzki](https://github.com/PawelWMS) +* [prefetchnta](https://github.com/prefetchnta) +* [Rafael Leal Dias](https://github.com/rafaeldias) +* [Randy](https://github.com/randy408) +* [raiden00pl](https://github.com/raiden00pl) +* [Robin Mallinson](https://github.com/rmallins) +* [Rod Vagg](https://github.com/rvagg) +* [Roland Meertens](https://github.com/rmeertens) +* [Romain Porte](https://github.com/MicroJoe) +* [SANJEEV BA](https://github.com/basanjeev) +* [Sang-Heon Jeon](https://github.com/lntuition) +* [Sayan Bandyopadhyay](https://github.com/saynb) +* [Simon Sobisch](https://github.com/GitMensch) +* [Simon Ricaldone](https://github.com/simon-p-r) +* [Stoian Ivanov](https://github.com/sdrsdr) +* [SuperH-0630](https://github.com/SuperH-0630) +* [Square789](https://github.com/Square789) +* [Stephan Gatzka](https://github.com/gatzka) +* [Tony Langhammer](https://github.com/BigBrainAFK) +* [Vemake](https://github.com/vemakereporter) +* [vwvw](https://github.com/vwvw) +* [warmsocks](https://github.com/warmsocks) +* [Wei Tan](https://github.com/tan-wei) +* [Weston Schmidt](https://github.com/schmidtw) +* [xiaomianhehe](https://github.com/xiaomianhehe) +* [yangfl](https://github.com/yangfl) +* [yuta-oxo](https://github.com/yuta-oxo) +* [Zach Hindes](https://github.com/zhindes) +* [Zhao Zhixu](https://github.com/zhaozhixu) +* [10km](https://github.com/10km) + +And probably more people on [SourceForge](https://sourceforge.net/p/cjson/bugs/search/?q=status%3Aclosed-rejected+or+status%3Aclosed-out-of-date+or+status%3Awont-fix+or+status%3Aclosed-fixed+or+status%3Aclosed&page=0) + +Also thanks to all the people who reported bugs and suggested new features. diff --git a/managed_components/espressif__cjson/cJSON/LICENSE b/managed_components/espressif__cjson/cJSON/LICENSE new file mode 100644 index 0000000..78deb04 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/managed_components/espressif__cjson/cJSON/Makefile b/managed_components/espressif__cjson/cJSON/Makefile new file mode 100644 index 0000000..e2676d2 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/Makefile @@ -0,0 +1,163 @@ +CJSON_OBJ = cJSON.o +UTILS_OBJ = cJSON_Utils.o +CJSON_LIBNAME = libcjson +UTILS_LIBNAME = libcjson_utils +CJSON_TEST = cJSON_test + +CJSON_TEST_SRC = cJSON.c test.c + +LDLIBS = -lm + +LIBVERSION = 1.7.19 +CJSON_SOVERSION = 1 +UTILS_SOVERSION = 1 + +CJSON_SO_LDFLAG=-Wl,-soname=$(CJSON_LIBNAME).so.$(CJSON_SOVERSION) +UTILS_SO_LDFLAG=-Wl,-soname=$(UTILS_LIBNAME).so.$(UTILS_SOVERSION) + +PREFIX ?= /usr/local +INCLUDE_PATH ?= include/cjson +LIBRARY_PATH ?= lib + +INSTALL_INCLUDE_PATH = $(DESTDIR)$(PREFIX)/$(INCLUDE_PATH) +INSTALL_LIBRARY_PATH = $(DESTDIR)$(PREFIX)/$(LIBRARY_PATH) + +INSTALL ?= cp -a + +CC = gcc -std=c89 + +# validate gcc version for use fstack-protector-strong +MIN_GCC_VERSION = "4.9" +GCC_VERSION := "`$(CC) -dumpversion`" +IS_GCC_ABOVE_MIN_VERSION := $(shell expr "$(GCC_VERSION)" ">=" "$(MIN_GCC_VERSION)") +ifeq "$(IS_GCC_ABOVE_MIN_VERSION)" "1" + CFLAGS += -fstack-protector-strong +else + CFLAGS += -fstack-protector +endif + +PIC_FLAGS = -fPIC +R_CFLAGS = $(PIC_FLAGS) -pedantic -Wall -Werror -Wstrict-prototypes -Wwrite-strings -Wshadow -Winit-self -Wcast-align -Wformat=2 -Wmissing-prototypes -Wstrict-overflow=2 -Wcast-qual -Wc++-compat -Wundef -Wswitch-default -Wconversion $(CFLAGS) + +uname := $(shell sh -c 'uname -s 2>/dev/null || echo false') + +#library file extensions +SHARED = so +STATIC = a + +## create dynamic (shared) library on Darwin (base OS for MacOSX and IOS) +ifeq (Darwin, $(uname)) + SHARED = dylib + CJSON_SO_LDFLAG = "" + UTILS_SO_LDFLAG = "" +endif + +#cJSON library names +CJSON_SHARED = $(CJSON_LIBNAME).$(SHARED) +CJSON_SHARED_VERSION = $(CJSON_LIBNAME).$(SHARED).$(LIBVERSION) +CJSON_SHARED_SO = $(CJSON_LIBNAME).$(SHARED).$(CJSON_SOVERSION) +CJSON_STATIC = $(CJSON_LIBNAME).$(STATIC) + +#cJSON_Utils library names +UTILS_SHARED = $(UTILS_LIBNAME).$(SHARED) +UTILS_SHARED_VERSION = $(UTILS_LIBNAME).$(SHARED).$(LIBVERSION) +UTILS_SHARED_SO = $(UTILS_LIBNAME).$(SHARED).$(UTILS_SOVERSION) +UTILS_STATIC = $(UTILS_LIBNAME).$(STATIC) + +SHARED_CMD = $(CC) -shared -o + +.PHONY: all shared static tests clean install + +all: shared static tests + +shared: $(CJSON_SHARED) $(UTILS_SHARED) + +static: $(CJSON_STATIC) $(UTILS_STATIC) + +tests: $(CJSON_TEST) + +test: tests + ./$(CJSON_TEST) + +.c.o: + $(CC) -c $(R_CFLAGS) $< + +#tests +#cJSON +$(CJSON_TEST): $(CJSON_TEST_SRC) cJSON.h + $(CC) $(R_CFLAGS) $(CJSON_TEST_SRC) -o $@ $(LDLIBS) -I. + +#static libraries +#cJSON +$(CJSON_STATIC): $(CJSON_OBJ) + $(AR) rcs $@ $< +#cJSON_Utils +$(UTILS_STATIC): $(UTILS_OBJ) + $(AR) rcs $@ $< + +#shared libraries .so.1.0.0 +#cJSON +$(CJSON_SHARED_VERSION): $(CJSON_OBJ) + $(CC) -shared -o $@ $< $(CJSON_SO_LDFLAG) $(LDFLAGS) +#cJSON_Utils +$(UTILS_SHARED_VERSION): $(UTILS_OBJ) + $(CC) -shared -o $@ $< $(CJSON_OBJ) $(UTILS_SO_LDFLAG) $(LDFLAGS) + +#objects +#cJSON +$(CJSON_OBJ): cJSON.c cJSON.h +#cJSON_Utils +$(UTILS_OBJ): cJSON_Utils.c cJSON_Utils.h cJSON.h + + +#links .so -> .so.1 -> .so.1.0.0 +#cJSON +$(CJSON_SHARED_SO): $(CJSON_SHARED_VERSION) + ln -s $(CJSON_SHARED_VERSION) $(CJSON_SHARED_SO) +$(CJSON_SHARED): $(CJSON_SHARED_SO) + ln -s $(CJSON_SHARED_SO) $(CJSON_SHARED) +#cJSON_Utils +$(UTILS_SHARED_SO): $(UTILS_SHARED_VERSION) + ln -s $(UTILS_SHARED_VERSION) $(UTILS_SHARED_SO) +$(UTILS_SHARED): $(UTILS_SHARED_SO) + ln -s $(UTILS_SHARED_SO) $(UTILS_SHARED) + +#install +#cJSON +install-cjson: + mkdir -p $(INSTALL_LIBRARY_PATH) $(INSTALL_INCLUDE_PATH) + $(INSTALL) cJSON.h $(INSTALL_INCLUDE_PATH) + $(INSTALL) $(CJSON_SHARED) $(CJSON_SHARED_SO) $(CJSON_SHARED_VERSION) $(INSTALL_LIBRARY_PATH) +#cJSON_Utils +install-utils: install-cjson + $(INSTALL) cJSON_Utils.h $(INSTALL_INCLUDE_PATH) + $(INSTALL) $(UTILS_SHARED) $(UTILS_SHARED_SO) $(UTILS_SHARED_VERSION) $(INSTALL_LIBRARY_PATH) + +install: install-cjson install-utils + +#uninstall +#cJSON +uninstall-cjson: uninstall-utils + $(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED) + $(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED_VERSION) + $(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED_SO) + $(RM) $(INSTALL_INCLUDE_PATH)/cJSON.h + +#cJSON_Utils +uninstall-utils: + $(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED) + $(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED_VERSION) + $(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED_SO) + $(RM) $(INSTALL_INCLUDE_PATH)/cJSON_Utils.h + +remove-dir: + $(if $(wildcard $(INSTALL_LIBRARY_PATH)/*.*),,rmdir $(INSTALL_LIBRARY_PATH)) + $(if $(wildcard $(INSTALL_INCLUDE_PATH)/*.*),,rmdir $(INSTALL_INCLUDE_PATH)) + +uninstall: uninstall-utils uninstall-cjson remove-dir + +clean: + $(RM) $(CJSON_OBJ) $(UTILS_OBJ) #delete object files + $(RM) $(CJSON_SHARED) $(CJSON_SHARED_VERSION) $(CJSON_SHARED_SO) $(CJSON_STATIC) #delete cJSON + $(RM) $(UTILS_SHARED) $(UTILS_SHARED_VERSION) $(UTILS_SHARED_SO) $(UTILS_STATIC) #delete cJSON_Utils + $(RM) $(CJSON_TEST) #delete test diff --git a/managed_components/espressif__cjson/cJSON/README.md b/managed_components/espressif__cjson/cJSON/README.md new file mode 100644 index 0000000..9c7ed14 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/README.md @@ -0,0 +1,590 @@ +# cJSON + +Ultralightweight JSON parser in ANSI C. + +## Table of contents +* [License](#license) +* [Usage](#usage) + * [Welcome to cJSON](#welcome-to-cjson) + * [Building](#building) + * [Copying the source](#copying-the-source) + * [CMake](#cmake) + * [Makefile](#makefile) + * [Meson](#meson) + * [Vcpkg](#Vcpkg) + * [Including cJSON](#including-cjson) + * [Data Structure](#data-structure) + * [Working with the data structure](#working-with-the-data-structure) + * [Basic types](#basic-types) + * [Arrays](#arrays) + * [Objects](#objects) + * [Parsing JSON](#parsing-json) + * [Printing JSON](#printing-json) + * [Example](#example) + * [Printing](#printing) + * [Parsing](#parsing) + * [Caveats](#caveats) + * [Zero Character](#zero-character) + * [Character Encoding](#character-encoding) + * [C Standard](#c-standard) + * [Floating Point Numbers](#floating-point-numbers) + * [Deep Nesting Of Arrays And Objects](#deep-nesting-of-arrays-and-objects) + * [Thread Safety](#thread-safety) + * [Case Sensitivity](#case-sensitivity) + * [Duplicate Object Members](#duplicate-object-members) + * [Enjoy cJSON!](#enjoy-cjson) + +## License + +MIT License + +> Copyright (c) 2009-2017 Dave Gamble and cJSON contributors +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +## Usage + +### Welcome to cJSON. + +cJSON aims to be the dumbest possible parser that you can get your job done with. +It's a single file of C, and a single header file. + +JSON is described best here: http://www.json.org/ +It's like XML, but fat-free. You use it to move data around, store things, or just +generally represent your program's state. + +As a library, cJSON exists to take away as much legwork as it can, but not get in your way. +As a point of pragmatism (i.e. ignoring the truth), I'm going to say that you can use it +in one of two modes: Auto and Manual. Let's have a quick run-through. + +I lifted some JSON from this page: http://www.json.org/fatfree.html +That page inspired me to write cJSON, which is a parser that tries to share the same +philosophy as JSON itself. Simple, dumb, out of the way. + +### Building + +There are several ways to incorporate cJSON into your project. + +#### copying the source + +Because the entire library is only one C file and one header file, you can just copy `cJSON.h` and `cJSON.c` to your projects source and start using it. + +cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible. + +#### CMake + +With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 3.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a `build` directory and run CMake inside it. + +``` +mkdir build +cd build +cmake .. +``` + +This will create a Makefile and a bunch of other files. You can then compile it: + +``` +make +``` + +And install it with `make install` if you want. By default it installs the headers `/usr/local/include/cjson` and the libraries to `/usr/local/lib`. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library. + +You can change the build process with a list of different options that you can pass to CMake. Turn them on with `On` and off with `Off`: + +* `-DENABLE_CJSON_TEST=On`: Enable building the tests. (on by default) +* `-DENABLE_CJSON_UTILS=On`: Enable building cJSON_Utils. (off by default) +* `-DENABLE_TARGET_EXPORT=On`: Enable the export of CMake targets. Turn off if it makes problems. (on by default) +* `-DENABLE_CUSTOM_COMPILER_FLAGS=On`: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default) +* `-DENABLE_VALGRIND=On`: Run tests with [valgrind](http://valgrind.org). (off by default) +* `-DENABLE_SANITIZERS=On`: Compile cJSON with [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) enabled (if possible). (off by default) +* `-DENABLE_SAFE_STACK`: Enable the [SafeStack](https://clang.llvm.org/docs/SafeStack.html) instrumentation pass. Currently only works with the Clang compiler. (off by default) +* `-DBUILD_SHARED_LIBS=On`: Build the shared libraries. (on by default) +* `-DBUILD_SHARED_AND_STATIC_LIBS=On`: Build both shared and static libraries. (off by default) +* `-DCMAKE_INSTALL_PREFIX=/usr`: Set a prefix for the installation. +* `-DENABLE_LOCALES=On`: Enable the usage of localeconv method. ( on by default ) +* `-DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On`: Enable overriding the value of `BUILD_SHARED_LIBS` with `-DCJSON_BUILD_SHARED_LIBS`. +* `-DENABLE_CJSON_VERSION_SO`: Enable cJSON so version. ( on by default ) + +If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example: +``` +mkdir build +cd build +cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr +make +make DESTDIR=$pkgdir install +``` + +On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows. + +#### Makefile + +**NOTE:** This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs. + +If you don't have CMake available, but still have GNU make. You can use the makefile to build cJSON: + +Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite). + +``` +make all +``` + +If you want, you can install the compiled library to your system using `make install`. By default it will install the headers in `/usr/local/include/cjson` and the libraries in `/usr/local/lib`. But you can change this behavior by setting the `PREFIX` and `DESTDIR` variables: `make PREFIX=/usr DESTDIR=temp install`. And uninstall them with: `make PREFIX=/usr DESTDIR=temp uninstall`. + +#### Meson + +To make cjson work in a project using meson, the libcjson dependency has to be included: + +```meson +project('c-json-example', 'c') + +cjson = dependency('libcjson') + +example = executable( + 'example', + 'example.c', + dependencies: [cjson], +) +``` + + +#### Vcpkg + +You can download and install cJSON using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: +``` +git clone https://github.com/Microsoft/vcpkg.git +cd vcpkg +./bootstrap-vcpkg.sh +./vcpkg integrate install +vcpkg install cjson +``` + +The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + +### Including cJSON + +If you installed it via CMake or the Makefile, you can include cJSON like this: + +```c +#include +``` + +### Data Structure + +cJSON represents JSON data using the `cJSON` struct data type: + +```c +/* The cJSON structure: */ +typedef struct cJSON +{ + struct cJSON *next; + struct cJSON *prev; + struct cJSON *child; + int type; + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + double valuedouble; + char *string; +} cJSON; +``` + +An item of this type represents a JSON value. The type is stored in `type` as a bit-flag (**this means that you cannot find out the type by just comparing the value of `type`**). + +To check the type of an item, use the corresponding `cJSON_Is...` function. It does a `NULL` check followed by a type check and returns a boolean value if the item is of this type. + +The type can be one of the following: + +* `cJSON_Invalid` (check with `cJSON_IsInvalid`): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes. +* `cJSON_False` (check with `cJSON_IsFalse`): Represents a `false` boolean value. You can also check for boolean values in general with `cJSON_IsBool`. +* `cJSON_True` (check with `cJSON_IsTrue`): Represents a `true` boolean value. You can also check for boolean values in general with `cJSON_IsBool`. +* `cJSON_NULL` (check with `cJSON_IsNull`): Represents a `null` value. +* `cJSON_Number` (check with `cJSON_IsNumber`): Represents a number value. The value is stored as a double in `valuedouble` and also in `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`. +* `cJSON_String` (check with `cJSON_IsString`): Represents a string value. It is stored in the form of a zero terminated string in `valuestring`. +* `cJSON_Array` (check with `cJSON_IsArray`): Represent an array value. This is implemented by pointing `child` to a linked list of `cJSON` items that represent the values in the array. The elements are linked together using `next` and `prev`, where the first element has `prev.next == NULL` and the last element `next == NULL`. +* `cJSON_Object` (check with `cJSON_IsObject`): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in `string`. +* `cJSON_Raw` (check with `cJSON_IsRaw`): Represents any kind of JSON that is stored as a zero terminated array of characters in `valuestring`. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn't check if it is valid JSON. + +Additionally there are the following two flags: + +* `cJSON_IsReference`: Specifies that the item that `child` points to and/or `valuestring` is not owned by this item, it is only a reference. So `cJSON_Delete` and other functions will only deallocate this item, not its `child`/`valuestring`. +* `cJSON_StringIsConst`: This means that `string` points to a constant string. This means that `cJSON_Delete` and other functions will not try to deallocate `string`. + +### Working with the data structure + +For every value type there is a `cJSON_Create...` function that can be used to create an item of that type. +All of these will allocate a `cJSON` struct that can later be deleted with `cJSON_Delete`. +Note that you have to delete them at some point, otherwise you will get a memory leak. +**Important**: If you have added an item to an array or an object already, you **mustn't** delete it with `cJSON_Delete`. Adding it to an array or object transfers its ownership so that when that array or object is deleted, +it gets deleted as well. You also could use `cJSON_SetValuestring` to change a `cJSON_String`'s `valuestring`, and you needn't to free the previous `valuestring` manually. + +#### Basic types + +* **null** is created with `cJSON_CreateNull` +* **booleans** are created with `cJSON_CreateTrue`, `cJSON_CreateFalse` or `cJSON_CreateBool` +* **numbers** are created with `cJSON_CreateNumber`. This will set both `valuedouble` and `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint` +* **strings** are created with `cJSON_CreateString` (copies the string) or with `cJSON_CreateStringReference` (directly points to the string. This means that `valuestring` won't be deleted by `cJSON_Delete` and you are responsible for its lifetime, useful for constants) + +#### Arrays + +You can create an empty array with `cJSON_CreateArray`. `cJSON_CreateArrayReference` can be used to create an array that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`. + +To add items to an array, use `cJSON_AddItemToArray` to append items to the end. +Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another item, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere. +To insert items in the middle, use `cJSON_InsertItemInArray`. It will insert an item at the given 0 based index and shift all the existing items to the right. + +If you want to take an item out of an array at a given index and continue using it, use `cJSON_DetachItemFromArray`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak. + +Deleting items is done with `cJSON_DeleteItemFromArray`. It works like `cJSON_DetachItemFromArray`, but deletes the detached item via `cJSON_Delete`. + +You can also replace an item in an array in place. Either with `cJSON_ReplaceItemInArray` using an index or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place. + +To get the size of an array, use `cJSON_GetArraySize`. Use `cJSON_GetArrayItem` to get an element at a given index. + +Because an array is stored as a linked list, iterating it via index is inefficient (`O(n²)`), so you can iterate over an array using the `cJSON_ArrayForEach` macro in `O(n)` time complexity. + +#### Objects + +You can create an empty object with `cJSON_CreateObject`. `cJSON_CreateObjectReference` can be used to create an object that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`. + +To add items to an object, use `cJSON_AddItemToObject`. Use `cJSON_AddItemToObjectCS` to add an item to an object with a name that is a constant or reference (key of the item, `string` in the `cJSON` struct), so that it doesn't get freed by `cJSON_Delete`. +Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another object, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere. + +If you want to take an item out of an object, use `cJSON_DetachItemFromObjectCaseSensitive`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak. + +Deleting items is done with `cJSON_DeleteItemFromObjectCaseSensitive`. It works like `cJSON_DetachItemFromObjectCaseSensitive` followed by `cJSON_Delete`. + +You can also replace an item in an object in place. Either with `cJSON_ReplaceItemInObjectCaseSensitive` using a key or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place. + +To get the size of an object, you can use `cJSON_GetArraySize`, this works because internally objects are stored as arrays. + +If you want to access an item in an object, use `cJSON_GetObjectItemCaseSensitive`. + +To iterate over an object, you can use the `cJSON_ArrayForEach` macro the same way as for arrays. + +cJSON also provides convenient helper functions for quickly creating a new item and adding it to an object, like `cJSON_AddNullToObject`. They return a pointer to the new item or `NULL` if they failed. + +### Parsing JSON + +Given some JSON in a zero terminated string, you can parse it with `cJSON_Parse`. + +```c +cJSON *json = cJSON_Parse(string); +``` + +Given some JSON in a string (whether zero terminated or not), you can parse it with `cJSON_ParseWithLength`. + +```c +cJSON *json = cJSON_ParseWithLength(string, buffer_length); +``` + +It will parse the JSON and allocate a tree of `cJSON` items that represents it. Once it returns, you are fully responsible for deallocating it after use with `cJSON_Delete`. + +The allocator used by `cJSON_Parse` is `malloc` and `free` by default but can be changed (globally) with `cJSON_InitHooks`. + +If an error occurs a pointer to the position of the error in the input string can be accessed using `cJSON_GetErrorPtr`. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use `cJSON_ParseWithOpts` with `return_parse_end`. +By default, characters in the input string that follow the parsed JSON will not be considered as an error. + +If you want more options, use `cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)`. +`return_parse_end` returns a pointer to the end of the JSON in the input string or the position that an error occurs at (thereby replacing `cJSON_GetErrorPtr` in a thread safe way). `require_null_terminated`, if set to `1` will make it an error if the input string contains data after the JSON. + +If you want more options giving buffer length, use `cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)`. + +### Printing JSON + +Given a tree of `cJSON` items, you can print them as a string using `cJSON_Print`. + +```c +char *string = cJSON_Print(json); +``` + +It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually `free`, depends on what has been set with `cJSON_InitHooks`). + +`cJSON_Print` will print with whitespace for formatting. If you want to print without formatting, use `cJSON_PrintUnformatted`. + +If you have a rough idea of how big your resulting string will be, you can use `cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)`. `fmt` is a boolean to turn formatting with whitespace on and off. `prebuffer` specifies the first buffer size to use for printing. `cJSON_Print` currently uses 256 bytes for its first buffer size. Once printing runs out of space, a new buffer is allocated and the old gets copied over before printing is continued. + +These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and its length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough. + +### Example + +In this example we want to build and parse the following JSON: + +```json +{ + "name": "Awesome 4K", + "resolutions": [ + { + "width": 1280, + "height": 720 + }, + { + "width": 1920, + "height": 1080 + }, + { + "width": 3840, + "height": 2160 + } + ] +} +``` + +#### Printing + +Let's build the above JSON and print it to a string: + +```c +//create a monitor with a list of supported resolutions +//NOTE: Returns a heap allocated string, you are required to free it after use. +char *create_monitor(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *name = NULL; + cJSON *resolutions = NULL; + cJSON *resolution = NULL; + cJSON *width = NULL; + cJSON *height = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + if (monitor == NULL) + { + goto end; + } + + name = cJSON_CreateString("Awesome 4K"); + if (name == NULL) + { + goto end; + } + /* after creation was successful, immediately add it to the monitor, + * thereby transferring ownership of the pointer to it */ + cJSON_AddItemToObject(monitor, "name", name); + + resolutions = cJSON_CreateArray(); + if (resolutions == NULL) + { + goto end; + } + cJSON_AddItemToObject(monitor, "resolutions", resolutions); + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + resolution = cJSON_CreateObject(); + if (resolution == NULL) + { + goto end; + } + cJSON_AddItemToArray(resolutions, resolution); + + width = cJSON_CreateNumber(resolution_numbers[index][0]); + if (width == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "width", width); + + height = cJSON_CreateNumber(resolution_numbers[index][1]); + if (height == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "height", height); + } + + string = cJSON_Print(monitor); + if (string == NULL) + { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} +``` + +Alternatively we can use the `cJSON_Add...ToObject` helper functions to make our lives a little easier: + +```c +//NOTE: Returns a heap allocated string, you are required to free it after use. +char *create_monitor_with_helpers(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *resolutions = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + + if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL) + { + goto end; + } + + resolutions = cJSON_AddArrayToObject(monitor, "resolutions"); + if (resolutions == NULL) + { + goto end; + } + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + cJSON *resolution = cJSON_CreateObject(); + + if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL) + { + goto end; + } + + if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL) + { + goto end; + } + + cJSON_AddItemToArray(resolutions, resolution); + } + + string = cJSON_Print(monitor); + if (string == NULL) + { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} +``` + +#### Parsing + +In this example we will parse a JSON in the above format and check if the monitor supports a Full HD resolution while printing some diagnostic output: + +```c +/* return 1 if the monitor supports full hd, 0 otherwise */ +int supports_full_hd(const char * const monitor) +{ + const cJSON *resolution = NULL; + const cJSON *resolutions = NULL; + const cJSON *name = NULL; + int status = 0; + cJSON *monitor_json = cJSON_Parse(monitor); + if (monitor_json == NULL) + { + const char *error_ptr = cJSON_GetErrorPtr(); + if (error_ptr != NULL) + { + fprintf(stderr, "Error before: %s\n", error_ptr); + } + status = 0; + goto end; + } + + name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name"); + if (cJSON_IsString(name) && (name->valuestring != NULL)) + { + printf("Checking monitor \"%s\"\n", name->valuestring); + } + + resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions"); + cJSON_ArrayForEach(resolution, resolutions) + { + cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width"); + cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height"); + + if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height)) + { + status = 0; + goto end; + } + + if ((width->valuedouble == 1920) && (height->valuedouble == 1080)) + { + status = 1; + goto end; + } + } + +end: + cJSON_Delete(monitor_json); + return status; +} +``` + +Note that there are no NULL checks except for the result of `cJSON_Parse` because `cJSON_GetObjectItemCaseSensitive` checks for `NULL` inputs already, so a `NULL` value is just propagated and `cJSON_IsNumber` and `cJSON_IsString` return `0` if the input is `NULL`. + +### Caveats + +#### Zero Character + +cJSON doesn't support strings that contain the zero character `'\0'` or `\u0000`. This is impossible with the current API because strings are zero terminated. + +#### Character Encoding + +cJSON only supports UTF-8 encoded input. In most cases it doesn't reject invalid UTF-8 as input though, it just propagates it through as is. As long as the input doesn't contain invalid UTF-8, the output will always be valid UTF-8. + +#### C Standard + +cJSON is written in ANSI C (or C89, C90). If your compiler or C library doesn't follow this standard, correct behavior is not guaranteed. + +NOTE: ANSI C is not C++ therefore it shouldn't be compiled with a C++ compiler. You can compile it with a C compiler and link it with your C++ code however. Although compiling with a C++ compiler might work, correct behavior is not guaranteed. + +#### Floating Point Numbers + +cJSON does not officially support any `double` implementations other than IEEE754 double precision floating point numbers. It might still work with other implementations but bugs with these will be considered invalid. + +The maximum length of a floating point literal that cJSON supports is currently 63 characters. + +#### Deep Nesting Of Arrays And Objects + +cJSON doesn't support arrays and objects that are nested too deeply because this would result in a stack overflow. To prevent this cJSON limits the depth to `CJSON_NESTING_LIMIT` which is 1000 by default but can be changed at compile time. + +#### Thread Safety + +In general cJSON is **not thread safe**. + +However it is thread safe under the following conditions: + +* `cJSON_GetErrorPtr` is never used (the `return_parse_end` parameter of `cJSON_ParseWithOpts` can be used instead) +* `cJSON_InitHooks` is only ever called before using cJSON in any threads. +* `setlocale` is never called before all calls to cJSON functions have returned. + +#### Case Sensitivity + +When cJSON was originally created, it didn't follow the JSON standard and didn't make a distinction between uppercase and lowercase letters. If you want the correct, standard compliant, behavior, you need to use the `CaseSensitive` functions where available. + +#### Duplicate Object Members + +cJSON supports parsing and printing JSON that contains objects that have multiple members with the same name. `cJSON_GetObjectItemCaseSensitive` however will always only return the first one. + +# Enjoy cJSON! + +- Dave Gamble (original author) +- Max Bruckner and Alan Wang (current maintainer) +- and the other [cJSON contributors](CONTRIBUTORS.md) diff --git a/managed_components/espressif__cjson/cJSON/SECURITY.md b/managed_components/espressif__cjson/cJSON/SECURITY.md new file mode 100644 index 0000000..33d99a2 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/SECURITY.md @@ -0,0 +1,11 @@ +# Security Policy + +## Supported Versions + +Security is of the highest importance and all security vulnerabilities or suspected security vulnerabilities should be reported to cjson team privately, to minimize attacks against current users of cjson before they are fixed. Vulnerabilities will be investigated and patched on the next patch (or minor) release as soon as possible. This information could be kept entirely internal to the project. + +## Reporting a Vulnerability + +If you know of a publicly disclosed security vulnerability for cjson, please IMMEDIATELY contact wp_scut@163.com and peterlee@apache.org to inform the cjson Team. + +IMPORTANT: Do not file public issues on GitHub for security vulnerabilities. diff --git a/managed_components/espressif__cjson/cJSON/appveyor.yml b/managed_components/espressif__cjson/cJSON/appveyor.yml new file mode 100644 index 0000000..464bf03 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/appveyor.yml @@ -0,0 +1,86 @@ +os: Visual Studio 2015 + +# ENABLE_CUSTOM_COMPILER_FLAGS - on by default +# ENABLE_SANITIZERS - off by default +# ENABLE_PUBLIC_SYMBOLS - on by default +# BUILD_SHARED_LIBS - on by default +# ENABLE_TARGET_EXPORT - on by default +# ENABLE_CJSON_UTILS - off by default +# ENABLE_CJSON_TEST -on by default +# ENABLE_VALGRIND - off by default +# ENABLE_FUZZING - off by default + +environment: + matrix: + - GENERATOR: "Visual Studio 14 2015" + BUILD_SHARED_LIBS: ON + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 14 2015" + BUILD_SHARED_LIBS: OFF + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 12 2013" + BUILD_SHARED_LIBS: ON + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 12 2013" + BUILD_SHARED_LIBS: OFF + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 11 2012" + BUILD_SHARED_LIBS: ON + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 11 2012" + BUILD_SHARED_LIBS: OFF + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 10 2010" + BUILD_SHARED_LIBS: ON + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 10 2010" + BUILD_SHARED_LIBS: OFF + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 9 2008" + BUILD_SHARED_LIBS: ON + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + - GENERATOR: "Visual Studio 9 2008" + BUILD_SHARED_LIBS: OFF + ENABLE_CJSON_TEST: OFF + ENABLE_CJSON_UTILS: ON + + +platform: + - x86 + - x64 +matrix: + exclude: + - platform: x64 + GENERATOR: "Visual Studio 9 2008" + +configuration: + - Release + + +build_script: + - ps: if($env:PLATFORM -eq "x64") { $env:CMAKE_GEN_SUFFIX=" Win64" } + - cmake "-G%GENERATOR%%CMAKE_GEN_SUFFIX%" -DBUILD_SHARED_LIBS=%BUILD_SHARED_LIBS% -DENABLE_CJSON_TEST=%ENABLE_CJSON_TEST% -H. -Bbuild + - cmake --build build --config "%CONFIGURATION%" + + +on_failure: + - ps: if(Test-Path builds/CMakeFiles/CMakeOutput.log) { cat builds/CMakeFiles/CMakeOutput.log } + - ps: if(Test-Path builds/CMakeFiles/CMakeError.log) { cat builds/CMakeFiles/CMakeError.log } \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/cJSON.c b/managed_components/espressif__cjson/cJSON/cJSON.c new file mode 100644 index 0000000..88c2d95 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/cJSON.c @@ -0,0 +1,3206 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 19) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char *number_c_string; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + size_t number_string_length = 0; + cJSON_bool has_decimal_point = false; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_string_length++; + break; + + case '.': + number_string_length++; + has_decimal_point = true; + break; + + default: + goto loop_end; + } + } +loop_end: + /* malloc for temporary buffer, add 1 for '\0' */ + number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1); + if (number_c_string == NULL) + { + return false; /* allocation failure */ + } + + memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); + number_c_string[number_string_length] = '\0'; + + if (has_decimal_point) + { + for (i = 0; i < number_string_length; i++) + { + if (number_c_string[i] == '.') + { + /* replace '.' with the decimal point of the current locale (for strtod) */ + number_c_string[i] = decimal_point; + } + } + } + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (object == NULL) + { + return (double)NAN; + } + + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + if (output_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* nesting is too deep */ + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + if (output_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* nesting is too deep */ + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/managed_components/espressif__cjson/cJSON/cJSON.h b/managed_components/espressif__cjson/cJSON/cJSON.h new file mode 100644 index 0000000..cab5feb --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 19 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/managed_components/espressif__cjson/cJSON/cJSON_Utils.c b/managed_components/espressif__cjson/cJSON/cJSON_Utils.c new file mode 100644 index 0000000..8fa24f8 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/cJSON_Utils.c @@ -0,0 +1,1481 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUCC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUCC__ +#pragma GCC visibility pop +#endif + +#include "cJSON_Utils.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +static unsigned char* cJSONUtils_strdup(const unsigned char* const string) +{ + size_t length = 0; + unsigned char *copy = NULL; + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*) cJSON_malloc(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +/* string comparison which doesn't consider NULL pointers equal */ +static int compare_strings(const unsigned char *string1, const unsigned char *string2, const cJSON_bool case_sensitive) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + if (case_sensitive) + { + return strcmp((const char*)string1, (const char*)string2); + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + + +/* Compare the next path element of two JSON pointers, two NULL pointers are considered unequal: */ +static cJSON_bool compare_pointers(const unsigned char *name, const unsigned char *pointer, const cJSON_bool case_sensitive) +{ + if ((name == NULL) || (pointer == NULL)) + { + return false; + } + + for (; (*name != '\0') && (*pointer != '\0') && (*pointer != '/'); (void)name++, pointer++) /* compare until next '/' */ + { + if (*pointer == '~') + { + /* check for escaped '~' (~0) and '/' (~1) */ + if (((pointer[1] != '0') || (*name != '~')) && ((pointer[1] != '1') || (*name != '/'))) + { + /* invalid escape sequence or wrong character in *name */ + return false; + } + else + { + pointer++; + } + } + else if ((!case_sensitive && (tolower(*name) != tolower(*pointer))) || (case_sensitive && (*name != *pointer))) + { + return false; + } + } + if (((*pointer != 0) && (*pointer != '/')) != (*name != 0)) + { + /* one string has ended, the other not */ + return false;; + } + + return true; +} + +/* calculate the length of a string if encoded as JSON pointer with ~0 and ~1 escape sequences */ +static size_t pointer_encoded_length(const unsigned char *string) +{ + size_t length; + for (length = 0; *string != '\0'; (void)string++, length++) + { + /* character needs to be escaped? */ + if ((*string == '~') || (*string == '/')) + { + length++; + } + } + + return length; +} + +/* copy a string while escaping '~' and '/' with ~0 and ~1 JSON pointer escape codes */ +static void encode_string_as_pointer(unsigned char *destination, const unsigned char *source) +{ + for (; source[0] != '\0'; (void)source++, destination++) + { + if (source[0] == '/') + { + destination[0] = '~'; + destination[1] = '1'; + destination++; + } + else if (source[0] == '~') + { + destination[0] = '~'; + destination[1] = '0'; + destination++; + } + else + { + destination[0] = source[0]; + } + } + + destination[0] = '\0'; +} + +CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target) +{ + size_t child_index = 0; + cJSON *current_child = 0; + + if ((object == NULL) || (target == NULL)) + { + return NULL; + } + + if (object == target) + { + /* found */ + return (char*)cJSONUtils_strdup((const unsigned char*)""); + } + + /* recursively search all children of the object or array */ + for (current_child = object->child; current_child != NULL; (void)(current_child = current_child->next), child_index++) + { + unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target); + /* found the target? */ + if (target_pointer != NULL) + { + if (cJSON_IsArray(object)) + { + /* reserve enough memory for a 64 bit integer + '/' and '\0' */ + unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/")); + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (child_index > ULONG_MAX) + { + cJSON_free(target_pointer); + cJSON_free(full_pointer); + return NULL; + } + sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* / */ + cJSON_free(target_pointer); + + return (char*)full_pointer; + } + + if (cJSON_IsObject(object)) + { + unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + pointer_encoded_length((unsigned char*)current_child->string) + 2); + full_pointer[0] = '/'; + encode_string_as_pointer(full_pointer + 1, (unsigned char*)current_child->string); + strcat((char*)full_pointer, (char*)target_pointer); + cJSON_free(target_pointer); + + return (char*)full_pointer; + } + + /* reached leaf of the tree, found nothing */ + cJSON_free(target_pointer); + return NULL; + } + } + + /* not found */ + return NULL; +} + +/* non broken version of cJSON_GetArrayItem */ +static cJSON *get_array_item(const cJSON *array, size_t item) +{ + cJSON *child = array ? array->child : NULL; + while ((child != NULL) && (item > 0)) + { + item--; + child = child->next; + } + + return child; +} + +static cJSON_bool decode_array_index_from_pointer(const unsigned char * const pointer, size_t * const index) +{ + size_t parsed_index = 0; + size_t position = 0; + + if ((pointer[0] == '0') && ((pointer[1] != '\0') && (pointer[1] != '/'))) + { + /* leading zeroes are not permitted */ + return 0; + } + + for (position = 0; (pointer[position] >= '0') && (pointer[position] <= '9'); position++) + { + parsed_index = (10 * parsed_index) + (size_t)(pointer[position] - '0'); + + } + + if ((pointer[position] != '\0') && (pointer[position] != '/')) + { + return 0; + } + + *index = parsed_index; + + return 1; +} + +static cJSON *get_item_from_pointer(cJSON * const object, const char * pointer, const cJSON_bool case_sensitive) +{ + cJSON *current_element = object; + + if (pointer == NULL) + { + return NULL; + } + + /* follow path of the pointer */ + while ((pointer[0] == '/') && (current_element != NULL)) + { + pointer++; + if (cJSON_IsArray(current_element)) + { + size_t index = 0; + if (!decode_array_index_from_pointer((const unsigned char*)pointer, &index)) + { + return NULL; + } + + current_element = get_array_item(current_element, index); + } + else if (cJSON_IsObject(current_element)) + { + current_element = current_element->child; + /* GetObjectItem. */ + while ((current_element != NULL) && !compare_pointers((unsigned char*)current_element->string, (const unsigned char*)pointer, case_sensitive)) + { + current_element = current_element->next; + } + } + else + { + return NULL; + } + + /* skip to the next path token or end of string */ + while ((pointer[0] != '\0') && (pointer[0] != '/')) + { + pointer++; + } + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer) +{ + return get_item_from_pointer(object, pointer, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer) +{ + return get_item_from_pointer(object, pointer, true); +} + +/* JSON Patch implementation. */ +static void decode_pointer_inplace(unsigned char *string) +{ + unsigned char *decoded_string = string; + + if (string == NULL) { + return; + } + + for (; *string; (void)decoded_string++, string++) + { + if (string[0] == '~') + { + if (string[1] == '0') + { + decoded_string[0] = '~'; + } + else if (string[1] == '1') + { + decoded_string[1] = '/'; + } + else + { + /* invalid escape sequence */ + return; + } + + string++; + } + } + + decoded_string[0] = '\0'; +} + +/* non-broken cJSON_DetachItemFromArray */ +static cJSON *detach_item_from_array(cJSON *array, size_t which) +{ + cJSON *c = array->child; + while (c && (which > 0)) + { + c = c->next; + which--; + } + if (!c) + { + /* item doesn't exist */ + return NULL; + } + if (c != array->child) + { + /* not the first element */ + c->prev->next = c->next; + } + if (c->next) + { + c->next->prev = c->prev; + } + if (c == array->child) + { + array->child = c->next; + } + else if (c->next == NULL) + { + array->child->prev = c->prev; + } + /* make sure the detached item doesn't point anywhere anymore */ + c->prev = c->next = NULL; + + return c; +} + +/* detach an item at the given path */ +static cJSON *detach_path(cJSON *object, const unsigned char *path, const cJSON_bool case_sensitive) +{ + unsigned char *parent_pointer = NULL; + unsigned char *child_pointer = NULL; + cJSON *parent = NULL; + cJSON *detached_item = NULL; + + /* copy path and split it in parent and child */ + parent_pointer = cJSONUtils_strdup(path); + if (parent_pointer == NULL) { + goto cleanup; + } + + child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); /* last '/' */ + if (child_pointer == NULL) + { + goto cleanup; + } + /* split strings */ + child_pointer[0] = '\0'; + child_pointer++; + + parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive); + decode_pointer_inplace(child_pointer); + + if (cJSON_IsArray(parent)) + { + size_t index = 0; + if (!decode_array_index_from_pointer(child_pointer, &index)) + { + goto cleanup; + } + detached_item = detach_item_from_array(parent, index); + } + else if (cJSON_IsObject(parent)) + { + detached_item = cJSON_DetachItemFromObject(parent, (char*)child_pointer); + } + else + { + /* Couldn't find object to remove child from. */ + goto cleanup; + } + +cleanup: + if (parent_pointer != NULL) + { + cJSON_free(parent_pointer); + } + + return detached_item; +} + +/* sort lists using mergesort */ +static cJSON *sort_list(cJSON *list, const cJSON_bool case_sensitive) +{ + cJSON *first = list; + cJSON *second = list; + cJSON *current_item = list; + cJSON *result = list; + cJSON *result_tail = NULL; + + if ((list == NULL) || (list->next == NULL)) + { + /* One entry is sorted already. */ + return result; + } + + while ((current_item != NULL) && (current_item->next != NULL) && (compare_strings((unsigned char*)current_item->string, (unsigned char*)current_item->next->string, case_sensitive) < 0)) + { + /* Test for list sorted. */ + current_item = current_item->next; + } + if ((current_item == NULL) || (current_item->next == NULL)) + { + /* Leave sorted lists unmodified. */ + return result; + } + + /* reset pointer to the beginning */ + current_item = list; + while (current_item != NULL) + { + /* Walk two pointers to find the middle. */ + second = second->next; + current_item = current_item->next; + /* advances current_item two steps at a time */ + if (current_item != NULL) + { + current_item = current_item->next; + } + } + if ((second != NULL) && (second->prev != NULL)) + { + /* Split the lists */ + second->prev->next = NULL; + second->prev = NULL; + } + + /* Recursively sort the sub-lists. */ + first = sort_list(first, case_sensitive); + second = sort_list(second, case_sensitive); + result = NULL; + + /* Merge the sub-lists */ + while ((first != NULL) && (second != NULL)) + { + cJSON *smaller = NULL; + if (compare_strings((unsigned char*)first->string, (unsigned char*)second->string, case_sensitive) < 0) + { + smaller = first; + } + else + { + smaller = second; + } + + if (result == NULL) + { + /* start merged list with the smaller element */ + result_tail = smaller; + result = smaller; + } + else + { + /* add smaller element to the list */ + result_tail->next = smaller; + smaller->prev = result_tail; + result_tail = smaller; + } + + if (first == smaller) + { + first = first->next; + } + else + { + second = second->next; + } + } + + if (first != NULL) + { + /* Append rest of first list. */ + if (result == NULL) + { + return first; + } + result_tail->next = first; + first->prev = result_tail; + } + if (second != NULL) + { + /* Append rest of second list */ + if (result == NULL) + { + return second; + } + result_tail->next = second; + second->prev = result_tail; + } + + return result; +} + +static void sort_object(cJSON * const object, const cJSON_bool case_sensitive) +{ + if (object == NULL) + { + return; + } + object->child = sort_list(object->child, case_sensitive); +} + +static cJSON_bool compare_json(cJSON *a, cJSON *b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + /* mismatched type. */ + return false; + } + switch (a->type & 0xFF) + { + case cJSON_Number: + /* numeric mismatch. */ + if ((a->valueint != b->valueint) || (!compare_double(a->valuedouble, b->valuedouble))) + { + return false; + } + else + { + return true; + } + + case cJSON_String: + /* string mismatch. */ + if (strcmp(a->valuestring, b->valuestring) != 0) + { + return false; + } + else + { + return true; + } + + case cJSON_Array: + for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next) + { + cJSON_bool identical = compare_json(a, b, case_sensitive); + if (!identical) + { + return false; + } + } + + /* array size mismatch? (one of both children is not NULL) */ + if ((a != NULL) || (b != NULL)) + { + return false; + } + else + { + return true; + } + + case cJSON_Object: + sort_object(a, case_sensitive); + sort_object(b, case_sensitive); + for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next) + { + cJSON_bool identical = false; + /* compare object keys */ + if (compare_strings((unsigned char*)a->string, (unsigned char*)b->string, case_sensitive)) + { + /* missing member */ + return false; + } + identical = compare_json(a, b, case_sensitive); + if (!identical) + { + return false; + } + } + + /* object length mismatch (one of both children is not null) */ + if ((a != NULL) || (b != NULL)) + { + return false; + } + else + { + return true; + } + + default: + break; + } + + /* null, true or false */ + return true; +} + +/* non broken version of cJSON_InsertItemInArray */ +static cJSON_bool insert_item_in_array(cJSON *array, size_t which, cJSON *newitem) +{ + cJSON *child = array->child; + while (child && (which > 0)) + { + child = child->next; + which--; + } + if (which > 0) + { + /* item is after the end of the array */ + return 0; + } + if (child == NULL) + { + cJSON_AddItemToArray(array, newitem); + return 1; + } + + /* insert into the linked list */ + newitem->next = child; + newitem->prev = child->prev; + child->prev = newitem; + + /* was it at the beginning */ + if (child == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + + return 1; +} + +static cJSON *get_object_item(const cJSON * const object, const char* name, const cJSON_bool case_sensitive) +{ + if (case_sensitive) + { + return cJSON_GetObjectItemCaseSensitive(object, name); + } + + return cJSON_GetObjectItem(object, name); +} + +enum patch_operation { INVALID, ADD, REMOVE, REPLACE, MOVE, COPY, TEST }; + +static enum patch_operation decode_patch_operation(const cJSON * const patch, const cJSON_bool case_sensitive) +{ + cJSON *operation = get_object_item(patch, "op", case_sensitive); + if (!cJSON_IsString(operation)) + { + return INVALID; + } + + if (strcmp(operation->valuestring, "add") == 0) + { + return ADD; + } + + if (strcmp(operation->valuestring, "remove") == 0) + { + return REMOVE; + } + + if (strcmp(operation->valuestring, "replace") == 0) + { + return REPLACE; + } + + if (strcmp(operation->valuestring, "move") == 0) + { + return MOVE; + } + + if (strcmp(operation->valuestring, "copy") == 0) + { + return COPY; + } + + if (strcmp(operation->valuestring, "test") == 0) + { + return TEST; + } + + return INVALID; +} + +/* overwrite and existing item with another one and free resources on the way */ +static void overwrite_item(cJSON * const root, const cJSON replacement) +{ + if (root == NULL) + { + return; + } + + if (root->string != NULL) + { + cJSON_free(root->string); + } + if (root->valuestring != NULL) + { + cJSON_free(root->valuestring); + } + if (root->child != NULL) + { + cJSON_Delete(root->child); + } + + memcpy(root, &replacement, sizeof(cJSON)); +} + +static int apply_patch(cJSON *object, const cJSON *patch, const cJSON_bool case_sensitive) +{ + cJSON *path = NULL; + cJSON *value = NULL; + cJSON *parent = NULL; + enum patch_operation opcode = INVALID; + unsigned char *parent_pointer = NULL; + unsigned char *child_pointer = NULL; + int status = 0; + + path = get_object_item(patch, "path", case_sensitive); + if (!cJSON_IsString(path)) + { + /* malformed patch. */ + status = 2; + goto cleanup; + } + + opcode = decode_patch_operation(patch, case_sensitive); + if (opcode == INVALID) + { + status = 3; + goto cleanup; + } + else if (opcode == TEST) + { + /* compare value: {...} with the given path */ + status = !compare_json(get_item_from_pointer(object, path->valuestring, case_sensitive), get_object_item(patch, "value", case_sensitive), case_sensitive); + goto cleanup; + } + + /* special case for replacing the root */ + if (path->valuestring[0] == '\0') + { + if (opcode == REMOVE) + { + static const cJSON invalid = { NULL, NULL, NULL, cJSON_Invalid, NULL, 0, 0, NULL}; + + overwrite_item(object, invalid); + + status = 0; + goto cleanup; + } + + if ((opcode == REPLACE) || (opcode == ADD)) + { + value = get_object_item(patch, "value", case_sensitive); + if (value == NULL) + { + /* missing "value" for add/replace. */ + status = 7; + goto cleanup; + } + + value = cJSON_Duplicate(value, 1); + if (value == NULL) + { + /* out of memory for add/replace. */ + status = 8; + goto cleanup; + } + + overwrite_item(object, *value); + + /* delete the duplicated value */ + cJSON_free(value); + value = NULL; + + /* the string "value" isn't needed */ + if (object->string != NULL) + { + cJSON_free(object->string); + object->string = NULL; + } + + status = 0; + goto cleanup; + } + } + + if ((opcode == REMOVE) || (opcode == REPLACE)) + { + /* Get rid of old. */ + cJSON *old_item = detach_path(object, (unsigned char*)path->valuestring, case_sensitive); + if (old_item == NULL) + { + status = 13; + goto cleanup; + } + cJSON_Delete(old_item); + if (opcode == REMOVE) + { + /* For Remove, this job is done. */ + status = 0; + goto cleanup; + } + } + + /* Copy/Move uses "from". */ + if ((opcode == MOVE) || (opcode == COPY)) + { + cJSON *from = get_object_item(patch, "from", case_sensitive); + if (from == NULL) + { + /* missing "from" for copy/move. */ + status = 4; + goto cleanup; + } + + if (opcode == MOVE) + { + value = detach_path(object, (unsigned char*)from->valuestring, case_sensitive); + } + if (opcode == COPY) + { + value = get_item_from_pointer(object, from->valuestring, case_sensitive); + } + if (value == NULL) + { + /* missing "from" for copy/move. */ + status = 5; + goto cleanup; + } + if (opcode == COPY) + { + value = cJSON_Duplicate(value, 1); + } + if (value == NULL) + { + /* out of memory for copy/move. */ + status = 6; + goto cleanup; + } + } + else /* Add/Replace uses "value". */ + { + value = get_object_item(patch, "value", case_sensitive); + if (value == NULL) + { + /* missing "value" for add/replace. */ + status = 7; + goto cleanup; + } + value = cJSON_Duplicate(value, 1); + if (value == NULL) + { + /* out of memory for add/replace. */ + status = 8; + goto cleanup; + } + } + + /* Now, just add "value" to "path". */ + + /* split pointer in parent and child */ + parent_pointer = cJSONUtils_strdup((unsigned char*)path->valuestring); + if (parent_pointer) { + child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); + } + if (child_pointer != NULL) + { + child_pointer[0] = '\0'; + child_pointer++; + } + parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive); + decode_pointer_inplace(child_pointer); + + /* add, remove, replace, move, copy, test. */ + if ((parent == NULL) || (child_pointer == NULL)) + { + /* Couldn't find object to add to. */ + status = 9; + goto cleanup; + } + else if (cJSON_IsArray(parent)) + { + if (strcmp((char*)child_pointer, "-") == 0) + { + cJSON_AddItemToArray(parent, value); + value = NULL; + } + else + { + size_t index = 0; + if (!decode_array_index_from_pointer(child_pointer, &index)) + { + status = 11; + goto cleanup; + } + + if (!insert_item_in_array(parent, index, value)) + { + status = 10; + goto cleanup; + } + value = NULL; + } + } + else if (cJSON_IsObject(parent)) + { + if (case_sensitive) + { + cJSON_DeleteItemFromObjectCaseSensitive(parent, (char*)child_pointer); + } + else + { + cJSON_DeleteItemFromObject(parent, (char*)child_pointer); + } + cJSON_AddItemToObject(parent, (char*)child_pointer, value); + value = NULL; + } + else /* parent is not an object */ + { + /* Couldn't find object to add to. */ + status = 9; + goto cleanup; + } + +cleanup: + if (value != NULL) + { + cJSON_Delete(value); + } + if (parent_pointer != NULL) + { + cJSON_free(parent_pointer); + } + + return status; +} + +CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches) +{ + const cJSON *current_patch = NULL; + int status = 0; + + if (!cJSON_IsArray(patches)) + { + /* malformed patches. */ + return 1; + } + + if (patches != NULL) + { + current_patch = patches->child; + } + + while (current_patch != NULL) + { + status = apply_patch(object, current_patch, false); + if (status != 0) + { + return status; + } + current_patch = current_patch->next; + } + + return 0; +} + +CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches) +{ + const cJSON *current_patch = NULL; + int status = 0; + + if (!cJSON_IsArray(patches)) + { + /* malformed patches. */ + return 1; + } + + if (patches != NULL) + { + current_patch = patches->child; + } + + while (current_patch != NULL) + { + status = apply_patch(object, current_patch, true); + if (status != 0) + { + return status; + } + current_patch = current_patch->next; + } + + return 0; +} + +static void compose_patch(cJSON * const patches, const unsigned char * const operation, const unsigned char * const path, const unsigned char *suffix, const cJSON * const value) +{ + cJSON *patch = NULL; + + if ((patches == NULL) || (operation == NULL) || (path == NULL)) + { + return; + } + + patch = cJSON_CreateObject(); + if (patch == NULL) + { + return; + } + cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)operation)); + + if (suffix == NULL) + { + cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path)); + } + else + { + size_t suffix_length = pointer_encoded_length(suffix); + size_t path_length = strlen((const char*)path); + unsigned char *full_path = (unsigned char*)cJSON_malloc(path_length + suffix_length + sizeof("/")); + + sprintf((char*)full_path, "%s/", (const char*)path); + encode_string_as_pointer(full_path + path_length + 1, suffix); + + cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)full_path)); + cJSON_free(full_path); + } + + if (value != NULL) + { + cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(value, 1)); + } + cJSON_AddItemToArray(patches, patch); +} + +CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value) +{ + compose_patch(array, (const unsigned char*)operation, (const unsigned char*)path, NULL, value); +} + +static void create_patches(cJSON * const patches, const unsigned char * const path, cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive) +{ + if ((from == NULL) || (to == NULL)) + { + return; + } + + if ((from->type & 0xFF) != (to->type & 0xFF)) + { + compose_patch(patches, (const unsigned char*)"replace", path, 0, to); + return; + } + + switch (from->type & 0xFF) + { + case cJSON_Number: + if ((from->valueint != to->valueint) || !compare_double(from->valuedouble, to->valuedouble)) + { + compose_patch(patches, (const unsigned char*)"replace", path, NULL, to); + } + return; + + case cJSON_String: + if (strcmp(from->valuestring, to->valuestring) != 0) + { + compose_patch(patches, (const unsigned char*)"replace", path, NULL, to); + } + return; + + case cJSON_Array: + { + size_t index = 0; + cJSON *from_child = from->child; + cJSON *to_child = to->child; + unsigned char *new_path = (unsigned char*)cJSON_malloc(strlen((const char*)path) + 20 + sizeof("/")); /* Allow space for 64bit int. log10(2^64) = 20 */ + + /* generate patches for all array elements that exist in both "from" and "to" */ + for (index = 0; (from_child != NULL) && (to_child != NULL); (void)(from_child = from_child->next), (void)(to_child = to_child->next), index++) + { + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (index > ULONG_MAX) + { + cJSON_free(new_path); + return; + } + sprintf((char*)new_path, "%s/%lu", path, (unsigned long)index); /* path of the current array element */ + create_patches(patches, new_path, from_child, to_child, case_sensitive); + } + + /* remove leftover elements from 'from' that are not in 'to' */ + for (; (from_child != NULL); (void)(from_child = from_child->next)) + { + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (index > ULONG_MAX) + { + cJSON_free(new_path); + return; + } + sprintf((char*)new_path, "%lu", (unsigned long)index); + compose_patch(patches, (const unsigned char*)"remove", path, new_path, NULL); + } + /* add new elements in 'to' that were not in 'from' */ + for (; (to_child != NULL); (void)(to_child = to_child->next), index++) + { + compose_patch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to_child); + } + cJSON_free(new_path); + return; + } + + case cJSON_Object: + { + cJSON *from_child = NULL; + cJSON *to_child = NULL; + sort_object(from, case_sensitive); + sort_object(to, case_sensitive); + + from_child = from->child; + to_child = to->child; + /* for all object values in the object with more of them */ + while ((from_child != NULL) || (to_child != NULL)) + { + int diff; + if (from_child == NULL) + { + diff = 1; + } + else if (to_child == NULL) + { + diff = -1; + } + else + { + diff = compare_strings((unsigned char*)from_child->string, (unsigned char*)to_child->string, case_sensitive); + } + + if (diff == 0) + { + /* both object keys are the same */ + size_t path_length = strlen((const char*)path); + size_t from_child_name_length = pointer_encoded_length((unsigned char*)from_child->string); + unsigned char *new_path = (unsigned char*)cJSON_malloc(path_length + from_child_name_length + sizeof("/")); + + sprintf((char*)new_path, "%s/", path); + encode_string_as_pointer(new_path + path_length + 1, (unsigned char*)from_child->string); + + /* create a patch for the element */ + create_patches(patches, new_path, from_child, to_child, case_sensitive); + cJSON_free(new_path); + + from_child = from_child->next; + to_child = to_child->next; + } + else if (diff < 0) + { + /* object element doesn't exist in 'to' --> remove it */ + compose_patch(patches, (const unsigned char*)"remove", path, (unsigned char*)from_child->string, NULL); + + from_child = from_child->next; + } + else + { + /* object element doesn't exist in 'from' --> add it */ + compose_patch(patches, (const unsigned char*)"add", path, (unsigned char*)to_child->string, to_child); + + to_child = to_child->next; + } + } + return; + } + + default: + break; + } +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to) +{ + cJSON *patches = NULL; + + if ((from == NULL) || (to == NULL)) + { + return NULL; + } + + patches = cJSON_CreateArray(); + create_patches(patches, (const unsigned char*)"", from, to, false); + + return patches; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to) +{ + cJSON *patches = NULL; + + if ((from == NULL) || (to == NULL)) + { + return NULL; + } + + patches = cJSON_CreateArray(); + create_patches(patches, (const unsigned char*)"", from, to, true); + + return patches; +} + +CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object) +{ + sort_object(object, false); +} + +CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object) +{ + sort_object(object, true); +} + +static cJSON *merge_patch(cJSON *target, const cJSON * const patch, const cJSON_bool case_sensitive) +{ + cJSON *patch_child = NULL; + + if (!cJSON_IsObject(patch)) + { + /* scalar value, array or NULL, just duplicate */ + cJSON_Delete(target); + return cJSON_Duplicate(patch, 1); + } + + if (!cJSON_IsObject(target)) + { + cJSON_Delete(target); + target = cJSON_CreateObject(); + } + + patch_child = patch->child; + while (patch_child != NULL) + { + if (cJSON_IsNull(patch_child)) + { + /* NULL is the indicator to remove a value, see RFC7396 */ + if (case_sensitive) + { + cJSON_DeleteItemFromObjectCaseSensitive(target, patch_child->string); + } + else + { + cJSON_DeleteItemFromObject(target, patch_child->string); + } + } + else + { + cJSON *replace_me = NULL; + cJSON *replacement = NULL; + + if (case_sensitive) + { + replace_me = cJSON_DetachItemFromObjectCaseSensitive(target, patch_child->string); + } + else + { + replace_me = cJSON_DetachItemFromObject(target, patch_child->string); + } + + replacement = merge_patch(replace_me, patch_child, case_sensitive); + if (replacement == NULL) + { + cJSON_Delete(target); + return NULL; + } + + cJSON_AddItemToObject(target, patch_child->string, replacement); + } + patch_child = patch_child->next; + } + return target; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch) +{ + return merge_patch(target, patch, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch) +{ + return merge_patch(target, patch, true); +} + +static cJSON *generate_merge_patch(cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive) +{ + cJSON *from_child = NULL; + cJSON *to_child = NULL; + cJSON *patch = NULL; + if (to == NULL) + { + /* patch to delete everything */ + return cJSON_CreateNull(); + } + if (!cJSON_IsObject(to) || !cJSON_IsObject(from)) + { + return cJSON_Duplicate(to, 1); + } + + sort_object(from, case_sensitive); + sort_object(to, case_sensitive); + + from_child = from->child; + to_child = to->child; + patch = cJSON_CreateObject(); + if (patch == NULL) + { + return NULL; + } + while (from_child || to_child) + { + int diff; + if (from_child != NULL) + { + if (to_child != NULL) + { + diff = strcmp(from_child->string, to_child->string); + } + else + { + diff = -1; + } + } + else + { + diff = 1; + } + + if (diff < 0) + { + /* from has a value that to doesn't have -> remove */ + cJSON_AddItemToObject(patch, from_child->string, cJSON_CreateNull()); + + from_child = from_child->next; + } + else if (diff > 0) + { + /* to has a value that from doesn't have -> add to patch */ + cJSON_AddItemToObject(patch, to_child->string, cJSON_Duplicate(to_child, 1)); + + to_child = to_child->next; + } + else + { + /* object key exists in both objects */ + if (!compare_json(from_child, to_child, case_sensitive)) + { + /* not identical --> generate a patch */ + cJSON_AddItemToObject(patch, to_child->string, cJSONUtils_GenerateMergePatch(from_child, to_child)); + } + + /* next key in the object */ + from_child = from_child->next; + to_child = to_child->next; + } + } + if (patch->child == NULL) + { + /* no patch generated */ + cJSON_Delete(patch); + return NULL; + } + + return patch; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to) +{ + return generate_merge_patch(from, to, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to) +{ + return generate_merge_patch(from, to, true); +} diff --git a/managed_components/espressif__cjson/cJSON/cJSON_Utils.h b/managed_components/espressif__cjson/cJSON/cJSON_Utils.h new file mode 100644 index 0000000..a970c65 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/cJSON_Utils.h @@ -0,0 +1,88 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON_Utils__h +#define cJSON_Utils__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "cJSON.h" + +/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer); +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer); + +/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */ +/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to); +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to); +/* Utility for generating patch array entries. */ +CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value); +/* Returns 0 for success. */ +CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches); +CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches); + +/* +// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use: +//int cJSONUtils_AtomicApplyPatches(cJSON **object, cJSON *patches) +//{ +// cJSON *modme = cJSON_Duplicate(*object, 1); +// int error = cJSONUtils_ApplyPatches(modme, patches); +// if (!error) +// { +// cJSON_Delete(*object); +// *object = modme; +// } +// else +// { +// cJSON_Delete(modme); +// } +// +// return error; +//} +// Code not added to library since this strategy is a LOT slower. +*/ + +/* Implement RFC7386 (https://tools.ietf.org/html/rfc7396) JSON Merge Patch spec. */ +/* target will be modified by patch. return value is new ptr for target. */ +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch); +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch); +/* generates a patch to move from -> to */ +/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to); +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to); + +/* Given a root object and a target object, construct a pointer from one to the other. */ +CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target); + +/* Sorts the members of the object into alphabetical order. */ +CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object); +CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/.gitignore b/managed_components/espressif__cjson/cJSON/fuzzing/.gitignore new file mode 100644 index 0000000..c82a262 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/.gitignore @@ -0,0 +1 @@ +afl-build diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/CMakeLists.txt b/managed_components/espressif__cjson/cJSON/fuzzing/CMakeLists.txt new file mode 100644 index 0000000..1166000 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/CMakeLists.txt @@ -0,0 +1,34 @@ +option(ENABLE_FUZZING "Create executables and targets for fuzzing cJSON with afl." Off) +if (ENABLE_FUZZING) + find_program(AFL_FUZZ afl-fuzz) + if ("${AFL_FUZZ}" MATCHES "AFL_FUZZ-NOTFOUND") + message(FATAL_ERROR "Couldn't find afl-fuzz.") + endif() + + add_executable(afl-main afl.c) + target_link_libraries(afl-main "${CJSON_LIB}") + + if (NOT ENABLE_SANITIZERS) + message(FATAL_ERROR "Enable sanitizers with -DENABLE_SANITIZERS=On to do fuzzing.") + endif() + + option(ENABLE_FUZZING_PRINT "Fuzz printing functions together with parser." On) + set(fuzz_print_parameter "no") + if (ENABLE_FUZZING_PRINT) + set(fuzz_print_parameter "yes") + endif() + + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error") + + add_custom_target(afl + COMMAND "${AFL_FUZZ}" -i "${CMAKE_CURRENT_SOURCE_DIR}/inputs" -o "${CMAKE_CURRENT_BINARY_DIR}/findings" -x "${CMAKE_CURRENT_SOURCE_DIR}/json.dict" -- "${CMAKE_CURRENT_BINARY_DIR}/afl-main" "@@" "${fuzz_print_parameter}" + DEPENDS afl-main) + + +endif() + +if(ENABLE_CJSON_TEST) + ADD_EXECUTABLE(fuzz_main fuzz_main.c cjson_read_fuzzer.c) + TARGET_LINK_LIBRARIES(fuzz_main cjson) +endif() + diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/afl-prepare-linux.sh b/managed_components/espressif__cjson/cJSON/fuzzing/afl-prepare-linux.sh new file mode 100644 index 0000000..41c9b89 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/afl-prepare-linux.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +set -x +echo core | sudo tee /proc/sys/kernel/core_pattern +echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/afl.c b/managed_components/espressif__cjson/cJSON/fuzzing/afl.c new file mode 100644 index 0000000..036ed14 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/afl.c @@ -0,0 +1,176 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "../cJSON.h" + +static char *read_file(const char *filename) +{ + FILE *file = NULL; + long length = 0; + char *content = NULL; + size_t read_chars = 0; + + /* open in read binary mode */ + file = fopen(filename, "rb"); + if (file == NULL) + { + goto cleanup; + } + + /* get the length */ + if (fseek(file, 0, SEEK_END) != 0) + { + goto cleanup; + } + length = ftell(file); + if (length < 0) + { + goto cleanup; + } + if (fseek(file, 0, SEEK_SET) != 0) + { + goto cleanup; + } + + /* allocate content buffer */ + content = (char*)malloc((size_t)length + sizeof("")); + if (content == NULL) + { + goto cleanup; + } + + /* read the file into memory */ + read_chars = fread(content, sizeof(char), (size_t)length, file); + if ((long)read_chars != length) + { + free(content); + content = NULL; + goto cleanup; + } + content[read_chars] = '\0'; + + +cleanup: + if (file != NULL) + { + fclose(file); + } + + return content; +} + +int main(int argc, char** argv) +{ + const char *filename = NULL; + cJSON *item = NULL; + char *json = NULL; + int status = EXIT_FAILURE; + char *printed_json = NULL; + + if ((argc < 2) || (argc > 3)) + { + printf("Usage:\n"); + printf("%s input_file [enable_printing]\n", argv[0]); + printf("\t input_file: file containing the test data\n"); + printf("\t enable_printing: print after parsing, 'yes' or 'no', defaults to 'no'\n"); + goto cleanup; + } + + filename = argv[1]; + +#if __AFL_HAVE_MANUAL_CONTROL + while (__AFL_LOOP(1000)) + { +#endif + status = EXIT_SUCCESS; + + json = read_file(filename); + if ((json == NULL) || (json[0] == '\0') || (json[1] == '\0')) + { + status = EXIT_FAILURE; + goto cleanup; + } + item = cJSON_Parse(json + 2); + if (item == NULL) + { + goto cleanup; + } + + if ((argc == 3) && (strncmp(argv[2], "yes", 3) == 0)) + { + int do_format = 0; + if (json[1] == 'f') + { + do_format = 1; + } + + if (json[0] == 'b') + { + /* buffered printing */ + printed_json = cJSON_PrintBuffered(item, 1, do_format); + } + else + { + /* unbuffered printing */ + if (do_format) + { + printed_json = cJSON_Print(item); + } + else + { + printed_json = cJSON_PrintUnformatted(item); + } + } + if (printed_json == NULL) + { + status = EXIT_FAILURE; + goto cleanup; + } + printf("%s\n", printed_json); + } + +cleanup: + if (item != NULL) + { + cJSON_Delete(item); + item = NULL; + } + if (json != NULL) + { + free(json); + json = NULL; + } + if (printed_json != NULL) + { + free(printed_json); + printed_json = NULL; + } +#if __AFL_HAVE_MANUAL_CONTROL + } +#endif + + return status; +} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/afl.sh b/managed_components/espressif__cjson/cJSON/fuzzing/afl.sh new file mode 100644 index 0000000..8f0f02f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/afl.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +mkdir -p afl-build || exit 1 +cd afl-build || exit 1 +#cleanup +rm -r -- * + +CC=afl-clang-fast cmake ../.. -DENABLE_FUZZING=On -DENABLE_SANITIZERS=On -DBUILD_SHARED_LIBS=Off +make afl diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/cjson_read_fuzzer.c b/managed_components/espressif__cjson/cJSON/fuzzing/cjson_read_fuzzer.c new file mode 100644 index 0000000..aa9c7ba --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/cjson_read_fuzzer.c @@ -0,0 +1,77 @@ +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include "../cJSON.h" + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */ + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + cJSON *json; + size_t offset = 4; + unsigned char *copied; + char *printed_json = NULL; + int minify, require_termination, formatted, buffered; + + + if(size <= offset) return 0; + if(data[size-1] != '\0') return 0; + if(data[0] != '1' && data[0] != '0') return 0; + if(data[1] != '1' && data[1] != '0') return 0; + if(data[2] != '1' && data[2] != '0') return 0; + if(data[3] != '1' && data[3] != '0') return 0; + + minify = data[0] == '1' ? 1 : 0; + require_termination = data[1] == '1' ? 1 : 0; + formatted = data[2] == '1' ? 1 : 0; + buffered = data[3] == '1' ? 1 : 0; + + json = cJSON_ParseWithOpts((const char*)data + offset, NULL, require_termination); + + if(json == NULL) return 0; + + if(buffered) + { + printed_json = cJSON_PrintBuffered(json, 1, formatted); + } + else + { + /* unbuffered printing */ + if(formatted) + { + printed_json = cJSON_Print(json); + } + else + { + printed_json = cJSON_PrintUnformatted(json); + } + } + + if(printed_json != NULL) free(printed_json); + + if(minify) + { + copied = (unsigned char*)malloc(size); + if(copied == NULL) return 0; + + memcpy(copied, data, size); + + cJSON_Minify((char*)copied + offset); + + free(copied); + } + + cJSON_Delete(json); + + return 0; +} + +#ifdef __cplusplus +} +#endif + diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/fuzz_main.c b/managed_components/espressif__cjson/cJSON/fuzzing/fuzz_main.c new file mode 100644 index 0000000..09dc156 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/fuzz_main.c @@ -0,0 +1,54 @@ +#include +#include +#include + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */ + +/* fuzz target entry point, works without libFuzzer */ + +int main(int argc, char **argv) +{ + FILE *f; + char *buf = NULL; + long siz_buf; + + if(argc < 2) + { + fprintf(stderr, "no input file\n"); + goto err; + } + + f = fopen(argv[1], "rb"); + if(f == NULL) + { + fprintf(stderr, "error opening input file %s\n", argv[1]); + goto err; + } + + fseek(f, 0, SEEK_END); + + siz_buf = ftell(f); + rewind(f); + + if(siz_buf < 1) goto err; + + buf = (char*)malloc((size_t)siz_buf); + if(buf == NULL) + { + fprintf(stderr, "malloc() failed\n"); + goto err; + } + + if(fread(buf, (size_t)siz_buf, 1, f) != 1) + { + fprintf(stderr, "fread() failed\n"); + goto err; + } + + (void)LLVMFuzzerTestOneInput((uint8_t*)buf, (size_t)siz_buf); + +err: + free(buf); + + return 0; +} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test1 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test1 new file mode 100644 index 0000000..6a0c0d7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test1 @@ -0,0 +1,22 @@ +bf{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": ["GML", "XML"] + }, + "GlossSee": "markup" + } + } + } + } +} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test10 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test10 new file mode 100644 index 0000000..01e9a82 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test10 @@ -0,0 +1 @@ +bf["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test11 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test11 new file mode 100644 index 0000000..e81d60d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test11 @@ -0,0 +1,8 @@ +bf{ +"name": "Jack (\"Bee\") Nimble", +"format": {"type": "rect", +"width": 1920, +"height": 1080, +"interlace": false,"frame rate": 24 +} +} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test2 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test2 new file mode 100644 index 0000000..3fdf8cb --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test2 @@ -0,0 +1,11 @@ +bf{"menu": { + "id": "file", + "value": "File", + "popup": { + "menuitem": [ + {"value": "New", "onclick": "CreateNewDoc()"}, + {"value": "Open", "onclick": "OpenDoc()"}, + {"value": "Close", "onclick": "CloseDoc()"} + ] + } +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3 new file mode 100644 index 0000000..11edd2f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3 @@ -0,0 +1,26 @@ +bf{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.bu b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.bu new file mode 100644 index 0000000..eaac4e3 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.bu @@ -0,0 +1,26 @@ +bu{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uf b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uf new file mode 100644 index 0000000..edad977 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uf @@ -0,0 +1,26 @@ +uf{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uu b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uu new file mode 100644 index 0000000..1356b6d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test3.uu @@ -0,0 +1,26 @@ +uu{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test4 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test4 new file mode 100644 index 0000000..943943d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test4 @@ -0,0 +1,88 @@ +bf{"web-app": { + "servlet": [ + { + "servlet-name": "cofaxCDS", + "servlet-class": "org.cofax.cds.CDSServlet", + "init-param": { + "configGlossary:installationAt": "Philadelphia, PA", + "configGlossary:adminEmail": "ksm@pobox.com", + "configGlossary:poweredBy": "Cofax", + "configGlossary:poweredByIcon": "/images/cofax.gif", + "configGlossary:staticPath": "/content/static", + "templateProcessorClass": "org.cofax.WysiwygTemplate", + "templateLoaderClass": "org.cofax.FilesTemplateLoader", + "templatePath": "templates", + "templateOverridePath": "", + "defaultListTemplate": "listTemplate.htm", + "defaultFileTemplate": "articleTemplate.htm", + "useJSP": false, + "jspListTemplate": "listTemplate.jsp", + "jspFileTemplate": "articleTemplate.jsp", + "cachePackageTagsTrack": 200, + "cachePackageTagsStore": 200, + "cachePackageTagsRefresh": 60, + "cacheTemplatesTrack": 100, + "cacheTemplatesStore": 50, + "cacheTemplatesRefresh": 15, + "cachePagesTrack": 200, + "cachePagesStore": 100, + "cachePagesRefresh": 10, + "cachePagesDirtyRead": 10, + "searchEngineListTemplate": "forSearchEnginesList.htm", + "searchEngineFileTemplate": "forSearchEngines.htm", + "searchEngineRobotsDb": "WEB-INF/robots.db", + "useDataStore": true, + "dataStoreClass": "org.cofax.SqlDataStore", + "redirectionClass": "org.cofax.SqlRedirection", + "dataStoreName": "cofax", + "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon", + "dataStoreUser": "sa", + "dataStorePassword": "dataStoreTestQuery", + "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';", + "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log", + "dataStoreInitConns": 10, + "dataStoreMaxConns": 100, + "dataStoreConnUsageLimit": 100, + "dataStoreLogLevel": "debug", + "maxUrlLength": 500}}, + { + "servlet-name": "cofaxEmail", + "servlet-class": "org.cofax.cds.EmailServlet", + "init-param": { + "mailHost": "mail1", + "mailHostOverride": "mail2"}}, + { + "servlet-name": "cofaxAdmin", + "servlet-class": "org.cofax.cds.AdminServlet"}, + + { + "servlet-name": "fileServlet", + "servlet-class": "org.cofax.cds.FileServlet"}, + { + "servlet-name": "cofaxTools", + "servlet-class": "org.cofax.cms.CofaxToolsServlet", + "init-param": { + "templatePath": "toolstemplates/", + "log": 1, + "logLocation": "/usr/local/tomcat/logs/CofaxTools.log", + "logMaxSize": "", + "dataLog": 1, + "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log", + "dataLogMaxSize": "", + "removePageCache": "/content/admin/remove?cache=pages&id=", + "removeTemplateCache": "/content/admin/remove?cache=templates&id=", + "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder", + "lookInContext": 1, + "adminGroupID": 4, + "betaServer": true}}], + "servlet-mapping": { + "cofaxCDS": "/", + "cofaxEmail": "/cofaxutil/aemail/*", + "cofaxAdmin": "/admin/*", + "fileServlet": "/static/*", + "cofaxTools": "/tools/*"}, + + "taglib": { + "taglib-uri": "cofax.tld", + "taglib-location": "/WEB-INF/tlds/cofax.tld"}}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test5 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test5 new file mode 100644 index 0000000..f6cc84e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test5 @@ -0,0 +1,27 @@ +bf{"menu": { + "header": "SVG Viewer", + "items": [ + {"id": "Open"}, + {"id": "OpenNew", "label": "Open New"}, + null, + {"id": "ZoomIn", "label": "Zoom In"}, + {"id": "ZoomOut", "label": "Zoom Out"}, + {"id": "OriginalView", "label": "Original View"}, + null, + {"id": "Quality"}, + {"id": "Pause"}, + {"id": "Mute"}, + null, + {"id": "Find", "label": "Find..."}, + {"id": "FindAgain", "label": "Find Again"}, + {"id": "Copy"}, + {"id": "CopyAgain", "label": "Copy Again"}, + {"id": "CopySVG", "label": "Copy SVG"}, + {"id": "ViewSVG", "label": "View SVG"}, + {"id": "ViewSource", "label": "View Source"}, + {"id": "SaveAs", "label": "Save As"}, + null, + {"id": "Help"}, + {"id": "About", "label": "About Adobe CVG Viewer..."} + ] +}} diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test6 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test6 new file mode 100644 index 0000000..af27975 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test6 @@ -0,0 +1,16 @@ +bf + + + + + Application Error + + + + + diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test7 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test7 new file mode 100644 index 0000000..4a3c0b7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test7 @@ -0,0 +1,22 @@ +bf[ + { + "precision": "zip", + "Latitude": 37.7668, + "Longitude": -122.3959, + "Address": "", + "City": "SAN FRANCISCO", + "State": "CA", + "Zip": "94107", + "Country": "US" + }, + { + "precision": "zip", + "Latitude": 37.371991, + "Longitude": -122.026020, + "Address": "", + "City": "SUNNYVALE", + "State": "CA", + "Zip": "94085", + "Country": "US" + } + ] diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test8 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test8 new file mode 100644 index 0000000..3ffe570 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test8 @@ -0,0 +1,13 @@ +bf{ + "Image": { + "Width": 800, + "Height": 600, + "Title": "View from 15th Floor", + "Thumbnail": { + "Url": "http:/*www.example.com/image/481989943", + "Height": 125, + "Width": "100" + }, + "IDs": [116, 943, 234, 38793] + } + } diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test9 b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test9 new file mode 100644 index 0000000..28c9033 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/inputs/test9 @@ -0,0 +1,5 @@ +bf[ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ] diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/json.dict b/managed_components/espressif__cjson/cJSON/fuzzing/json.dict new file mode 100644 index 0000000..9bb03d7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/json.dict @@ -0,0 +1,47 @@ +# +# AFL dictionary for JSON +# ----------------------------- +# + +object_start="{" +object_end="}" +object_empty="{}" +object_one_element="{\"one\":1}" +object_two_elements="{\"1\":1,\"2\":2}" +object_separator=":" + +array_start="[" +array_end="]" +array_empty="[]" +array_one_element="[1]" +array_two_elements="[1,2]" + +separator="," + +escape_sequence_b="\\b" +escape_sequence_f="\\f" +escape_sequence_n="\\n" +escape_sequence_r="\\r" +escape_sequence_t="\\t" +escape_sequence_quote="\\\"" +escape_sequence_backslash="\\\\" +escape_sequence_slash="\\/" +escape_sequence_utf16_base="\\u" +escape_sequence_utf16="\\u12ab" + +number_integer="1" +number_double="1.0" +number_negative_integer="-1" +number_negative_double="-1.0" +number_engineering1="1e1" +number_engineering2="1e-1" +number_positive_integer="+1" +number_positive_double="+1.0" +number_e="e" +number_plus="+" +number_minus="-" +number_separator="." + +null="null" +true="true" +false="false" diff --git a/managed_components/espressif__cjson/cJSON/fuzzing/ossfuzz.sh b/managed_components/espressif__cjson/cJSON/fuzzing/ossfuzz.sh new file mode 100644 index 0000000..a2da64b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/fuzzing/ossfuzz.sh @@ -0,0 +1,18 @@ +#!/bin/bash -eu + +# This script is meant to be run by +# https://github.com/google/oss-fuzz/blob/master/projects/cjson/Dockerfile + +mkdir build +cd build +cmake -DBUILD_SHARED_LIBS=OFF -DENABLE_CJSON_TEST=OFF .. +make -j$(nproc) + +$CXX $CXXFLAGS $SRC/cjson/fuzzing/cjson_read_fuzzer.c -I. \ + -o $OUT/cjson_read_fuzzer \ + $LIB_FUZZING_ENGINE $SRC/cjson/build/libcjson.a + +find $SRC/cjson/fuzzing/inputs -name "*" | \ + xargs zip $OUT/cjson_read_fuzzer_seed_corpus.zip + +cp $SRC/cjson/fuzzing/json.dict $OUT/cjson_read_fuzzer.dict diff --git a/managed_components/espressif__cjson/cJSON/library_config/cJSONConfig.cmake.in b/managed_components/espressif__cjson/cJSON/library_config/cJSONConfig.cmake.in new file mode 100644 index 0000000..909f7a9 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/library_config/cJSONConfig.cmake.in @@ -0,0 +1,29 @@ +# Whether the utils lib was build. +set(CJSON_UTILS_FOUND @ENABLE_CJSON_UTILS@) + +# The include directories used by cJSON +set(CJSON_INCLUDE_DIRS "@CMAKE_INSTALL_FULL_INCLUDEDIR@") +set(CJSON_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@") + +get_filename_component(_dir "${CMAKE_CURRENT_LIST_FILE}" PATH) + +# The cJSON library +set(CJSON_LIBRARY "@CJSON_LIB@") +if(@ENABLE_TARGET_EXPORT@) + # Include the target + include("${_dir}/cjson.cmake") +endif() + +if(CJSON_UTILS_FOUND) + # The cJSON utils library + set(CJSON_UTILS_LIBRARY @CJSON_UTILS_LIB@) + # All cJSON libraries + set(CJSON_LIBRARIES "@CJSON_UTILS_LIB@" "@CJSON_LIB@") + if(@ENABLE_TARGET_EXPORT@) + # Include the target + include("${_dir}/cjson_utils.cmake") + endif() +else() + # All cJSON libraries + set(CJSON_LIBRARIES "@CJSON_LIB@") +endif() diff --git a/managed_components/espressif__cjson/cJSON/library_config/cJSONConfigVersion.cmake.in b/managed_components/espressif__cjson/cJSON/library_config/cJSONConfigVersion.cmake.in new file mode 100644 index 0000000..22ffec0 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/library_config/cJSONConfigVersion.cmake.in @@ -0,0 +1,11 @@ +set(PACKAGE_VERSION "@PROJECT_VERSION@") + +# Check whether the requested PACKAGE_FIND_VERSION is compatible +if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") + set(PACKAGE_VERSION_COMPATIBLE FALSE) +else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") + set(PACKAGE_VERSION_EXACT TRUE) + endif() +endif() diff --git a/managed_components/espressif__cjson/cJSON/library_config/libcjson.pc.in b/managed_components/espressif__cjson/cJSON/library_config/libcjson.pc.in new file mode 100644 index 0000000..de48fe0 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/library_config/libcjson.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: libcjson +Version: @PROJECT_VERSION@ +Description: Ultralightweight JSON parser in ANSI C +URL: https://github.com/DaveGamble/cJSON +Libs: -L${libdir} -lcjson +Libs.private: -lm +Cflags: -I${includedir} -I${includedir}/cjson diff --git a/managed_components/espressif__cjson/cJSON/library_config/libcjson_utils.pc.in b/managed_components/espressif__cjson/cJSON/library_config/libcjson_utils.pc.in new file mode 100644 index 0000000..df2b4e5 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/library_config/libcjson_utils.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: libcjson_utils +Version: @PROJECT_VERSION@ +Description: An implementation of JSON Pointer, Patch and Merge Patch based on cJSON. +URL: https://github.com/DaveGamble/cJSON +Libs: -L${libdir} -lcjson_utils +Cflags: -I${includedir} -I${includedir}/cjson +Requires: libcjson diff --git a/managed_components/espressif__cjson/cJSON/library_config/uninstall.cmake b/managed_components/espressif__cjson/cJSON/library_config/uninstall.cmake new file mode 100644 index 0000000..a400668 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/library_config/uninstall.cmake @@ -0,0 +1,27 @@ +cmake_minimum_required(VERSION 3.5) + +set(MANIFEST "${CMAKE_CURRENT_BINARY_DIR}/install_manifest.txt") + +if(NOT EXISTS ${MANIFEST}) + message(FATAL_ERROR "Cannot find install mainfest: ${MANIFEST}") +endif() + +file(STRINGS ${MANIFEST} files) +foreach(file ${files}) + if(EXISTS ${file} OR IS_SYMLINK ${file}) + message(STATUS "Removing: ${file}") + + execute_process(COMMAND rm -f ${file} + RESULT_VARIABLE result + OUTPUT_QUIET + ERROR_VARIABLE stderr + ERROR_STRIP_TRAILING_WHITESPACE + ) + + if(NOT ${result} EQUAL 0) + message(FATAL_ERROR "${stderr}") + endif() + else() + message(STATUS "Does-not-exist: ${file}") + endif() +endforeach(file) diff --git a/managed_components/espressif__cjson/cJSON/test.c b/managed_components/espressif__cjson/cJSON/test.c new file mode 100644 index 0000000..986fc6e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/test.c @@ -0,0 +1,268 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include +#include "cJSON.h" + +/* Used by some code below as an example datatype. */ +struct record +{ + const char *precision; + double lat; + double lon; + const char *address; + const char *city; + const char *state; + const char *zip; + const char *country; +}; + + +/* Create a bunch of objects as demonstration. */ +static int print_preallocated(cJSON *root) +{ + /* declarations */ + char *out = NULL; + char *buf = NULL; + char *buf_fail = NULL; + size_t len = 0; + size_t len_fail = 0; + + /* formatted print */ + out = cJSON_Print(root); + + /* create buffer to succeed */ + /* the extra 5 bytes are because of inaccuracies when reserving memory */ + len = strlen(out) + 5; + buf = (char*)malloc(len); + if (buf == NULL) + { + printf("Failed to allocate memory.\n"); + exit(1); + } + + /* create buffer to fail */ + len_fail = strlen(out); + buf_fail = (char*)malloc(len_fail); + if (buf_fail == NULL) + { + printf("Failed to allocate memory.\n"); + exit(1); + } + + /* Print to buffer */ + if (!cJSON_PrintPreallocated(root, buf, (int)len, 1)) { + printf("cJSON_PrintPreallocated failed!\n"); + if (strcmp(out, buf) != 0) { + printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n"); + printf("cJSON_Print result:\n%s\n", out); + printf("cJSON_PrintPreallocated result:\n%s\n", buf); + } + free(out); + free(buf_fail); + free(buf); + return -1; + } + + /* success */ + printf("%s\n", buf); + + /* force it to fail */ + if (cJSON_PrintPreallocated(root, buf_fail, (int)len_fail, 1)) { + printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n"); + printf("cJSON_Print result:\n%s\n", out); + printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail); + free(out); + free(buf_fail); + free(buf); + return -1; + } + + free(out); + free(buf_fail); + free(buf); + return 0; +} + +/* Create a bunch of objects as demonstration. */ +static void create_objects(void) +{ + /* declare a few. */ + cJSON *root = NULL; + cJSON *fmt = NULL; + cJSON *img = NULL; + cJSON *thm = NULL; + cJSON *fld = NULL; + int i = 0; + + /* Our "days of the week" array: */ + const char *strings[7] = + { + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + }; + /* Our matrix: */ + int numbers[3][3] = + { + {0, -1, 0}, + {1, 0, 0}, + {0 ,0, 1} + }; + /* Our "gallery" item: */ + int ids[4] = { 116, 943, 234, 38793 }; + /* Our array of "records": */ + struct record fields[2] = + { + { + "zip", + 37.7668, + -1.223959e+2, + "", + "SAN FRANCISCO", + "CA", + "94107", + "US" + }, + { + "zip", + 37.371991, + -1.22026e+2, + "", + "SUNNYVALE", + "CA", + "94085", + "US" + } + }; + volatile double zero = 0.0; + + /* Here we construct some JSON standards, from the JSON site. */ + + /* Our "Video" datatype: */ + root = cJSON_CreateObject(); + cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble")); + cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject()); + cJSON_AddStringToObject(fmt, "type", "rect"); + cJSON_AddNumberToObject(fmt, "width", 1920); + cJSON_AddNumberToObject(fmt, "height", 1080); + cJSON_AddFalseToObject (fmt, "interlace"); + cJSON_AddNumberToObject(fmt, "frame rate", 24); + + /* Print to text */ + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); + + /* Our "days of the week" array: */ + root = cJSON_CreateStringArray(strings, 7); + + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); + + /* Our matrix: */ + root = cJSON_CreateArray(); + for (i = 0; i < 3; i++) + { + cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3)); + } + + /* cJSON_ReplaceItemInArray(root, 1, cJSON_CreateString("Replacement")); */ + + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); + + /* Our "gallery" item: */ + root = cJSON_CreateObject(); + cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject()); + cJSON_AddNumberToObject(img, "Width", 800); + cJSON_AddNumberToObject(img, "Height", 600); + cJSON_AddStringToObject(img, "Title", "View from 15th Floor"); + cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject()); + cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943"); + cJSON_AddNumberToObject(thm, "Height", 125); + cJSON_AddStringToObject(thm, "Width", "100"); + cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4)); + + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); + + /* Our array of "records": */ + root = cJSON_CreateArray(); + for (i = 0; i < 2; i++) + { + cJSON_AddItemToArray(root, fld = cJSON_CreateObject()); + cJSON_AddStringToObject(fld, "precision", fields[i].precision); + cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat); + cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon); + cJSON_AddStringToObject(fld, "Address", fields[i].address); + cJSON_AddStringToObject(fld, "City", fields[i].city); + cJSON_AddStringToObject(fld, "State", fields[i].state); + cJSON_AddStringToObject(fld, "Zip", fields[i].zip); + cJSON_AddStringToObject(fld, "Country", fields[i].country); + } + + /* cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root, 1), "City", cJSON_CreateIntArray(ids, 4)); */ + + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); + + root = cJSON_CreateObject(); + cJSON_AddNumberToObject(root, "number", 1.0 / zero); + + if (print_preallocated(root) != 0) { + cJSON_Delete(root); + exit(EXIT_FAILURE); + } + cJSON_Delete(root); +} + +int CJSON_CDECL main(void) +{ + /* print the version */ + printf("Version: %s\n", cJSON_Version()); + + /* Now some samplecode for building objects concisely: */ + create_objects(); + + return 0; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/CMakeLists.txt b/managed_components/espressif__cjson/cJSON/tests/CMakeLists.txt new file mode 100644 index 0000000..c759221 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/CMakeLists.txt @@ -0,0 +1,119 @@ +if(ENABLE_CJSON_TEST) + add_library(unity STATIC unity/src/unity.c) + + # Disable -Werror for Unity + if (FLAG_SUPPORTED_Werror) + if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error") + else() + target_compile_options(unity PRIVATE "-Wno-error") + endif() + endif() + # Disable -fvisibility=hidden for Unity + if (FLAG_SUPPORTED_fvisibilityhidden) + if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=default") + else() + target_compile_options(unity PRIVATE "-fvisibility=default") + endif() + endif() + # Disable -fsanitize=float-divide-by-zero for Unity (GCC bug on x86 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80097) + if (FLAG_SUPPORTED_fsanitizefloatdividebyzero AND (CMAKE_C_COMPILER_ID STREQUAL "GNU")) + if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-sanitize=float-divide-by-zero") + else() + target_compile_options(unity PRIVATE "-fno-sanitize=float-divide-by-zero") + endif() + endif() + # Disable -Wswitch-enum for Unity + if (FLAG_SUPPORTED_Wswitchenum) + if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-switch-enum") + else() + target_compile_options(unity PRIVATE "-Wno-switch-enum") + endif() + endif() + + #copy test files + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/inputs") + file(GLOB test_files "inputs/*") + file(COPY ${test_files} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/inputs/") + + set(unity_tests + parse_examples + parse_number + parse_hex4 + parse_string + parse_array + parse_object + parse_value + print_string + print_number + print_array + print_object + print_value + misc_tests + parse_with_opts + compare_tests + cjson_add + readme_examples + minify_tests + ) + + option(ENABLE_VALGRIND OFF "Enable the valgrind memory checker for the tests.") + if (ENABLE_VALGRIND) + find_program(MEMORYCHECK_COMMAND valgrind) + if ("${MEMORYCHECK_COMMAND}" MATCHES "MEMORYCHECK_COMMAND-NOTFOUND") + message(WARNING "Valgrind couldn't be found.") + unset(MEMORYCHECK_COMMAND) + else() + set(MEMORYCHECK_COMMAND_OPTIONS --trace-children=yes --leak-check=full --error-exitcode=1 --suppressions=${CMAKE_CURRENT_SOURCE_DIR}/../valgrind.supp) + endif() + endif() + + foreach(unity_test ${unity_tests}) + add_executable("${unity_test}" "${unity_test}.c") + if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC") + target_sources(${unity_test} PRIVATE unity_setup.c) + endif() + target_link_libraries("${unity_test}" "${CJSON_LIB}" unity) + if(MEMORYCHECK_COMMAND) + add_test(NAME "${unity_test}" + COMMAND "${MEMORYCHECK_COMMAND}" ${MEMORYCHECK_COMMAND_OPTIONS} "${CMAKE_CURRENT_BINARY_DIR}/${unity_test}") + else() + add_test(NAME "${unity_test}" + COMMAND "./${unity_test}") + endif() + endforeach() + + add_dependencies(check ${unity_tests}) + + if (ENABLE_CJSON_UTILS) + #copy test files + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests") + file(GLOB test_files "json-patch-tests/*") + file(COPY ${test_files} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests/") + + set (cjson_utils_tests + json_patch_tests + old_utils_tests + misc_utils_tests) + + foreach (cjson_utils_test ${cjson_utils_tests}) + add_executable("${cjson_utils_test}" "${cjson_utils_test}.c") + target_link_libraries("${cjson_utils_test}" "${CJSON_LIB}" "${CJSON_UTILS_LIB}" unity) + if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC") + target_sources(${cjson_utils_test} PRIVATE unity_setup.c) + endif() + if(MEMORYCHECK_COMMAND) + add_test(NAME "${cjson_utils_test}" + COMMAND "${MEMORYCHECK_COMMAND}" ${MEMORYCHECK_COMMAND_OPTIONS} "${CMAKE_CURRENT_BINARY_DIR}/${cjson_utils_test}") + else() + add_test(NAME "${cjson_utils_test}" + COMMAND "./${cjson_utils_test}") + endif() + endforeach() + + add_dependencies(check ${cjson_utils_tests}) + endif() +endif() diff --git a/managed_components/espressif__cjson/cJSON/tests/cjson_add.c b/managed_components/espressif__cjson/cJSON/tests/cjson_add.c new file mode 100644 index 0000000..ac96ce7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/cjson_add.c @@ -0,0 +1,471 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void * CJSON_CDECL failing_malloc(size_t size) +{ + (void)size; + return NULL; +} + +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void CJSON_CDECL normal_free(void *pointer) +{ + free(pointer); +} + +static cJSON_Hooks failing_hooks = { + failing_malloc, + normal_free +}; + +static void cjson_add_null_should_add_null(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *null = NULL; + + cJSON_AddNullToObject(root, "null"); + + TEST_ASSERT_NOT_NULL(null = cJSON_GetObjectItemCaseSensitive(root, "null")); + TEST_ASSERT_EQUAL_INT(null->type, cJSON_NULL); + + cJSON_Delete(root); +} + +static void cjson_add_null_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddNullToObject(NULL, "null")); + TEST_ASSERT_NULL(cJSON_AddNullToObject(root, NULL)); + + cJSON_Delete(root); +} + +static void cjson_add_null_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddNullToObject(root, "null")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_add_true_should_add_true(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *true_item = NULL; + + cJSON_AddTrueToObject(root, "true"); + + TEST_ASSERT_NOT_NULL(true_item = cJSON_GetObjectItemCaseSensitive(root, "true")); + TEST_ASSERT_EQUAL_INT(true_item->type, cJSON_True); + + cJSON_Delete(root); +} + +static void cjson_add_true_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddTrueToObject(NULL, "true")); + TEST_ASSERT_NULL(cJSON_AddTrueToObject(root, NULL)); + + cJSON_Delete(root); +} + +static void cjson_add_true_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddTrueToObject(root, "true")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_create_int_array_should_fail_on_allocation_failure(void) +{ + int numbers[] = {1, 2, 3}; + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_CreateIntArray(numbers, 3)); + + cJSON_InitHooks(NULL); +} + +static void cjson_create_float_array_should_fail_on_allocation_failure(void) +{ + float numbers[] = {1.0f, 2.0f, 3.0f}; + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_CreateFloatArray(numbers, 3)); + + cJSON_InitHooks(NULL); +} + +static void cjson_create_double_array_should_fail_on_allocation_failure(void) +{ + double numbers[] = {1.0, 2.0, 3.0}; + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_CreateDoubleArray(numbers, 3)); + + cJSON_InitHooks(NULL); +} + +static void cjson_create_string_array_should_fail_on_allocation_failure(void) +{ + const char* strings[] = {"1", "2", "3"}; + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_CreateStringArray(strings, 3)); + + cJSON_InitHooks(NULL); +} + +static void cjson_add_false_should_add_false(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *false_item = NULL; + + cJSON_AddFalseToObject(root, "false"); + + TEST_ASSERT_NOT_NULL(false_item = cJSON_GetObjectItemCaseSensitive(root, "false")); + TEST_ASSERT_EQUAL_INT(false_item->type, cJSON_False); + + cJSON_Delete(root); +} + +static void cjson_add_false_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddFalseToObject(NULL, "false")); + TEST_ASSERT_NULL(cJSON_AddFalseToObject(root, NULL)); + + cJSON_Delete(root); +} + +static void cjson_add_false_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddFalseToObject(root, "false")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_add_bool_should_add_bool(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *true_item = NULL; + cJSON *false_item = NULL; + + /* true */ + cJSON_AddBoolToObject(root, "true", true); + TEST_ASSERT_NOT_NULL(true_item = cJSON_GetObjectItemCaseSensitive(root, "true")); + TEST_ASSERT_EQUAL_INT(true_item->type, cJSON_True); + + /* false */ + cJSON_AddBoolToObject(root, "false", false); + TEST_ASSERT_NOT_NULL(false_item = cJSON_GetObjectItemCaseSensitive(root, "false")); + TEST_ASSERT_EQUAL_INT(false_item->type, cJSON_False); + + cJSON_Delete(root); +} + +static void cjson_add_bool_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddBoolToObject(NULL, "false", false)); + TEST_ASSERT_NULL(cJSON_AddBoolToObject(root, NULL, false)); + + cJSON_Delete(root); +} + +static void cjson_add_bool_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddBoolToObject(root, "false", false)); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_add_number_should_add_number(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *number = NULL; + + cJSON_AddNumberToObject(root, "number", 42); + + TEST_ASSERT_NOT_NULL(number = cJSON_GetObjectItemCaseSensitive(root, "number")); + + TEST_ASSERT_EQUAL_INT(number->type, cJSON_Number); + TEST_ASSERT_EQUAL_DOUBLE(number->valuedouble, 42); + TEST_ASSERT_EQUAL_INT(number->valueint, 42); + + cJSON_Delete(root); +} + +static void cjson_add_number_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddNumberToObject(NULL, "number", 42)); + TEST_ASSERT_NULL(cJSON_AddNumberToObject(root, NULL, 42)); + + cJSON_Delete(root); +} + +static void cjson_add_number_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddNumberToObject(root, "number", 42)); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_add_string_should_add_string(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *string = NULL; + + cJSON_AddStringToObject(root, "string", "Hello World!"); + + TEST_ASSERT_NOT_NULL(string = cJSON_GetObjectItemCaseSensitive(root, "string")); + TEST_ASSERT_EQUAL_INT(string->type, cJSON_String); + TEST_ASSERT_EQUAL_STRING(string->valuestring, "Hello World!"); + + cJSON_Delete(root); +} + +static void cjson_add_string_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddStringToObject(NULL, "string", "string")); + TEST_ASSERT_NULL(cJSON_AddStringToObject(root, NULL, "string")); + + cJSON_Delete(root); +} + +static void cjson_add_string_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddStringToObject(root, "string", "string")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cjson_add_raw_should_add_raw(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *raw = NULL; + + cJSON_AddRawToObject(root, "raw", "{}"); + + TEST_ASSERT_NOT_NULL(raw = cJSON_GetObjectItemCaseSensitive(root, "raw")); + TEST_ASSERT_EQUAL_INT(raw->type, cJSON_Raw); + TEST_ASSERT_EQUAL_STRING(raw->valuestring, "{}"); + + cJSON_Delete(root); +} + +static void cjson_add_raw_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddRawToObject(NULL, "raw", "{}")); + TEST_ASSERT_NULL(cJSON_AddRawToObject(root, NULL, "{}")); + + cJSON_Delete(root); +} + +static void cjson_add_raw_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddRawToObject(root, "raw", "{}")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cJSON_add_object_should_add_object(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *object = NULL; + + cJSON_AddObjectToObject(root, "object"); + TEST_ASSERT_NOT_NULL(object = cJSON_GetObjectItemCaseSensitive(root, "object")); + TEST_ASSERT_EQUAL_INT(object->type, cJSON_Object); + + cJSON_Delete(root); +} + +static void cjson_add_object_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddObjectToObject(NULL, "object")); + TEST_ASSERT_NULL(cJSON_AddObjectToObject(root, NULL)); + + cJSON_Delete(root); +} + +static void cjson_add_object_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddObjectToObject(root, "object")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +static void cJSON_add_array_should_add_array(void) +{ + cJSON *root = cJSON_CreateObject(); + cJSON *array = NULL; + + cJSON_AddArrayToObject(root, "array"); + TEST_ASSERT_NOT_NULL(array = cJSON_GetObjectItemCaseSensitive(root, "array")); + TEST_ASSERT_EQUAL_INT(array->type, cJSON_Array); + + cJSON_Delete(root); +} + +static void cjson_add_array_should_fail_with_null_pointers(void) +{ + cJSON *root = cJSON_CreateObject(); + + TEST_ASSERT_NULL(cJSON_AddArrayToObject(NULL, "array")); + TEST_ASSERT_NULL(cJSON_AddArrayToObject(root, NULL)); + + cJSON_Delete(root); +} + +static void cjson_add_array_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateObject(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddArrayToObject(root, "array")); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_add_null_should_add_null); + RUN_TEST(cjson_add_null_should_fail_with_null_pointers); + RUN_TEST(cjson_add_null_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_true_should_add_true); + RUN_TEST(cjson_add_true_should_fail_with_null_pointers); + RUN_TEST(cjson_add_true_should_fail_on_allocation_failure); + + RUN_TEST(cjson_create_int_array_should_fail_on_allocation_failure); + RUN_TEST(cjson_create_float_array_should_fail_on_allocation_failure); + RUN_TEST(cjson_create_double_array_should_fail_on_allocation_failure); + RUN_TEST(cjson_create_string_array_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_false_should_add_false); + RUN_TEST(cjson_add_false_should_fail_with_null_pointers); + RUN_TEST(cjson_add_false_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_bool_should_add_bool); + RUN_TEST(cjson_add_bool_should_fail_with_null_pointers); + RUN_TEST(cjson_add_bool_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_number_should_add_number); + RUN_TEST(cjson_add_number_should_fail_with_null_pointers); + RUN_TEST(cjson_add_number_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_string_should_add_string); + RUN_TEST(cjson_add_string_should_fail_with_null_pointers); + RUN_TEST(cjson_add_string_should_fail_on_allocation_failure); + + RUN_TEST(cjson_add_raw_should_add_raw); + RUN_TEST(cjson_add_raw_should_fail_with_null_pointers); + RUN_TEST(cjson_add_raw_should_fail_on_allocation_failure); + + RUN_TEST(cJSON_add_object_should_add_object); + RUN_TEST(cjson_add_object_should_fail_with_null_pointers); + RUN_TEST(cjson_add_object_should_fail_on_allocation_failure); + + RUN_TEST(cJSON_add_array_should_add_array); + RUN_TEST(cjson_add_array_should_fail_with_null_pointers); + RUN_TEST(cjson_add_array_should_fail_on_allocation_failure); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/common.h b/managed_components/espressif__cjson/cJSON/tests/common.h new file mode 100644 index 0000000..4db6bf8 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/common.h @@ -0,0 +1,122 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef CJSON_TESTS_COMMON_H +#define CJSON_TESTS_COMMON_H + +#include "../cJSON.c" + +void reset(cJSON *item); +void reset(cJSON *item) { + if ((item != NULL) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if ((item->valuestring != NULL) && !(item->type & cJSON_IsReference)) + { + global_hooks.deallocate(item->valuestring); + } + if ((item->string != NULL) && !(item->type & cJSON_StringIsConst)) + { + global_hooks.deallocate(item->string); + } + + memset(item, 0, sizeof(cJSON)); +} + +char* read_file(const char *filename); +char* read_file(const char *filename) { + FILE *file = NULL; + long length = 0; + char *content = NULL; + size_t read_chars = 0; + + /* open in read binary mode */ + file = fopen(filename, "rb"); + if (file == NULL) + { + goto cleanup; + } + + /* get the length */ + if (fseek(file, 0, SEEK_END) != 0) + { + goto cleanup; + } + length = ftell(file); + if (length < 0) + { + goto cleanup; + } + if (fseek(file, 0, SEEK_SET) != 0) + { + goto cleanup; + } + + /* allocate content buffer */ + content = (char*)malloc((size_t)length + sizeof("")); + if (content == NULL) + { + goto cleanup; + } + + /* read the file into memory */ + read_chars = fread(content, sizeof(char), (size_t)length, file); + if ((long)read_chars != length) + { + free(content); + content = NULL; + goto cleanup; + } + content[read_chars] = '\0'; + + +cleanup: + if (file != NULL) + { + fclose(file); + } + + return content; +} + +/* assertion helper macros */ +#define assert_has_type(item, item_type) TEST_ASSERT_BITS_MESSAGE(0xFF, item_type, item->type, "Item doesn't have expected type.") +#define assert_has_no_reference(item) TEST_ASSERT_BITS_MESSAGE(cJSON_IsReference, 0, item->type, "Item should not have a string as reference.") +#define assert_has_no_const_string(item) TEST_ASSERT_BITS_MESSAGE(cJSON_StringIsConst, 0, item->type, "Item should not have a const string.") +#define assert_has_valuestring(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->valuestring, "Valuestring is NULL.") +#define assert_has_no_valuestring(item) TEST_ASSERT_NULL_MESSAGE(item->valuestring, "Valuestring is not NULL.") +#define assert_has_string(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->string, "String is NULL") +#define assert_has_no_string(item) TEST_ASSERT_NULL_MESSAGE(item->string, "String is not NULL.") +#define assert_not_in_list(item) \ + TEST_ASSERT_NULL_MESSAGE(item->next, "Linked list next pointer is not NULL.");\ + TEST_ASSERT_NULL_MESSAGE(item->prev, "Linked list previous pointer is not NULL.") +#define assert_has_child(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->child, "Item doesn't have a child.") +#define assert_has_no_child(item) TEST_ASSERT_NULL_MESSAGE(item->child, "Item has a child.") +#define assert_is_invalid(item) \ + assert_has_type(item, cJSON_Invalid);\ + assert_not_in_list(item);\ + assert_has_no_child(item);\ + assert_has_no_string(item);\ + assert_has_no_valuestring(item) + +#endif diff --git a/managed_components/espressif__cjson/cJSON/tests/compare_tests.c b/managed_components/espressif__cjson/cJSON/tests/compare_tests.c new file mode 100644 index 0000000..797c774 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/compare_tests.c @@ -0,0 +1,208 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON_bool compare_from_string(const char * const a, const char * const b, const cJSON_bool case_sensitive) +{ + cJSON *a_json = NULL; + cJSON *b_json = NULL; + cJSON_bool result = false; + + a_json = cJSON_Parse(a); + TEST_ASSERT_NOT_NULL_MESSAGE(a_json, "Failed to parse a."); + b_json = cJSON_Parse(b); + TEST_ASSERT_NOT_NULL_MESSAGE(b_json, "Failed to parse b."); + + result = cJSON_Compare(a_json, b_json, case_sensitive); + + cJSON_Delete(a_json); + cJSON_Delete(b_json); + + return result; +} + +static void cjson_compare_should_compare_null_pointer_as_not_equal(void) +{ + TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, true)); + TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, false)); +} + +static void cjson_compare_should_compare_invalid_as_not_equal(void) +{ + cJSON invalid[1]; + memset(invalid, '\0', sizeof(invalid)); + + TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false)); + TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true)); +} + +static void cjson_compare_should_compare_numbers(void) +{ + TEST_ASSERT_TRUE(compare_from_string("1", "1", true)); + TEST_ASSERT_TRUE(compare_from_string("1", "1", false)); + TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", true)); + TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", false)); + TEST_ASSERT_TRUE(compare_from_string("1E100", "10E99", false)); + + TEST_ASSERT_FALSE(compare_from_string("0.5E-100", "0.5E-101", false)); + + TEST_ASSERT_FALSE(compare_from_string("1", "2", true)); + TEST_ASSERT_FALSE(compare_from_string("1", "2", false)); +} + +static void cjson_compare_should_compare_booleans(void) +{ + /* true */ + TEST_ASSERT_TRUE(compare_from_string("true", "true", true)); + TEST_ASSERT_TRUE(compare_from_string("true", "true", false)); + + /* false */ + TEST_ASSERT_TRUE(compare_from_string("false", "false", true)); + TEST_ASSERT_TRUE(compare_from_string("false", "false", false)); + + /* mixed */ + TEST_ASSERT_FALSE(compare_from_string("true", "false", true)); + TEST_ASSERT_FALSE(compare_from_string("true", "false", false)); + TEST_ASSERT_FALSE(compare_from_string("false", "true", true)); + TEST_ASSERT_FALSE(compare_from_string("false", "true", false)); +} + +static void cjson_compare_should_compare_null(void) +{ + TEST_ASSERT_TRUE(compare_from_string("null", "null", true)); + TEST_ASSERT_TRUE(compare_from_string("null", "null", false)); + + TEST_ASSERT_FALSE(compare_from_string("null", "true", true)); + TEST_ASSERT_FALSE(compare_from_string("null", "true", false)); +} + +static void cjson_compare_should_not_accept_invalid_types(void) +{ + cJSON invalid[1]; + memset(invalid, '\0', sizeof(invalid)); + + invalid->type = cJSON_Number | cJSON_String; + + TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true)); + TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false)); +} + +static void cjson_compare_should_compare_strings(void) +{ + TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", true)); + TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", false)); + + TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", true)); + TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", false)); +} + +static void cjson_compare_should_compare_raw(void) +{ + cJSON *raw1 = NULL; + cJSON *raw2 = NULL; + + raw1 = cJSON_Parse("\"[true, false]\""); + TEST_ASSERT_NOT_NULL(raw1); + raw2 = cJSON_Parse("\"[true, false]\""); + TEST_ASSERT_NOT_NULL(raw2); + + raw1->type = cJSON_Raw; + raw2->type = cJSON_Raw; + + TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, true)); + TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, false)); + + cJSON_Delete(raw1); + cJSON_Delete(raw2); +} + +static void cjson_compare_should_compare_arrays(void) +{ + TEST_ASSERT_TRUE(compare_from_string("[]", "[]", true)); + TEST_ASSERT_TRUE(compare_from_string("[]", "[]", false)); + + TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true)); + TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false)); + + TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", true)); + TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", false)); + + TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true)); + TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false)); + + /* Arrays that are a prefix of another array */ + TEST_ASSERT_FALSE(compare_from_string("[1,2,3]", "[1,2]", true)); + TEST_ASSERT_FALSE(compare_from_string("[1,2,3]", "[1,2]", false)); +} + +static void cjson_compare_should_compare_objects(void) +{ + TEST_ASSERT_TRUE(compare_from_string("{}", "{}", true)); + TEST_ASSERT_TRUE(compare_from_string("{}", "{}", false)); + + TEST_ASSERT_TRUE(compare_from_string( + "{\"false\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + "{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + true)); + TEST_ASSERT_FALSE(compare_from_string( + "{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + "{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + true)); + TEST_ASSERT_TRUE(compare_from_string( + "{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + "{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + false)); + TEST_ASSERT_FALSE(compare_from_string( + "{\"Flse\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + "{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}", + false)); + /* test objects that are a subset of each other */ + TEST_ASSERT_FALSE(compare_from_string( + "{\"one\": 1, \"two\": 2}", + "{\"one\": 1, \"two\": 2, \"three\": 3}", + true)) + TEST_ASSERT_FALSE(compare_from_string( + "{\"one\": 1, \"two\": 2}", + "{\"one\": 1, \"two\": 2, \"three\": 3}", + false)) +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_compare_should_compare_null_pointer_as_not_equal); + RUN_TEST(cjson_compare_should_compare_invalid_as_not_equal); + RUN_TEST(cjson_compare_should_compare_numbers); + RUN_TEST(cjson_compare_should_compare_booleans); + RUN_TEST(cjson_compare_should_compare_null); + RUN_TEST(cjson_compare_should_not_accept_invalid_types); + RUN_TEST(cjson_compare_should_compare_strings); + RUN_TEST(cjson_compare_should_compare_raw); + RUN_TEST(cjson_compare_should_compare_arrays); + RUN_TEST(cjson_compare_should_compare_objects); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test1 b/managed_components/espressif__cjson/cJSON/tests/inputs/test1 new file mode 100644 index 0000000..eacfbf5 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test1 @@ -0,0 +1,22 @@ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": ["GML", "XML"] + }, + "GlossSee": "markup" + } + } + } + } +} diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test1.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test1.expected new file mode 100644 index 0000000..a5839e8 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test1.expected @@ -0,0 +1,22 @@ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": ["GML", "XML"] + }, + "GlossSee": "markup" + } + } + } + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test10 b/managed_components/espressif__cjson/cJSON/tests/inputs/test10 new file mode 100644 index 0000000..d19eb8b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test10 @@ -0,0 +1 @@ +["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test10.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test10.expected new file mode 100644 index 0000000..747ba62 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test10.expected @@ -0,0 +1 @@ +["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test11 b/managed_components/espressif__cjson/cJSON/tests/inputs/test11 new file mode 100644 index 0000000..039c61b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test11 @@ -0,0 +1,8 @@ +{ +"name": "Jack (\"Bee\") Nimble", +"format": {"type": "rect", +"width": 1920, +"height": 1080, +"interlace": false,"frame rate": 24 +} +} diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test11.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test11.expected new file mode 100644 index 0000000..24e72ec --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test11.expected @@ -0,0 +1,10 @@ +{ + "name": "Jack (\"Bee\") Nimble", + "format": { + "type": "rect", + "width": 1920, + "height": 1080, + "interlace": false, + "frame rate": 24 + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test2 b/managed_components/espressif__cjson/cJSON/tests/inputs/test2 new file mode 100644 index 0000000..5600991 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test2 @@ -0,0 +1,11 @@ +{"menu": { + "id": "file", + "value": "File", + "popup": { + "menuitem": [ + {"value": "New", "onclick": "CreateNewDoc()"}, + {"value": "Open", "onclick": "OpenDoc()"}, + {"value": "Close", "onclick": "CloseDoc()"} + ] + } +}} diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test2.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test2.expected new file mode 100644 index 0000000..d42a017 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test2.expected @@ -0,0 +1,18 @@ +{ + "menu": { + "id": "file", + "value": "File", + "popup": { + "menuitem": [{ + "value": "New", + "onclick": "CreateNewDoc()" + }, { + "value": "Open", + "onclick": "OpenDoc()" + }, { + "value": "Close", + "onclick": "CloseDoc()" + }] + } + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test3 b/managed_components/espressif__cjson/cJSON/tests/inputs/test3 new file mode 100644 index 0000000..7f74aca --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test3 @@ -0,0 +1,26 @@ +{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } +}} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test3.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test3.expected new file mode 100644 index 0000000..a9b9c55 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test3.expected @@ -0,0 +1,28 @@ +{ + "widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }, + "image": { + "src": "Images/Sun.png", + "name": "sun1", + "hOffset": 250, + "vOffset": 250, + "alignment": "center" + }, + "text": { + "data": "Click Here", + "size": 36, + "style": "bold", + "name": "text1", + "hOffset": 250, + "vOffset": 100, + "alignment": "center", + "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" + } + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test4 b/managed_components/espressif__cjson/cJSON/tests/inputs/test4 new file mode 100644 index 0000000..55cd56b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test4 @@ -0,0 +1,88 @@ +{"web-app": { + "servlet": [ + { + "servlet-name": "cofaxCDS", + "servlet-class": "org.cofax.cds.CDSServlet", + "init-param": { + "configGlossary:installationAt": "Philadelphia, PA", + "configGlossary:adminEmail": "ksm@pobox.com", + "configGlossary:poweredBy": "Cofax", + "configGlossary:poweredByIcon": "/images/cofax.gif", + "configGlossary:staticPath": "/content/static", + "templateProcessorClass": "org.cofax.WysiwygTemplate", + "templateLoaderClass": "org.cofax.FilesTemplateLoader", + "templatePath": "templates", + "templateOverridePath": "", + "defaultListTemplate": "listTemplate.htm", + "defaultFileTemplate": "articleTemplate.htm", + "useJSP": false, + "jspListTemplate": "listTemplate.jsp", + "jspFileTemplate": "articleTemplate.jsp", + "cachePackageTagsTrack": 200, + "cachePackageTagsStore": 200, + "cachePackageTagsRefresh": 60, + "cacheTemplatesTrack": 100, + "cacheTemplatesStore": 50, + "cacheTemplatesRefresh": 15, + "cachePagesTrack": 200, + "cachePagesStore": 100, + "cachePagesRefresh": 10, + "cachePagesDirtyRead": 10, + "searchEngineListTemplate": "forSearchEnginesList.htm", + "searchEngineFileTemplate": "forSearchEngines.htm", + "searchEngineRobotsDb": "WEB-INF/robots.db", + "useDataStore": true, + "dataStoreClass": "org.cofax.SqlDataStore", + "redirectionClass": "org.cofax.SqlRedirection", + "dataStoreName": "cofax", + "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon", + "dataStoreUser": "sa", + "dataStorePassword": "dataStoreTestQuery", + "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';", + "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log", + "dataStoreInitConns": 10, + "dataStoreMaxConns": 100, + "dataStoreConnUsageLimit": 100, + "dataStoreLogLevel": "debug", + "maxUrlLength": 500}}, + { + "servlet-name": "cofaxEmail", + "servlet-class": "org.cofax.cds.EmailServlet", + "init-param": { + "mailHost": "mail1", + "mailHostOverride": "mail2"}}, + { + "servlet-name": "cofaxAdmin", + "servlet-class": "org.cofax.cds.AdminServlet"}, + + { + "servlet-name": "fileServlet", + "servlet-class": "org.cofax.cds.FileServlet"}, + { + "servlet-name": "cofaxTools", + "servlet-class": "org.cofax.cms.CofaxToolsServlet", + "init-param": { + "templatePath": "toolstemplates/", + "log": 1, + "logLocation": "/usr/local/tomcat/logs/CofaxTools.log", + "logMaxSize": "", + "dataLog": 1, + "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log", + "dataLogMaxSize": "", + "removePageCache": "/content/admin/remove?cache=pages&id=", + "removeTemplateCache": "/content/admin/remove?cache=templates&id=", + "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder", + "lookInContext": 1, + "adminGroupID": 4, + "betaServer": true}}], + "servlet-mapping": { + "cofaxCDS": "/", + "cofaxEmail": "/cofaxutil/aemail/*", + "cofaxAdmin": "/admin/*", + "fileServlet": "/static/*", + "cofaxTools": "/tools/*"}, + + "taglib": { + "taglib-uri": "cofax.tld", + "taglib-location": "/WEB-INF/tlds/cofax.tld"}}} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test4.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test4.expected new file mode 100644 index 0000000..3648a95 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test4.expected @@ -0,0 +1,94 @@ +{ + "web-app": { + "servlet": [{ + "servlet-name": "cofaxCDS", + "servlet-class": "org.cofax.cds.CDSServlet", + "init-param": { + "configGlossary:installationAt": "Philadelphia, PA", + "configGlossary:adminEmail": "ksm@pobox.com", + "configGlossary:poweredBy": "Cofax", + "configGlossary:poweredByIcon": "/images/cofax.gif", + "configGlossary:staticPath": "/content/static", + "templateProcessorClass": "org.cofax.WysiwygTemplate", + "templateLoaderClass": "org.cofax.FilesTemplateLoader", + "templatePath": "templates", + "templateOverridePath": "", + "defaultListTemplate": "listTemplate.htm", + "defaultFileTemplate": "articleTemplate.htm", + "useJSP": false, + "jspListTemplate": "listTemplate.jsp", + "jspFileTemplate": "articleTemplate.jsp", + "cachePackageTagsTrack": 200, + "cachePackageTagsStore": 200, + "cachePackageTagsRefresh": 60, + "cacheTemplatesTrack": 100, + "cacheTemplatesStore": 50, + "cacheTemplatesRefresh": 15, + "cachePagesTrack": 200, + "cachePagesStore": 100, + "cachePagesRefresh": 10, + "cachePagesDirtyRead": 10, + "searchEngineListTemplate": "forSearchEnginesList.htm", + "searchEngineFileTemplate": "forSearchEngines.htm", + "searchEngineRobotsDb": "WEB-INF/robots.db", + "useDataStore": true, + "dataStoreClass": "org.cofax.SqlDataStore", + "redirectionClass": "org.cofax.SqlRedirection", + "dataStoreName": "cofax", + "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon", + "dataStoreUser": "sa", + "dataStorePassword": "dataStoreTestQuery", + "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';", + "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log", + "dataStoreInitConns": 10, + "dataStoreMaxConns": 100, + "dataStoreConnUsageLimit": 100, + "dataStoreLogLevel": "debug", + "maxUrlLength": 500 + } + }, { + "servlet-name": "cofaxEmail", + "servlet-class": "org.cofax.cds.EmailServlet", + "init-param": { + "mailHost": "mail1", + "mailHostOverride": "mail2" + } + }, { + "servlet-name": "cofaxAdmin", + "servlet-class": "org.cofax.cds.AdminServlet" + }, { + "servlet-name": "fileServlet", + "servlet-class": "org.cofax.cds.FileServlet" + }, { + "servlet-name": "cofaxTools", + "servlet-class": "org.cofax.cms.CofaxToolsServlet", + "init-param": { + "templatePath": "toolstemplates/", + "log": 1, + "logLocation": "/usr/local/tomcat/logs/CofaxTools.log", + "logMaxSize": "", + "dataLog": 1, + "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log", + "dataLogMaxSize": "", + "removePageCache": "/content/admin/remove?cache=pages&id=", + "removeTemplateCache": "/content/admin/remove?cache=templates&id=", + "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder", + "lookInContext": 1, + "adminGroupID": 4, + "betaServer": true + } + }], + "servlet-mapping": { + "cofaxCDS": "/", + "cofaxEmail": "/cofaxutil/aemail/*", + "cofaxAdmin": "/admin/*", + "fileServlet": "/static/*", + "cofaxTools": "/tools/*" + }, + "taglib": { + "taglib-uri": "cofax.tld", + "taglib-location": "/WEB-INF/tlds/cofax.tld" + } + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test5 b/managed_components/espressif__cjson/cJSON/tests/inputs/test5 new file mode 100644 index 0000000..49980ca --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test5 @@ -0,0 +1,27 @@ +{"menu": { + "header": "SVG Viewer", + "items": [ + {"id": "Open"}, + {"id": "OpenNew", "label": "Open New"}, + null, + {"id": "ZoomIn", "label": "Zoom In"}, + {"id": "ZoomOut", "label": "Zoom Out"}, + {"id": "OriginalView", "label": "Original View"}, + null, + {"id": "Quality"}, + {"id": "Pause"}, + {"id": "Mute"}, + null, + {"id": "Find", "label": "Find..."}, + {"id": "FindAgain", "label": "Find Again"}, + {"id": "Copy"}, + {"id": "CopyAgain", "label": "Copy Again"}, + {"id": "CopySVG", "label": "Copy SVG"}, + {"id": "ViewSVG", "label": "View SVG"}, + {"id": "ViewSource", "label": "View Source"}, + {"id": "SaveAs", "label": "Save As"}, + null, + {"id": "Help"}, + {"id": "About", "label": "About Adobe CVG Viewer..."} + ] +}} diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test5.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test5.expected new file mode 100644 index 0000000..886ed58 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test5.expected @@ -0,0 +1,54 @@ +{ + "menu": { + "header": "SVG Viewer", + "items": [{ + "id": "Open" + }, { + "id": "OpenNew", + "label": "Open New" + }, null, { + "id": "ZoomIn", + "label": "Zoom In" + }, { + "id": "ZoomOut", + "label": "Zoom Out" + }, { + "id": "OriginalView", + "label": "Original View" + }, null, { + "id": "Quality" + }, { + "id": "Pause" + }, { + "id": "Mute" + }, null, { + "id": "Find", + "label": "Find..." + }, { + "id": "FindAgain", + "label": "Find Again" + }, { + "id": "Copy" + }, { + "id": "CopyAgain", + "label": "Copy Again" + }, { + "id": "CopySVG", + "label": "Copy SVG" + }, { + "id": "ViewSVG", + "label": "View SVG" + }, { + "id": "ViewSource", + "label": "View Source" + }, { + "id": "SaveAs", + "label": "Save As" + }, null, { + "id": "Help" + }, { + "id": "About", + "label": "About Adobe CVG Viewer..." + }] + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test6 b/managed_components/espressif__cjson/cJSON/tests/inputs/test6 new file mode 100644 index 0000000..d5cb28f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test6 @@ -0,0 +1,16 @@ + + + + + + Application Error + + + + + \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test7 b/managed_components/espressif__cjson/cJSON/tests/inputs/test7 new file mode 100644 index 0000000..3308536 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test7 @@ -0,0 +1,22 @@ +[ + { + "precision": "zip", + "Latitude": 37.7668, + "Longitude": -122.3959, + "Address": "", + "City": "SAN FRANCISCO", + "State": "CA", + "Zip": "94107", + "Country": "US" + }, + { + "precision": "zip", + "Latitude": 37.371991, + "Longitude": -122.026020, + "Address": "", + "City": "SUNNYVALE", + "State": "CA", + "Zip": "94085", + "Country": "US" + } + ] diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test7.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test7.expected new file mode 100644 index 0000000..15adf79 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test7.expected @@ -0,0 +1,19 @@ +[{ + "precision": "zip", + "Latitude": 37.7668, + "Longitude": -122.3959, + "Address": "", + "City": "SAN FRANCISCO", + "State": "CA", + "Zip": "94107", + "Country": "US" + }, { + "precision": "zip", + "Latitude": 37.371991, + "Longitude": -122.02602, + "Address": "", + "City": "SUNNYVALE", + "State": "CA", + "Zip": "94085", + "Country": "US" + }] \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test8 b/managed_components/espressif__cjson/cJSON/tests/inputs/test8 new file mode 100644 index 0000000..4b1f5b9 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test8 @@ -0,0 +1,13 @@ +{ + "Image": { + "Width": 800, + "Height": 600, + "Title": "View from 15th Floor", + "Thumbnail": { + "Url": "http:/*www.example.com/image/481989943", + "Height": 125, + "Width": "100" + }, + "IDs": [116, 943, 234, 38793] + } + } diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test8.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test8.expected new file mode 100644 index 0000000..2e6b731 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test8.expected @@ -0,0 +1,13 @@ +{ + "Image": { + "Width": 800, + "Height": 600, + "Title": "View from 15th Floor", + "Thumbnail": { + "Url": "http:/*www.example.com/image/481989943", + "Height": 125, + "Width": "100" + }, + "IDs": [116, 943, 234, 38793] + } +} \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test9 b/managed_components/espressif__cjson/cJSON/tests/inputs/test9 new file mode 100644 index 0000000..2a939b9 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test9 @@ -0,0 +1,5 @@ +[ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1] + ] diff --git a/managed_components/espressif__cjson/cJSON/tests/inputs/test9.expected b/managed_components/espressif__cjson/cJSON/tests/inputs/test9.expected new file mode 100644 index 0000000..0eea3c9 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/inputs/test9.expected @@ -0,0 +1 @@ +[[0, -1, 0], [1, 0, 0], [0, 0, 1]] \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.editorconfig b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.editorconfig new file mode 100644 index 0000000..dc79da4 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.editorconfig @@ -0,0 +1,10 @@ +# EditorConfig is awesome: http://EditorConfig.org + +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +trim_trailing_whitespace = true +indent_style = space diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.gitignore b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.gitignore new file mode 100644 index 0000000..cd2b23d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.gitignore @@ -0,0 +1,4 @@ +*~ +\#* +!.editorconfig +!.gitignore diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.npmignore b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.npmignore new file mode 100644 index 0000000..2d6cdcb --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/.npmignore @@ -0,0 +1,2 @@ +.editorconfig +.gitignore diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/README.md b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/README.md new file mode 100644 index 0000000..fb9e447 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/README.md @@ -0,0 +1,75 @@ +JSON Patch Tests +================ + +These are test cases for implementations of [IETF JSON Patch (RFC6902)](http://tools.ietf.org/html/rfc6902). + +Some implementations can be found at [jsonpatch.com](http://jsonpatch.com). + + +Test Format +----------- + +Each test file is a JSON document that contains an array of test records. A +test record is an object with the following members: + +- doc: The JSON document to test against +- patch: The patch(es) to apply +- expected: The expected resulting document, OR +- error: A string describing an expected error +- comment: A string describing the test +- disabled: True if the test should be skipped + +All fields except 'doc' and 'patch' are optional. Test records consisting only +of a comment are also OK. + + +Files +----- + +- tests.json: the main test file +- spec_tests.json: tests from the RFC6902 spec + + +Writing Tests +------------- + +All tests should have a descriptive comment. Tests should be as +simple as possible - just what's required to test a specific piece of +behavior. If you want to test interacting behaviors, create tests for +each behavior as well as the interaction. + +If an 'error' member is specified, the error text should describe the +error the implementation should raise - *not* what's being tested. +Implementation error strings will vary, but the suggested error should +be easily matched to the implementation error string. Try to avoid +creating error tests that might pass because an incorrect error was +reported. + +Please feel free to contribute! + + +Credits +------- + +The seed test set was adapted from Byron Ruth's +[jsonpatch-js](https://github.com/bruth/jsonpatch-js/blob/master/test.js) and +extended by [Mike McCabe](https://github.com/mikemccabe). + + +License +------- + + Copyright 2014 The Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/cjson-utils-tests.json b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/cjson-utils-tests.json new file mode 100644 index 0000000..28a5e30 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/cjson-utils-tests.json @@ -0,0 +1,91 @@ +[ + { + "comment": "1", + "doc": { "foo": "bar"}, + "patch": [{ "op": "add", "path": "/baz", "value": "qux" }], + "expected": {"baz": "qux", "foo": "bar"} + }, + { + "comment": "2", + "doc": { "foo": [ "bar", "baz" ] }, + "patch": [{ "op": "add", "path": "/foo/1", "value": "qux" }], + "expected": {"foo": [ "bar", "qux", "baz" ] } + }, + { + "comment": "3", + "doc": {"baz": "qux","foo": "bar"}, + "patch": [{ "op": "remove", "path": "/baz" }], + "expected": {"foo": "bar" } + }, + { + "comment": "4", + "doc": { "foo": [ "bar", "qux", "baz" ] }, + "patch": [{ "op": "remove", "path": "/foo/1" }], + "expected": {"foo": [ "bar", "baz" ] } + }, + { + "comment": "5", + "doc": { "baz": "qux","foo": "bar"}, + "patch": [{ "op": "replace", "path": "/baz", "value": "boo" }], + "expected": {"baz": "boo","foo": "bar"} + }, + { + "comment": "6", + "doc": {"foo": {"bar": "baz","waldo": "fred"},"qux": {"corge": "grault"}}, + "patch": [{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }], + "expected": {"foo": {"bar": "baz"},"qux": {"corge": "grault","thud": "fred"}} + }, + { + "comment": "7", + "doc": { "foo": [ "all", "grass", "cows", "eat" ] }, + "patch": [ { "op": "move", "from": "/foo/1", "path": "/foo/3" }], + "expected": { "foo": [ "all", "cows", "eat", "grass" ] } + }, + { + "comment": "8", + "doc": {"baz": "qux","foo": [ "a", 2, "c" ]}, + "patch": [{ "op": "test", "path": "/baz", "value": "qux" },{ "op": "test", "path": "/foo/1", "value": 2 }] + }, + { + "comment": "9", + "doc": { "baz": "qux" }, + "patch": [ { "op": "test", "path": "/baz", "value": "bar" }], + "error": "\"bar\" doesn't exist" + }, + { + "comment": "10", + "doc": { "foo": "bar" }, + "patch": [{ "op": "add", "path": "/child", "value": { "grandchild": { } } }], + "expected": {"foo": "bar","child": {"grandchild": {}}} + }, + { + "comment": "11", + "doc": { "foo": "bar" }, + "patch": [{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }], + "expected": {"foo": "bar","baz": "qux"} + }, + { + "comment": "12", + "doc": { "foo": "bar" }, + "patch": [{ "op": "add", "path": "/baz/bat", "value": "qux" }], + "error": "Can't add to nonexistent object" + }, + { + "comment": "13", + "doc": {"/": 9,"~1": 10}, + "patch": [{"op": "test", "path": "/~01", "value": 10}] + }, + { + "comment": "14", + "doc": { "foo": ["bar"] }, + "patch": [ { "op": "add", "path": "/foo/-", "value": ["abc", "def"] }], + "expected": {"foo": ["bar", ["abc", "def"]] } + }, + + { + "comment": "15", + "doc": {"foo": {"bar": 1}}, + "patch": [{"op": "add", "path": "/foo/bar/baz", "value": "5"}], + "error": "attempting to add to subfield of non-object" + } +] diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/package.json b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/package.json new file mode 100644 index 0000000..256f936 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/package.json @@ -0,0 +1,15 @@ +{ + "name": "json-patch-test-suite", + "version": "1.1.0", + "description": "JSON Patch RFC 6902 test suite", + "repository": "github:json-patch/json-patch-tests", + "homepage": "https://github.com/json-patch/json-patch-tests", + "bugs": "https://github.com/json-patch/json-patch-tests/issues", + "keywords": [ + "JSON", + "Patch", + "test", + "suite" + ], + "license": "Apache-2.0" +} diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/spec_tests.json b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/spec_tests.json new file mode 100644 index 0000000..c160535 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/spec_tests.json @@ -0,0 +1,233 @@ +[ + { + "comment": "4.1. add with missing object", + "doc": { "q": { "bar": 2 } }, + "patch": [ {"op": "add", "path": "/a/b", "value": 1} ], + "error": + "path /a does not exist -- missing objects are not created recursively" + }, + + { + "comment": "A.1. Adding an Object Member", + "doc": { + "foo": "bar" +}, + "patch": [ + { "op": "add", "path": "/baz", "value": "qux" } +], + "expected": { + "baz": "qux", + "foo": "bar" +} + }, + + { + "comment": "A.2. Adding an Array Element", + "doc": { + "foo": [ "bar", "baz" ] +}, + "patch": [ + { "op": "add", "path": "/foo/1", "value": "qux" } +], + "expected": { + "foo": [ "bar", "qux", "baz" ] +} + }, + + { + "comment": "A.3. Removing an Object Member", + "doc": { + "baz": "qux", + "foo": "bar" +}, + "patch": [ + { "op": "remove", "path": "/baz" } +], + "expected": { + "foo": "bar" +} + }, + + { + "comment": "A.4. Removing an Array Element", + "doc": { + "foo": [ "bar", "qux", "baz" ] +}, + "patch": [ + { "op": "remove", "path": "/foo/1" } +], + "expected": { + "foo": [ "bar", "baz" ] +} + }, + + { + "comment": "A.5. Replacing a Value", + "doc": { + "baz": "qux", + "foo": "bar" +}, + "patch": [ + { "op": "replace", "path": "/baz", "value": "boo" } +], + "expected": { + "baz": "boo", + "foo": "bar" +} + }, + + { + "comment": "A.6. Moving a Value", + "doc": { + "foo": { + "bar": "baz", + "waldo": "fred" + }, + "qux": { + "corge": "grault" + } +}, + "patch": [ + { "op": "move", "from": "/foo/waldo", "path": "/qux/thud" } +], + "expected": { + "foo": { + "bar": "baz" + }, + "qux": { + "corge": "grault", + "thud": "fred" + } +} + }, + + { + "comment": "A.7. Moving an Array Element", + "doc": { + "foo": [ "all", "grass", "cows", "eat" ] +}, + "patch": [ + { "op": "move", "from": "/foo/1", "path": "/foo/3" } +], + "expected": { + "foo": [ "all", "cows", "eat", "grass" ] +} + + }, + + { + "comment": "A.8. Testing a Value: Success", + "doc": { + "baz": "qux", + "foo": [ "a", 2, "c" ] +}, + "patch": [ + { "op": "test", "path": "/baz", "value": "qux" }, + { "op": "test", "path": "/foo/1", "value": 2 } +], + "expected": { + "baz": "qux", + "foo": [ "a", 2, "c" ] + } + }, + + { + "comment": "A.9. Testing a Value: Error", + "doc": { + "baz": "qux" +}, + "patch": [ + { "op": "test", "path": "/baz", "value": "bar" } +], + "error": "string not equivalent" + }, + + { + "comment": "A.10. Adding a nested Member Object", + "doc": { + "foo": "bar" +}, + "patch": [ + { "op": "add", "path": "/child", "value": { "grandchild": { } } } +], + "expected": { + "foo": "bar", + "child": { + "grandchild": { + } + } +} + }, + + { + "comment": "A.11. Ignoring Unrecognized Elements", + "doc": { + "foo":"bar" +}, + "patch": [ + { "op": "add", "path": "/baz", "value": "qux", "xyz": 123 } +], + "expected": { + "foo":"bar", + "baz":"qux" +} + }, + + { + "comment": "A.12. Adding to a Non-existent Target", + "doc": { + "foo": "bar" +}, + "patch": [ + { "op": "add", "path": "/baz/bat", "value": "qux" } +], + "error": "add to a non-existent target" + }, + + { + "comment": "A.13 Invalid JSON Patch Document", + "doc": { + "foo": "bar" + }, + "patch": [ + { "op": "add", "path": "/baz", "value": "qux", "op": "remove" } +], + "error": "operation has two 'op' members", + "disabled": true + }, + + { + "comment": "A.14. ~ Escape Ordering", + "doc": { + "/": 9, + "~1": 10 + }, + "patch": [{"op": "test", "path": "/~01", "value": 10}], + "expected": { + "/": 9, + "~1": 10 + } + }, + + { + "comment": "A.15. Comparing Strings and Numbers", + "doc": { + "/": 9, + "~1": 10 + }, + "patch": [{"op": "test", "path": "/~01", "value": "10"}], + "error": "number is not equal to string" + }, + + { + "comment": "A.16. Adding an Array Value", + "doc": { + "foo": ["bar"] + }, + "patch": [{ "op": "add", "path": "/foo/-", "value": ["abc", "def"] }], + "expected": { + "foo": ["bar", ["abc", "def"]] + } + } + +] diff --git a/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/tests.json b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/tests.json new file mode 100644 index 0000000..2554078 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json-patch-tests/tests.json @@ -0,0 +1,464 @@ +[ + { "comment": "empty list, empty docs", + "doc": {}, + "patch": [], + "expected": {} }, + + { "comment": "empty patch list", + "doc": {"foo": 1}, + "patch": [], + "expected": {"foo": 1} }, + + { "comment": "rearrangements OK?", + "doc": {"foo": 1, "bar": 2}, + "patch": [], + "expected": {"bar":2, "foo": 1} }, + + { "comment": "rearrangements OK? How about one level down ... array", + "doc": [{"foo": 1, "bar": 2}], + "patch": [], + "expected": [{"bar":2, "foo": 1}] }, + + { "comment": "rearrangements OK? How about one level down...", + "doc": {"foo":{"foo": 1, "bar": 2}}, + "patch": [], + "expected": {"foo":{"bar":2, "foo": 1}} }, + + { "comment": "add replaces any existing field", + "doc": {"foo": null}, + "patch": [{"op": "add", "path": "/foo", "value":1}], + "expected": {"foo": 1} }, + + { "comment": "toplevel array", + "doc": [], + "patch": [{"op": "add", "path": "/0", "value": "foo"}], + "expected": ["foo"] }, + + { "comment": "toplevel array, no change", + "doc": ["foo"], + "patch": [], + "expected": ["foo"] }, + + { "comment": "toplevel object, numeric string", + "doc": {}, + "patch": [{"op": "add", "path": "/foo", "value": "1"}], + "expected": {"foo":"1"} }, + + { "comment": "toplevel object, integer", + "doc": {}, + "patch": [{"op": "add", "path": "/foo", "value": 1}], + "expected": {"foo":1} }, + + { "comment": "Toplevel scalar values OK?", + "doc": "foo", + "patch": [{"op": "replace", "path": "", "value": "bar"}], + "expected": "bar", + "disabled": true }, + + { "comment": "replace object document with array document?", + "doc": {}, + "patch": [{"op": "add", "path": "", "value": []}], + "expected": [] }, + + { "comment": "replace array document with object document?", + "doc": [], + "patch": [{"op": "add", "path": "", "value": {}}], + "expected": {} }, + + { "comment": "append to root array document?", + "doc": [], + "patch": [{"op": "add", "path": "/-", "value": "hi"}], + "expected": ["hi"] }, + + { "comment": "Add, / target", + "doc": {}, + "patch": [ {"op": "add", "path": "/", "value":1 } ], + "expected": {"":1} }, + + { "comment": "Add, /foo/ deep target (trailing slash)", + "doc": {"foo": {}}, + "patch": [ {"op": "add", "path": "/foo/", "value":1 } ], + "expected": {"foo":{"": 1}} }, + + { "comment": "Add composite value at top level", + "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": [1, 2]}], + "expected": {"foo": 1, "bar": [1, 2]} }, + + { "comment": "Add into composite value", + "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "add", "path": "/baz/0/foo", "value": "world"}], + "expected": {"foo": 1, "baz": [{"qux": "hello", "foo": "world"}]} }, + + { "doc": {"bar": [1, 2]}, + "patch": [{"op": "add", "path": "/bar/8", "value": "5"}], + "error": "Out of bounds (upper)" }, + + { "doc": {"bar": [1, 2]}, + "patch": [{"op": "add", "path": "/bar/-1", "value": "5"}], + "error": "Out of bounds (lower)" }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": true}], + "expected": {"foo": 1, "bar": true} }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": false}], + "expected": {"foo": 1, "bar": false} }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": null}], + "expected": {"foo": 1, "bar": null} }, + + { "comment": "0 can be an array index or object element name", + "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/0", "value": "bar"}], + "expected": {"foo": 1, "0": "bar" } }, + + { "doc": ["foo"], + "patch": [{"op": "add", "path": "/1", "value": "bar"}], + "expected": ["foo", "bar"] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1", "value": "bar"}], + "expected": ["foo", "bar", "sil"] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/0", "value": "bar"}], + "expected": ["bar", "foo", "sil"] }, + + { "comment": "push item to array via last index + 1", + "doc": ["foo", "sil"], + "patch": [{"op":"add", "path": "/2", "value": "bar"}], + "expected": ["foo", "sil", "bar"] }, + + { "comment": "add item to array at index > length should fail", + "doc": ["foo", "sil"], + "patch": [{"op":"add", "path": "/3", "value": "bar"}], + "error": "index is greater than number of items in array" }, + + { "comment": "test against implementation-specific numeric parsing", + "doc": {"1e0": "foo"}, + "patch": [{"op": "test", "path": "/1e0", "value": "foo"}], + "expected": {"1e0": "foo"} }, + + { "comment": "test with bad number should fail", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/1e0", "value": "bar"}], + "error": "test op shouldn't get array element 1" }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/bar", "value": 42}], + "error": "Object operation on array target" }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1", "value": ["bar", "baz"]}], + "expected": ["foo", ["bar", "baz"], "sil"], + "comment": "value in array add not flattened" }, + + { "doc": {"foo": 1, "bar": [1, 2, 3, 4]}, + "patch": [{"op": "remove", "path": "/bar"}], + "expected": {"foo": 1} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "remove", "path": "/baz/0/qux"}], + "expected": {"foo": 1, "baz": [{}]} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "replace", "path": "/foo", "value": [1, 2, 3, 4]}], + "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]} }, + + { "doc": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]}, + "patch": [{"op": "replace", "path": "/baz/0/qux", "value": "world"}], + "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "world"}]} }, + + { "doc": ["foo"], + "patch": [{"op": "replace", "path": "/0", "value": "bar"}], + "expected": ["bar"] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": 0}], + "expected": [0] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": true}], + "expected": [true] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": false}], + "expected": [false] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": null}], + "expected": [null] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "replace", "path": "/1", "value": ["bar", "baz"]}], + "expected": ["foo", ["bar", "baz"]], + "comment": "value in array replace not flattened" }, + + { "comment": "replace whole document", + "doc": {"foo": "bar"}, + "patch": [{"op": "replace", "path": "", "value": {"baz": "qux"}}], + "expected": {"baz": "qux"} }, + + { "comment": "test replace with missing parent key should fail", + "doc": {"bar": "baz"}, + "patch": [{"op": "replace", "path": "/foo/bar", "value": false}], + "error": "replace op should fail with missing parent key" }, + + { "comment": "spurious patch properties", + "doc": {"foo": 1}, + "patch": [{"op": "test", "path": "/foo", "value": 1, "spurious": 1}], + "expected": {"foo": 1} }, + + { "doc": {"foo": null}, + "patch": [{"op": "test", "path": "/foo", "value": null}], + "expected": {"foo": null}, + "comment": "null value should be valid obj property" }, + + { "doc": {"foo": null}, + "patch": [{"op": "replace", "path": "/foo", "value": "truthy"}], + "expected": {"foo": "truthy"}, + "comment": "null value should be valid obj property to be replaced with something truthy" }, + + { "doc": {"foo": null}, + "patch": [{"op": "move", "from": "/foo", "path": "/bar"}], + "expected": {"bar": null}, + "comment": "null value should be valid obj property to be moved" }, + + { "doc": {"foo": null}, + "patch": [{"op": "copy", "from": "/foo", "path": "/bar"}], + "expected": {"foo": null, "bar": null}, + "comment": "null value should be valid obj property to be copied" }, + + { "doc": {"foo": null}, + "patch": [{"op": "remove", "path": "/foo"}], + "expected": {}, + "comment": "null value should be valid obj property to be removed" }, + + { "doc": {"foo": "bar"}, + "patch": [{"op": "replace", "path": "/foo", "value": null}], + "expected": {"foo": null}, + "comment": "null value should still be valid obj property replace other value" }, + + { "doc": {"foo": {"foo": 1, "bar": 2}}, + "patch": [{"op": "test", "path": "/foo", "value": {"bar": 2, "foo": 1}}], + "expected": {"foo": {"foo": 1, "bar": 2}}, + "comment": "test should pass despite rearrangement" }, + + { "doc": {"foo": [{"foo": 1, "bar": 2}]}, + "patch": [{"op": "test", "path": "/foo", "value": [{"bar": 2, "foo": 1}]}], + "expected": {"foo": [{"foo": 1, "bar": 2}]}, + "comment": "test should pass despite (nested) rearrangement" }, + + { "doc": {"foo": {"bar": [1, 2, 5, 4]}}, + "patch": [{"op": "test", "path": "/foo", "value": {"bar": [1, 2, 5, 4]}}], + "expected": {"foo": {"bar": [1, 2, 5, 4]}}, + "comment": "test should pass - no error" }, + + { "doc": {"foo": {"bar": [1, 2, 5, 4]}}, + "patch": [{"op": "test", "path": "/foo", "value": [1, 2]}], + "error": "test op should fail" }, + + { "comment": "Whole document", + "doc": { "foo": 1 }, + "patch": [{"op": "test", "path": "", "value": {"foo": 1}}], + "disabled": true }, + + { "comment": "Empty-string element", + "doc": { "": 1 }, + "patch": [{"op": "test", "path": "/", "value": 1}], + "expected": { "": 1 } }, + + { "doc": { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 + }, + "patch": [{"op": "test", "path": "/foo", "value": ["bar", "baz"]}, + {"op": "test", "path": "/foo/0", "value": "bar"}, + {"op": "test", "path": "/", "value": 0}, + {"op": "test", "path": "/a~1b", "value": 1}, + {"op": "test", "path": "/c%d", "value": 2}, + {"op": "test", "path": "/e^f", "value": 3}, + {"op": "test", "path": "/g|h", "value": 4}, + {"op": "test", "path": "/i\\j", "value": 5}, + {"op": "test", "path": "/k\"l", "value": 6}, + {"op": "test", "path": "/ ", "value": 7}, + {"op": "test", "path": "/m~0n", "value": 8}], + "expected": { + "": 0, + " ": 7, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "foo": [ + "bar", + "baz" + ], + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + "m~n": 8 + } + }, + { "comment": "Move to same location has no effect", + "doc": {"foo": 1}, + "patch": [{"op": "move", "from": "/foo", "path": "/foo"}], + "expected": {"foo": 1} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "move", "from": "/foo", "path": "/bar"}], + "expected": {"baz": [{"qux": "hello"}], "bar": 1} }, + + { "doc": {"baz": [{"qux": "hello"}], "bar": 1}, + "patch": [{"op": "move", "from": "/baz/0/qux", "path": "/baz/1"}], + "expected": {"baz": [{}, "hello"], "bar": 1} }, + + { "doc": {"baz": [{"qux": "hello"}], "bar": 1}, + "patch": [{"op": "copy", "from": "/baz/0", "path": "/boo"}], + "expected": {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}} }, + + { "comment": "replacing the root of the document is possible with add", + "doc": {"foo": "bar"}, + "patch": [{"op": "add", "path": "", "value": {"baz": "qux"}}], + "expected": {"baz":"qux"}}, + + { "comment": "Adding to \"/-\" adds to the end of the array", + "doc": [ 1, 2 ], + "patch": [ { "op": "add", "path": "/-", "value": { "foo": [ "bar", "baz" ] } } ], + "expected": [ 1, 2, { "foo": [ "bar", "baz" ] } ]}, + + { "comment": "Adding to \"/-\" adds to the end of the array, even n levels down", + "doc": [ 1, 2, [ 3, [ 4, 5 ] ] ], + "patch": [ { "op": "add", "path": "/2/1/-", "value": { "foo": [ "bar", "baz" ] } } ], + "expected": [ 1, 2, [ 3, [ 4, 5, { "foo": [ "bar", "baz" ] } ] ] ]}, + + { "comment": "test remove with bad number should fail", + "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "remove", "path": "/baz/1e0/qux"}], + "error": "remove op shouldn't remove from array with bad number" }, + + { "comment": "test remove on array", + "doc": [1, 2, 3, 4], + "patch": [{"op": "remove", "path": "/0"}], + "expected": [2, 3, 4] }, + + { "comment": "test repeated removes", + "doc": [1, 2, 3, 4], + "patch": [{ "op": "remove", "path": "/1" }, + { "op": "remove", "path": "/2" }], + "expected": [1, 3] }, + + { "comment": "test remove with bad index should fail", + "doc": [1, 2, 3, 4], + "patch": [{"op": "remove", "path": "/1e0"}], + "error": "remove op shouldn't remove from array with bad number" }, + + { "comment": "test replace with bad number should fail", + "doc": [""], + "patch": [{"op": "replace", "path": "/1e0", "value": false}], + "error": "replace op shouldn't replace in array with bad number" }, + + { "comment": "test copy with bad number should fail", + "doc": {"baz": [1,2,3], "bar": 1}, + "patch": [{"op": "copy", "from": "/baz/1e0", "path": "/boo"}], + "error": "copy op shouldn't work with bad number" }, + + { "comment": "test move with bad number should fail", + "doc": {"foo": 1, "baz": [1,2,3,4]}, + "patch": [{"op": "move", "from": "/baz/1e0", "path": "/foo"}], + "error": "move op shouldn't work with bad number" }, + + { "comment": "test add with bad number should fail", + "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1e0", "value": "bar"}], + "error": "add op shouldn't add to array with bad number" }, + + { "comment": "missing 'value' parameter to add", + "doc": [ 1 ], + "patch": [ { "op": "add", "path": "/-" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing 'value' parameter to replace", + "doc": [ 1 ], + "patch": [ { "op": "replace", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing 'value' parameter to test", + "doc": [ null ], + "patch": [ { "op": "test", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing value parameter to test - where undef is falsy", + "doc": [ false ], + "patch": [ { "op": "test", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing from parameter to copy", + "doc": [ 1 ], + "patch": [ { "op": "copy", "path": "/-" } ], + "error": "missing 'from' parameter" }, + + { "comment": "missing from location to copy", + "doc": { "foo": 1 }, + "patch": [ { "op": "copy", "from": "/bar", "path": "/foo" } ], + "error": "missing 'from' location" }, + + { "comment": "missing from parameter to move", + "doc": { "foo": 1 }, + "patch": [ { "op": "move", "path": "" } ], + "error": "missing 'from' parameter" }, + + { "comment": "missing from location to move", + "doc": { "foo": 1 }, + "patch": [ { "op": "move", "from": "/bar", "path": "/foo" } ], + "error": "missing 'from' location" }, + + { "comment": "duplicate ops", + "doc": { "foo": "bar" }, + "patch": [ { "op": "add", "path": "/baz", "value": "qux", + "op": "move", "from":"/foo" } ], + "error": "patch has two 'op' members", + "disabled": true }, + + { "comment": "unrecognized op should fail", + "doc": {"foo": 1}, + "patch": [{"op": "spam", "path": "/foo", "value": 1}], + "error": "Unrecognized op 'spam'" }, + + { "comment": "test with bad array number that has leading zeros", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/00", "value": "foo"}], + "error": "test op should reject the array value, it has leading zeros" }, + + { "comment": "test with bad array number that has leading zeros", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/01", "value": "bar"}], + "error": "test op should reject the array value, it has leading zeros" }, + + { "comment": "Removing nonexistent field", + "doc": {"foo" : "bar"}, + "patch": [{"op": "remove", "path": "/baz"}], + "error": "removing a nonexistent field should fail" }, + + { "comment": "Removing nonexistent index", + "doc": ["foo", "bar"], + "patch": [{"op": "remove", "path": "/2"}], + "error": "removing a nonexistent index should fail" }, + + { "comment": "Patch with different capitalisation than doc", + "doc": {"foo":"bar"}, + "patch": [{"op": "add", "path": "/FOO", "value": "BAR"}], + "expected": {"foo": "bar", "FOO": "BAR"} + } + +] diff --git a/managed_components/espressif__cjson/cJSON/tests/json_patch_tests.c b/managed_components/espressif__cjson/cJSON/tests/json_patch_tests.c new file mode 100644 index 0000000..7c3d6ae --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/json_patch_tests.c @@ -0,0 +1,243 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" +#include "../cJSON_Utils.h" + +static cJSON *parse_test_file(const char * const filename) +{ + char *file = NULL; + cJSON *json = NULL; + + file = read_file(filename); + TEST_ASSERT_NOT_NULL_MESSAGE(file, "Failed to read file."); + + json = cJSON_Parse(file); + TEST_ASSERT_NOT_NULL_MESSAGE(json, "Failed to parse test json."); + TEST_ASSERT_TRUE_MESSAGE(cJSON_IsArray(json), "Json is not an array."); + + free(file); + + return json; +} + +static cJSON_bool test_apply_patch(const cJSON * const test) +{ + cJSON *doc = NULL; + cJSON *patch = NULL; + cJSON *expected = NULL; + cJSON *error_element = NULL; + cJSON *comment = NULL; + cJSON *disabled = NULL; + + cJSON *object = NULL; + cJSON_bool successful = false; + + /* extract all the data out of the test */ + comment = cJSON_GetObjectItemCaseSensitive(test, "comment"); + if (cJSON_IsString(comment)) + { + printf("Testing \"%s\"\n", comment->valuestring); + } + else + { + printf("Testing unknown\n"); + } + + disabled = cJSON_GetObjectItemCaseSensitive(test, "disabled"); + if (cJSON_IsTrue(disabled)) + { + printf("SKIPPED\n"); + return true; + } + + doc = cJSON_GetObjectItemCaseSensitive(test, "doc"); + TEST_ASSERT_NOT_NULL_MESSAGE(doc, "No \"doc\" in the test."); + patch = cJSON_GetObjectItemCaseSensitive(test, "patch"); + TEST_ASSERT_NOT_NULL_MESSAGE(patch, "No \"patch\"in the test."); + /* Make a working copy of 'doc' */ + object = cJSON_Duplicate(doc, true); + TEST_ASSERT_NOT_NULL(object); + + expected = cJSON_GetObjectItemCaseSensitive(test, "expected"); + error_element = cJSON_GetObjectItemCaseSensitive(test, "error"); + if (error_element != NULL) + { + /* excepting an error */ + TEST_ASSERT_TRUE_MESSAGE(0 != cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Test didn't fail as it's supposed to."); + + successful = true; + } + else + { + /* apply the patch */ + TEST_ASSERT_EQUAL_INT_MESSAGE(0, cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Failed to apply patches."); + successful = true; + + if (expected != NULL) + { + successful = cJSON_Compare(object, expected, true); + } + } + + cJSON_Delete(object); + + if (successful) + { + printf("OK\n"); + } + else + { + printf("FAILED\n"); + } + + return successful; +} + +static cJSON_bool test_generate_test(cJSON *test) +{ + cJSON *doc = NULL; + cJSON *patch = NULL; + cJSON *expected = NULL; + cJSON *disabled = NULL; + + cJSON *object = NULL; + cJSON_bool successful = false; + + char *printed_patch = NULL; + + disabled = cJSON_GetObjectItemCaseSensitive(test, "disabled"); + if (cJSON_IsTrue(disabled)) + { + printf("SKIPPED\n"); + return true; + } + + doc = cJSON_GetObjectItemCaseSensitive(test, "doc"); + TEST_ASSERT_NOT_NULL_MESSAGE(doc, "No \"doc\" in the test."); + + /* Make a working copy of 'doc' */ + object = cJSON_Duplicate(doc, true); + TEST_ASSERT_NOT_NULL(object); + + expected = cJSON_GetObjectItemCaseSensitive(test, "expected"); + if (expected == NULL) + { + cJSON_Delete(object); + /* if there is no expected output, this test doesn't make sense */ + return true; + } + + patch = cJSONUtils_GeneratePatchesCaseSensitive(doc, expected); + TEST_ASSERT_NOT_NULL_MESSAGE(patch, "Failed to generate patches."); + + printed_patch = cJSON_Print(patch); + printf("%s\n", printed_patch); + free(printed_patch); + + /* apply the generated patch */ + TEST_ASSERT_EQUAL_INT_MESSAGE(0, cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Failed to apply generated patch."); + + successful = cJSON_Compare(object, expected, true); + + cJSON_Delete(patch); + cJSON_Delete(object); + + if (successful) + { + printf("generated patch: OK\n"); + } + else + { + printf("generated patch: FAILED\n"); + } + + return successful; +} + +static void cjson_utils_should_pass_json_patch_test_tests(void) +{ + cJSON *tests = parse_test_file("json-patch-tests/tests.json"); + cJSON *test = NULL; + + cJSON_bool failed = false; + cJSON_ArrayForEach(test, tests) + { + failed |= !test_apply_patch(test); + failed |= !test_generate_test(test); + } + + cJSON_Delete(tests); + + TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed."); +} + +static void cjson_utils_should_pass_json_patch_test_spec_tests(void) +{ + cJSON *tests = parse_test_file("json-patch-tests/spec_tests.json"); + cJSON *test = NULL; + + cJSON_bool failed = false; + cJSON_ArrayForEach(test, tests) + { + failed |= !test_apply_patch(test); + failed |= !test_generate_test(test); + } + + cJSON_Delete(tests); + + TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed."); +} + +static void cjson_utils_should_pass_json_patch_test_cjson_utils_tests(void) +{ + cJSON *tests = parse_test_file("json-patch-tests/cjson-utils-tests.json"); + cJSON *test = NULL; + + cJSON_bool failed = false; + cJSON_ArrayForEach(test, tests) + { + failed |= !test_apply_patch(test); + failed |= !test_generate_test(test); + } + + cJSON_Delete(tests); + + TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed."); +} + +int main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_utils_should_pass_json_patch_test_tests); + RUN_TEST(cjson_utils_should_pass_json_patch_test_spec_tests); + RUN_TEST(cjson_utils_should_pass_json_patch_test_cjson_utils_tests); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/minify_tests.c b/managed_components/espressif__cjson/cJSON/tests/minify_tests.c new file mode 100644 index 0000000..000821d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/minify_tests.c @@ -0,0 +1,174 @@ +/* + Copyright (c) 2009-2019 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + + +static void cjson_minify_should_not_overflow_buffer(void) +{ + char unclosed_multiline_comment[] = "/* bla"; + char pending_escape[] = "\"\\"; + + cJSON_Minify(unclosed_multiline_comment); + TEST_ASSERT_EQUAL_STRING("", unclosed_multiline_comment); + + cJSON_Minify(pending_escape); + TEST_ASSERT_EQUAL_STRING("\"\\", pending_escape); +} + +static void cjson_minify_should_remove_single_line_comments(void) +{ + const char to_minify[] = "{// this is {} \"some kind\" of [] comment /*, don't you see\n}"; + + char* minified = (char*) malloc(sizeof(to_minify)); + TEST_ASSERT_NOT_NULL(minified); + strcpy(minified, to_minify); + + cJSON_Minify(minified); + TEST_ASSERT_EQUAL_STRING("{}", minified); + + free(minified); +} + +static void cjson_minify_should_remove_spaces(void) +{ + const char to_minify[] = "{ \"key\":\ttrue\r\n }"; + + char* minified = (char*) malloc(sizeof(to_minify)); + TEST_ASSERT_NOT_NULL(minified); + strcpy(minified, to_minify); + + cJSON_Minify(minified); + TEST_ASSERT_EQUAL_STRING("{\"key\":true}", minified); + + free(minified); +} + +static void cjson_minify_should_remove_multiline_comments(void) +{ + const char to_minify[] = "{/* this is\n a /* multi\n //line \n {comment \"\\\" */}"; + + char* minified = (char*) malloc(sizeof(to_minify)); + TEST_ASSERT_NOT_NULL(minified); + strcpy(minified, to_minify); + + cJSON_Minify(minified); + TEST_ASSERT_EQUAL_STRING("{}", minified); + + free(minified); +} + +static void cjson_minify_should_not_modify_strings(void) +{ + const char to_minify[] = "\"this is a string \\\" \\t bla\""; + + char* minified = (char*) malloc(sizeof(to_minify)); + TEST_ASSERT_NOT_NULL(minified); + strcpy(minified, to_minify); + + cJSON_Minify(minified); + TEST_ASSERT_EQUAL_STRING(to_minify, minified); + + free(minified); +} + +static void cjson_minify_should_minify_json(void) { + const char to_minify[] = + "{\n" + " \"glossary\": { // comment\n" + " \"title\": \"example glossary\",\n" + " /* multi\n" + " line */\n" + " \"GlossDiv\": {\n" + " \"title\": \"S\",\n" + " \"GlossList\": {\n" + " \"GlossEntry\": {\n" + " \"ID\": \"SGML\",\n" + " \"SortAs\": \"SGML\",\n" + " \"Acronym\": \"SGML\",\n" + " \"Abbrev\": \"ISO 8879:1986\",\n" + " \"GlossDef\": {\n" + " \"GlossSeeAlso\": [\"GML\", \"XML\"]\n" + " },\n" + " \"GlossSee\": \"markup\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; + const char* minified = + "{" + "\"glossary\":{" + "\"title\":\"example glossary\"," + "\"GlossDiv\":{" + "\"title\":\"S\"," + "\"GlossList\":{" + "\"GlossEntry\":{" + "\"ID\":\"SGML\"," + "\"SortAs\":\"SGML\"," + "\"Acronym\":\"SGML\"," + "\"Abbrev\":\"ISO 8879:1986\"," + "\"GlossDef\":{" + "\"GlossSeeAlso\":[\"GML\",\"XML\"]" + "}," + "\"GlossSee\":\"markup\"" + "}" + "}" + "}" + "}" + "}"; + + char *buffer = (char*) malloc(sizeof(to_minify)); + strcpy(buffer, to_minify); + + cJSON_Minify(buffer); + TEST_ASSERT_EQUAL_STRING(minified, buffer); + + free(buffer); +} + +static void cjson_minify_should_not_loop_infinitely(void) { + char string[] = { '8', ' ', '/', ' ', '5', '\n', '\0' }; + /* this should not be an infinite loop */ + cJSON_Minify(string); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_minify_should_not_overflow_buffer); + RUN_TEST(cjson_minify_should_minify_json); + RUN_TEST(cjson_minify_should_remove_single_line_comments); + RUN_TEST(cjson_minify_should_remove_multiline_comments); + RUN_TEST(cjson_minify_should_remove_spaces); + RUN_TEST(cjson_minify_should_not_modify_strings); + RUN_TEST(cjson_minify_should_not_loop_infinitely); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/misc_tests.c b/managed_components/espressif__cjson/cJSON/tests/misc_tests.c new file mode 100644 index 0000000..fe2325e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/misc_tests.c @@ -0,0 +1,838 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void cjson_array_foreach_should_loop_over_arrays(void) +{ + cJSON array[1]; + cJSON elements[10]; + cJSON *element_pointer = NULL; + size_t i = 0; + + memset(array, 0, sizeof(array)); + memset(elements, 0, sizeof(elements)); + + /* create array */ + array[0].child = &elements[0]; + elements[0].prev = NULL; + elements[9].next = NULL; + for (i = 0; i < 9; i++) + { + elements[i].next = &elements[i + 1]; + elements[i + 1].prev = &elements[i]; + } + + i = 0; + cJSON_ArrayForEach(element_pointer, array) + { + TEST_ASSERT_TRUE_MESSAGE(element_pointer == &elements[i], "Not iterating over array properly"); + i++; + } +} + +static void cjson_array_foreach_should_not_dereference_null_pointer(void) +{ + cJSON *array = NULL; + cJSON *element = NULL; + cJSON_ArrayForEach(element, array); +} + +static void cjson_get_object_item_should_get_object_items(void) +{ + cJSON *item = NULL; + cJSON *found = NULL; + + item = cJSON_Parse("{\"one\":1, \"Two\":2, \"tHree\":3}"); + + found = cJSON_GetObjectItem(NULL, "test"); + TEST_ASSERT_NULL_MESSAGE(found, "Failed to fail on NULL pointer."); + + found = cJSON_GetObjectItem(item, NULL); + TEST_ASSERT_NULL_MESSAGE(found, "Failed to fail on NULL string."); + + found = cJSON_GetObjectItem(item, "one"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find first item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 1); + + found = cJSON_GetObjectItem(item, "tWo"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find first item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 2); + + found = cJSON_GetObjectItem(item, "three"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 3); + + found = cJSON_GetObjectItem(item, "four"); + TEST_ASSERT_NULL_MESSAGE(found, "Should not find something that isn't there."); + + cJSON_Delete(item); +} + +static void cjson_get_object_item_case_sensitive_should_get_object_items(void) +{ + cJSON *item = NULL; + cJSON *found = NULL; + + item = cJSON_Parse("{\"one\":1, \"Two\":2, \"tHree\":3}"); + + found = cJSON_GetObjectItemCaseSensitive(NULL, "test"); + TEST_ASSERT_NULL_MESSAGE(found, "Failed to fail on NULL pointer."); + + found = cJSON_GetObjectItemCaseSensitive(item, NULL); + TEST_ASSERT_NULL_MESSAGE(found, "Failed to fail on NULL string."); + + found = cJSON_GetObjectItemCaseSensitive(item, "one"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find first item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 1); + + found = cJSON_GetObjectItemCaseSensitive(item, "Two"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find first item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 2); + + found = cJSON_GetObjectItemCaseSensitive(item, "tHree"); + TEST_ASSERT_NOT_NULL_MESSAGE(found, "Failed to find item."); + TEST_ASSERT_EQUAL_DOUBLE(found->valuedouble, 3); + + found = cJSON_GetObjectItemCaseSensitive(item, "One"); + TEST_ASSERT_NULL_MESSAGE(found, "Should not find something that isn't there."); + + cJSON_Delete(item); +} + +static void cjson_get_object_item_should_not_crash_with_array(void) +{ + cJSON *array = NULL; + cJSON *found = NULL; + array = cJSON_Parse("[1]"); + + found = cJSON_GetObjectItem(array, "name"); + TEST_ASSERT_NULL(found); + + cJSON_Delete(array); +} + +static void cjson_get_object_item_case_sensitive_should_not_crash_with_array(void) +{ + cJSON *array = NULL; + cJSON *found = NULL; + array = cJSON_Parse("[1]"); + + found = cJSON_GetObjectItemCaseSensitive(array, "name"); + TEST_ASSERT_NULL(found); + + cJSON_Delete(array); +} + +static void typecheck_functions_should_check_type(void) +{ + cJSON invalid[1]; + cJSON item[1]; + invalid->type = cJSON_Invalid; + invalid->type |= cJSON_StringIsConst; + item->type = cJSON_False; + item->type |= cJSON_StringIsConst; + + TEST_ASSERT_FALSE(cJSON_IsInvalid(NULL)); + TEST_ASSERT_FALSE(cJSON_IsInvalid(item)); + TEST_ASSERT_TRUE(cJSON_IsInvalid(invalid)); + + item->type = cJSON_False | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsFalse(NULL)); + TEST_ASSERT_FALSE(cJSON_IsFalse(invalid)); + TEST_ASSERT_TRUE(cJSON_IsFalse(item)); + TEST_ASSERT_TRUE(cJSON_IsBool(item)); + + item->type = cJSON_True | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsTrue(NULL)); + TEST_ASSERT_FALSE(cJSON_IsTrue(invalid)); + TEST_ASSERT_TRUE(cJSON_IsTrue(item)); + TEST_ASSERT_TRUE(cJSON_IsBool(item)); + + item->type = cJSON_NULL | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsNull(NULL)); + TEST_ASSERT_FALSE(cJSON_IsNull(invalid)); + TEST_ASSERT_TRUE(cJSON_IsNull(item)); + + item->type = cJSON_Number | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsNumber(NULL)); + TEST_ASSERT_FALSE(cJSON_IsNumber(invalid)); + TEST_ASSERT_TRUE(cJSON_IsNumber(item)); + + item->type = cJSON_String | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsString(NULL)); + TEST_ASSERT_FALSE(cJSON_IsString(invalid)); + TEST_ASSERT_TRUE(cJSON_IsString(item)); + + item->type = cJSON_Array | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsArray(NULL)); + TEST_ASSERT_FALSE(cJSON_IsArray(invalid)); + TEST_ASSERT_TRUE(cJSON_IsArray(item)); + + item->type = cJSON_Object | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsObject(NULL)); + TEST_ASSERT_FALSE(cJSON_IsObject(invalid)); + TEST_ASSERT_TRUE(cJSON_IsObject(item)); + + item->type = cJSON_Raw | cJSON_StringIsConst; + TEST_ASSERT_FALSE(cJSON_IsRaw(NULL)); + TEST_ASSERT_FALSE(cJSON_IsRaw(invalid)); + TEST_ASSERT_TRUE(cJSON_IsRaw(item)); +} + +static void cjson_should_not_parse_to_deeply_nested_jsons(void) +{ + char deep_json[CJSON_NESTING_LIMIT + 1]; + size_t position = 0; + + for (position = 0; position < sizeof(deep_json); position++) + { + deep_json[position] = '['; + } + deep_json[sizeof(deep_json) - 1] = '\0'; + + TEST_ASSERT_NULL_MESSAGE(cJSON_Parse(deep_json), "To deep JSONs should not be parsed."); +} + +static void cjson_should_not_follow_too_deep_circular_references(void) +{ + cJSON *o = cJSON_CreateArray(); + cJSON *a = cJSON_CreateArray(); + cJSON *b = cJSON_CreateArray(); + cJSON *x; + + cJSON_AddItemToArray(o, a); + cJSON_AddItemToArray(a, b); + cJSON_AddItemToArray(b, o); + + x = cJSON_Duplicate(o, 1); + TEST_ASSERT_NULL(x); + cJSON_DetachItemFromArray(b, 0); + cJSON_Delete(o); +} + +static void cjson_set_number_value_should_set_numbers(void) +{ + cJSON number[1] = {{NULL, NULL, NULL, cJSON_Number, NULL, 0, 0, NULL}}; + + cJSON_SetNumberValue(number, 1.5); + TEST_ASSERT_EQUAL(1, number->valueint); + TEST_ASSERT_EQUAL_DOUBLE(1.5, number->valuedouble); + + cJSON_SetNumberValue(number, -1.5); + TEST_ASSERT_EQUAL(-1, number->valueint); + TEST_ASSERT_EQUAL_DOUBLE(-1.5, number->valuedouble); + + cJSON_SetNumberValue(number, 1 + (double)INT_MAX); + TEST_ASSERT_EQUAL(INT_MAX, number->valueint); + TEST_ASSERT_EQUAL_DOUBLE(1 + (double)INT_MAX, number->valuedouble); + + cJSON_SetNumberValue(number, -1 + (double)INT_MIN); + TEST_ASSERT_EQUAL(INT_MIN, number->valueint); + TEST_ASSERT_EQUAL_DOUBLE(-1 + (double)INT_MIN, number->valuedouble); +} + +static void cjson_detach_item_via_pointer_should_detach_items(void) +{ + cJSON list[4]; + cJSON parent[1]; + + memset(list, '\0', sizeof(list)); + + /* link the list */ + list[0].next = &(list[1]); + list[1].next = &(list[2]); + list[2].next = &(list[3]); + + list[3].prev = &(list[2]); + list[2].prev = &(list[1]); + list[1].prev = &(list[0]); + list[0].prev = &(list[3]); + + parent->child = &list[0]; + + /* detach in the middle (list[1]) */ + TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[1])) == &(list[1]), "Failed to detach in the middle."); + TEST_ASSERT_TRUE_MESSAGE((list[1].prev == NULL) && (list[1].next == NULL), "Didn't set pointers of detached item to NULL."); + TEST_ASSERT_TRUE((list[0].next == &(list[2])) && (list[2].prev == &(list[0]))); + + /* detach beginning (list[0]) */ + TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[0])) == &(list[0]), "Failed to detach beginning."); + TEST_ASSERT_TRUE_MESSAGE((list[0].prev == NULL) && (list[0].next == NULL), "Didn't set pointers of detached item to NULL."); + TEST_ASSERT_TRUE_MESSAGE((list[2].prev == &(list[3])) && (parent->child == &(list[2])), "Didn't set the new beginning."); + + /* detach end (list[3])*/ + TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[3])) == &(list[3]), "Failed to detach end."); + TEST_ASSERT_TRUE_MESSAGE((list[3].prev == NULL) && (list[3].next == NULL), "Didn't set pointers of detached item to NULL."); + TEST_ASSERT_TRUE_MESSAGE((list[2].next == NULL) && (parent->child == &(list[2])), "Didn't set the new end"); + + /* detach single item (list[2]) */ + TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &list[2]) == &list[2], "Failed to detach single item."); + TEST_ASSERT_TRUE_MESSAGE((list[2].prev == NULL) && (list[2].next == NULL), "Didn't set pointers of detached item to NULL."); + TEST_ASSERT_NULL_MESSAGE(parent->child, "Child of the parent wasn't set to NULL."); +} + +static void cjson_detach_item_via_pointer_should_return_null_if_item_prev_is_null(void) +{ + cJSON list[2]; + cJSON parent[1]; + + memset(list, '\0', sizeof(list)); + + /* link the list */ + list[0].next = &(list[1]); + + parent->child = &list[0]; + TEST_ASSERT_NULL_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[1])), "Failed to detach in the middle."); + TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[0])) == &(list[0]), "Failed to detach in the middle."); +} + +static void cjson_replace_item_via_pointer_should_replace_items(void) +{ + cJSON replacements[3]; + cJSON *beginning = NULL; + cJSON *middle = NULL; + cJSON *end = NULL; + cJSON *array = NULL; + + beginning = cJSON_CreateNull(); + TEST_ASSERT_NOT_NULL(beginning); + middle = cJSON_CreateNull(); + TEST_ASSERT_NOT_NULL(middle); + end = cJSON_CreateNull(); + TEST_ASSERT_NOT_NULL(end); + + array = cJSON_CreateArray(); + TEST_ASSERT_NOT_NULL(array); + + cJSON_AddItemToArray(array, beginning); + cJSON_AddItemToArray(array, middle); + cJSON_AddItemToArray(array, end); + + memset(replacements, '\0', sizeof(replacements)); + + /* replace beginning */ + TEST_ASSERT_TRUE(cJSON_ReplaceItemViaPointer(array, beginning, &(replacements[0]))); + TEST_ASSERT_TRUE(replacements[0].prev == end); + TEST_ASSERT_TRUE(replacements[0].next == middle); + TEST_ASSERT_TRUE(middle->prev == &(replacements[0])); + TEST_ASSERT_TRUE(array->child == &(replacements[0])); + + /* replace middle */ + TEST_ASSERT_TRUE(cJSON_ReplaceItemViaPointer(array, middle, &(replacements[1]))); + TEST_ASSERT_TRUE(replacements[1].prev == &(replacements[0])); + TEST_ASSERT_TRUE(replacements[1].next == end); + TEST_ASSERT_TRUE(end->prev == &(replacements[1])); + + /* replace end */ + TEST_ASSERT_TRUE(cJSON_ReplaceItemViaPointer(array, end, &(replacements[2]))); + TEST_ASSERT_TRUE(replacements[2].prev == &(replacements[1])); + TEST_ASSERT_NULL(replacements[2].next); + TEST_ASSERT_TRUE(replacements[1].next == &(replacements[2])); + + cJSON_free(array); +} + +static void cjson_replace_item_in_object_should_preserve_name(void) +{ + cJSON root[1] = {{NULL, NULL, NULL, 0, NULL, 0, 0, NULL}}; + cJSON *child = NULL; + cJSON *replacement = NULL; + cJSON_bool flag = false; + + child = cJSON_CreateNumber(1); + TEST_ASSERT_NOT_NULL(child); + replacement = cJSON_CreateNumber(2); + TEST_ASSERT_NOT_NULL(replacement); + + flag = cJSON_AddItemToObject(root, "child", child); + TEST_ASSERT_TRUE_MESSAGE(flag, "add item to object failed"); + cJSON_ReplaceItemInObject(root, "child", replacement); + + TEST_ASSERT_TRUE(root->child == replacement); + TEST_ASSERT_EQUAL_STRING("child", replacement->string); + + cJSON_Delete(replacement); +} + +static void cjson_functions_should_not_crash_with_null_pointers(void) +{ + char buffer[10]; + cJSON *item = cJSON_CreateString("item"); + cJSON *array = cJSON_CreateArray(); + cJSON *item1 = cJSON_CreateString("item1"); + cJSON *item2 = cJSON_CreateString("corrupted array item3"); + cJSON *corruptedString = cJSON_CreateString("corrupted"); + struct cJSON *originalPrev; + + add_item_to_array(array, item1); + add_item_to_array(array, item2); + + originalPrev = item2->prev; + item2->prev = NULL; + free(corruptedString->valuestring); + corruptedString->valuestring = NULL; + + cJSON_InitHooks(NULL); + TEST_ASSERT_NULL(cJSON_Parse(NULL)); + TEST_ASSERT_NULL(cJSON_ParseWithOpts(NULL, NULL, true)); + TEST_ASSERT_NULL(cJSON_Print(NULL)); + TEST_ASSERT_NULL(cJSON_PrintUnformatted(NULL)); + TEST_ASSERT_NULL(cJSON_PrintBuffered(NULL, 10, true)); + TEST_ASSERT_FALSE(cJSON_PrintPreallocated(NULL, buffer, sizeof(buffer), true)); + TEST_ASSERT_FALSE(cJSON_PrintPreallocated(item, NULL, 1, true)); + cJSON_Delete(NULL); + cJSON_GetArraySize(NULL); + TEST_ASSERT_NULL(cJSON_GetArrayItem(NULL, 0)); + TEST_ASSERT_NULL(cJSON_GetObjectItem(NULL, "item")); + TEST_ASSERT_NULL(cJSON_GetObjectItem(item, NULL)); + TEST_ASSERT_NULL(cJSON_GetObjectItemCaseSensitive(NULL, "item")); + TEST_ASSERT_NULL(cJSON_GetObjectItemCaseSensitive(item, NULL)); + TEST_ASSERT_FALSE(cJSON_HasObjectItem(NULL, "item")); + TEST_ASSERT_FALSE(cJSON_HasObjectItem(item, NULL)); + TEST_ASSERT_FALSE(cJSON_IsInvalid(NULL)); + TEST_ASSERT_FALSE(cJSON_IsFalse(NULL)); + TEST_ASSERT_FALSE(cJSON_IsTrue(NULL)); + TEST_ASSERT_FALSE(cJSON_IsBool(NULL)); + TEST_ASSERT_FALSE(cJSON_IsNull(NULL)); + TEST_ASSERT_FALSE(cJSON_IsNumber(NULL)); + TEST_ASSERT_FALSE(cJSON_IsString(NULL)); + TEST_ASSERT_FALSE(cJSON_IsArray(NULL)); + TEST_ASSERT_FALSE(cJSON_IsObject(NULL)); + TEST_ASSERT_FALSE(cJSON_IsRaw(NULL)); + TEST_ASSERT_NULL(cJSON_CreateString(NULL)); + TEST_ASSERT_NULL(cJSON_CreateRaw(NULL)); + TEST_ASSERT_NULL(cJSON_CreateIntArray(NULL, 10)); + TEST_ASSERT_NULL(cJSON_CreateFloatArray(NULL, 10)); + TEST_ASSERT_NULL(cJSON_CreateDoubleArray(NULL, 10)); + TEST_ASSERT_NULL(cJSON_CreateStringArray(NULL, 10)); + cJSON_AddItemToArray(NULL, item); + cJSON_AddItemToArray(item, NULL); + cJSON_AddItemToObject(item, "item", NULL); + cJSON_AddItemToObject(item, NULL, item); + cJSON_AddItemToObject(NULL, "item", item); + cJSON_AddItemToObjectCS(item, "item", NULL); + cJSON_AddItemToObjectCS(item, NULL, item); + cJSON_AddItemToObjectCS(NULL, "item", item); + cJSON_AddItemReferenceToArray(NULL, item); + cJSON_AddItemReferenceToArray(item, NULL); + cJSON_AddItemReferenceToObject(item, "item", NULL); + cJSON_AddItemReferenceToObject(item, NULL, item); + cJSON_AddItemReferenceToObject(NULL, "item", item); + TEST_ASSERT_NULL(cJSON_DetachItemViaPointer(NULL, item)); + TEST_ASSERT_NULL(cJSON_DetachItemViaPointer(item, NULL)); + TEST_ASSERT_NULL(cJSON_DetachItemFromArray(NULL, 0)); + cJSON_DeleteItemFromArray(NULL, 0); + TEST_ASSERT_NULL(cJSON_DetachItemFromObject(NULL, "item")); + TEST_ASSERT_NULL(cJSON_DetachItemFromObject(item, NULL)); + TEST_ASSERT_NULL(cJSON_DetachItemFromObjectCaseSensitive(NULL, "item")); + TEST_ASSERT_NULL(cJSON_DetachItemFromObjectCaseSensitive(item, NULL)); + cJSON_DeleteItemFromObject(NULL, "item"); + cJSON_DeleteItemFromObject(item, NULL); + cJSON_DeleteItemFromObjectCaseSensitive(NULL, "item"); + cJSON_DeleteItemFromObjectCaseSensitive(item, NULL); + TEST_ASSERT_FALSE(cJSON_InsertItemInArray(array, 0, NULL)); + TEST_ASSERT_FALSE(cJSON_InsertItemInArray(array, 1, item)); + TEST_ASSERT_FALSE(cJSON_InsertItemInArray(NULL, 0, item)); + TEST_ASSERT_FALSE(cJSON_InsertItemInArray(item, 0, NULL)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemViaPointer(NULL, item, item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemViaPointer(item, NULL, item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemViaPointer(item, item, NULL)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInArray(item, 0, NULL)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInArray(NULL, 0, item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObject(NULL, "item", item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObject(item, NULL, item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObject(item, "item", NULL)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObjectCaseSensitive(NULL, "item", item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObjectCaseSensitive(item, NULL, item)); + TEST_ASSERT_FALSE(cJSON_ReplaceItemInObjectCaseSensitive(item, "item", NULL)); + TEST_ASSERT_NULL(cJSON_Duplicate(NULL, true)); + TEST_ASSERT_FALSE(cJSON_Compare(item, NULL, false)); + TEST_ASSERT_FALSE(cJSON_Compare(NULL, item, false)); + TEST_ASSERT_NULL(cJSON_SetValuestring(NULL, "test")); + TEST_ASSERT_NULL(cJSON_SetValuestring(corruptedString, "test")); + TEST_ASSERT_NULL(cJSON_SetValuestring(item, NULL)); + cJSON_Minify(NULL); + /* cJSON_SetNumberHelper should handle NULL gracefully */ + TEST_ASSERT_TRUE(isnan(cJSON_SetNumberHelper(NULL, 0))); + + /* restore corrupted item2 to delete it */ + item2->prev = originalPrev; + cJSON_Delete(corruptedString); + cJSON_Delete(array); + cJSON_Delete(item); +} + +static void cjson_set_valuestring_should_return_null_if_strings_overlap(void) +{ + cJSON *obj; + char* str; + char* str2; + + obj = cJSON_Parse("\"foo0z\""); + + str = cJSON_SetValuestring(obj, "abcde"); + str += 1; + /* The string passed to strcpy overlap which is not allowed.*/ + str2 = cJSON_SetValuestring(obj, str); + /* If it overlaps, the string will be messed up.*/ + TEST_ASSERT_TRUE(strcmp(str, "bcde") == 0); + TEST_ASSERT_NULL(str2); + cJSON_Delete(obj); +} + +static void *CJSON_CDECL failing_realloc(void *pointer, size_t size) +{ + (void)size; + (void)pointer; + return NULL; +} + +static void ensure_should_fail_on_failed_realloc(void) +{ + printbuffer buffer = {NULL, 10, 0, 0, false, false, {&malloc, &free, &failing_realloc}}; + buffer.buffer = (unsigned char *)malloc(100); + TEST_ASSERT_NOT_NULL(buffer.buffer); + + TEST_ASSERT_NULL_MESSAGE(ensure(&buffer, 200), "Ensure didn't fail with failing realloc."); +} + +static void skip_utf8_bom_should_skip_bom(void) +{ + const unsigned char string[] = "\xEF\xBB\xBF{}"; + parse_buffer buffer = {0, 0, 0, 0, {0, 0, 0}}; + buffer.content = string; + buffer.length = sizeof(string); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(skip_utf8_bom(&buffer) == &buffer); + TEST_ASSERT_EQUAL_UINT(3U, (unsigned int)buffer.offset); +} + +static void skip_utf8_bom_should_not_skip_bom_if_not_at_beginning(void) +{ + const unsigned char string[] = " \xEF\xBB\xBF{}"; + parse_buffer buffer = {0, 0, 0, 0, {0, 0, 0}}; + buffer.content = string; + buffer.length = sizeof(string); + buffer.hooks = global_hooks; + buffer.offset = 1; + + TEST_ASSERT_NULL(skip_utf8_bom(&buffer)); +} + +static void cjson_get_string_value_should_get_a_string(void) +{ + cJSON *string = cJSON_CreateString("test"); + cJSON *number = cJSON_CreateNumber(1); + + TEST_ASSERT_TRUE(cJSON_GetStringValue(string) == string->valuestring); + TEST_ASSERT_NULL(cJSON_GetStringValue(number)); + TEST_ASSERT_NULL(cJSON_GetStringValue(NULL)); + + cJSON_Delete(number); + cJSON_Delete(string); +} + +static void cjson_get_number_value_should_get_a_number(void) +{ + cJSON *string = cJSON_CreateString("test"); + cJSON *number = cJSON_CreateNumber(1); + + TEST_ASSERT_EQUAL_DOUBLE(cJSON_GetNumberValue(number), number->valuedouble); + TEST_ASSERT_DOUBLE_IS_NAN(cJSON_GetNumberValue(string)); + TEST_ASSERT_DOUBLE_IS_NAN(cJSON_GetNumberValue(NULL)); + + cJSON_Delete(number); + cJSON_Delete(string); +} + +static void cjson_create_string_reference_should_create_a_string_reference(void) +{ + const char *string = "I am a string!"; + + cJSON *string_reference = cJSON_CreateStringReference(string); + TEST_ASSERT_TRUE(string_reference->valuestring == string); + TEST_ASSERT_EQUAL_INT(cJSON_IsReference | cJSON_String, string_reference->type); + + cJSON_Delete(string_reference); +} + +static void cjson_create_object_reference_should_create_an_object_reference(void) +{ + cJSON *number_reference = NULL; + cJSON *number_object = cJSON_CreateObject(); + cJSON *number = cJSON_CreateNumber(42); + const char key[] = "number"; + + TEST_ASSERT_TRUE(cJSON_IsNumber(number)); + TEST_ASSERT_TRUE(cJSON_IsObject(number_object)); + cJSON_AddItemToObjectCS(number_object, key, number); + + number_reference = cJSON_CreateObjectReference(number); + TEST_ASSERT_TRUE(number_reference->child == number); + TEST_ASSERT_EQUAL_INT(cJSON_Object | cJSON_IsReference, number_reference->type); + + cJSON_Delete(number_object); + cJSON_Delete(number_reference); +} + +static void cjson_create_array_reference_should_create_an_array_reference(void) +{ + cJSON *number_reference = NULL; + cJSON *number_array = cJSON_CreateArray(); + cJSON *number = cJSON_CreateNumber(42); + + TEST_ASSERT_TRUE(cJSON_IsNumber(number)); + TEST_ASSERT_TRUE(cJSON_IsArray(number_array)); + cJSON_AddItemToArray(number_array, number); + + number_reference = cJSON_CreateArrayReference(number); + TEST_ASSERT_TRUE(number_reference->child == number); + TEST_ASSERT_EQUAL_INT(cJSON_Array | cJSON_IsReference, number_reference->type); + + cJSON_Delete(number_array); + cJSON_Delete(number_reference); +} + +static void cjson_add_item_to_object_or_array_should_not_add_itself(void) +{ + cJSON *object = cJSON_CreateObject(); + cJSON *array = cJSON_CreateArray(); + cJSON_bool flag = false; + + flag = cJSON_AddItemToObject(object, "key", object); + TEST_ASSERT_FALSE_MESSAGE(flag, "add an object to itself should fail"); + + flag = cJSON_AddItemToArray(array, array); + TEST_ASSERT_FALSE_MESSAGE(flag, "add an array to itself should fail"); + + cJSON_Delete(object); + cJSON_Delete(array); +} + +static void cjson_add_item_to_object_should_not_use_after_free_when_string_is_aliased(void) +{ + cJSON *object = cJSON_CreateObject(); + cJSON *number = cJSON_CreateNumber(42); + char *name = (char *)cJSON_strdup((const unsigned char *)"number", &global_hooks); + + TEST_ASSERT_NOT_NULL(object); + TEST_ASSERT_NOT_NULL(number); + TEST_ASSERT_NOT_NULL(name); + + number->string = name; + + /* The following should not have a use after free + * that would show up in valgrind or with AddressSanitizer */ + cJSON_AddItemToObject(object, number->string, number); + + cJSON_Delete(object); +} + +static void cjson_delete_item_from_array_should_not_broken_list_structure(void) +{ + const char expected_json1[] = "{\"rd\":[{\"a\":\"123\"}]}"; + const char expected_json2[] = "{\"rd\":[{\"a\":\"123\"},{\"b\":\"456\"}]}"; + const char expected_json3[] = "{\"rd\":[{\"b\":\"456\"}]}"; + char *str1 = NULL; + char *str2 = NULL; + char *str3 = NULL; + + cJSON *root = cJSON_Parse("{}"); + + cJSON *array = cJSON_AddArrayToObject(root, "rd"); + cJSON *item1 = cJSON_Parse("{\"a\":\"123\"}"); + cJSON *item2 = cJSON_Parse("{\"b\":\"456\"}"); + + cJSON_AddItemToArray(array, item1); + str1 = cJSON_PrintUnformatted(root); + TEST_ASSERT_EQUAL_STRING(expected_json1, str1); + free(str1); + + cJSON_AddItemToArray(array, item2); + str2 = cJSON_PrintUnformatted(root); + TEST_ASSERT_EQUAL_STRING(expected_json2, str2); + free(str2); + + /* this should not broken list structure */ + cJSON_DeleteItemFromArray(array, 0); + str3 = cJSON_PrintUnformatted(root); + TEST_ASSERT_EQUAL_STRING(expected_json3, str3); + free(str3); + + cJSON_Delete(root); +} + +static void cjson_set_valuestring_to_object_should_not_leak_memory(void) +{ + cJSON *root = cJSON_Parse("{}"); + const char *stringvalue = "valuestring could be changed safely"; + const char *reference_valuestring = "reference item should be freed by yourself"; + const char *short_valuestring = "shorter valuestring"; + const char *long_valuestring = "new valuestring which much longer than previous should be changed safely"; + cJSON *item1 = cJSON_CreateString(stringvalue); + cJSON *item2 = cJSON_CreateStringReference(reference_valuestring); + char *ptr1 = NULL; + char *return_value = NULL; + + cJSON_AddItemToObject(root, "one", item1); + cJSON_AddItemToObject(root, "two", item2); + + ptr1 = item1->valuestring; + return_value = cJSON_SetValuestring(cJSON_GetObjectItem(root, "one"), short_valuestring); + TEST_ASSERT_NOT_NULL(return_value); + TEST_ASSERT_EQUAL_PTR_MESSAGE(ptr1, return_value, "new valuestring shorter than old should not reallocate memory"); + TEST_ASSERT_EQUAL_STRING(short_valuestring, cJSON_GetObjectItem(root, "one")->valuestring); + + /* we needn't to free the original valuestring manually */ + ptr1 = item1->valuestring; + return_value = cJSON_SetValuestring(cJSON_GetObjectItem(root, "one"), long_valuestring); + TEST_ASSERT_NOT_NULL(return_value); + TEST_ASSERT_NOT_EQUAL_MESSAGE(ptr1, return_value, "new valuestring longer than old should reallocate memory") + TEST_ASSERT_EQUAL_STRING(long_valuestring, cJSON_GetObjectItem(root, "one")->valuestring); + + return_value = cJSON_SetValuestring(cJSON_GetObjectItem(root, "two"), long_valuestring); + TEST_ASSERT_NULL_MESSAGE(return_value, "valuestring of reference object should not be changed"); + TEST_ASSERT_EQUAL_STRING(reference_valuestring, cJSON_GetObjectItem(root, "two")->valuestring); + + cJSON_Delete(root); +} + +static void cjson_set_bool_value_must_not_break_objects(void) +{ + cJSON *bobj, *sobj, *oobj, *refobj = NULL; + + TEST_ASSERT_TRUE((cJSON_SetBoolValue(refobj, 1) == cJSON_Invalid)); + + bobj = cJSON_CreateFalse(); + TEST_ASSERT_TRUE(cJSON_IsFalse(bobj)); + TEST_ASSERT_TRUE((cJSON_SetBoolValue(bobj, 1) == cJSON_True)); + TEST_ASSERT_TRUE(cJSON_IsTrue(bobj)); + cJSON_SetBoolValue(bobj, 1); + TEST_ASSERT_TRUE(cJSON_IsTrue(bobj)); + TEST_ASSERT_TRUE((cJSON_SetBoolValue(bobj, 0) == cJSON_False)); + TEST_ASSERT_TRUE(cJSON_IsFalse(bobj)); + cJSON_SetBoolValue(bobj, 0); + TEST_ASSERT_TRUE(cJSON_IsFalse(bobj)); + + sobj = cJSON_CreateString("test"); + TEST_ASSERT_TRUE(cJSON_IsString(sobj)); + cJSON_SetBoolValue(sobj, 1); + TEST_ASSERT_TRUE(cJSON_IsString(sobj)); + cJSON_SetBoolValue(sobj, 0); + TEST_ASSERT_TRUE(cJSON_IsString(sobj)); + + oobj = cJSON_CreateObject(); + TEST_ASSERT_TRUE(cJSON_IsObject(oobj)); + cJSON_SetBoolValue(oobj, 1); + TEST_ASSERT_TRUE(cJSON_IsObject(oobj)); + cJSON_SetBoolValue(oobj, 0); + TEST_ASSERT_TRUE(cJSON_IsObject(oobj)); + + refobj = cJSON_CreateStringReference("conststring"); + TEST_ASSERT_TRUE(cJSON_IsString(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_SetBoolValue(refobj, 1); + TEST_ASSERT_TRUE(cJSON_IsString(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_SetBoolValue(refobj, 0); + TEST_ASSERT_TRUE(cJSON_IsString(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_Delete(refobj); + + refobj = cJSON_CreateObjectReference(oobj); + TEST_ASSERT_TRUE(cJSON_IsObject(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_SetBoolValue(refobj, 1); + TEST_ASSERT_TRUE(cJSON_IsObject(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_SetBoolValue(refobj, 0); + TEST_ASSERT_TRUE(cJSON_IsObject(refobj)); + TEST_ASSERT_TRUE(refobj->type & cJSON_IsReference); + cJSON_Delete(refobj); + + cJSON_Delete(oobj); + cJSON_Delete(bobj); + cJSON_Delete(sobj); +} + +static void cjson_parse_big_numbers_should_not_report_error(void) +{ + cJSON *valid_big_number_json_object1 = cJSON_Parse("{\"a\": true, \"b\": [ null,9999999999999999999999999999999999999999999999912345678901234567]}"); + cJSON *valid_big_number_json_object2 = cJSON_Parse("{\"a\": true, \"b\": [ null,999999999999999999999999999999999999999999999991234567890.1234567E3]}"); + const char *invalid_big_number_json1 = "{\"a\": true, \"b\": [ null,99999999999999999999999999999999999999999999999.1234567890.1234567]}"; + const char *invalid_big_number_json2 = "{\"a\": true, \"b\": [ null,99999999999999999999999999999999999999999999999E1234567890e1234567]}"; + + TEST_ASSERT_NOT_NULL(valid_big_number_json_object1); + TEST_ASSERT_NOT_NULL(valid_big_number_json_object2); + TEST_ASSERT_NULL_MESSAGE(cJSON_Parse(invalid_big_number_json1), "Invalid big number JSONs should not be parsed."); + TEST_ASSERT_NULL_MESSAGE(cJSON_Parse(invalid_big_number_json2), "Invalid big number JSONs should not be parsed."); + + cJSON_Delete(valid_big_number_json_object1); + cJSON_Delete(valid_big_number_json_object2); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_array_foreach_should_loop_over_arrays); + RUN_TEST(cjson_array_foreach_should_not_dereference_null_pointer); + RUN_TEST(cjson_get_object_item_should_get_object_items); + RUN_TEST(cjson_get_object_item_case_sensitive_should_get_object_items); + RUN_TEST(cjson_get_object_item_should_not_crash_with_array); + RUN_TEST(cjson_get_object_item_case_sensitive_should_not_crash_with_array); + RUN_TEST(typecheck_functions_should_check_type); + RUN_TEST(cjson_should_not_parse_to_deeply_nested_jsons); + RUN_TEST(cjson_should_not_follow_too_deep_circular_references); + RUN_TEST(cjson_set_number_value_should_set_numbers); + RUN_TEST(cjson_detach_item_via_pointer_should_detach_items); + RUN_TEST(cjson_detach_item_via_pointer_should_return_null_if_item_prev_is_null); + RUN_TEST(cjson_replace_item_via_pointer_should_replace_items); + RUN_TEST(cjson_replace_item_in_object_should_preserve_name); + RUN_TEST(cjson_functions_should_not_crash_with_null_pointers); + RUN_TEST(cjson_set_valuestring_should_return_null_if_strings_overlap); + RUN_TEST(ensure_should_fail_on_failed_realloc); + RUN_TEST(skip_utf8_bom_should_skip_bom); + RUN_TEST(skip_utf8_bom_should_not_skip_bom_if_not_at_beginning); + RUN_TEST(cjson_get_string_value_should_get_a_string); + RUN_TEST(cjson_get_number_value_should_get_a_number); + RUN_TEST(cjson_create_string_reference_should_create_a_string_reference); + RUN_TEST(cjson_create_object_reference_should_create_an_object_reference); + RUN_TEST(cjson_create_array_reference_should_create_an_array_reference); + RUN_TEST(cjson_add_item_to_object_or_array_should_not_add_itself); + RUN_TEST(cjson_add_item_to_object_should_not_use_after_free_when_string_is_aliased); + RUN_TEST(cjson_delete_item_from_array_should_not_broken_list_structure); + RUN_TEST(cjson_set_valuestring_to_object_should_not_leak_memory); + RUN_TEST(cjson_set_bool_value_must_not_break_objects); + RUN_TEST(cjson_parse_big_numbers_should_not_report_error); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/misc_utils_tests.c b/managed_components/espressif__cjson/cJSON/tests/misc_utils_tests.c new file mode 100644 index 0000000..7d300bc --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/misc_utils_tests.c @@ -0,0 +1,80 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" +#include "../cJSON_Utils.h" + +static void cjson_utils_functions_shouldnt_crash_with_null_pointers(void) +{ + cJSON *item = cJSON_CreateString("item"); + TEST_ASSERT_NOT_NULL(item); + + TEST_ASSERT_NULL(cJSONUtils_GetPointer(item, NULL)); + TEST_ASSERT_NULL(cJSONUtils_GetPointer(NULL, "pointer")); + TEST_ASSERT_NULL(cJSONUtils_GetPointerCaseSensitive(NULL, "pointer")); + TEST_ASSERT_NULL(cJSONUtils_GetPointerCaseSensitive(item, NULL)); + TEST_ASSERT_NULL(cJSONUtils_GeneratePatches(item, NULL)); + TEST_ASSERT_NULL(cJSONUtils_GeneratePatches(NULL, item)); + TEST_ASSERT_NULL(cJSONUtils_GeneratePatchesCaseSensitive(item, NULL)); + TEST_ASSERT_NULL(cJSONUtils_GeneratePatchesCaseSensitive(NULL, item)); + cJSONUtils_AddPatchToArray(item, "path", "add", NULL); + cJSONUtils_AddPatchToArray(item, "path", NULL, item); + cJSONUtils_AddPatchToArray(item, NULL, "add", item); + cJSONUtils_AddPatchToArray(NULL, "path", "add", item); + cJSONUtils_ApplyPatches(item, NULL); + cJSONUtils_ApplyPatches(NULL, item); + cJSONUtils_ApplyPatchesCaseSensitive(item, NULL); + cJSONUtils_ApplyPatchesCaseSensitive(NULL, item); + TEST_ASSERT_NULL(cJSONUtils_MergePatch(item, NULL)); + item = cJSON_CreateString("item"); + TEST_ASSERT_NULL(cJSONUtils_MergePatchCaseSensitive(item, NULL)); + item = cJSON_CreateString("item"); + /* these calls are actually valid */ + /* cJSONUtils_MergePatch(NULL, item); */ + /* cJSONUtils_MergePatchCaseSensitive(NULL, item);*/ + /* cJSONUtils_GenerateMergePatch(item, NULL); */ + /* cJSONUtils_GenerateMergePatch(NULL, item); */ + /* cJSONUtils_GenerateMergePatchCaseSensitive(item, NULL); */ + /* cJSONUtils_GenerateMergePatchCaseSensitive(NULL, item); */ + + TEST_ASSERT_NULL(cJSONUtils_FindPointerFromObjectTo(item, NULL)); + TEST_ASSERT_NULL(cJSONUtils_FindPointerFromObjectTo(NULL, item)); + cJSONUtils_SortObject(NULL); + cJSONUtils_SortObjectCaseSensitive(NULL); + + cJSON_Delete(item); +} + +int main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(cjson_utils_functions_shouldnt_crash_with_null_pointers); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/old_utils_tests.c b/managed_components/espressif__cjson/cJSON/tests/old_utils_tests.c new file mode 100644 index 0000000..690dbb5 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/old_utils_tests.c @@ -0,0 +1,225 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" +#include "../cJSON_Utils.h" + +/* JSON Apply Merge tests: */ +static const char *merges[15][3] = +{ + {"{\"a\":\"b\"}", "{\"a\":\"c\"}", "{\"a\":\"c\"}"}, + {"{\"a\":\"b\"}", "{\"b\":\"c\"}", "{\"a\":\"b\",\"b\":\"c\"}"}, + {"{\"a\":\"b\"}", "{\"a\":null}", "{}"}, + {"{\"a\":\"b\",\"b\":\"c\"}", "{\"a\":null}", "{\"b\":\"c\"}"}, + {"{\"a\":[\"b\"]}", "{\"a\":\"c\"}", "{\"a\":\"c\"}"}, + {"{\"a\":\"c\"}", "{\"a\":[\"b\"]}", "{\"a\":[\"b\"]}"}, + {"{\"a\":{\"b\":\"c\"}}", "{\"a\":{\"b\":\"d\",\"c\":null}}", "{\"a\":{\"b\":\"d\"}}"}, + {"{\"a\":[{\"b\":\"c\"}]}", "{\"a\":[1]}", "{\"a\":[1]}"}, + {"[\"a\",\"b\"]", "[\"c\",\"d\"]", "[\"c\",\"d\"]"}, + {"{\"a\":\"b\"}", "[\"c\"]", "[\"c\"]"}, + {"{\"a\":\"foo\"}", "null", "null"}, + {"{\"a\":\"foo\"}", "\"bar\"", "\"bar\""}, + {"{\"e\":null}", "{\"a\":1}", "{\"e\":null,\"a\":1}"}, + {"[1,2]", "{\"a\":\"b\",\"c\":null}", "{\"a\":\"b\"}"}, + {"{}","{\"a\":{\"bb\":{\"ccc\":null}}}", "{\"a\":{\"bb\":{}}}"} +}; + +static void json_pointer_tests(void) +{ + cJSON *root = NULL; + const char *json= + "{" + "\"foo\": [\"bar\", \"baz\"]," + "\"\": 0," + "\"a/b\": 1," + "\"c%d\": 2," + "\"e^f\": 3," + "\"g|h\": 4," + "\"i\\\\j\": 5," + "\"k\\\"l\": 6," + "\" \": 7," + "\"m~n\": 8" + "}"; + + root = cJSON_Parse(json); + + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, ""), root); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/foo"), cJSON_GetObjectItem(root, "foo")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/foo/0"), cJSON_GetObjectItem(root, "foo")->child); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/foo/0"), cJSON_GetObjectItem(root, "foo")->child); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/"), cJSON_GetObjectItem(root, "")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/a~1b"), cJSON_GetObjectItem(root, "a/b")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/c%d"), cJSON_GetObjectItem(root, "c%d")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/c^f"), cJSON_GetObjectItem(root, "c^f")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/c|f"), cJSON_GetObjectItem(root, "c|f")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/i\\j"), cJSON_GetObjectItem(root, "i\\j")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/k\"l"), cJSON_GetObjectItem(root, "k\"l")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/ "), cJSON_GetObjectItem(root, " ")); + TEST_ASSERT_EQUAL_PTR(cJSONUtils_GetPointer(root, "/m~0n"), cJSON_GetObjectItem(root, "m~n")); + + cJSON_Delete(root); +} + +static void misc_tests(void) +{ + /* Misc tests */ + int numbers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + cJSON *object = NULL; + cJSON *object1 = NULL; + cJSON *object2 = NULL; + cJSON *object3 = NULL; + cJSON *object4 = NULL; + cJSON *nums = NULL; + cJSON *num6 = NULL; + char *pointer = NULL; + + printf("JSON Pointer construct\n"); + object = cJSON_CreateObject(); + nums = cJSON_CreateIntArray(numbers, 10); + num6 = cJSON_GetArrayItem(nums, 6); + cJSON_AddItemToObject(object, "numbers", nums); + + pointer = cJSONUtils_FindPointerFromObjectTo(object, num6); + TEST_ASSERT_EQUAL_STRING("/numbers/6", pointer); + free(pointer); + + pointer = cJSONUtils_FindPointerFromObjectTo(object, nums); + TEST_ASSERT_EQUAL_STRING("/numbers", pointer); + free(pointer); + + pointer = cJSONUtils_FindPointerFromObjectTo(object, object); + TEST_ASSERT_EQUAL_STRING("", pointer); + free(pointer); + + object1 = cJSON_CreateObject(); + object2 = cJSON_CreateString("m~n"); + cJSON_AddItemToObject(object1, "m~n", object2); + pointer = cJSONUtils_FindPointerFromObjectTo(object1, object2); + TEST_ASSERT_EQUAL_STRING("/m~0n",pointer); + free(pointer); + + object3 = cJSON_CreateObject(); + object4 = cJSON_CreateString("m/n"); + cJSON_AddItemToObject(object3, "m/n", object4); + pointer = cJSONUtils_FindPointerFromObjectTo(object3, object4); + TEST_ASSERT_EQUAL_STRING("/m~1n",pointer); + free(pointer); + + cJSON_Delete(object); + cJSON_Delete(object1); + cJSON_Delete(object3); +} + +static void sort_tests(void) +{ + /* Misc tests */ + const char *random = "QWERTYUIOPASDFGHJKLZXCVBNM"; + char buf[2] = {'\0', '\0'}; + cJSON *sortme = NULL; + size_t i = 0; + cJSON *current_element = NULL; + + /* JSON Sort test: */ + sortme = cJSON_CreateObject(); + for (i = 0; i < 26; i++) + { + buf[0] = random[i]; + cJSON_AddItemToObject(sortme, buf, cJSON_CreateNumber(1)); + } + + cJSONUtils_SortObject(sortme); + + /* check sorting */ + current_element = sortme->child->next; + for (i = 1; (i < 26) && (current_element != NULL) && (current_element->prev != NULL); i++) + { + TEST_ASSERT_TRUE(current_element->string[0] >= current_element->prev->string[0]); + current_element = current_element->next; + } + + cJSON_Delete(sortme); +} + +static void merge_tests(void) +{ + size_t i = 0; + char *patchtext = NULL; + char *after = NULL; + + /* Merge tests: */ + printf("JSON Merge Patch tests\n"); + for (i = 0; i < 15; i++) + { + cJSON *object_to_be_merged = cJSON_Parse(merges[i][0]); + cJSON *patch = cJSON_Parse(merges[i][1]); + patchtext = cJSON_PrintUnformatted(patch); + object_to_be_merged = cJSONUtils_MergePatch(object_to_be_merged, patch); + after = cJSON_PrintUnformatted(object_to_be_merged); + TEST_ASSERT_EQUAL_STRING(merges[i][2], after); + + free(patchtext); + free(after); + cJSON_Delete(object_to_be_merged); + cJSON_Delete(patch); + } +} + +static void generate_merge_tests(void) +{ + size_t i = 0; + char *patchedtext = NULL; + + /* Generate Merge tests: */ + for (i = 0; i < 15; i++) + { + cJSON *from = cJSON_Parse(merges[i][0]); + cJSON *to = cJSON_Parse(merges[i][2]); + cJSON *patch = cJSONUtils_GenerateMergePatch(from,to); + from = cJSONUtils_MergePatch(from,patch); + patchedtext = cJSON_PrintUnformatted(from); + TEST_ASSERT_EQUAL_STRING(merges[i][2], patchedtext); + + cJSON_Delete(from); + cJSON_Delete(to); + cJSON_Delete(patch); + free(patchedtext); + } +} + +int main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(json_pointer_tests); + RUN_TEST(misc_tests); + RUN_TEST(sort_tests); + RUN_TEST(merge_tests); + RUN_TEST(generate_merge_tests); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_array.c b/managed_components/espressif__cjson/cJSON/tests/parse_array.c new file mode 100644 index 0000000..d013f22 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_array.c @@ -0,0 +1,167 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON item[1]; + +static void assert_is_array(cJSON *array_item) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(array_item, "Item is NULL."); + + assert_not_in_list(array_item); + assert_has_type(array_item, cJSON_Array); + assert_has_no_reference(array_item); + assert_has_no_const_string(array_item); + assert_has_no_valuestring(array_item); + assert_has_no_string(array_item); +} + +static void assert_not_array(const char *json) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)json; + buffer.length = strlen(json) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_FALSE(parse_array(item, &buffer)); + assert_is_invalid(item); +} + +static void assert_parse_array(const char *json) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)json; + buffer.length = strlen(json) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(parse_array(item, &buffer)); + assert_is_array(item); +} + +static void parse_array_should_parse_empty_arrays(void) +{ + assert_parse_array("[]"); + assert_has_no_child(item); + + assert_parse_array("[\n\t]"); + assert_has_no_child(item); +} + + +static void parse_array_should_parse_arrays_with_one_element(void) +{ + + assert_parse_array("[1]"); + assert_has_child(item); + assert_has_type(item->child, cJSON_Number); + reset(item); + + assert_parse_array("[\"hello!\"]"); + assert_has_child(item); + assert_has_type(item->child, cJSON_String); + TEST_ASSERT_EQUAL_STRING("hello!", item->child->valuestring); + reset(item); + + assert_parse_array("[[]]"); + assert_has_child(item); + TEST_ASSERT_NOT_NULL(item->child); + assert_has_type(item->child, cJSON_Array); + assert_has_no_child(item->child); + reset(item); + + assert_parse_array("[null]"); + assert_has_child(item); + assert_has_type(item->child, cJSON_NULL); + reset(item); +} + +static void parse_array_should_parse_arrays_with_multiple_elements(void) +{ + assert_parse_array("[1\t,\n2, 3]"); + assert_has_child(item); + TEST_ASSERT_NOT_NULL(item->child->next); + TEST_ASSERT_NOT_NULL(item->child->next->next); + TEST_ASSERT_NULL(item->child->next->next->next); + assert_has_type(item->child, cJSON_Number); + assert_has_type(item->child->next, cJSON_Number); + assert_has_type(item->child->next->next, cJSON_Number); + reset(item); + + { + size_t i = 0; + cJSON *node = NULL; + int expected_types[7] = + { + cJSON_Number, + cJSON_NULL, + cJSON_True, + cJSON_False, + cJSON_Array, + cJSON_String, + cJSON_Object + }; + assert_parse_array("[1, null, true, false, [], \"hello\", {}]"); + + node = item->child; + for ( + i = 0; + (i < (sizeof(expected_types)/sizeof(int))) + && (node != NULL); + (void)i++, node = node->next) + { + TEST_ASSERT_BITS(0xFF, expected_types[i], node->type); + } + TEST_ASSERT_EQUAL_INT(i, 7); + reset(item); + } +} + +static void parse_array_should_not_parse_non_arrays(void) +{ + assert_not_array(""); + assert_not_array("["); + assert_not_array("]"); + assert_not_array("{\"hello\":[]}"); + assert_not_array("42"); + assert_not_array("3.14"); + assert_not_array("\"[]hello world!\n\""); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + memset(item, 0, sizeof(cJSON)); + + UNITY_BEGIN(); + RUN_TEST(parse_array_should_parse_empty_arrays); + RUN_TEST(parse_array_should_parse_arrays_with_one_element); + RUN_TEST(parse_array_should_parse_arrays_with_multiple_elements); + RUN_TEST(parse_array_should_not_parse_non_arrays); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_examples.c b/managed_components/espressif__cjson/cJSON/tests/parse_examples.c new file mode 100644 index 0000000..d35d6cf --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_examples.c @@ -0,0 +1,299 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON *parse_file(const char *filename) +{ + cJSON *parsed = NULL; + char *content = read_file(filename); + + parsed = cJSON_Parse(content); + + if (content != NULL) + { + free(content); + } + + return parsed; +} + +static void do_test(const char *test_name) +{ + char *expected = NULL; + char *actual = NULL; + cJSON *tree = NULL; + + size_t test_name_length = 0; + /* path of the test input */ + char *test_path = NULL; + /* path of the expected output */ + char *expected_path = NULL; + + test_name_length = strlen(test_name); + + /* allocate file paths */ +#define TEST_DIR_PATH "inputs/" + test_path = (char*)malloc(sizeof(TEST_DIR_PATH) + test_name_length); + TEST_ASSERT_NOT_NULL_MESSAGE(test_path, "Failed to allocate test_path buffer."); + expected_path = (char*)malloc(sizeof(TEST_DIR_PATH) + test_name_length + sizeof(".expected")); + TEST_ASSERT_NOT_NULL_MESSAGE(expected_path, "Failed to allocate expected_path buffer."); + + /* create file paths */ + sprintf(test_path, TEST_DIR_PATH"%s", test_name); + sprintf(expected_path, TEST_DIR_PATH"%s.expected", test_name); + + /* read expected output */ + expected = read_file(expected_path); + TEST_ASSERT_NOT_NULL_MESSAGE(expected, "Failed to read expected output."); + + /* read and parse test */ + tree = parse_file(test_path); + TEST_ASSERT_NOT_NULL_MESSAGE(tree, "Failed to read of parse test."); + + /* print the parsed tree */ + actual = cJSON_Print(tree); + TEST_ASSERT_NOT_NULL_MESSAGE(actual, "Failed to print tree back to JSON."); + + + TEST_ASSERT_EQUAL_STRING(expected, actual); + + /* cleanup resources */ + if (expected != NULL) + { + free(expected); + } + if (tree != NULL) + { + cJSON_Delete(tree); + } + if (actual != NULL) + { + free(actual); + } + if (test_path != NULL) + { + free(test_path); + } + if (expected_path != NULL) + { + free(expected_path); + } +} + +static void file_test1_should_be_parsed_and_printed(void) +{ + do_test("test1"); +} + +static void file_test2_should_be_parsed_and_printed(void) +{ + do_test("test2"); +} + +static void file_test3_should_be_parsed_and_printed(void) +{ + do_test("test3"); +} + +static void file_test4_should_be_parsed_and_printed(void) +{ + do_test("test4"); +} + +static void file_test5_should_be_parsed_and_printed(void) +{ + do_test("test5"); +} + +static void file_test6_should_not_be_parsed(void) +{ + char *test6 = NULL; + cJSON *tree = NULL; + + test6 = read_file("inputs/test6"); + TEST_ASSERT_NOT_NULL_MESSAGE(test6, "Failed to read test6 data."); + + tree = cJSON_Parse(test6); + TEST_ASSERT_NULL_MESSAGE(tree, "Should fail to parse what is not JSON."); + + TEST_ASSERT_EQUAL_PTR_MESSAGE(test6, cJSON_GetErrorPtr(), "Error pointer is incorrect."); + + if (test6 != NULL) + { + free(test6); + } + if (tree != NULL) + { + cJSON_Delete(tree); + } +} + +static void file_test7_should_be_parsed_and_printed(void) +{ + do_test("test7"); +} + +static void file_test8_should_be_parsed_and_printed(void) +{ + do_test("test8"); +} + +static void file_test9_should_be_parsed_and_printed(void) +{ + do_test("test9"); +} + +static void file_test10_should_be_parsed_and_printed(void) +{ + do_test("test10"); +} + +static void file_test11_should_be_parsed_and_printed(void) +{ + do_test("test11"); +} + +static void test12_should_not_be_parsed(void) +{ + const char *test12 = "{ \"name\": "; + cJSON *tree = NULL; + + tree = cJSON_Parse(test12); + TEST_ASSERT_NULL_MESSAGE(tree, "Should fail to parse incomplete JSON."); + + TEST_ASSERT_EQUAL_PTR_MESSAGE(test12 + strlen(test12), cJSON_GetErrorPtr(), "Error pointer is incorrect."); + + if (tree != NULL) + { + cJSON_Delete(tree); + } +} + +static void test13_should_be_parsed_without_null_termination(void) +{ + cJSON *tree = NULL; + const char test_13[] = "{" \ + "\"Image\":{" \ + "\"Width\":800," \ + "\"Height\":600," \ + "\"Title\":\"Viewfrom15thFloor\"," \ + "\"Thumbnail\":{" \ + "\"Url\":\"http:/*www.example.com/image/481989943\"," \ + "\"Height\":125," \ + "\"Width\":\"100\"" \ + "}," \ + "\"IDs\":[116,943,234,38793]" \ + "}" \ + "}"; + + char test_13_wo_null[sizeof(test_13) - 1]; + memcpy(test_13_wo_null, test_13, sizeof(test_13) - 1); + + tree = cJSON_ParseWithLength(test_13_wo_null, sizeof(test_13) - 1); + TEST_ASSERT_NOT_NULL_MESSAGE(tree, "Failed to parse valid json."); + + if (tree != NULL) + { + cJSON_Delete(tree); + } +} + +static void test14_should_not_be_parsed(void) +{ + cJSON *tree = NULL; + const char test_14[] = "{" \ + "\"Image\":{" \ + "\"Width\":800," \ + "\"Height\":600," \ + "\"Title\":\"Viewfrom15thFloor\"," \ + "\"Thumbnail\":{" \ + "\"Url\":\"http:/*www.example.com/image/481989943\"," \ + "\"Height\":125," \ + "\"Width\":\"100\"" \ + "}," \ + "\"IDs\":[116,943,234,38793]" \ + "}" \ + "}"; + + tree = cJSON_ParseWithLength(test_14, sizeof(test_14) - 2); + TEST_ASSERT_NULL_MESSAGE(tree, "Should not continue after buffer_length is reached."); + + if (tree != NULL) + { + cJSON_Delete(tree); + } +} + +/* Address Sanitizer */ +static void test15_should_not_heap_buffer_overflow(void) +{ + const char *strings[] = { + "{\"1\":1,", + "{\"1\":1, ", + }; + + size_t i; + + for (i = 0; i < sizeof(strings) / sizeof(strings[0]); i+=1) + { + const char *json_string = strings[i]; + size_t len = strlen(json_string); + cJSON *json = NULL; + + char *exact_size_heap = (char*)malloc(len); + TEST_ASSERT_NOT_NULL(exact_size_heap); + + memcpy(exact_size_heap, json_string, len); + json = cJSON_ParseWithLength(exact_size_heap, len); + + cJSON_Delete(json); + free(exact_size_heap); + } +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + RUN_TEST(file_test1_should_be_parsed_and_printed); + RUN_TEST(file_test2_should_be_parsed_and_printed); + RUN_TEST(file_test3_should_be_parsed_and_printed); + RUN_TEST(file_test4_should_be_parsed_and_printed); + RUN_TEST(file_test5_should_be_parsed_and_printed); + RUN_TEST(file_test6_should_not_be_parsed); + RUN_TEST(file_test7_should_be_parsed_and_printed); + RUN_TEST(file_test8_should_be_parsed_and_printed); + RUN_TEST(file_test9_should_be_parsed_and_printed); + RUN_TEST(file_test10_should_be_parsed_and_printed); + RUN_TEST(file_test11_should_be_parsed_and_printed); + RUN_TEST(test12_should_not_be_parsed); + RUN_TEST(test13_should_be_parsed_without_null_termination); + RUN_TEST(test14_should_not_be_parsed); + RUN_TEST(test15_should_not_heap_buffer_overflow); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_hex4.c b/managed_components/espressif__cjson/cJSON/tests/parse_hex4.c new file mode 100644 index 0000000..83cbe65 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_hex4.c @@ -0,0 +1,73 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void parse_hex4_should_parse_all_combinations(void) +{ + unsigned int number = 0; + unsigned char digits_lower[6]; + unsigned char digits_upper[6]; + /* test all combinations */ + for (number = 0; number <= 0xFFFF; number++) + { + TEST_ASSERT_EQUAL_INT_MESSAGE(4, sprintf((char*)digits_lower, "%.4x", number), "sprintf failed."); + TEST_ASSERT_EQUAL_INT_MESSAGE(4, sprintf((char*)digits_upper, "%.4X", number), "sprintf failed."); + + TEST_ASSERT_EQUAL_INT_MESSAGE(number, parse_hex4(digits_lower), "Failed to parse lowercase digits."); + TEST_ASSERT_EQUAL_INT_MESSAGE(number, parse_hex4(digits_upper), "Failed to parse uppercase digits."); + } +} + +static void parse_hex4_should_parse_mixed_case(void) +{ + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beef")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beeF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beEf")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beEF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEef")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEeF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEEf")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEEF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"Beef")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeeF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeEf")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeEF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEef")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEeF")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEEf")); + TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEEF")); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + RUN_TEST(parse_hex4_should_parse_all_combinations); + RUN_TEST(parse_hex4_should_parse_mixed_case); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_number.c b/managed_components/espressif__cjson/cJSON/tests/parse_number.c new file mode 100644 index 0000000..defda4a --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_number.c @@ -0,0 +1,130 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON item[1]; + +static void assert_is_number(cJSON *number_item) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(number_item, "Item is NULL."); + + assert_not_in_list(number_item); + assert_has_no_child(number_item); + assert_has_type(number_item, cJSON_Number); + assert_has_no_reference(number_item); + assert_has_no_const_string(number_item); + assert_has_no_valuestring(number_item); + assert_has_no_string(number_item); +} + +static void assert_parse_number(const char *string, int integer, double real) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)string; + buffer.length = strlen(string) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(parse_number(item, &buffer)); + assert_is_number(item); + TEST_ASSERT_EQUAL_INT(integer, item->valueint); + TEST_ASSERT_EQUAL_DOUBLE(real, item->valuedouble); +} + +static void assert_parse_big_number(const char *string) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)string; + buffer.length = strlen(string) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(parse_number(item, &buffer)); + assert_is_number(item); +} + +static void parse_number_should_parse_zero(void) +{ + assert_parse_number("0", 0, 0); + assert_parse_number("0.0", 0, 0.0); + assert_parse_number("-0", 0, -0.0); +} + +static void parse_number_should_parse_negative_integers(void) +{ + assert_parse_number("-1", -1, -1); + assert_parse_number("-32768", -32768, -32768.0); + assert_parse_number("-2147483648", (int)-2147483648.0, -2147483648.0); +} + +static void parse_number_should_parse_positive_integers(void) +{ + assert_parse_number("1", 1, 1); + assert_parse_number("32767", 32767, 32767.0); + assert_parse_number("2147483647", (int)2147483647.0, 2147483647.0); +} + +static void parse_number_should_parse_positive_reals(void) +{ + assert_parse_number("0.001", 0, 0.001); + assert_parse_number("10e-10", 0, 10e-10); + assert_parse_number("10E-10", 0, 10e-10); + assert_parse_number("10e10", INT_MAX, 10e10); + assert_parse_number("123e+127", INT_MAX, 123e127); + assert_parse_number("123e-128", 0, 123e-128); +} + +static void parse_number_should_parse_negative_reals(void) +{ + assert_parse_number("-0.001", 0, -0.001); + assert_parse_number("-10e-10", 0, -10e-10); + assert_parse_number("-10E-10", 0, -10e-10); + assert_parse_number("-10e20", INT_MIN, -10e20); + assert_parse_number("-123e+127", INT_MIN, -123e127); + assert_parse_number("-123e-128", 0, -123e-128); +} + +static void parse_number_should_parse_big_numbers(void) +{ + assert_parse_big_number("9999999999999999999999999999999999999999999999912345678901234567"); + assert_parse_big_number("9999999999999999999999999999999999999999999999912345678901234567E10"); + assert_parse_big_number("999999999999999999999999999999999999999999999991234567890.1234567"); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + memset(item, 0, sizeof(cJSON)); + UNITY_BEGIN(); + RUN_TEST(parse_number_should_parse_zero); + RUN_TEST(parse_number_should_parse_negative_integers); + RUN_TEST(parse_number_should_parse_positive_integers); + RUN_TEST(parse_number_should_parse_positive_reals); + RUN_TEST(parse_number_should_parse_negative_reals); + RUN_TEST(parse_number_should_parse_big_numbers); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_object.c b/managed_components/espressif__cjson/cJSON/tests/parse_object.c new file mode 100644 index 0000000..5f8e7cf --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_object.c @@ -0,0 +1,176 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON item[1]; + +static void assert_is_object(cJSON *object_item) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(object_item, "Item is NULL."); + + assert_not_in_list(object_item); + assert_has_type(object_item, cJSON_Object); + assert_has_no_reference(object_item); + assert_has_no_const_string(object_item); + assert_has_no_valuestring(object_item); + assert_has_no_string(object_item); +} + +static void assert_is_child(cJSON *child_item, const char *name, int type) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(child_item, "Child item is NULL."); + TEST_ASSERT_NOT_NULL_MESSAGE(child_item->string, "Child item doesn't have a name."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(name, child_item->string, "Child item has the wrong name."); + TEST_ASSERT_BITS(0xFF, type, child_item->type); +} + +static void assert_not_object(const char *json) +{ + parse_buffer parsebuffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + parsebuffer.content = (const unsigned char*)json; + parsebuffer.length = strlen(json) + sizeof(""); + parsebuffer.hooks = global_hooks; + + TEST_ASSERT_FALSE(parse_object(item, &parsebuffer)); + assert_is_invalid(item); + reset(item); +} + +static void assert_parse_object(const char *json) +{ + parse_buffer parsebuffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + parsebuffer.content = (const unsigned char*)json; + parsebuffer.length = strlen(json) + sizeof(""); + parsebuffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(parse_object(item, &parsebuffer)); + assert_is_object(item); +} + +static void parse_object_should_parse_empty_objects(void) +{ + assert_parse_object("{}"); + assert_has_no_child(item); + reset(item); + + assert_parse_object("{\n\t}"); + assert_has_no_child(item); + reset(item); +} + +static void parse_object_should_parse_objects_with_one_element(void) +{ + + assert_parse_object("{\"one\":1}"); + assert_is_child(item->child, "one", cJSON_Number); + reset(item); + + assert_parse_object("{\"hello\":\"world!\"}"); + assert_is_child(item->child, "hello", cJSON_String); + reset(item); + + assert_parse_object("{\"array\":[]}"); + assert_is_child(item->child, "array", cJSON_Array); + reset(item); + + assert_parse_object("{\"null\":null}"); + assert_is_child(item->child, "null", cJSON_NULL); + reset(item); +} + +static void parse_object_should_parse_objects_with_multiple_elements(void) +{ + assert_parse_object("{\"one\":1\t,\t\"two\"\n:2, \"three\":3}"); + assert_is_child(item->child, "one", cJSON_Number); + assert_is_child(item->child->next, "two", cJSON_Number); + assert_is_child(item->child->next->next, "three", cJSON_Number); + reset(item); + + { + size_t i = 0; + cJSON *node = NULL; + int expected_types[7] = + { + cJSON_Number, + cJSON_NULL, + cJSON_True, + cJSON_False, + cJSON_Array, + cJSON_String, + cJSON_Object + }; + const char *expected_names[7] = + { + "one", + "NULL", + "TRUE", + "FALSE", + "array", + "world", + "object" + }; + assert_parse_object("{\"one\":1, \"NULL\":null, \"TRUE\":true, \"FALSE\":false, \"array\":[], \"world\":\"hello\", \"object\":{}}"); + + node = item->child; + for ( + i = 0; + (i < (sizeof(expected_types)/sizeof(int))) + && (node != NULL); + (void)i++, node = node->next) + { + assert_is_child(node, expected_names[i], expected_types[i]); + } + TEST_ASSERT_EQUAL_INT(i, 7); + reset(item); + } +} + +static void parse_object_should_not_parse_non_objects(void) +{ + assert_not_object(""); + assert_not_object("{"); + assert_not_object("}"); + assert_not_object("[\"hello\",{}]"); + assert_not_object("42"); + assert_not_object("3.14"); + assert_not_object("\"{}hello world!\n\""); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + memset(item, 0, sizeof(cJSON)); + + UNITY_BEGIN(); + RUN_TEST(parse_object_should_parse_empty_objects); + RUN_TEST(parse_object_should_not_parse_non_objects); + RUN_TEST(parse_object_should_parse_objects_with_multiple_elements); + RUN_TEST(parse_object_should_parse_objects_with_one_element); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_string.c b/managed_components/espressif__cjson/cJSON/tests/parse_string.c new file mode 100644 index 0000000..ce1c138 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_string.c @@ -0,0 +1,135 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON item[1]; + +static void assert_is_string(cJSON *string_item) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(string_item, "Item is NULL."); + + assert_not_in_list(string_item); + assert_has_no_child(string_item); + assert_has_type(string_item, cJSON_String); + assert_has_no_reference(string_item); + assert_has_no_const_string(string_item); + assert_has_valuestring(string_item); + assert_has_no_string(string_item); +} + +static void assert_parse_string(const char *string, const char *expected) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)string; + buffer.length = strlen(string) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE_MESSAGE(parse_string(item, &buffer), "Couldn't parse string."); + assert_is_string(item); + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, item->valuestring, "The parsed result isn't as expected."); + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; +} + +static void assert_not_parse_string(const char * const string) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*)string; + buffer.length = strlen(string) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_FALSE_MESSAGE(parse_string(item, &buffer), "Malformed string should not be accepted."); + assert_is_invalid(item); +} + + + +static void parse_string_should_parse_strings(void) +{ + assert_parse_string("\"\"", ""); + assert_parse_string( + "\" !\\\"#$%&'()*+,-./\\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_'abcdefghijklmnopqrstuvwxyz{|}~\"", + " !\"#$%&'()*+,-.//0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~"); + assert_parse_string( + "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\u20AC\\u732b\"", + "\"\\/\b\f\n\r\t€猫"); + reset(item); + assert_parse_string("\"\b\f\n\r\t\"", "\b\f\n\r\t"); + reset(item); +} + +static void parse_string_should_parse_utf16_surrogate_pairs(void) +{ + assert_parse_string("\"\\uD83D\\udc31\"", "🐱"); + reset(item); +} + +static void parse_string_should_not_parse_non_strings(void) +{ + assert_not_parse_string("this\" is not a string\""); + reset(item); + assert_not_parse_string(""); + reset(item); +} + +static void parse_string_should_not_parse_invalid_backslash(void) +{ + assert_not_parse_string("Abcdef\\123"); + reset(item); + assert_not_parse_string("Abcdef\\e23"); + reset(item); +} + +static void parse_string_should_not_overflow_with_closing_backslash(void) +{ + assert_not_parse_string("\"000000000000000000\\"); + reset(item); +} + +static void parse_string_should_parse_bug_94(void) +{ + const char string[] = "\"~!@\\\\#$%^&*()\\\\\\\\-\\\\+{}[]:\\\\;\\\\\\\"\\\\<\\\\>?/.,DC=ad,DC=com\""; + assert_parse_string(string, "~!@\\#$%^&*()\\\\-\\+{}[]:\\;\\\"\\<\\>?/.,DC=ad,DC=com"); + reset(item); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item and error pointer */ + memset(item, 0, sizeof(cJSON)); + + UNITY_BEGIN(); + RUN_TEST(parse_string_should_parse_strings); + RUN_TEST(parse_string_should_parse_utf16_surrogate_pairs); + RUN_TEST(parse_string_should_not_parse_non_strings); + RUN_TEST(parse_string_should_not_parse_invalid_backslash); + RUN_TEST(parse_string_should_parse_bug_94); + RUN_TEST(parse_string_should_not_overflow_with_closing_backslash); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_value.c b/managed_components/espressif__cjson/cJSON/tests/parse_value.c new file mode 100644 index 0000000..6b6b095 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_value.c @@ -0,0 +1,112 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static cJSON item[1]; + +static void assert_is_value(cJSON *value_item, int type) +{ + TEST_ASSERT_NOT_NULL_MESSAGE(value_item, "Item is NULL."); + + assert_not_in_list(value_item); + assert_has_type(value_item, type); + assert_has_no_reference(value_item); + assert_has_no_const_string(value_item); + assert_has_no_string(value_item); +} + +static void assert_parse_value(const char *string, int type) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.content = (const unsigned char*) string; + buffer.length = strlen(string) + sizeof(""); + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE(parse_value(item, &buffer)); + assert_is_value(item, type); +} + +static void parse_value_should_parse_null(void) +{ + assert_parse_value("null", cJSON_NULL); + reset(item); +} + +static void parse_value_should_parse_true(void) +{ + assert_parse_value("true", cJSON_True); + reset(item); +} + +static void parse_value_should_parse_false(void) +{ + assert_parse_value("false", cJSON_False); + reset(item); +} + +static void parse_value_should_parse_number(void) +{ + assert_parse_value("1.5", cJSON_Number); + reset(item); +} + +static void parse_value_should_parse_string(void) +{ + assert_parse_value("\"\"", cJSON_String); + reset(item); + assert_parse_value("\"hello\"", cJSON_String); + reset(item); +} + +static void parse_value_should_parse_array(void) +{ + assert_parse_value("[]", cJSON_Array); + reset(item); +} + +static void parse_value_should_parse_object(void) +{ + assert_parse_value("{}", cJSON_Object); + reset(item); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + memset(item, 0, sizeof(cJSON)); + UNITY_BEGIN(); + RUN_TEST(parse_value_should_parse_null); + RUN_TEST(parse_value_should_parse_true); + RUN_TEST(parse_value_should_parse_false); + RUN_TEST(parse_value_should_parse_number); + RUN_TEST(parse_value_should_parse_string); + RUN_TEST(parse_value_should_parse_array); + RUN_TEST(parse_value_should_parse_object); + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/parse_with_opts.c b/managed_components/espressif__cjson/cJSON/tests/parse_with_opts.c new file mode 100644 index 0000000..e390b92 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/parse_with_opts.c @@ -0,0 +1,112 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void parse_with_opts_should_handle_null(void) +{ + const char *error_pointer = NULL; + cJSON *item = NULL; + TEST_ASSERT_NULL_MESSAGE(cJSON_ParseWithOpts(NULL, &error_pointer, false), "Failed to handle NULL input."); + item = cJSON_ParseWithOpts("{}", NULL, false); + TEST_ASSERT_NOT_NULL_MESSAGE(item, "Failed to handle NULL error pointer."); + cJSON_Delete(item); + TEST_ASSERT_NULL_MESSAGE(cJSON_ParseWithOpts(NULL, NULL, false), "Failed to handle both NULL."); + TEST_ASSERT_NULL_MESSAGE(cJSON_ParseWithOpts("{", NULL, false), "Failed to handle NULL error pointer with parse error."); +} + +static void parse_with_opts_should_handle_empty_strings(void) +{ + const char empty_string[] = ""; + const char *error_pointer = NULL; + + TEST_ASSERT_NULL(cJSON_ParseWithOpts(empty_string, NULL, false)); + TEST_ASSERT_EQUAL_PTR(empty_string, cJSON_GetErrorPtr()); + + TEST_ASSERT_NULL(cJSON_ParseWithOpts(empty_string, &error_pointer, false)); + TEST_ASSERT_EQUAL_PTR(empty_string, error_pointer); + TEST_ASSERT_EQUAL_PTR(empty_string, cJSON_GetErrorPtr()); +} + +static void parse_with_opts_should_handle_incomplete_json(void) +{ + const char json[] = "{ \"name\": "; + const char *parse_end = NULL; + + TEST_ASSERT_NULL(cJSON_ParseWithOpts(json, &parse_end, false)); + TEST_ASSERT_EQUAL_PTR(json + strlen(json), parse_end); + TEST_ASSERT_EQUAL_PTR(json + strlen(json), cJSON_GetErrorPtr()); +} + +static void parse_with_opts_should_require_null_if_requested(void) +{ + cJSON *item = cJSON_ParseWithOpts("{}", NULL, true); + TEST_ASSERT_NOT_NULL(item); + cJSON_Delete(item); + item = cJSON_ParseWithOpts("{} \n", NULL, true); + TEST_ASSERT_NOT_NULL(item); + cJSON_Delete(item); + TEST_ASSERT_NULL(cJSON_ParseWithOpts("{}x", NULL, true)); +} + +static void parse_with_opts_should_return_parse_end(void) +{ + const char json[] = "[] empty array XD"; + const char *parse_end = NULL; + + cJSON *item = cJSON_ParseWithOpts(json, &parse_end, false); + TEST_ASSERT_NOT_NULL(item); + TEST_ASSERT_EQUAL_PTR(json + 2, parse_end); + cJSON_Delete(item); +} + +static void parse_with_opts_should_parse_utf8_bom(void) +{ + cJSON *with_bom = NULL; + cJSON *without_bom = NULL; + + with_bom = cJSON_ParseWithOpts("\xEF\xBB\xBF{}", NULL, true); + TEST_ASSERT_NOT_NULL(with_bom); + without_bom = cJSON_ParseWithOpts("{}", NULL, true); + TEST_ASSERT_NOT_NULL(with_bom); + + TEST_ASSERT_TRUE(cJSON_Compare(with_bom, without_bom, true)); + + cJSON_Delete(with_bom); + cJSON_Delete(without_bom); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(parse_with_opts_should_handle_null); + RUN_TEST(parse_with_opts_should_handle_empty_strings); + RUN_TEST(parse_with_opts_should_handle_incomplete_json); + RUN_TEST(parse_with_opts_should_require_null_if_requested); + RUN_TEST(parse_with_opts_should_return_parse_end); + RUN_TEST(parse_with_opts_should_parse_utf8_bom); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/print_array.c b/managed_components/espressif__cjson/cJSON/tests/print_array.c new file mode 100644 index 0000000..7d40f2e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/print_array.c @@ -0,0 +1,100 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void assert_print_array(const char * const expected, const char * const input) +{ + unsigned char printed_unformatted[1024]; + unsigned char printed_formatted[1024]; + + cJSON item[1]; + + printbuffer formatted_buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + printbuffer unformatted_buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + parse_buffer parsebuffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + parsebuffer.content = (const unsigned char*)input; + parsebuffer.length = strlen(input) + sizeof(""); + parsebuffer.hooks = global_hooks; + + /* buffer for formatted printing */ + formatted_buffer.buffer = printed_formatted; + formatted_buffer.length = sizeof(printed_formatted); + formatted_buffer.offset = 0; + formatted_buffer.noalloc = true; + formatted_buffer.hooks = global_hooks; + + /* buffer for unformatted printing */ + unformatted_buffer.buffer = printed_unformatted; + unformatted_buffer.length = sizeof(printed_unformatted); + unformatted_buffer.offset = 0; + unformatted_buffer.noalloc = true; + unformatted_buffer.hooks = global_hooks; + + memset(item, 0, sizeof(item)); + TEST_ASSERT_TRUE_MESSAGE(parse_array(item, &parsebuffer), "Failed to parse array."); + + unformatted_buffer.format = false; + TEST_ASSERT_TRUE_MESSAGE(print_array(item, &unformatted_buffer), "Failed to print unformatted string."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(input, printed_unformatted, "Unformatted array is not correct."); + + formatted_buffer.format = true; + TEST_ASSERT_TRUE_MESSAGE(print_array(item, &formatted_buffer), "Failed to print formatted string."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, printed_formatted, "Formatted array is not correct."); + + reset(item); +} + +static void print_array_should_print_empty_arrays(void) +{ + assert_print_array("[]", "[]"); +} + +static void print_array_should_print_arrays_with_one_element(void) +{ + + assert_print_array("[1]", "[1]"); + assert_print_array("[\"hello!\"]", "[\"hello!\"]"); + assert_print_array("[[]]", "[[]]"); + assert_print_array("[null]", "[null]"); +} + +static void print_array_should_print_arrays_with_multiple_elements(void) +{ + assert_print_array("[1, 2, 3]", "[1,2,3]"); + assert_print_array("[1, null, true, false, [], \"hello\", {\n\t}]", "[1,null,true,false,[],\"hello\",{}]"); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + UNITY_BEGIN(); + + RUN_TEST(print_array_should_print_empty_arrays); + RUN_TEST(print_array_should_print_arrays_with_one_element); + RUN_TEST(print_array_should_print_arrays_with_multiple_elements); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/print_number.c b/managed_components/espressif__cjson/cJSON/tests/print_number.c new file mode 100644 index 0000000..3fbf9cb --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/print_number.c @@ -0,0 +1,125 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void assert_print_number(const char *expected, double input) +{ + unsigned char printed[1024]; + unsigned char new_buffer[26]; + unsigned int i = 0; + cJSON item[1]; + printbuffer buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.buffer = printed; + buffer.length = sizeof(printed); + buffer.offset = 0; + buffer.noalloc = true; + buffer.hooks = global_hooks; + buffer.buffer = new_buffer; + + memset(item, 0, sizeof(item)); + memset(new_buffer, 0, sizeof(new_buffer)); + cJSON_SetNumberValue(item, input); + TEST_ASSERT_TRUE_MESSAGE(print_number(item, &buffer), "Failed to print number."); + + /* In MinGW or visual studio(before 2015),the exponten is represented using three digits,like:"1e-009","1e+017" + * remove extra "0" to output "1e-09" or "1e+17",which makes testcase PASS */ + for(i = 0;i 3 && new_buffer[i] =='0') + { + if((new_buffer[i-3] =='e' && new_buffer[i-2] == '-' && new_buffer[i] =='0') ||(new_buffer[i-2] =='e' && new_buffer[i-1] =='+')) + { + while(new_buffer[i] !='\0') + { + new_buffer[i] = new_buffer[i+1]; + i++; + } + } + } + } + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, buffer.buffer, "Printed number is not as expected."); +} + +static void print_number_should_print_zero(void) +{ + assert_print_number("0", 0); +} + +static void print_number_should_print_negative_integers(void) +{ + assert_print_number("-1", -1.0); + assert_print_number("-32768", -32768.0); + assert_print_number("-2147483648", -2147483648.0); +} + +static void print_number_should_print_positive_integers(void) +{ + assert_print_number("1", 1.0); + assert_print_number("32767", 32767.0); + assert_print_number("2147483647", 2147483647.0); +} + +static void print_number_should_print_positive_reals(void) +{ + assert_print_number("0.123", 0.123); + assert_print_number("1e-09", 10e-10); + assert_print_number("1000000000000", 10e11); + assert_print_number("1.23e+129", 123e+127); + assert_print_number("1.23e-126", 123e-128); + assert_print_number("3.1415926535897931", 3.1415926535897931); +} + +static void print_number_should_print_negative_reals(void) +{ + assert_print_number("-0.0123", -0.0123); + assert_print_number("-1e-09", -10e-10); + assert_print_number("-1e+21", -10e20); + assert_print_number("-1.23e+129", -123e+127); + assert_print_number("-1.23e-126", -123e-128); +} + +static void print_number_should_print_non_number(void) +{ + TEST_IGNORE(); + /* FIXME: Cannot test this easily in C89! */ + /* assert_print_number("null", NaN); */ + /* assert_print_number("null", INFTY); */ + /* assert_print_number("null", -INFTY); */ +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + UNITY_BEGIN(); + + RUN_TEST(print_number_should_print_zero); + RUN_TEST(print_number_should_print_negative_integers); + RUN_TEST(print_number_should_print_positive_integers); + RUN_TEST(print_number_should_print_positive_reals); + RUN_TEST(print_number_should_print_negative_reals); + RUN_TEST(print_number_should_print_non_number); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/print_object.c b/managed_components/espressif__cjson/cJSON/tests/print_object.c new file mode 100644 index 0000000..507d975 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/print_object.c @@ -0,0 +1,101 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void assert_print_object(const char * const expected, const char * const input) +{ + unsigned char printed_unformatted[1024]; + unsigned char printed_formatted[1024]; + + cJSON item[1]; + + printbuffer formatted_buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + printbuffer unformatted_buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + parse_buffer parsebuffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + + /* buffer for parsing */ + parsebuffer.content = (const unsigned char*)input; + parsebuffer.length = strlen(input) + sizeof(""); + parsebuffer.hooks = global_hooks; + + /* buffer for formatted printing */ + formatted_buffer.buffer = printed_formatted; + formatted_buffer.length = sizeof(printed_formatted); + formatted_buffer.offset = 0; + formatted_buffer.noalloc = true; + formatted_buffer.hooks = global_hooks; + + /* buffer for unformatted printing */ + unformatted_buffer.buffer = printed_unformatted; + unformatted_buffer.length = sizeof(printed_unformatted); + unformatted_buffer.offset = 0; + unformatted_buffer.noalloc = true; + unformatted_buffer.hooks = global_hooks; + + memset(item, 0, sizeof(item)); + TEST_ASSERT_TRUE_MESSAGE(parse_object(item, &parsebuffer), "Failed to parse object."); + + unformatted_buffer.format = false; + TEST_ASSERT_TRUE_MESSAGE(print_object(item, &unformatted_buffer), "Failed to print unformatted string."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(input, printed_unformatted, "Unformatted object is not correct."); + + formatted_buffer.format = true; + TEST_ASSERT_TRUE_MESSAGE(print_object(item, &formatted_buffer), "Failed to print formatted string."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, printed_formatted, "Formatted object is not correct."); + + reset(item); +} + +static void print_object_should_print_empty_objects(void) +{ + assert_print_object("{\n}", "{}"); +} + +static void print_object_should_print_objects_with_one_element(void) +{ + + assert_print_object("{\n\t\"one\":\t1\n}", "{\"one\":1}"); + assert_print_object("{\n\t\"hello\":\t\"world!\"\n}", "{\"hello\":\"world!\"}"); + assert_print_object("{\n\t\"array\":\t[]\n}", "{\"array\":[]}"); + assert_print_object("{\n\t\"null\":\tnull\n}", "{\"null\":null}"); +} + +static void print_object_should_print_objects_with_multiple_elements(void) +{ + assert_print_object("{\n\t\"one\":\t1,\n\t\"two\":\t2,\n\t\"three\":\t3\n}", "{\"one\":1,\"two\":2,\"three\":3}"); + assert_print_object("{\n\t\"one\":\t1,\n\t\"NULL\":\tnull,\n\t\"TRUE\":\ttrue,\n\t\"FALSE\":\tfalse,\n\t\"array\":\t[],\n\t\"world\":\t\"hello\",\n\t\"object\":\t{\n\t}\n}", "{\"one\":1,\"NULL\":null,\"TRUE\":true,\"FALSE\":false,\"array\":[],\"world\":\"hello\",\"object\":{}}"); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + UNITY_BEGIN(); + + RUN_TEST(print_object_should_print_empty_objects); + RUN_TEST(print_object_should_print_objects_with_one_element); + RUN_TEST(print_object_should_print_objects_with_multiple_elements); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/print_string.c b/managed_components/espressif__cjson/cJSON/tests/print_string.c new file mode 100644 index 0000000..e6f5b92 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/print_string.c @@ -0,0 +1,78 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void assert_print_string(const char *expected, const char *input) +{ + unsigned char printed[1024]; + printbuffer buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.buffer = printed; + buffer.length = sizeof(printed); + buffer.offset = 0; + buffer.noalloc = true; + buffer.hooks = global_hooks; + + TEST_ASSERT_TRUE_MESSAGE(print_string_ptr((const unsigned char*)input, &buffer), "Failed to print string."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, printed, "The printed string isn't as expected."); +} + +static void print_string_should_print_empty_strings(void) +{ + assert_print_string("\"\"", ""); + assert_print_string("\"\"", NULL); +} + +static void print_string_should_print_ascii(void) +{ + char ascii[0x7F]; + size_t i = 1; + + /* create ascii table */ + for (i = 1; i < 0x7F; i++) + { + ascii[i-1] = (char)i; + } + ascii[0x7F-1] = '\0'; + + assert_print_string("\"\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\"", + ascii); +} + +static void print_string_should_print_utf8(void) +{ + assert_print_string("\"ü猫慕\"", "ü猫慕"); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + UNITY_BEGIN(); + + RUN_TEST(print_string_should_print_empty_strings); + RUN_TEST(print_string_should_print_ascii); + RUN_TEST(print_string_should_print_utf8); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/print_value.c b/managed_components/espressif__cjson/cJSON/tests/print_value.c new file mode 100644 index 0000000..b54db5b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/print_value.c @@ -0,0 +1,107 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static void assert_print_value(const char *input) +{ + unsigned char printed[1024]; + cJSON item[1]; + printbuffer buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + parse_buffer parsebuffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + buffer.buffer = printed; + buffer.length = sizeof(printed); + buffer.offset = 0; + buffer.noalloc = true; + buffer.hooks = global_hooks; + + parsebuffer.content = (const unsigned char*)input; + parsebuffer.length = strlen(input) + sizeof(""); + parsebuffer.hooks = global_hooks; + + memset(item, 0, sizeof(item)); + + TEST_ASSERT_TRUE_MESSAGE(parse_value(item, &parsebuffer), "Failed to parse value."); + + TEST_ASSERT_TRUE_MESSAGE(print_value(item, &buffer), "Failed to print value."); + TEST_ASSERT_EQUAL_STRING_MESSAGE(input, buffer.buffer, "Printed value is not as expected."); + + reset(item); +} + +static void print_value_should_print_null(void) +{ + assert_print_value("null"); +} + +static void print_value_should_print_true(void) +{ + assert_print_value("true"); +} + +static void print_value_should_print_false(void) +{ + assert_print_value("false"); +} + +static void print_value_should_print_number(void) +{ + assert_print_value("1.5"); +} + +static void print_value_should_print_string(void) +{ + assert_print_value("\"\""); + assert_print_value("\"hello\""); +} + +static void print_value_should_print_array(void) +{ + assert_print_value("[]"); +} + +static void print_value_should_print_object(void) +{ + assert_print_value("{}"); +} + +int CJSON_CDECL main(void) +{ + /* initialize cJSON item */ + UNITY_BEGIN(); + + RUN_TEST(print_value_should_print_null); + RUN_TEST(print_value_should_print_true); + RUN_TEST(print_value_should_print_false); + RUN_TEST(print_value_should_print_number); + RUN_TEST(print_value_should_print_string); + RUN_TEST(print_value_should_print_array); + RUN_TEST(print_value_should_print_object); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/readme_examples.c b/managed_components/espressif__cjson/cJSON/tests/readme_examples.c new file mode 100644 index 0000000..09850cd --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/readme_examples.c @@ -0,0 +1,258 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include + +#include "unity/examples/unity_config.h" +#include "unity/src/unity.h" +#include "common.h" + +static const char *json = "{\n\ +\t\"name\":\t\"Awesome 4K\",\n\ +\t\"resolutions\":\t[{\n\ +\t\t\t\"width\":\t1280,\n\ +\t\t\t\"height\":\t720\n\ +\t\t}, {\n\ +\t\t\t\"width\":\t1920,\n\ +\t\t\t\"height\":\t1080\n\ +\t\t}, {\n\ +\t\t\t\"width\":\t3840,\n\ +\t\t\t\"height\":\t2160\n\ +\t\t}]\n\ +}"; + +static char* create_monitor(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *name = NULL; + cJSON *resolutions = NULL; + cJSON *resolution = NULL; + cJSON *width = NULL; + cJSON *height = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + if (monitor == NULL) + { + goto end; + } + + name = cJSON_CreateString("Awesome 4K"); + if (name == NULL) + { + goto end; + } + /* after creation was successful, immediately add it to the monitor, + * thereby transferring ownership of the pointer to it */ + cJSON_AddItemToObject(monitor, "name", name); + + resolutions = cJSON_CreateArray(); + if (resolutions == NULL) + { + goto end; + } + cJSON_AddItemToObject(monitor, "resolutions", resolutions); + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + resolution = cJSON_CreateObject(); + if (resolution == NULL) + { + goto end; + } + cJSON_AddItemToArray(resolutions, resolution); + + width = cJSON_CreateNumber(resolution_numbers[index][0]); + if (width == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "width", width); + + height = cJSON_CreateNumber(resolution_numbers[index][1]); + if (height == NULL) + { + goto end; + } + cJSON_AddItemToObject(resolution, "height", height); + } + + string = cJSON_Print(monitor); + if (string == NULL) + { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} + +static char *create_monitor_with_helpers(void) +{ + const unsigned int resolution_numbers[3][2] = { + {1280, 720}, + {1920, 1080}, + {3840, 2160} + }; + char *string = NULL; + cJSON *resolutions = NULL; + size_t index = 0; + + cJSON *monitor = cJSON_CreateObject(); + + if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL) + { + goto end; + } + + resolutions = cJSON_AddArrayToObject(monitor, "resolutions"); + if (resolutions == NULL) + { + goto end; + } + + for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index) + { + cJSON *resolution = cJSON_CreateObject(); + + if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL) + { + goto end; + } + + if(cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL) + { + goto end; + } + + cJSON_AddItemToArray(resolutions, resolution); + } + + string = cJSON_Print(monitor); + if (string == NULL) { + fprintf(stderr, "Failed to print monitor.\n"); + } + +end: + cJSON_Delete(monitor); + return string; +} + +/* return 1 if the monitor supports full hd, 0 otherwise */ +static int supports_full_hd(const char * const monitor) +{ + const cJSON *resolution = NULL; + const cJSON *resolutions = NULL; + const cJSON *name = NULL; + int status = 0; + cJSON *monitor_json = cJSON_Parse(monitor); + if (monitor_json == NULL) + { + const char *error_ptr = cJSON_GetErrorPtr(); + if (error_ptr != NULL) + { + fprintf(stderr, "Error before: %s\n", error_ptr); + } + status = 0; + goto end; + } + + name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name"); + if (cJSON_IsString(name) && (name->valuestring != NULL)) + { + printf("Checking monitor \"%s\"\n", name->valuestring); + } + + resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions"); + cJSON_ArrayForEach(resolution, resolutions) + { + cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width"); + cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height"); + + if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height)) + { + status = 0; + goto end; + } + + if (compare_double(width->valuedouble, 1920) && compare_double(height->valuedouble, 1080)) + { + status = 1; + goto end; + } + } + +end: + cJSON_Delete(monitor_json); + return status; +} + +static void create_monitor_should_create_a_monitor(void) +{ + char *monitor = create_monitor(); + + TEST_ASSERT_EQUAL_STRING(monitor, json); + + free(monitor); +} + +static void create_monitor_with_helpers_should_create_a_monitor(void) +{ + char *monitor = create_monitor_with_helpers(); + + TEST_ASSERT_EQUAL_STRING(json, monitor); + + free(monitor); +} + +static void supports_full_hd_should_check_for_full_hd_support(void) +{ + static const char *monitor_without_hd = "{\n\ +\t\t\"name\": \"lame monitor\",\n\ +\t\t\"resolutions\":\t[{\n\ +\t\t\t\"width\":\t640,\n\ +\t\t\t\"height\":\t480\n\ +\t\t}]\n\ +}"; + + TEST_ASSERT(supports_full_hd(json)); + TEST_ASSERT_FALSE(supports_full_hd(monitor_without_hd)); +} + +int CJSON_CDECL main(void) +{ + UNITY_BEGIN(); + + RUN_TEST(create_monitor_should_create_a_monitor); + RUN_TEST(create_monitor_with_helpers_should_create_a_monitor); + RUN_TEST(supports_full_hd_should_check_for_full_hd_support); + + return UNITY_END(); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/.gitattributes b/managed_components/espressif__cjson/cJSON/tests/unity/.gitattributes new file mode 100644 index 0000000..ad95226 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/.gitattributes @@ -0,0 +1,30 @@ +* text=auto + +# These files are text and should be normalized (convert crlf to lf) +*.rb text +*.test text +*.c text +*.cpp text +*.h text +*.txt text +*.yml text +*.s79 text +*.bat text +*.xcl text +*.inc text +*.info text +*.md text +makefile text +rakefile text + + +#These files are binary and should not be normalized +*.doc binary +*.odt binary +*.pdf binary +*.ewd binary +*.eww binary +*.dni binary +*.wsdt binary +*.dbgdt binary +*.mac binary diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/.gitignore b/managed_components/espressif__cjson/cJSON/tests/unity/.gitignore new file mode 100644 index 0000000..a383c3c --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/.gitignore @@ -0,0 +1,9 @@ +build/ +test/sandbox +.DS_Store +examples/example_1/test1.exe +examples/example_1/test2.exe +examples/example_2/all_tests.exe +examples/example_1/test1.out +examples/example_1/test2.out +examples/example_2/all_tests.out diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/.travis.yml b/managed_components/espressif__cjson/cJSON/tests/unity/.travis.yml new file mode 100644 index 0000000..bd165b1 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/.travis.yml @@ -0,0 +1,29 @@ +language: c + +matrix: + include: + - os: osx + compiler: clang + osx_image: xcode7.3 + - os: linux + dist: trusty + compiler: gcc + +before_install: + - if [ "$TRAVIS_OS_NAME" == "osx" ]; then rvm install 2.1 && rvm use 2.1 && ruby -v; fi + - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install --assume-yes --quiet gcc-multilib; fi +install: + - gem install rspec + - gem install rubocop +script: + - cd test && rake ci + - make -s + - make -s DEBUG=-m32 #32-bit architecture with 64-bit support + - make -s DEBUG=-m32 UNITY_SUPPORT_64= #32-bit build without 64-bit types + - make -s UNITY_INCLUDE_DOUBLE= # without double + - cd ../extras/fixture/test && rake ci + - make -s default noStdlibMalloc + - make -s C89 + - cd ../../../examples/example_1 && make -s ci + - cd ../example_2 && make -s ci + - cd ../example_3 && rake diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/README.md b/managed_components/espressif__cjson/cJSON/tests/unity/README.md new file mode 100644 index 0000000..ec73b4a --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/README.md @@ -0,0 +1,231 @@ +Unity Test API +============== + +[![Unity Build Status](https://api.travis-ci.org/ThrowTheSwitch/Unity.png?branch=master)](https://travis-ci.org/ThrowTheSwitch/Unity) +__Copyright (c) 2007 - 2017 Unity Project by Mike Karlesky, Mark VanderVoord, and Greg Williams__ + +Running Tests +------------- + + RUN_TEST(func, linenum) + +Each Test is run within the macro `RUN_TEST`. This macro performs necessary setup before the test is called and handles cleanup and result tabulation afterwards. + +Ignoring Tests +-------------- + +There are times when a test is incomplete or not valid for some reason. At these times, TEST_IGNORE can be called. Control will immediately be returned to the caller of the test, and no failures will be returned. + + TEST_IGNORE() + +Ignore this test and return immediately + + TEST_IGNORE_MESSAGE (message) + +Ignore this test and return immediately. Output a message stating why the test was ignored. + +Aborting Tests +-------------- + +There are times when a test will contain an infinite loop on error conditions, or there may be reason to escape from the test early without executing the rest of the test. A pair of macros support this functionality in Unity. The first `TEST_PROTECT` sets up the feature, and handles emergency abort cases. `TEST_ABORT` can then be used at any time within the tests to return to the last `TEST_PROTECT` call. + + TEST_PROTECT() + +Setup and Catch macro + + TEST_ABORT() + +Abort Test macro + +Example: + + main() + { + if (TEST_PROTECT()) + { + MyTest(); + } + } + +If MyTest calls `TEST_ABORT`, program control will immediately return to `TEST_PROTECT` with a return value of zero. + + +Unity Assertion Summary +======================= + +Basic Validity Tests +-------------------- + + TEST_ASSERT_TRUE(condition) + +Evaluates whatever code is in condition and fails if it evaluates to false + + TEST_ASSERT_FALSE(condition) + +Evaluates whatever code is in condition and fails if it evaluates to true + + TEST_ASSERT(condition) + +Another way of calling `TEST_ASSERT_TRUE` + + TEST_ASSERT_UNLESS(condition) + +Another way of calling `TEST_ASSERT_FALSE` + + TEST_FAIL() + TEST_FAIL_MESSAGE(message) + +This test is automatically marked as a failure. The message is output stating why. + +Numerical Assertions: Integers +------------------------------ + + TEST_ASSERT_EQUAL_INT(expected, actual) + TEST_ASSERT_EQUAL_INT8(expected, actual) + TEST_ASSERT_EQUAL_INT16(expected, actual) + TEST_ASSERT_EQUAL_INT32(expected, actual) + TEST_ASSERT_EQUAL_INT64(expected, actual) + +Compare two integers for equality and display errors as signed integers. A cast will be performed +to your natural integer size so often this can just be used. When you need to specify the exact size, +like when comparing arrays, you can use a specific version: + + TEST_ASSERT_EQUAL_UINT(expected, actual) + TEST_ASSERT_EQUAL_UINT8(expected, actual) + TEST_ASSERT_EQUAL_UINT16(expected, actual) + TEST_ASSERT_EQUAL_UINT32(expected, actual) + TEST_ASSERT_EQUAL_UINT64(expected, actual) + +Compare two integers for equality and display errors as unsigned integers. Like INT, there are +variants for different sizes also. + + TEST_ASSERT_EQUAL_HEX(expected, actual) + TEST_ASSERT_EQUAL_HEX8(expected, actual) + TEST_ASSERT_EQUAL_HEX16(expected, actual) + TEST_ASSERT_EQUAL_HEX32(expected, actual) + TEST_ASSERT_EQUAL_HEX64(expected, actual) + +Compares two integers for equality and display errors as hexadecimal. Like the other integer comparisons, +you can specify the size... here the size will also effect how many nibbles are shown (for example, `HEX16` +will show 4 nibbles). + + TEST_ASSERT_EQUAL(expected, actual) + +Another way of calling TEST_ASSERT_EQUAL_INT + + TEST_ASSERT_INT_WITHIN(delta, expected, actual) + +Asserts that the actual value is within plus or minus delta of the expected value. This also comes in +size specific variants. + + + TEST_ASSERT_GREATER_THAN(threshold, actual) + +Asserts that the actual value is greater than the threshold. This also comes in size specific variants. + + + TEST_ASSERT_LESS_THAN(threshold, actual) + +Asserts that the actual value is less than the threshold. This also comes in size specific variants. + + +Arrays +------ + + _ARRAY + +You can append `_ARRAY` to any of these macros to make an array comparison of that type. Here you will +need to care a bit more about the actual size of the value being checked. You will also specify an +additional argument which is the number of elements to compare. For example: + + TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, elements) + + _EACH_EQUAL + +Another array comparison option is to check that EVERY element of an array is equal to a single expected +value. You do this by specifying the EACH_EQUAL macro. For example: + + TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, elements) + +Numerical Assertions: Bitwise +----------------------------- + + TEST_ASSERT_BITS(mask, expected, actual) + +Use an integer mask to specify which bits should be compared between two other integers. High bits in the mask are compared, low bits ignored. + + TEST_ASSERT_BITS_HIGH(mask, actual) + +Use an integer mask to specify which bits should be inspected to determine if they are all set high. High bits in the mask are compared, low bits ignored. + + TEST_ASSERT_BITS_LOW(mask, actual) + +Use an integer mask to specify which bits should be inspected to determine if they are all set low. High bits in the mask are compared, low bits ignored. + + TEST_ASSERT_BIT_HIGH(bit, actual) + +Test a single bit and verify that it is high. The bit is specified 0-31 for a 32-bit integer. + + TEST_ASSERT_BIT_LOW(bit, actual) + +Test a single bit and verify that it is low. The bit is specified 0-31 for a 32-bit integer. + +Numerical Assertions: Floats +---------------------------- + + TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) + +Asserts that the actual value is within plus or minus delta of the expected value. + + TEST_ASSERT_EQUAL_FLOAT(expected, actual) + TEST_ASSERT_EQUAL_DOUBLE(expected, actual) + +Asserts that two floating point values are "equal" within a small % delta of the expected value. + +String Assertions +----------------- + + TEST_ASSERT_EQUAL_STRING(expected, actual) + +Compare two null-terminate strings. Fail if any character is different or if the lengths are different. + + TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) + +Compare two strings. Fail if any character is different, stop comparing after len characters. + + TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) + +Compare two null-terminate strings. Fail if any character is different or if the lengths are different. Output a custom message on failure. + + TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) + +Compare two strings. Fail if any character is different, stop comparing after len characters. Output a custom message on failure. + +Pointer Assertions +------------------ + +Most pointer operations can be performed by simply using the integer comparisons above. However, a couple of special cases are added for clarity. + + TEST_ASSERT_NULL(pointer) + +Fails if the pointer is not equal to NULL + + TEST_ASSERT_NOT_NULL(pointer) + +Fails if the pointer is equal to NULL + +Memory Assertions +----------------- + + TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) + +Compare two blocks of memory. This is a good generic assertion for types that can't be coerced into acting like +standard types... but since it's a memory compare, you have to be careful that your data types are packed. + +_MESSAGE +-------- + +you can append _MESSAGE to any of the macros to make them take an additional argument. This argument +is a string that will be printed at the end of the failure strings. This is useful for specifying more +information about the problem. + diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_prompt.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_prompt.rb new file mode 100644 index 0000000..0f1dc4e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_prompt.rb @@ -0,0 +1,118 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +if RUBY_PLATFORM =~ /(win|w)32$/ + begin + require 'Win32API' + rescue LoadError + puts 'ERROR! "Win32API" library not found' + puts '"Win32API" is required for colour on a windows machine' + puts ' try => "gem install Win32API" on the command line' + puts + end + # puts + # puts 'Windows Environment Detected...' + # puts 'Win32API Library Found.' + # puts +end + +class ColourCommandLine + def initialize + return unless RUBY_PLATFORM =~ /(win|w)32$/ + get_std_handle = Win32API.new('kernel32', 'GetStdHandle', ['L'], 'L') + @set_console_txt_attrb = + Win32API.new('kernel32', 'SetConsoleTextAttribute', %w(L N), 'I') + @hout = get_std_handle.call(-11) + end + + def change_to(new_colour) + if RUBY_PLATFORM =~ /(win|w)32$/ + @set_console_txt_attrb.call(@hout, win32_colour(new_colour)) + else + "\033[30;#{posix_colour(new_colour)};22m" + end + end + + def win32_colour(colour) + case colour + when :black then 0 + when :dark_blue then 1 + when :dark_green then 2 + when :dark_cyan then 3 + when :dark_red then 4 + when :dark_purple then 5 + when :dark_yellow, :narrative then 6 + when :default_white, :default, :dark_white then 7 + when :silver then 8 + when :blue then 9 + when :green, :success then 10 + when :cyan, :output then 11 + when :red, :failure then 12 + when :purple then 13 + when :yellow then 14 + when :white then 15 + else + 0 + end + end + + def posix_colour(colour) + # ANSI Escape Codes - Foreground colors + # | Code | Color | + # | 39 | Default foreground color | + # | 30 | Black | + # | 31 | Red | + # | 32 | Green | + # | 33 | Yellow | + # | 34 | Blue | + # | 35 | Magenta | + # | 36 | Cyan | + # | 37 | Light gray | + # | 90 | Dark gray | + # | 91 | Light red | + # | 92 | Light green | + # | 93 | Light yellow | + # | 94 | Light blue | + # | 95 | Light magenta | + # | 96 | Light cyan | + # | 97 | White | + + case colour + when :black then 30 + when :red, :failure then 31 + when :green, :success then 32 + when :yellow then 33 + when :blue, :narrative then 34 + when :purple, :magenta then 35 + when :cyan, :output then 36 + when :white, :default_white then 37 + when :default then 39 + else + 39 + end + end + + def out_c(mode, colour, str) + case RUBY_PLATFORM + when /(win|w)32$/ + change_to(colour) + $stdout.puts str if mode == :puts + $stdout.print str if mode == :print + change_to(:default_white) + else + $stdout.puts("#{change_to(colour)}#{str}\033[0m") if mode == :puts + $stdout.print("#{change_to(colour)}#{str}\033[0m") if mode == :print + end + end +end # ColourCommandLine + +def colour_puts(role, str) + ColourCommandLine.new.out_c(:puts, role, str) +end + +def colour_print(role, str) + ColourCommandLine.new.out_c(:print, role, str) +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_reporter.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_reporter.rb new file mode 100644 index 0000000..bb1fbfc --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/colour_reporter.rb @@ -0,0 +1,39 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +require "#{File.expand_path(File.dirname(__FILE__))}/colour_prompt" + +$colour_output = true + +def report(message) + if !$colour_output + $stdout.puts(message) + else + message = message.join('\n') if message.class == Array + message.each_line do |line| + line.chomp! + colour = case line + when /(?:total\s+)?tests:?\s+(\d+)\s+(?:total\s+)?failures:?\s+\d+\s+Ignored:?/i + Regexp.last_match(1).to_i.zero? ? :green : :red + when /PASS/ + :green + when /^OK$/ + :green + when /(?:FAIL|ERROR)/ + :red + when /IGNORE/ + :yellow + when /^(?:Creating|Compiling|Linking)/ + :white + else + :silver + end + colour_puts(colour, line) + end + end + $stdout.flush + $stderr.flush +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_config.yml b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_config.yml new file mode 100644 index 0000000..4a5e474 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_config.yml @@ -0,0 +1,36 @@ +#this is a sample configuration file for generate_module +#you would use it by calling generate_module with the -ygenerate_config.yml option +#files like this are useful for customizing generate_module to your environment +:generate_module: + :defaults: + #these defaults are used in place of any missing options at the command line + :path_src: ../src/ + :path_inc: ../src/ + :path_tst: ../test/ + :update_svn: true + :includes: + #use [] for no additional includes, otherwise list the includes on separate lines + :src: + - Defs.h + - Board.h + :inc: [] + :tst: + - Defs.h + - Board.h + - Exception.h + :boilerplates: + #these are inserted at the top of generated files. + #just comment out or remove if not desired. + #use %1$s where you would like the file name to appear (path/extension not included) + :src: | + //------------------------------------------- + // %1$s.c + //------------------------------------------- + :inc: | + //------------------------------------------- + // %1$s.h + //------------------------------------------- + :tst: | + //------------------------------------------- + // Test%1$s.c : Units tests for %1$s.c + //------------------------------------------- diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_module.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_module.rb new file mode 100644 index 0000000..13b4cc7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_module.rb @@ -0,0 +1,308 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +# This script creates all the files with start code necessary for a new module. +# A simple module only requires a source file, header file, and test file. +# Triad modules require a source, header, and test file for each triad type (like model, conductor, and hardware). + +require 'rubygems' +require 'fileutils' +require 'pathname' + +# TEMPLATE_TST +TEMPLATE_TST ||= '#include "unity.h" +%2$s#include "%1$s.h" + +void setUp(void) +{ +} + +void tearDown(void) +{ +} + +void test_%1$s_NeedToImplement(void) +{ + TEST_IGNORE_MESSAGE("Need to Implement %1$s"); +} +'.freeze + +# TEMPLATE_SRC +TEMPLATE_SRC ||= '%2$s#include "%1$s.h" +'.freeze + +# TEMPLATE_INC +TEMPLATE_INC ||= '#ifndef _%3$s_H +#define _%3$s_H +%2$s + +#endif // _%3$s_H +'.freeze + +class UnityModuleGenerator + ############################ + def initialize(options = nil) + here = File.expand_path(File.dirname(__FILE__)) + '/' + + @options = UnityModuleGenerator.default_options + case options + when NilClass then @options + when String then @options.merge!(UnityModuleGenerator.grab_config(options)) + when Hash then @options.merge!(options) + else raise 'If you specify arguments, it should be a filename or a hash of options' + end + + # Create default file paths if none were provided + @options[:path_src] = here + '../src/' if @options[:path_src].nil? + @options[:path_inc] = @options[:path_src] if @options[:path_inc].nil? + @options[:path_tst] = here + '../test/' if @options[:path_tst].nil? + @options[:path_src] += '/' unless @options[:path_src][-1] == 47 + @options[:path_inc] += '/' unless @options[:path_inc][-1] == 47 + @options[:path_tst] += '/' unless @options[:path_tst][-1] == 47 + + # Built in patterns + @patterns = { + 'src' => { + '' => { inc: [] } + }, + 'test' => { + '' => { inc: [] } + }, + 'dh' => { + 'Driver' => { inc: [create_filename('%1$s', 'Hardware.h')] }, + 'Hardware' => { inc: [] } + }, + 'dih' => { + 'Driver' => { inc: [create_filename('%1$s', 'Hardware.h'), create_filename('%1$s', 'Interrupt.h')] }, + 'Interrupt' => { inc: [create_filename('%1$s', 'Hardware.h')] }, + 'Hardware' => { inc: [] } + }, + 'mch' => { + 'Model' => { inc: [] }, + 'Conductor' => { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'Hardware.h')] }, + 'Hardware' => { inc: [] } + }, + 'mvp' => { + 'Model' => { inc: [] }, + 'Presenter' => { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'View.h')] }, + 'View' => { inc: [] } + } + } + end + + ############################ + def self.default_options + { + pattern: 'src', + includes: { + src: [], + inc: [], + tst: [] + }, + update_svn: false, + boilerplates: {}, + test_prefix: 'Test', + mock_prefix: 'Mock' + } + end + + ############################ + def self.grab_config(config_file) + options = default_options + unless config_file.nil? || config_file.empty? + require 'yaml' + yaml_guts = YAML.load_file(config_file) + options.merge!(yaml_guts[:unity] || yaml_guts[:cmock]) + raise "No :unity or :cmock section found in #{config_file}" unless options + end + options + end + + ############################ + def files_to_operate_on(module_name, pattern = nil) + # strip any leading path information from the module name and save for later + subfolder = File.dirname(module_name) + module_name = File.basename(module_name) + + # create triad definition + prefix = @options[:test_prefix] || 'Test' + triad = [{ ext: '.c', path: @options[:path_src], prefix: '', template: TEMPLATE_SRC, inc: :src, boilerplate: @options[:boilerplates][:src] }, + { ext: '.h', path: @options[:path_inc], prefix: '', template: TEMPLATE_INC, inc: :inc, boilerplate: @options[:boilerplates][:inc] }, + { ext: '.c', path: @options[:path_tst], prefix: prefix, template: TEMPLATE_TST, inc: :tst, boilerplate: @options[:boilerplates][:tst] }] + + # prepare the pattern for use + pattern = (pattern || @options[:pattern] || 'src').downcase + patterns = @patterns[pattern] + raise "ERROR: The design pattern '#{pattern}' specified isn't one that I recognize!" if patterns.nil? + + # single file patterns (currently just 'test') can reject the other parts of the triad + triad.select! { |v| v[:inc] == :tst } if pattern == 'test' + + # Assemble the path/names of the files we need to work with. + files = [] + triad.each do |cfg| + patterns.each_pair do |pattern_file, pattern_traits| + submodule_name = create_filename(module_name, pattern_file) + filename = cfg[:prefix] + submodule_name + cfg[:ext] + files << { + path: (Pathname.new("#{cfg[:path]}#{subfolder}") + filename).cleanpath, + name: submodule_name, + template: cfg[:template], + boilerplate: cfg[:boilerplate], + includes: case (cfg[:inc]) + when :src then (@options[:includes][:src] || []) | (pattern_traits[:inc].map { |f| format(f, module_name) }) + when :inc then (@options[:includes][:inc] || []) + when :tst then (@options[:includes][:tst] || []) | (pattern_traits[:inc].map { |f| format("#{@options[:mock_prefix]}#{f}", module_name) }) + end + } + end + end + + files + end + + ############################ + def create_filename(part1, part2 = '') + if part2.empty? + case (@options[:naming]) + when 'bumpy' then part1 + when 'camel' then part1 + when 'snake' then part1.downcase + when 'caps' then part1.upcase + else part1 + end + else + case (@options[:naming]) + when 'bumpy' then part1 + part2 + when 'camel' then part1 + part2 + when 'snake' then part1.downcase + '_' + part2.downcase + when 'caps' then part1.upcase + '_' + part2.upcase + else part1 + '_' + part2 + end + end + end + + ############################ + def generate(module_name, pattern = nil) + files = files_to_operate_on(module_name, pattern) + + # Abort if all of the module files already exist + all_files_exist = true + files.each do |file| + all_files_exist = false unless File.exist?(file[:path]) + end + raise "ERROR: File #{files[0][:name]} already exists. Exiting." if all_files_exist + + # Create Source Modules + files.each_with_index do |file, _i| + # If this file already exists, don't overwrite it. + if File.exist?(file[:path]) + puts "File #{file[:path]} already exists!" + next + end + # Create the path first if necessary. + FileUtils.mkdir_p(File.dirname(file[:path]), verbose: false) + File.open(file[:path], 'w') do |f| + f.write("#{file[:boilerplate]}\n" % [file[:name]]) unless file[:boilerplate].nil? + f.write(file[:template] % [file[:name], + file[:includes].map { |ff| "#include \"#{ff}\"\n" }.join, + file[:name].upcase]) + end + if @options[:update_svn] + `svn add \"#{file[:path]}\"` + if $!.exitstatus.zero? + puts "File #{file[:path]} created and added to source control" + else + puts "File #{file[:path]} created but FAILED adding to source control!" + end + else + puts "File #{file[:path]} created" + end + end + puts 'Generate Complete' + end + + ############################ + def destroy(module_name, pattern = nil) + files_to_operate_on(module_name, pattern).each do |filespec| + file = filespec[:path] + if File.exist?(file) + if @options[:update_svn] + `svn delete \"#{file}\" --force` + puts "File #{file} deleted and removed from source control" + else + FileUtils.remove(file) + puts "File #{file} deleted" + end + else + puts "File #{file} does not exist so cannot be removed." + end + end + puts 'Destroy Complete' + end +end + +############################ +# Handle As Command Line If Called That Way +if $0 == __FILE__ + destroy = false + options = {} + module_name = nil + + # Parse the command line parameters. + ARGV.each do |arg| + case arg + when /^-d/ then destroy = true + when /^-u/ then options[:update_svn] = true + when /^-p\"?(\w+)\"?/ then options[:pattern] = Regexp.last_match(1) + when /^-s\"?(.+)\"?/ then options[:path_src] = Regexp.last_match(1) + when /^-i\"?(.+)\"?/ then options[:path_inc] = Regexp.last_match(1) + when /^-t\"?(.+)\"?/ then options[:path_tst] = Regexp.last_match(1) + when /^-n\"?(.+)\"?/ then options[:naming] = Regexp.last_match(1) + when /^-y\"?(.+)\"?/ then options = UnityModuleGenerator.grab_config(Regexp.last_match(1)) + when /^(\w+)/ + raise "ERROR: You can't have more than one Module name specified!" unless module_name.nil? + module_name = arg + when /^-(h|-help)/ + ARGV = [].freeze + else + raise "ERROR: Unknown option specified '#{arg}'" + end + end + + unless ARGV[0] + puts ["\nGENERATE MODULE\n-------- ------", + "\nUsage: ruby generate_module [options] module_name", + " -i\"include\" sets the path to output headers to 'include' (DEFAULT ../src)", + " -s\"../src\" sets the path to output source to '../src' (DEFAULT ../src)", + " -t\"C:/test\" sets the path to output source to 'C:/test' (DEFAULT ../test)", + ' -p"MCH" sets the output pattern to MCH.', + ' dh - driver hardware.', + ' dih - driver interrupt hardware.', + ' mch - model conductor hardware.', + ' mvp - model view presenter.', + ' src - just a source module, header and test. (DEFAULT)', + ' test - just a test file.', + ' -d destroy module instead of creating it.', + ' -n"camel" sets the file naming convention.', + ' bumpy - BumpyCaseFilenames.', + ' camel - camelCaseFilenames.', + ' snake - snake_case_filenames.', + ' caps - CAPS_CASE_FILENAMES.', + ' -u update subversion too (requires subversion command line)', + ' -y"my.yml" selects a different yaml config file for module generation', + ''].join("\n") + exit + end + + raise 'ERROR: You must have a Module name specified! (use option -h for help)' if module_name.nil? + if destroy + UnityModuleGenerator.new(options).destroy(module_name) + else + UnityModuleGenerator.new(options).generate(module_name) + end + +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_test_runner.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_test_runner.rb new file mode 100644 index 0000000..344a2d0 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/generate_test_runner.rb @@ -0,0 +1,454 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +File.expand_path(File.join(File.dirname(__FILE__), 'colour_prompt')) + +class UnityTestRunnerGenerator + def initialize(options = nil) + @options = UnityTestRunnerGenerator.default_options + case options + when NilClass then @options + when String then @options.merge!(UnityTestRunnerGenerator.grab_config(options)) + when Hash then @options.merge!(options) + else raise 'If you specify arguments, it should be a filename or a hash of options' + end + require "#{File.expand_path(File.dirname(__FILE__))}/type_sanitizer" + end + + def self.default_options + { + includes: [], + defines: [], + plugins: [], + framework: :unity, + test_prefix: 'test|spec|should', + mock_prefix: 'Mock', + setup_name: 'setUp', + teardown_name: 'tearDown', + main_name: 'main', # set to :auto to automatically generate each time + main_export_decl: '', + cmdline_args: false, + use_param_tests: false + } + end + + def self.grab_config(config_file) + options = default_options + unless config_file.nil? || config_file.empty? + require 'yaml' + yaml_guts = YAML.load_file(config_file) + options.merge!(yaml_guts[:unity] || yaml_guts[:cmock]) + raise "No :unity or :cmock section found in #{config_file}" unless options + end + options + end + + def run(input_file, output_file, options = nil) + @options.merge!(options) unless options.nil? + + # pull required data from source file + source = File.read(input_file) + source = source.force_encoding('ISO-8859-1').encode('utf-8', replace: nil) + tests = find_tests(source) + headers = find_includes(source) + testfile_includes = (headers[:local] + headers[:system]) + used_mocks = find_mocks(testfile_includes) + testfile_includes = (testfile_includes - used_mocks) + testfile_includes.delete_if { |inc| inc =~ /(unity|cmock)/ } + + # build runner file + generate(input_file, output_file, tests, used_mocks, testfile_includes) + + # determine which files were used to return them + all_files_used = [input_file, output_file] + all_files_used += testfile_includes.map { |filename| filename + '.c' } unless testfile_includes.empty? + all_files_used += @options[:includes] unless @options[:includes].empty? + all_files_used += headers[:linkonly] unless headers[:linkonly].empty? + all_files_used.uniq + end + + def generate(input_file, output_file, tests, used_mocks, testfile_includes) + File.open(output_file, 'w') do |output| + create_header(output, used_mocks, testfile_includes) + create_externs(output, tests, used_mocks) + create_mock_management(output, used_mocks) + create_suite_setup(output) + create_suite_teardown(output) + create_reset(output, used_mocks) + create_main(output, input_file, tests, used_mocks) + end + + return unless @options[:header_file] && !@options[:header_file].empty? + + File.open(@options[:header_file], 'w') do |output| + create_h_file(output, @options[:header_file], tests, testfile_includes, used_mocks) + end + end + + def find_tests(source) + tests_and_line_numbers = [] + + source_scrubbed = source.clone + source_scrubbed = source_scrubbed.gsub(/"[^"\n]*"/, '') # remove things in strings + source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments + source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments + lines = source_scrubbed.split(/(^\s*\#.*$) # Treat preprocessor directives as a logical line + | (;|\{|\}) /x) # Match ;, {, and } as end of lines + + lines.each_with_index do |line, _index| + # find tests + next unless line =~ /^((?:\s*TEST_CASE\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/ + arguments = Regexp.last_match(1) + name = Regexp.last_match(2) + call = Regexp.last_match(3) + params = Regexp.last_match(4) + args = nil + if @options[:use_param_tests] && !arguments.empty? + args = [] + arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) { |a| args << a[0] } + end + tests_and_line_numbers << { test: name, args: args, call: call, params: params, line_number: 0 } + end + tests_and_line_numbers.uniq! { |v| v[:test] } + + # determine line numbers and create tests to run + source_lines = source.split("\n") + source_index = 0 + tests_and_line_numbers.size.times do |i| + source_lines[source_index..-1].each_with_index do |line, index| + next unless line =~ /\s+#{tests_and_line_numbers[i][:test]}(?:\s|\()/ + source_index += index + tests_and_line_numbers[i][:line_number] = source_index + 1 + break + end + end + + tests_and_line_numbers + end + + def find_includes(source) + # remove comments (block and line, in three steps to ensure correct precedence) + source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks + source.gsub!(/\/\*.*?\*\//m, '') # remove block comments + source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain) + + # parse out includes + includes = { + local: source.scan(/^\s*#include\s+\"\s*(.+)\.[hH]\s*\"/).flatten, + system: source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten.map { |inc| "<#{inc}>" }, + linkonly: source.scan(/^TEST_FILE\(\s*\"\s*(.+)\.[cC]\w*\s*\"/).flatten + } + includes + end + + def find_mocks(includes) + mock_headers = [] + includes.each do |include_path| + include_file = File.basename(include_path) + mock_headers << include_path if include_file =~ /^#{@options[:mock_prefix]}/i + end + mock_headers + end + + def create_header(output, mocks, testfile_includes = []) + output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */') + create_runtest(output, mocks) + output.puts("\n/*=======Automagically Detected Files To Include=====*/") + output.puts('#ifdef __WIN32__') + output.puts('#define UNITY_INCLUDE_SETUP_STUBS') + output.puts('#endif') + output.puts("#include \"#{@options[:framework]}.h\"") + output.puts('#include "cmock.h"') unless mocks.empty? + output.puts('#include ') + output.puts('#include ') + if @options[:defines] && !@options[:defines].empty? + @options[:defines].each { |d| output.puts("#define #{d}") } + end + if @options[:header_file] && !@options[:header_file].empty? + output.puts("#include \"#{File.basename(@options[:header_file])}\"") + else + @options[:includes].flatten.uniq.compact.each do |inc| + output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h', '')}.h\""}") + end + testfile_includes.each do |inc| + output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h', '')}.h\""}") + end + end + mocks.each do |mock| + output.puts("#include \"#{mock.gsub('.h', '')}.h\"") + end + output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception) + + return unless @options[:enforce_strict_ordering] + + output.puts('') + output.puts('int GlobalExpectCount;') + output.puts('int GlobalVerifyOrder;') + output.puts('char* GlobalOrderError;') + end + + def create_externs(output, tests, _mocks) + output.puts("\n/*=======External Functions This Runner Calls=====*/") + output.puts("extern void #{@options[:setup_name]}(void);") + output.puts("extern void #{@options[:teardown_name]}(void);") + tests.each do |test| + output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});") + end + output.puts('') + end + + def create_mock_management(output, mock_headers) + return if mock_headers.empty? + + output.puts("\n/*=======Mock Management=====*/") + output.puts('static void CMock_Init(void)') + output.puts('{') + + if @options[:enforce_strict_ordering] + output.puts(' GlobalExpectCount = 0;') + output.puts(' GlobalVerifyOrder = 0;') + output.puts(' GlobalOrderError = NULL;') + end + + mocks = mock_headers.map { |mock| File.basename(mock) } + mocks.each do |mock| + mock_clean = TypeSanitizer.sanitize_c_identifier(mock) + output.puts(" #{mock_clean}_Init();") + end + output.puts("}\n") + + output.puts('static void CMock_Verify(void)') + output.puts('{') + mocks.each do |mock| + mock_clean = TypeSanitizer.sanitize_c_identifier(mock) + output.puts(" #{mock_clean}_Verify();") + end + output.puts("}\n") + + output.puts('static void CMock_Destroy(void)') + output.puts('{') + mocks.each do |mock| + mock_clean = TypeSanitizer.sanitize_c_identifier(mock) + output.puts(" #{mock_clean}_Destroy();") + end + output.puts("}\n") + end + + def create_suite_setup(output) + output.puts("\n/*=======Suite Setup=====*/") + output.puts('static void suite_setup(void)') + output.puts('{') + if @options[:suite_setup].nil? + # New style, call suiteSetUp() if we can use weak symbols + output.puts('#if defined(UNITY_WEAK_ATTRIBUTE) || defined(UNITY_WEAK_PRAGMA)') + output.puts(' suiteSetUp();') + output.puts('#endif') + else + # Old style, C code embedded in the :suite_setup option + output.puts(@options[:suite_setup]) + end + output.puts('}') + end + + def create_suite_teardown(output) + output.puts("\n/*=======Suite Teardown=====*/") + output.puts('static int suite_teardown(int num_failures)') + output.puts('{') + if @options[:suite_teardown].nil? + # New style, call suiteTearDown() if we can use weak symbols + output.puts('#if defined(UNITY_WEAK_ATTRIBUTE) || defined(UNITY_WEAK_PRAGMA)') + output.puts(' return suiteTearDown(num_failures);') + output.puts('#else') + output.puts(' return num_failures;') + output.puts('#endif') + else + # Old style, C code embedded in the :suite_teardown option + output.puts(@options[:suite_teardown]) + end + output.puts('}') + end + + def create_runtest(output, used_mocks) + cexception = @options[:plugins].include? :cexception + va_args1 = @options[:use_param_tests] ? ', ...' : '' + va_args2 = @options[:use_param_tests] ? '__VA_ARGS__' : '' + output.puts("\n/*=======Test Runner Used To Run Each Test Below=====*/") + output.puts('#define RUN_TEST_NO_ARGS') if @options[:use_param_tests] + output.puts("#define RUN_TEST(TestFunc, TestLineNum#{va_args1}) \\") + output.puts('{ \\') + output.puts(" Unity.CurrentTestName = #TestFunc#{va_args2.empty? ? '' : " \"(\" ##{va_args2} \")\""}; \\") + output.puts(' Unity.CurrentTestLineNumber = TestLineNum; \\') + output.puts(' if (UnityTestMatches()) { \\') if @options[:cmdline_args] + output.puts(' Unity.NumberOfTests++; \\') + output.puts(' CMock_Init(); \\') unless used_mocks.empty? + output.puts(' UNITY_CLR_DETAILS(); \\') unless used_mocks.empty? + output.puts(' if (TEST_PROTECT()) \\') + output.puts(' { \\') + output.puts(' CEXCEPTION_T e; \\') if cexception + output.puts(' Try { \\') if cexception + output.puts(" #{@options[:setup_name]}(); \\") + output.puts(" TestFunc(#{va_args2}); \\") + output.puts(' } Catch(e) { TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, "Unhandled Exception!"); } \\') if cexception + output.puts(' } \\') + output.puts(' if (TEST_PROTECT()) \\') + output.puts(' { \\') + output.puts(" #{@options[:teardown_name]}(); \\") + output.puts(' CMock_Verify(); \\') unless used_mocks.empty? + output.puts(' } \\') + output.puts(' CMock_Destroy(); \\') unless used_mocks.empty? + output.puts(' UnityConcludeTest(); \\') + output.puts(' } \\') if @options[:cmdline_args] + output.puts("}\n") + end + + def create_reset(output, used_mocks) + output.puts("\n/*=======Test Reset Option=====*/") + output.puts('void resetTest(void);') + output.puts('void resetTest(void)') + output.puts('{') + output.puts(' CMock_Verify();') unless used_mocks.empty? + output.puts(' CMock_Destroy();') unless used_mocks.empty? + output.puts(" #{@options[:teardown_name]}();") + output.puts(' CMock_Init();') unless used_mocks.empty? + output.puts(" #{@options[:setup_name]}();") + output.puts('}') + end + + def create_main(output, filename, tests, used_mocks) + output.puts("\n\n/*=======MAIN=====*/") + main_name = @options[:main_name].to_sym == :auto ? "main_#{filename.gsub('.c', '')}" : (@options[:main_name]).to_s + if @options[:cmdline_args] + if main_name != 'main' + output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv);") + end + output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv)") + output.puts('{') + output.puts(' int parse_status = UnityParseOptions(argc, argv);') + output.puts(' if (parse_status != 0)') + output.puts(' {') + output.puts(' if (parse_status < 0)') + output.puts(' {') + output.puts(" UnityPrint(\"#{filename.gsub('.c', '')}.\");") + output.puts(' UNITY_PRINT_EOL();') + if @options[:use_param_tests] + tests.each do |test| + if test[:args].nil? || test[:args].empty? + output.puts(" UnityPrint(\" #{test[:test]}(RUN_TEST_NO_ARGS)\");") + output.puts(' UNITY_PRINT_EOL();') + else + test[:args].each do |args| + output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");") + output.puts(' UNITY_PRINT_EOL();') + end + end + end + else + tests.each { |test| output.puts(" UnityPrint(\" #{test[:test]}\");\n UNITY_PRINT_EOL();") } + end + output.puts(' return 0;') + output.puts(' }') + output.puts(' return parse_status;') + output.puts(' }') + else + if main_name != 'main' + output.puts("#{@options[:main_export_decl]} int #{main_name}(void);") + end + output.puts("int #{main_name}(void)") + output.puts('{') + end + output.puts(' suite_setup();') + output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");") + if @options[:use_param_tests] + tests.each do |test| + if test[:args].nil? || test[:args].empty? + output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]}, RUN_TEST_NO_ARGS);") + else + test[:args].each { |args| output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]}, #{args});") } + end + end + else + tests.each { |test| output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]});") } + end + output.puts + output.puts(' CMock_Guts_MemFreeFinal();') unless used_mocks.empty? + output.puts(" return suite_teardown(UnityEnd());") + output.puts('}') + end + + def create_h_file(output, filename, tests, testfile_includes, used_mocks) + filename = File.basename(filename).gsub(/[-\/\\\.\,\s]/, '_').upcase + output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */') + output.puts("#ifndef _#{filename}") + output.puts("#define _#{filename}\n\n") + output.puts("#include \"#{@options[:framework]}.h\"") + output.puts('#include "cmock.h"') unless used_mocks.empty? + @options[:includes].flatten.uniq.compact.each do |inc| + output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h', '')}.h\""}") + end + testfile_includes.each do |inc| + output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h', '')}.h\""}") + end + output.puts "\n" + tests.each do |test| + if test[:params].nil? || test[:params].empty? + output.puts("void #{test[:test]}(void);") + else + output.puts("void #{test[:test]}(#{test[:params]});") + end + end + output.puts("#endif\n\n") + end +end + +if $0 == __FILE__ + options = { includes: [] } + + # parse out all the options first (these will all be removed as we go) + ARGV.reject! do |arg| + case arg + when '-cexception' + options[:plugins] = [:cexception] + true + when /\.*\.ya?ml/ + options = UnityTestRunnerGenerator.grab_config(arg) + true + when /--(\w+)=\"?(.*)\"?/ + options[Regexp.last_match(1).to_sym] = Regexp.last_match(2) + true + when /\.*\.h/ + options[:includes] << arg + true + else false + end + end + + # make sure there is at least one parameter left (the input file) + unless ARGV[0] + puts ["\nusage: ruby #{__FILE__} (files) (options) input_test_file (output)", + "\n input_test_file - this is the C file you want to create a runner for", + ' output - this is the name of the runner file to generate', + ' defaults to (input_test_file)_Runner', + ' files:', + ' *.yml / *.yaml - loads configuration from here in :unity or :cmock', + ' *.h - header files are added as #includes in runner', + ' options:', + ' -cexception - include cexception support', + ' --setup_name="" - redefine setUp func name to something else', + ' --teardown_name="" - redefine tearDown func name to something else', + ' --main_name="" - redefine main func name to something else', + ' --test_prefix="" - redefine test prefix from default test|spec|should', + ' --suite_setup="" - code to execute for setup of entire suite', + ' --suite_teardown="" - code to execute for teardown of entire suite', + ' --use_param_tests=1 - enable parameterized tests (disabled by default)', + ' --header_file="" - path/name of test header file to generate too'].join("\n") + exit 1 + end + + # create the default test runner name if not specified + ARGV[1] = ARGV[0].gsub('.c', '_Runner.c') unless ARGV[1] + + UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1]) +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/parse_output.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/parse_output.rb new file mode 100644 index 0000000..8e88fff --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/parse_output.rb @@ -0,0 +1,220 @@ +#============================================================ +# Author: John Theofanopoulos +# A simple parser. Takes the output files generated during the build process and +# extracts information relating to the tests. +# +# Notes: +# To capture an output file under VS builds use the following: +# devenv [build instructions] > Output.txt & type Output.txt +# +# To capture an output file under GCC/Linux builds use the following: +# make | tee Output.txt +# +# To use this parser use the following command +# ruby parseOutput.rb [options] [file] +# options: -xml : produce a JUnit compatible XML file +# file : file to scan for results +#============================================================ + +class ParseOutput + def initialize + @test_flag = false + @xml_out = false + @array_list = false + @total_tests = false + @class_index = false + end + + # Set the flag to indicate if there will be an XML output file or not + def set_xml_output + @xml_out = true + end + + # if write our output to XML + def write_xml_output + output = File.open('report.xml', 'w') + output << "\n" + @array_list.each do |item| + output << item << "\n" + end + output << "\n" + end + + # This function will try and determine when the suite is changed. This is + # is the name that gets added to the classname parameter. + def test_suite_verify(test_suite_name) + return if @test_flag + + @test_flag = true + # Split the path name + test_name = test_suite_name.split('/') + # Remove the extension + base_name = test_name[test_name.size - 1].split('.') + @test_suite = 'test.' + base_name[0] + printf "New Test: %s\n", @test_suite + end + + # Test was flagged as having passed so format the output + def test_passed(array) + last_item = array.length - 1 + test_name = array[last_item - 1] + test_suite_verify(array[@class_name]) + printf "%-40s PASS\n", test_name + + return unless @xml_out + + @array_list.push ' ' + end + + # Test was flagged as having passed so format the output. + # This is using the Unity fixture output and not the original Unity output. + def test_passed_unity_fixture(array) + test_suite = array[0].sub('TEST(', '') + test_suite = test_suite.sub(',', '') + test_name = array[1].sub(')', '') + + return unless @xml_out + + @array_list.push ' ' + end + + # Test was flagged as being ignored so format the output + def test_ignored(array) + last_item = array.length - 1 + test_name = array[last_item - 2] + reason = array[last_item].chomp + test_suite_verify(array[@class_name]) + printf "%-40s IGNORED\n", test_name + + if test_name.start_with? 'TEST(' + array2 = test_name.split(' ') + @test_suite = array2[0].sub('TEST(', '') + @test_suite = @test_suite.sub(',', '') + test_name = array2[1].sub(')', '') + end + + return unless @xml_out + + @array_list.push ' ' + @array_list.push ' ' + reason + ' ' + @array_list.push ' ' + end + + # Test was flagged as having failed so format the line + def test_failed(array) + last_item = array.length - 1 + test_name = array[last_item - 2] + reason = array[last_item].chomp + ' at line: ' + array[last_item - 3] + test_suite_verify(array[@class_name]) + printf "%-40s FAILED\n", test_name + + if test_name.start_with? 'TEST(' + array2 = test_name.split(' ') + @test_suite = array2[0].sub('TEST(', '') + @test_suite = @test_suite.sub(',', '') + test_name = array2[1].sub(')', '') + end + + return unless @xml_out + + @array_list.push ' ' + @array_list.push ' ' + reason + ' ' + @array_list.push ' ' + end + + # Figure out what OS we are running on. For now we are assuming if it's not Windows it must + # be Unix based. + def detect_os + os = RUBY_PLATFORM.split('-') + @class_name = if os.size == 2 + if os[1] == 'mingw32' + 1 + else + 0 + end + else + 0 + end + end + + # Main function used to parse the file that was captured. + def process(name) + @test_flag = false + @array_list = [] + + detect_os + + puts 'Parsing file: ' + name + + test_pass = 0 + test_fail = 0 + test_ignore = 0 + puts '' + puts '=================== RESULTS =====================' + puts '' + File.open(name).each do |line| + # Typical test lines look like this: + # /.c:36:test_tc1000_opsys:FAIL: Expected 1 Was 0 + # /.c:112:test_tc5004_initCanChannel:IGNORE: Not Yet Implemented + # /.c:115:test_tc5100_initCanVoidPtrs:PASS + # + # where path is different on Unix vs Windows devices (Windows leads with a drive letter) + line_array = line.split(':') + + # If we were able to split the line then we can look to see if any of our target words + # were found. Case is important. + if (line_array.size >= 4) || (line.start_with? 'TEST(') + # Determine if this test passed + if line.include? ':PASS' + test_passed(line_array) + test_pass += 1 + elsif line.include? ':FAIL:' + test_failed(line_array) + test_fail += 1 + elsif line.include? ':IGNORE:' + test_ignored(line_array) + test_ignore += 1 + elsif line.start_with? 'TEST(' + if line.include? ' PASS' + line_array = line.split(' ') + test_passed_unity_fixture(line_array) + test_pass += 1 + end + # If none of the keywords are found there are no more tests for this suite so clear + # the test flag + else + @test_flag = false + end + else + @test_flag = false + end + end + puts '' + puts '=================== SUMMARY =====================' + puts '' + puts 'Tests Passed : ' + test_pass.to_s + puts 'Tests Failed : ' + test_fail.to_s + puts 'Tests Ignored : ' + test_ignore.to_s + @total_tests = test_pass + test_fail + test_ignore + + return unless @xml_out + + heading = '' + @array_list.insert(0, heading) + write_xml_output + end +end + +# If the command line has no values in, used a default value of Output.txt +parse_my_file = ParseOutput.new + +if ARGV.size >= 1 + ARGV.each do |a| + if a == '-xml' + parse_my_file.set_xml_output + else + parse_my_file.process(a) + break + end + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/stylize_as_junit.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/stylize_as_junit.rb new file mode 100644 index 0000000..b3d8f40 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/stylize_as_junit.rb @@ -0,0 +1,252 @@ +#!/usr/bin/ruby +# +# unity_to_junit.rb +# +require 'fileutils' +require 'optparse' +require 'ostruct' +require 'set' + +require 'pp' + +VERSION = 1.0 + +class ArgvParser + # + # Return a structure describing the options. + # + def self.parse(args) + # The options specified on the command line will be collected in *options*. + # We set default values here. + options = OpenStruct.new + options.results_dir = '.' + options.root_path = '.' + options.out_file = 'results.xml' + + opts = OptionParser.new do |o| + o.banner = 'Usage: unity_to_junit.rb [options]' + + o.separator '' + o.separator 'Specific options:' + + o.on('-r', '--results ', 'Look for Unity Results files here.') do |results| + # puts "results #{results}" + options.results_dir = results + end + + o.on('-p', '--root_path ', 'Prepend this path to files in results.') do |root_path| + options.root_path = root_path + end + + o.on('-o', '--output ', 'XML file to generate.') do |out_file| + # puts "out_file: #{out_file}" + options.out_file = out_file + end + + o.separator '' + o.separator 'Common options:' + + # No argument, shows at tail. This will print an options summary. + o.on_tail('-h', '--help', 'Show this message') do + puts o + exit + end + + # Another typical switch to print the version. + o.on_tail('--version', 'Show version') do + puts "unity_to_junit.rb version #{VERSION}" + exit + end + end + + opts.parse!(args) + options + end # parse() +end # class OptparseExample + +class UnityToJUnit + include FileUtils::Verbose + attr_reader :report, :total_tests, :failures, :ignored + attr_writer :targets, :root, :out_file + + def initialize + @report = '' + @unit_name = '' + end + + def run + # Clean up result file names + results = @targets.map { |target| target.tr('\\', '/') } + # puts "Output File: #{@out_file}" + f = File.new(@out_file, 'w') + write_xml_header(f) + write_suites_header(f) + results.each do |result_file| + lines = File.readlines(result_file).map(&:chomp) + + raise "Empty test result file: #{result_file}" if lines.empty? + + result_output = get_details(result_file, lines) + tests, failures, ignored = parse_test_summary(lines) + result_output[:counts][:total] = tests + result_output[:counts][:failed] = failures + result_output[:counts][:ignored] = ignored + result_output[:counts][:passed] = (result_output[:counts][:total] - result_output[:counts][:failed] - result_output[:counts][:ignored]) + + # use line[0] from the test output to get the test_file path and name + test_file_str = lines[0].tr('\\', '/') + test_file_str = test_file_str.split(':') + test_file = if test_file_str.length < 2 + result_file + else + test_file_str[0] + ':' + test_file_str[1] + end + result_output[:source][:path] = File.dirname(test_file) + result_output[:source][:file] = File.basename(test_file) + + # save result_output + @unit_name = File.basename(test_file, '.*') + + write_suite_header(result_output[:counts], f) + write_failures(result_output, f) + write_tests(result_output, f) + write_ignored(result_output, f) + write_suite_footer(f) + end + write_suites_footer(f) + f.close + end + + def usage(err_msg = nil) + puts "\nERROR: " + puts err_msg if err_msg + puts 'Usage: unity_to_junit.rb [options]' + puts '' + puts 'Specific options:' + puts ' -r, --results Look for Unity Results files here.' + puts ' -p, --root_path Prepend this path to files in results.' + puts ' -o, --output XML file to generate.' + puts '' + puts 'Common options:' + puts ' -h, --help Show this message' + puts ' --version Show version' + + exit 1 + end + + protected + + def get_details(_result_file, lines) + results = results_structure + lines.each do |line| + line = line.tr('\\', '/') + _src_file, src_line, test_name, status, msg = line.split(/:/) + case status + when 'IGNORE' then results[:ignores] << { test: test_name, line: src_line, message: msg } + when 'FAIL' then results[:failures] << { test: test_name, line: src_line, message: msg } + when 'PASS' then results[:successes] << { test: test_name, line: src_line, message: msg } + end + end + results + end + + def parse_test_summary(summary) + raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } + [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] + end + + def here + File.expand_path(File.dirname(__FILE__)) + end + + private + + def results_structure + { + source: { path: '', file: '' }, + successes: [], + failures: [], + ignores: [], + counts: { total: 0, passed: 0, failed: 0, ignored: 0 }, + stdout: [] + } + end + + def write_xml_header(stream) + stream.puts "" + end + + def write_suites_header(stream) + stream.puts '' + end + + def write_suite_header(counts, stream) + stream.puts "\t" + end + + def write_failures(results, stream) + result = results[:failures] + result.each do |item| + filename = File.join(results[:source][:path], File.basename(results[:source][:file], '.*')) + stream.puts "\t\t" + stream.puts "\t\t\t" + stream.puts "\t\t\t [File] #{filename} [Line] #{item[:line]} " + stream.puts "\t\t" + end + end + + def write_tests(results, stream) + result = results[:successes] + result.each do |item| + stream.puts "\t\t" + end + end + + def write_ignored(results, stream) + result = results[:ignores] + result.each do |item| + filename = File.join(results[:source][:path], File.basename(results[:source][:file], '.*')) + puts "Writing ignored tests for test harness: #{filename}" + stream.puts "\t\t" + stream.puts "\t\t\t" + stream.puts "\t\t\t [File] #{filename} [Line] #{item[:line]} " + stream.puts "\t\t" + end + end + + def write_suite_footer(stream) + stream.puts "\t" + end + + def write_suites_footer(stream) + stream.puts '' + end +end # UnityToJUnit + +if __FILE__ == $0 + # parse out the command options + options = ArgvParser.parse(ARGV) + + # create an instance to work with + utj = UnityToJUnit.new + begin + # look in the specified or current directory for result files + targets = "#{options.results_dir.tr('\\', '/')}**/*.test*" + + results = Dir[targets] + raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? + utj.targets = results + + # set the root path + utj.root = options.root_path + + # set the output XML file name + # puts "Output File from options: #{options.out_file}" + utj.out_file = options.out_file + + # run the summarizer + puts utj.run + rescue StandardError => e + utj.usage e.message + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/test_file_filter.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/test_file_filter.rb new file mode 100644 index 0000000..aad28e3 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/test_file_filter.rb @@ -0,0 +1,25 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +require'yaml' + +module RakefileHelpers + class TestFileFilter + def initialize(all_files = false) + @all_files = all_files + + return false unless @all_files + return false unless File.exist?('test_file_filter.yml') + + filters = YAML.load_file('test_file_filter.yml') + @all_files = filters[:all_files] + @only_files = filters[:only_files] + @exclude_files = filters[:exclude_files] + end + + attr_accessor :all_files, :only_files, :exclude_files + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/type_sanitizer.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/type_sanitizer.rb new file mode 100644 index 0000000..dafb882 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/type_sanitizer.rb @@ -0,0 +1,6 @@ +module TypeSanitizer + def self.sanitize_c_identifier(unsanitized) + # convert filename to valid C identifier by replacing invalid chars with '_' + unsanitized.gsub(/[-\/\\\.\,\s]/, '_') + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.py b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.py new file mode 100644 index 0000000..4c20e52 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.py @@ -0,0 +1,139 @@ +#! python3 +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2015 Alexander Mueller / XelaRellum@web.de +# [Released under MIT License. Please refer to license.txt for details] +# Based on the ruby script by Mike Karlesky, Mark VanderVoord, Greg Williams +# ========================================== +import sys +import os +import re +from glob import glob + +class UnityTestSummary: + def __init__(self): + self.report = '' + self.total_tests = 0 + self.failures = 0 + self.ignored = 0 + + def run(self): + # Clean up result file names + results = [] + for target in self.targets: + results.append(target.replace('\\', '/')) + + # Dig through each result file, looking for details on pass/fail: + failure_output = [] + ignore_output = [] + + for result_file in results: + lines = list(map(lambda line: line.rstrip(), open(result_file, "r").read().split('\n'))) + if len(lines) == 0: + raise Exception("Empty test result file: %s" % result_file) + + details = self.get_details(result_file, lines) + failures = details['failures'] + ignores = details['ignores'] + if len(failures) > 0: failure_output.append('\n'.join(failures)) + if len(ignores) > 0: ignore_output.append('n'.join(ignores)) + tests,failures,ignored = self.parse_test_summary('\n'.join(lines)) + self.total_tests += tests + self.failures += failures + self.ignored += ignored + + if self.ignored > 0: + self.report += "\n" + self.report += "--------------------------\n" + self.report += "UNITY IGNORED TEST SUMMARY\n" + self.report += "--------------------------\n" + self.report += "\n".join(ignore_output) + + if self.failures > 0: + self.report += "\n" + self.report += "--------------------------\n" + self.report += "UNITY FAILED TEST SUMMARY\n" + self.report += "--------------------------\n" + self.report += '\n'.join(failure_output) + + self.report += "\n" + self.report += "--------------------------\n" + self.report += "OVERALL UNITY TEST SUMMARY\n" + self.report += "--------------------------\n" + self.report += "{total_tests} TOTAL TESTS {failures} TOTAL FAILURES {ignored} IGNORED\n".format(total_tests = self.total_tests, failures=self.failures, ignored=self.ignored) + self.report += "\n" + + return self.report + + def set_targets(self, target_array): + self.targets = target_array + + def set_root_path(self, path): + self.root = path + + def usage(self, err_msg=None): + print("\nERROR: ") + if err_msg: + print(err_msg) + print("\nUsage: unity_test_summary.py result_file_directory/ root_path/") + print(" result_file_directory - The location of your results files.") + print(" Defaults to current directory if not specified.") + print(" Should end in / if specified.") + print(" root_path - Helpful for producing more verbose output if using relative paths.") + sys.exit(1) + + def get_details(self, result_file, lines): + results = { 'failures': [], 'ignores': [], 'successes': [] } + for line in lines: + parts = line.split(':') + if len(parts) == 5: + src_file,src_line,test_name,status,msg = parts + elif len(parts) == 4: + src_file,src_line,test_name,status = parts + msg = '' + else: + continue + if len(self.root) > 0: + line_out = "%s%s" % (self.root, line) + else: + line_out = line + if status == 'IGNORE': + results['ignores'].append(line_out) + elif status == 'FAIL': + results['failures'].append(line_out) + elif status == 'PASS': + results['successes'].append(line_out) + return results + + def parse_test_summary(self, summary): + m = re.search(r"([0-9]+) Tests ([0-9]+) Failures ([0-9]+) Ignored", summary) + if not m: + raise Exception("Couldn't parse test results: %s" % summary) + + return int(m.group(1)), int(m.group(2)), int(m.group(3)) + + +if __name__ == '__main__': + uts = UnityTestSummary() + try: + #look in the specified or current directory for result files + if len(sys.argv) > 1: + targets_dir = sys.argv[1] + else: + targets_dir = './' + targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '*.test*'))) + if len(targets) == 0: + raise Exception("No *.testpass or *.testfail files found in '%s'" % targets_dir) + uts.set_targets(targets) + + #set the root path + if len(sys.argv) > 2: + root_path = sys.argv[2] + else: + root_path = os.path.split(__file__)[0] + uts.set_root_path(root_path) + + #run the summarizer + print(uts.run()) + except Exception as e: + uts.usage(e) diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.rb b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.rb new file mode 100644 index 0000000..b37dc5f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_test_summary.rb @@ -0,0 +1,136 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +# !/usr/bin/ruby +# +# unity_test_summary.rb +# +require 'fileutils' +require 'set' + +class UnityTestSummary + include FileUtils::Verbose + + attr_reader :report, :total_tests, :failures, :ignored + attr_writer :targets, :root + + def initialize(_opts = {}) + @report = '' + @total_tests = 0 + @failures = 0 + @ignored = 0 + end + + def run + # Clean up result file names + results = @targets.map { |target| target.tr('\\', '/') } + + # Dig through each result file, looking for details on pass/fail: + failure_output = [] + ignore_output = [] + + results.each do |result_file| + lines = File.readlines(result_file).map(&:chomp) + + raise "Empty test result file: #{result_file}" if lines.empty? + + output = get_details(result_file, lines) + failure_output << output[:failures] unless output[:failures].empty? + ignore_output << output[:ignores] unless output[:ignores].empty? + tests, failures, ignored = parse_test_summary(lines) + @total_tests += tests + @failures += failures + @ignored += ignored + end + + if @ignored > 0 + @report += "\n" + @report += "--------------------------\n" + @report += "UNITY IGNORED TEST SUMMARY\n" + @report += "--------------------------\n" + @report += ignore_output.flatten.join("\n") + end + + if @failures > 0 + @report += "\n" + @report += "--------------------------\n" + @report += "UNITY FAILED TEST SUMMARY\n" + @report += "--------------------------\n" + @report += failure_output.flatten.join("\n") + end + + @report += "\n" + @report += "--------------------------\n" + @report += "OVERALL UNITY TEST SUMMARY\n" + @report += "--------------------------\n" + @report += "#{@total_tests} TOTAL TESTS #{@failures} TOTAL FAILURES #{@ignored} IGNORED\n" + @report += "\n" + end + + def usage(err_msg = nil) + puts "\nERROR: " + puts err_msg if err_msg + puts "\nUsage: unity_test_summary.rb result_file_directory/ root_path/" + puts ' result_file_directory - The location of your results files.' + puts ' Defaults to current directory if not specified.' + puts ' Should end in / if specified.' + puts ' root_path - Helpful for producing more verbose output if using relative paths.' + exit 1 + end + + protected + + def get_details(_result_file, lines) + results = { failures: [], ignores: [], successes: [] } + lines.each do |line| + _src_file, _src_line, _test_name, status, _msg = line.split(/:/) + line_out = (@root && (@root != 0) ? "#{@root}#{line}" : line).gsub(/\//, '\\') + case status + when 'IGNORE' then results[:ignores] << line_out + when 'FAIL' then results[:failures] << line_out + when 'PASS' then results[:successes] << line_out + end + end + results + end + + def parse_test_summary(summary) + raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } + [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] + end + + def here + File.expand_path(File.dirname(__FILE__)) + end +end + +if $0 == __FILE__ + + # parse out the command options + opts, args = ARGV.partition { |v| v =~ /^--\w+/ } + opts.map! { |v| v[2..-1].to_sym } + + # create an instance to work with + uts = UnityTestSummary.new(opts) + + begin + # look in the specified or current directory for result files + args[0] ||= './' + targets = "#{ARGV[0].tr('\\', '/')}**/*.test*" + results = Dir[targets] + raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? + uts.targets = results + + # set the root path + args[1] ||= Dir.pwd + '/' + uts.root = ARGV[1] + + # run the summarizer + puts uts.run + rescue StandardError => e + uts.usage e.message + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_to_junit.py b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_to_junit.py new file mode 100644 index 0000000..71dd568 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/auto/unity_to_junit.py @@ -0,0 +1,146 @@ +import sys +import os +from glob import glob + +from pyparsing import * +from junit_xml import TestSuite, TestCase + + +class UnityTestSummary: + def __init__(self): + self.report = '' + self.total_tests = 0 + self.failures = 0 + self.ignored = 0 + self.targets = 0 + self.root = None + self.test_suites = dict() + + def run(self): + # Clean up result file names + results = [] + for target in self.targets: + results.append(target.replace('\\', '/')) + + # Dig through each result file, looking for details on pass/fail: + for result_file in results: + lines = list(map(lambda line: line.rstrip(), open(result_file, "r").read().split('\n'))) + if len(lines) == 0: + raise Exception("Empty test result file: %s" % result_file) + + # define an expression for your file reference + entry_one = Combine( + oneOf(list(alphas)) + ':/' + + Word(alphanums + '_-./')) + + entry_two = Word(printables + ' ', excludeChars=':') + entry = entry_one | entry_two + + delimiter = Literal(':').suppress() + tc_result_line = Group(entry.setResultsName('tc_file_name') + delimiter + entry.setResultsName( + 'tc_line_nr') + delimiter + entry.setResultsName('tc_name') + delimiter + entry.setResultsName( + 'tc_status') + Optional( + delimiter + entry.setResultsName('tc_msg'))).setResultsName("tc_line") + + eol = LineEnd().suppress() + sol = LineStart().suppress() + blank_line = sol + eol + + tc_summary_line = Group(Word(nums).setResultsName("num_of_tests") + "Tests" + Word(nums).setResultsName( + "num_of_fail") + "Failures" + Word(nums).setResultsName("num_of_ignore") + "Ignored").setResultsName( + "tc_summary") + tc_end_line = Or(Literal("FAIL"), Literal('Ok')).setResultsName("tc_result") + + # run it and see... + pp1 = tc_result_line | Optional(tc_summary_line | tc_end_line) + pp1.ignore(blank_line | OneOrMore("-")) + + result = list() + for l in lines: + result.append((pp1.parseString(l)).asDict()) + # delete empty results + result = filter(None, result) + + tc_list = list() + for r in result: + if 'tc_line' in r: + tmp_tc_line = r['tc_line'] + + # get only the file name which will be used as the classname + file_name = tmp_tc_line['tc_file_name'].split('\\').pop().split('/').pop().rsplit('.', 1)[0] + tmp_tc = TestCase(name=tmp_tc_line['tc_name'], classname=file_name) + if 'tc_status' in tmp_tc_line: + if str(tmp_tc_line['tc_status']) == 'IGNORE': + if 'tc_msg' in tmp_tc_line: + tmp_tc.add_skipped_info(message=tmp_tc_line['tc_msg'], + output=r'[File]={0}, [Line]={1}'.format( + tmp_tc_line['tc_file_name'], tmp_tc_line['tc_line_nr'])) + else: + tmp_tc.add_skipped_info(message=" ") + elif str(tmp_tc_line['tc_status']) == 'FAIL': + if 'tc_msg' in tmp_tc_line: + tmp_tc.add_failure_info(message=tmp_tc_line['tc_msg'], + output=r'[File]={0}, [Line]={1}'.format( + tmp_tc_line['tc_file_name'], tmp_tc_line['tc_line_nr'])) + else: + tmp_tc.add_failure_info(message=" ") + + tc_list.append((str(result_file), tmp_tc)) + + for k, v in tc_list: + try: + self.test_suites[k].append(v) + except KeyError: + self.test_suites[k] = [v] + ts = [] + for suite_name in self.test_suites: + ts.append(TestSuite(suite_name, self.test_suites[suite_name])) + + with open('result.xml', 'w') as f: + TestSuite.to_file(f, ts, prettyprint='True', encoding='utf-8') + + return self.report + + def set_targets(self, target_array): + self.targets = target_array + + def set_root_path(self, path): + self.root = path + + @staticmethod + def usage(err_msg=None): + print("\nERROR: ") + if err_msg: + print(err_msg) + print("\nUsage: unity_test_summary.py result_file_directory/ root_path/") + print(" result_file_directory - The location of your results files.") + print(" Defaults to current directory if not specified.") + print(" Should end in / if specified.") + print(" root_path - Helpful for producing more verbose output if using relative paths.") + sys.exit(1) + + +if __name__ == '__main__': + uts = UnityTestSummary() + try: + # look in the specified or current directory for result files + if len(sys.argv) > 1: + targets_dir = sys.argv[1] + else: + targets_dir = './' + targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '*.test*'))) + if len(targets) == 0: + raise Exception("No *.testpass or *.testfail files found in '%s'" % targets_dir) + uts.set_targets(targets) + + # set the root path + if len(sys.argv) > 2: + root_path = sys.argv[2] + else: + root_path = os.path.split(__file__)[0] + uts.set_root_path(root_path) + + # run the summarizer + print(uts.run()) + except Exception as e: + UnityTestSummary.usage(e) diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/ThrowTheSwitchCodingStandard.md b/managed_components/espressif__cjson/cJSON/tests/unity/docs/ThrowTheSwitchCodingStandard.md new file mode 100644 index 0000000..a85adef --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/ThrowTheSwitchCodingStandard.md @@ -0,0 +1,207 @@ +# ThrowTheSwitch.org Coding Standard + +Hi. Welcome to the coding standard for ThrowTheSwitch.org. For the most part, +we try to follow these standards to unify our contributors' code into a cohesive +unit (puns intended). You might find places where these standards aren't +followed. We're not perfect. Please be polite where you notice these discrepancies +and we'll try to be polite when we notice yours. + +;) + + +## Why Have A Coding Standard? + +Being consistent makes code easier to understand. We've made an attempt to keep +our standard simple because we also believe that we can only expect someone to +follow something that is understandable. Please do your best. + + +## Our Philosophy + +Before we get into details on syntax, let's take a moment to talk about our +vision for these tools. We're C developers and embedded software developers. +These tools are great to test any C code, but catering to embedded software has +made us more tolerant of compiler quirks. There are a LOT of quirky compilers +out there. By quirky I mean "doesn't follow standards because they feel like +they have a license to do as they wish." + +Our philosophy is "support every compiler we can". Most often, this means that +we aim for writing C code that is standards compliant (often C89... that seems +to be a sweet spot that is almost always compatible). But it also means these +tools are tolerant of things that aren't common. Some that aren't even +compliant. There are configuration options to override the size of standard +types. There are configuration options to force Unity to not use certain +standard library functions. A lot of Unity is configurable and we have worked +hard to make it not TOO ugly in the process. + +Similarly, our tools that parse C do their best. They aren't full C parsers +(yet) and, even if they were, they would still have to accept non-standard +additions like gcc extensions or specifying `@0x1000` to force a variable to +compile to a particular location. It's just what we do, because we like +everything to Just Work™. + +Speaking of having things Just Work™, that's our second philosophy. By that, we +mean that we do our best to have EVERY configuration option have a logical +default. We believe that if you're working with a simple compiler and target, +you shouldn't need to configure very much... we try to make the tools guess as +much as they can, but give the user the power to override it when it's wrong. + + +## Naming Things + +Let's talk about naming things. Programming is all about naming things. We name +files, functions, variables, and so much more. While we're not always going to +find the best name for something, we actually put quite a bit of effort into +finding *What Something WANTS to be Called*™. + +When naming things, we more or less follow this hierarchy, the first being the +most important to us (but we do all four whenever possible): +1. Readable +2. Descriptive +3. Consistent +4. Memorable + + +#### Readable + +We want to read our code. This means we like names and flow that are more +naturally read. We try to avoid double negatives. We try to avoid cryptic +abbreviations (sticking to ones we feel are common). + + +#### Descriptive + +We like descriptive names for things, especially functions and variables. +Finding the right name for something is an important endeavor. You might notice +from poking around our code that this often results in names that are a little +longer than the average. Guilty. We're okay with a tiny bit more typing if it +means our code is easier to understand. + +There are two exceptions to this rule that we also stick to as religiously as +possible: + +First, while we realize hungarian notation (and similar systems for encoding +type information into variable names) is providing a more descriptive name, we +feel that (for the average developer) it takes away from readability and +therefore is to be avoided. + +Second, loop counters and other local throw-away variables often have a purpose +which is obvious. There's no need, therefore, to get carried away with complex +naming. We find i, j, and k are better loop counters than loopCounterVar or +whatnot. We only break this rule when we see that more description could improve +understanding of an algorithm. + + +#### Consistent + +We like consistency, but we're not really obsessed with it. We try to name our +configuration macros in a consistent fashion... you'll notice a repeated use of +UNITY_EXCLUDE_BLAH or UNITY_USES_BLAH macros. This helps users avoid having to +remember each macro's details. + + +#### Memorable + +Where ever it doesn't violate the above principles, we try to apply memorable +names. Sometimes this means using something that is simply descriptive, but +often we strive for descriptive AND unique... we like quirky names that stand +out in our memory and are easier to search for. Take a look through the file +names in Ceedling and you'll get a good idea of what we are talking about here. +Why use preprocess when you can use preprocessinator? Or what better describes a +module in charge of invoking tasks during releases than release_invoker? Don't +get carried away. The names are still descriptive and fulfill the above +requirements, but they don't feel stale. + + +## C and C++ Details + +We don't really want to add to the style battles out there. Tabs or spaces? +How many spaces? Where do the braces go? These are age-old questions that will +never be answered... or at least not answered in a way that will make everyone +happy. + +We've decided on our own style preferences. If you'd like to contribute to these +projects (and we hope that you do), then we ask if you do your best to follow +the same. It will only hurt a little. We promise. + + +#### Whitespace + +Our C-style is to use spaces and to use 4 of them per indent level. It's a nice +power-of-2 number that looks decent on a wide screen. We have no more reason +than that. We break that rule when we have lines that wrap (macros or function +arguments or whatnot). When that happens, we like to indent further to line +things up in nice tidy columns. + +```C + if (stuff_happened) + { + do_something(); + } +``` + + +#### Case + +- Files - all lower case with underscores. +- Variables - all lower case with underscores +- Macros - all caps with underscores. +- Typedefs - all caps with underscores. (also ends with _T). +- Functions - camel cased. Usually named ModuleName_FuncName +- Constants and Globals - camel cased. + + +#### Braces + +The left brace is on the next line after the declaration. The right brace is +directly below that. Everything in between in indented one level. If you're +catching an error and you have a one-line, go ahead and to it on the same line. + +```C + while (blah) + { + //Like so. Even if only one line, we use braces. + } +``` + + +#### Comments + +Do you know what we hate? Old-school C block comments. BUT, we're using them +anyway. As we mentioned, our goal is to support every compiler we can, +especially embedded compilers. There are STILL C compilers out there that only +support old-school block comments. So that is what we're using. We apologize. We +think they are ugly too. + + +## Ruby Details + +Is there really such thing as a Ruby coding standard? Ruby is such a free form +language, it seems almost sacrilegious to suggest that people should comply to +one method! We'll keep it really brief! + + +#### Whitespace + +Our Ruby style is to use spaces and to use 2 of them per indent level. It's a +nice power-of-2 number that really grooves with Ruby's compact style. We have no +more reason than that. We break that rule when we have lines that wrap. When +that happens, we like to indent further to line things up in nice tidy columns. + + +#### Case + +- Files - all lower case with underscores. +- Variables - all lower case with underscores +- Classes, Modules, etc - Camel cased. +- Functions - all lower case with underscores +- Constants - all upper case with underscores + + +## Documentation + +Egad. Really? We use markdown and we like pdf files because they can be made to +look nice while still being portable. Good enough? + + +*Find The Latest of This And More at [ThrowTheSwitch.org](https://throwtheswitch.org)* diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf new file mode 100644 index 0000000..28f0c32 Binary files /dev/null and b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf differ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsReference.md b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsReference.md new file mode 100644 index 0000000..2dcf5e3 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityAssertionsReference.md @@ -0,0 +1,770 @@ +# Unity Assertions Reference + +## Background and Overview + +### Super Condensed Version + +- An assertion establishes truth (i.e. boolean True) for a single condition. +Upon boolean False, an assertion stops execution and reports the failure. +- Unity is mainly a rich collection of assertions and the support to gather up +and easily execute those assertions. +- The structure of Unity allows you to easily separate test assertions from +source code in, well, test code. +- Unity's assertions: +- Come in many, many flavors to handle different C types and assertion cases. +- Use context to provide detailed and helpful failure messages. +- Document types, expected values, and basic behavior in your source code for +free. + + +### Unity Is Several Things But Mainly It's Assertions + +One way to think of Unity is simply as a rich collection of assertions you can +use to establish whether your source code behaves the way you think it does. +Unity provides a framework to easily organize and execute those assertions in +test code separate from your source code. + + +### What's an Assertion? + +At their core, assertions are an establishment of truth - boolean truth. Was this +thing equal to that thing? Does that code doohickey have such-and-such property +or not? You get the idea. Assertions are executable code (to appreciate the big +picture on this read up on the difference between +[link:Dynamic Verification and Static Analysis]). A failing assertion stops +execution and reports an error through some appropriate I/O channel (e.g. +stdout, GUI, file, blinky light). + +Fundamentally, for dynamic verification all you need is a single assertion +mechanism. In fact, that's what the [assert() macro in C's standard library](http://en.wikipedia.org/en/wiki/Assert.h) +is for. So why not just use it? Well, we can do far better in the reporting +department. C's `assert()` is pretty dumb as-is and is particularly poor for +handling common data types like arrays, structs, etc. And, without some other +support, it's far too tempting to litter source code with C's `assert()`'s. It's +generally much cleaner, manageable, and more useful to separate test and source +code in the way Unity facilitates. + + +### Unity's Assertions: Helpful Messages _and_ Free Source Code Documentation + +Asserting a simple truth condition is valuable, but using the context of the +assertion is even more valuable. For instance, if you know you're comparing bit +flags and not just integers, then why not use that context to give explicit, +readable, bit-level feedback when an assertion fails? + +That's what Unity's collection of assertions do - capture context to give you +helpful, meaningful assertion failure messages. In fact, the assertions +themselves also serve as executable documentation about types and values in your +source code. So long as your tests remain current with your source and all those +tests pass, you have a detailed, up-to-date view of the intent and mechanisms in +your source code. And due to a wondrous mystery, well-tested code usually tends +to be well designed code. + + +## Assertion Conventions and Configurations + +### Naming and Parameter Conventions + +The convention of assertion parameters generally follows this order: + + TEST_ASSERT_X( {modifiers}, {expected}, actual, {size/count} ) + +The very simplest assertion possible uses only a single "actual" parameter (e.g. +a simple null check). + +"Actual" is the value being tested and unlike the other parameters in an +assertion construction is the only parameter present in all assertion variants. +"Modifiers" are masks, ranges, bit flag specifiers, floating point deltas. +"Expected" is your expected value (duh) to compare to an "actual" value; it's +marked as an optional parameter because some assertions only need a single +"actual" parameter (e.g. null check). +"Size/count" refers to string lengths, number of array elements, etc. + +Many of Unity's assertions are apparent duplications in that the same data type +is handled by several assertions. The differences among these are in how failure +messages are presented. For instance, a `_HEX` variant of an assertion prints +the expected and actual values of that assertion formatted as hexadecimal. + + +#### TEST_ASSERT_X_MESSAGE Variants + +_All_ assertions are complemented with a variant that includes a simple string +message as a final parameter. The string you specify is appended to an assertion +failure message in Unity output. + +For brevity, the assertion variants with a message parameter are not listed +below. Just tack on `_MESSAGE` as the final component to any assertion name in +the reference list below and add a string as the final parameter. + +_Example:_ + + TEST_ASSERT_X( {modifiers}, {expected}, actual, {size/count} ) + +becomes messageified like thus... + + TEST_ASSERT_X_MESSAGE( {modifiers}, {expected}, actual, {size/count}, message ) + + +#### TEST_ASSERT_X_ARRAY Variants + +Unity provides a collection of assertions for arrays containing a variety of +types. These are documented in the Array section below. These are almost on par +with the `_MESSAGE`variants of Unity's Asserts in that for pretty much any Unity +type assertion you can tack on `_ARRAY` and run assertions on an entire block of +memory. + + TEST_ASSERT_EQUAL_TYPEX_ARRAY( expected, actual, {size/count} ) + +"Expected" is an array itself. +"Size/count" is one or two parameters necessary to establish the number of array +elements and perhaps the length of elements within the array. + +Notes: +- The `_MESSAGE` variant convention still applies here to array assertions. The +`_MESSAGE` variants of the `_ARRAY` assertions have names ending with +`_ARRAY_MESSAGE`. +- Assertions for handling arrays of floating point values are grouped with float +and double assertions (see immediately following section). + + +### TEST_ASSERT_EACH_EQUAL_X Variants + +Unity provides a collection of assertions for arrays containing a variety of +types which can be compared to a single value as well. These are documented in +the Each Equal section below. these are almost on par with the `_MESSAGE` +variants of Unity's Asserts in that for pretty much any Unity type assertion you +can inject _EACH_EQUAL and run assertions on an entire block of memory. + + TEST_ASSERT_EACH_EQUAL_TYPEX( expected, actual, {size/count} ) + +"Expected" is a single value to compare to. +"Actual" is an array where each element will be compared to the expected value. +"Size/count" is one of two parameters necessary to establish the number of array +elements and perhaps the length of elements within the array. + +Notes: +- The `_MESSAGE` variant convention still applies here to Each Equal assertions. +- Assertions for handling Each Equal of floating point values are grouped with +float and double assertions (see immediately following section). + + +### Configuration + +#### Floating Point Support Is Optional + +Support for floating point types is configurable. That is, by defining the +appropriate preprocessor symbols, floats and doubles can be individually enabled +or disabled in Unity code. This is useful for embedded targets with no floating +point math support (i.e. Unity compiles free of errors for fixed point only +platforms). See Unity documentation for specifics. + + +#### Maximum Data Type Width Is Configurable + +Not all targets support 64 bit wide types or even 32 bit wide types. Define the +appropriate preprocessor symbols and Unity will omit all operations from +compilation that exceed the maximum width of your target. See Unity +documentation for specifics. + + +## The Assertions in All Their Blessed Glory + +### Basic Fail and Ignore + +##### `TEST_FAIL()` + +This fella is most often used in special conditions where your test code is +performing logic beyond a simple assertion. That is, in practice, `TEST_FAIL()` +will always be found inside a conditional code block. + +_Examples:_ +- Executing a state machine multiple times that increments a counter your test +code then verifies as a final step. +- Triggering an exception and verifying it (as in Try / Catch / Throw - see the +[CException](https://github.com/ThrowTheSwitch/CException) project). + +##### `TEST_IGNORE()` + +Marks a test case (i.e. function meant to contain test assertions) as ignored. +Usually this is employed as a breadcrumb to come back and implement a test case. +An ignored test case has effects if other assertions are in the enclosing test +case (see Unity documentation for more). + +### Boolean + +##### `TEST_ASSERT (condition)` + +##### `TEST_ASSERT_TRUE (condition)` + +##### `TEST_ASSERT_FALSE (condition)` + +##### `TEST_ASSERT_UNLESS (condition)` + +A simple wording variation on `TEST_ASSERT_FALSE`.The semantics of +`TEST_ASSERT_UNLESS` aid readability in certain test constructions or +conditional statements. + +##### `TEST_ASSERT_NULL (pointer)` + +##### `TEST_ASSERT_NOT_NULL (pointer)` + + +### Signed and Unsigned Integers (of all sizes) + +Large integer sizes can be disabled for build targets that do not support them. +For example, if your target only supports up to 16 bit types, by defining the +appropriate symbols Unity can be configured to omit 32 and 64 bit operations +that would break compilation (see Unity documentation for more). Refer to +Advanced Asserting later in this document for advice on dealing with other word +sizes. + +##### `TEST_ASSERT_EQUAL_INT (expected, actual)` + +##### `TEST_ASSERT_EQUAL_INT8 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_INT16 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_INT32 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_INT64 (expected, actual)` + +##### `TEST_ASSERT_EQUAL (expected, actual)` + +##### `TEST_ASSERT_NOT_EQUAL (expected, actual)` + +##### `TEST_ASSERT_EQUAL_UINT (expected, actual)` + +##### `TEST_ASSERT_EQUAL_UINT8 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_UINT16 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_UINT32 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_UINT64 (expected, actual)` + + +### Unsigned Integers (of all sizes) in Hexadecimal + +All `_HEX` assertions are identical in function to unsigned integer assertions +but produce failure messages with the `expected` and `actual` values formatted +in hexadecimal. Unity output is big endian. + +##### `TEST_ASSERT_EQUAL_HEX (expected, actual)` + +##### `TEST_ASSERT_EQUAL_HEX8 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_HEX16 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_HEX32 (expected, actual)` + +##### `TEST_ASSERT_EQUAL_HEX64 (expected, actual)` + + +### Masked and Bit-level Assertions + +Masked and bit-level assertions produce output formatted in hexadecimal. Unity +output is big endian. + + +##### `TEST_ASSERT_BITS (mask, expected, actual)` + +Only compares the masked (i.e. high) bits of `expected` and `actual` parameters. + + +##### `TEST_ASSERT_BITS_HIGH (mask, actual)` + +Asserts the masked bits of the `actual` parameter are high. + + +##### `TEST_ASSERT_BITS_LOW (mask, actual)` + +Asserts the masked bits of the `actual` parameter are low. + + +##### `TEST_ASSERT_BIT_HIGH (bit, actual)` + +Asserts the specified bit of the `actual` parameter is high. + + +##### `TEST_ASSERT_BIT_LOW (bit, actual)` + +Asserts the specified bit of the `actual` parameter is low. + +### Integer Less Than / Greater Than + +These assertions verify that the `actual` parameter is less than or greater +than `threshold` (exclusive). For example, if the threshold value is 0 for the +greater than assertion will fail if it is 0 or less. + +##### `TEST_ASSERT_GREATER_THAN (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_INT (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_INT8 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_INT16 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_INT32 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_UINT (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_UINT8 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_UINT16 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_UINT32 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_HEX8 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_HEX16 (threshold, actual)` + +##### `TEST_ASSERT_GREATER_THAN_HEX32 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_INT (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_INT8 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_INT16 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_INT32 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_UINT (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_UINT8 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_UINT16 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_UINT32 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_HEX8 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_HEX16 (threshold, actual)` + +##### `TEST_ASSERT_LESS_THAN_HEX32 (threshold, actual)` + + +### Integer Ranges (of all sizes) + +These assertions verify that the `expected` parameter is within +/- `delta` +(inclusive) of the `actual` parameter. For example, if the expected value is 10 +and the delta is 3 then the assertion will fail for any value outside the range +of 7 - 13. + +##### `TEST_ASSERT_INT_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_INT8_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_INT16_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_INT32_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_INT64_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_UINT_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_UINT8_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_UINT16_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_UINT32_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_UINT64_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_HEX_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_HEX8_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_HEX16_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_HEX32_WITHIN (delta, expected, actual)` + +##### `TEST_ASSERT_HEX64_WITHIN (delta, expected, actual)` + + +### Structs and Strings + +##### `TEST_ASSERT_EQUAL_PTR (expected, actual)` + +Asserts that the pointers point to the same memory location. + + +##### `TEST_ASSERT_EQUAL_STRING (expected, actual)` + +Asserts that the null terminated (`'\0'`)strings are identical. If strings are +of different lengths or any portion of the strings before their terminators +differ, the assertion fails. Two NULL strings (i.e. zero length) are considered +equivalent. + + +##### `TEST_ASSERT_EQUAL_MEMORY (expected, actual, len)` + +Asserts that the contents of the memory specified by the `expected` and `actual` +pointers is identical. The size of the memory blocks in bytes is specified by +the `len` parameter. + + +### Arrays + +`expected` and `actual` parameters are both arrays. `num_elements` specifies the +number of elements in the arrays to compare. + +`_HEX` assertions produce failure messages with expected and actual array +contents formatted in hexadecimal. + +For array of strings comparison behavior, see comments for +`TEST_ASSERT_EQUAL_STRING` in the preceding section. + +Assertions fail upon the first element in the compared arrays found not to +match. Failure messages specify the array index of the failed comparison. + +##### `TEST_ASSERT_EQUAL_INT_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_INT8_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_INT16_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_INT32_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_INT64_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_UINT_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_UINT8_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_UINT16_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_UINT32_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_UINT64_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_HEX_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_HEX8_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_HEX16_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_HEX32_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_HEX64_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_PTR_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_STRING_ARRAY (expected, actual, num_elements)` + +##### `TEST_ASSERT_EQUAL_MEMORY_ARRAY (expected, actual, len, num_elements)` + +`len` is the memory in bytes to be compared at each array element. + + +### Each Equal (Arrays to Single Value) + +`expected` are single values and `actual` are arrays. `num_elements` specifies +the number of elements in the arrays to compare. + +`_HEX` assertions produce failure messages with expected and actual array +contents formatted in hexadecimal. + +Assertions fail upon the first element in the compared arrays found not to +match. Failure messages specify the array index of the failed comparison. + +#### `TEST_ASSERT_EACH_EQUAL_INT (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_INT8 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_INT16 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_INT32 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_INT64 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_UINT (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_UINT8 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_UINT16 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_UINT32 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_UINT64 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_HEX (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_HEX8 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_HEX16 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_HEX32 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_HEX64 (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_PTR (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_STRING (expected, actual, num_elements)` + +#### `TEST_ASSERT_EACH_EQUAL_MEMORY (expected, actual, len, num_elements)` + +`len` is the memory in bytes to be compared at each array element. + + +### Floating Point (If enabled) + +##### `TEST_ASSERT_FLOAT_WITHIN (delta, expected, actual)` + +Asserts that the `actual` value is within +/- `delta` of the `expected` value. +The nature of floating point representation is such that exact evaluations of +equality are not guaranteed. + + +##### `TEST_ASSERT_EQUAL_FLOAT (expected, actual)` + +Asserts that the ?actual?value is "close enough to be considered equal" to the +`expected` value. If you are curious about the details, refer to the Advanced +Asserting section for more details on this. Omitting a user-specified delta in a +floating point assertion is both a shorthand convenience and a requirement of +code generation conventions for CMock. + + +##### `TEST_ASSERT_EQUAL_FLOAT_ARRAY (expected, actual, num_elements)` + +See Array assertion section for details. Note that individual array element +float comparisons are executed using T?EST_ASSERT_EQUAL_FLOAT?.That is, user +specified delta comparison values requires a custom-implemented floating point +array assertion. + + +##### `TEST_ASSERT_FLOAT_IS_INF (actual)` + +Asserts that `actual` parameter is equivalent to positive infinity floating +point representation. + + +##### `TEST_ASSERT_FLOAT_IS_NEG_INF (actual)` + +Asserts that `actual` parameter is equivalent to negative infinity floating +point representation. + + +##### `TEST_ASSERT_FLOAT_IS_NAN (actual)` + +Asserts that `actual` parameter is a Not A Number floating point representation. + + +##### `TEST_ASSERT_FLOAT_IS_DETERMINATE (actual)` + +Asserts that ?actual?parameter is a floating point representation usable for +mathematical operations. That is, the `actual` parameter is neither positive +infinity nor negative infinity nor Not A Number floating point representations. + + +##### `TEST_ASSERT_FLOAT_IS_NOT_INF (actual)` + +Asserts that `actual` parameter is a value other than positive infinity floating +point representation. + + +##### `TEST_ASSERT_FLOAT_IS_NOT_NEG_INF (actual)` + +Asserts that `actual` parameter is a value other than negative infinity floating +point representation. + + +##### `TEST_ASSERT_FLOAT_IS_NOT_NAN (actual)` + +Asserts that `actual` parameter is a value other than Not A Number floating +point representation. + + +##### `TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE (actual)` + +Asserts that `actual` parameter is not usable for mathematical operations. That +is, the `actual` parameter is either positive infinity or negative infinity or +Not A Number floating point representations. + + +### Double (If enabled) + +##### `TEST_ASSERT_DOUBLE_WITHIN (delta, expected, actual)` + +Asserts that the `actual` value is within +/- `delta` of the `expected` value. +The nature of floating point representation is such that exact evaluations of +equality are not guaranteed. + + +##### `TEST_ASSERT_EQUAL_DOUBLE (expected, actual)` + +Asserts that the `actual` value is "close enough to be considered equal" to the +`expected` value. If you are curious about the details, refer to the Advanced +Asserting section for more details. Omitting a user-specified delta in a +floating point assertion is both a shorthand convenience and a requirement of +code generation conventions for CMock. + + +##### `TEST_ASSERT_EQUAL_DOUBLE_ARRAY (expected, actual, num_elements)` + +See Array assertion section for details. Note that individual array element +double comparisons are executed using `TEST_ASSERT_EQUAL_DOUBLE`.That is, user +specified delta comparison values requires a custom implemented double array +assertion. + + +##### `TEST_ASSERT_DOUBLE_IS_INF (actual)` + +Asserts that `actual` parameter is equivalent to positive infinity floating +point representation. + + +##### `TEST_ASSERT_DOUBLE_IS_NEG_INF (actual)` + +Asserts that `actual` parameter is equivalent to negative infinity floating point +representation. + + +##### `TEST_ASSERT_DOUBLE_IS_NAN (actual)` + +Asserts that `actual` parameter is a Not A Number floating point representation. + + +##### `TEST_ASSERT_DOUBLE_IS_DETERMINATE (actual)` + +Asserts that `actual` parameter is a floating point representation usable for +mathematical operations. That is, the ?actual?parameter is neither positive +infinity nor negative infinity nor Not A Number floating point representations. + + +##### `TEST_ASSERT_DOUBLE_IS_NOT_INF (actual)` + +Asserts that `actual` parameter is a value other than positive infinity floating +point representation. + + +##### `TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF (actual)` + +Asserts that `actual` parameter is a value other than negative infinity floating +point representation. + + +##### `TEST_ASSERT_DOUBLE_IS_NOT_NAN (actual)` + +Asserts that `actual` parameter is a value other than Not A Number floating +point representation. + + +##### `TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE (actual)` + +Asserts that `actual` parameter is not usable for mathematical operations. That +is, the `actual` parameter is either positive infinity or negative infinity or +Not A Number floating point representations. + + +## Advanced Asserting: Details On Tricky Assertions + +This section helps you understand how to deal with some of the trickier +assertion situations you may run into. It will give you a glimpse into some of +the under-the-hood details of Unity's assertion mechanisms. If you're one of +those people who likes to know what is going on in the background, read on. If +not, feel free to ignore the rest of this document until you need it. + + +### How do the EQUAL assertions work for FLOAT and DOUBLE? + +As you may know, directly checking for equality between a pair of floats or a +pair of doubles is sloppy at best and an outright no-no at worst. Floating point +values can often be represented in multiple ways, particularly after a series of +operations on a value. Initializing a variable to the value of 2.0 is likely to +result in a floating point representation of 2 x 20,but a series of +mathematical operations might result in a representation of 8 x 2-2 +that also evaluates to a value of 2. At some point repeated operations cause +equality checks to fail. + +So Unity doesn't do direct floating point comparisons for equality. Instead, it +checks if two floating point values are "really close." If you leave Unity +running with defaults, "really close" means "within a significant bit or two." +Under the hood, `TEST_ASSERT_EQUAL_FLOAT` is really `TEST_ASSERT_FLOAT_WITHIN` +with the `delta` parameter calculated on the fly. For single precision, delta is +the expected value multiplied by 0.00001, producing a very small proportional +range around the expected value. + +If you are expecting a value of 20,000.0 the delta is calculated to be 0.2. So +any value between 19,999.8 and 20,000.2 will satisfy the equality check. This +works out to be roughly a single bit of range for a single-precision number, and +that's just about as tight a tolerance as you can reasonably get from a floating +point value. + +So what happens when it's zero? Zero - even more than other floating point +values - can be represented many different ways. It doesn't matter if you have +0 x 20or 0 x 263.It's still zero, right? Luckily, if you +subtract these values from each other, they will always produce a difference of +zero, which will still fall between 0 plus or minus a delta of 0. So it still +works! + +Double precision floating point numbers use a much smaller multiplier, again +approximating a single bit of error. + +If you don't like these ranges and you want to make your floating point equality +assertions less strict, you can change these multipliers to whatever you like by +defining UNITY_FLOAT_PRECISION and UNITY_DOUBLE_PRECISION. See Unity +documentation for more. + + +### How do we deal with targets with non-standard int sizes? + +It's "fun" that C is a standard where something as fundamental as an integer +varies by target. According to the C standard, an `int` is to be the target's +natural register size, and it should be at least 16-bits and a multiple of a +byte. It also guarantees an order of sizes: + +```C +char <= short <= int <= long <= long long +``` + +Most often, `int` is 32-bits. In many cases in the embedded world, `int` is +16-bits. There are rare microcontrollers out there that have 24-bit integers, +and this remains perfectly standard C. + +To make things even more interesting, there are compilers and targets out there +that have a hard choice to make. What if their natural register size is 10-bits +or 12-bits? Clearly they can't fulfill _both_ the requirement to be at least +16-bits AND the requirement to match the natural register size. In these +situations, they often choose the natural register size, leaving us with +something like this: + +```C +char (8 bit) <= short (12 bit) <= int (12 bit) <= long (16 bit) +``` + +Um... yikes. It's obviously breaking a rule or two... but they had to break SOME +rules, so they made a choice. + +When the C99 standard rolled around, it introduced alternate standard-size types. +It also introduced macros for pulling in MIN/MAX values for your integer types. +It's glorious! Unfortunately, many embedded compilers can't be relied upon to +use the C99 types (Sometimes because they have weird register sizes as described +above. Sometimes because they don't feel like it?). + +A goal of Unity from the beginning was to support every combination of +microcontroller or microprocessor and C compiler. Over time, we've gotten really +close to this. There are a few tricks that you should be aware of, though, if +you're going to do this effectively on some of these more idiosyncratic targets. + +First, when setting up Unity for a new target, you're going to want to pay +special attention to the macros for automatically detecting types +(where available) or manually configuring them yourself. You can get information +on both of these in Unity's documentation. + +What about the times where you suddenly need to deal with something odd, like a +24-bit `int`? The simplest solution is to use the next size up. If you have a +24-bit `int`, configure Unity to use 32-bit integers. If you have a 12-bit +`int`, configure Unity to use 16 bits. There are two ways this is going to +affect you: + +1. When Unity displays errors for you, it's going to pad the upper unused bits +with zeros. +2. You're going to have to be careful of assertions that perform signed +operations, particularly `TEST_ASSERT_INT_WITHIN`.Such assertions might wrap +your `int` in the wrong place, and you could experience false failures. You can +always back down to a simple `TEST_ASSERT` and do the operations yourself. + + +*Find The Latest of This And More at [ThrowTheSwitch.org](https://throwtheswitch.org)* diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityConfigurationGuide.md b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityConfigurationGuide.md new file mode 100644 index 0000000..96e5358 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityConfigurationGuide.md @@ -0,0 +1,435 @@ +# Unity Configuration Guide + +## C Standards, Compilers and Microcontrollers + +The embedded software world contains its challenges. Compilers support different +revisions of the C Standard. They ignore requirements in places, sometimes to +make the language more usable in some special regard. Sometimes it's to simplify +their support. Sometimes it's due to specific quirks of the microcontroller they +are targeting. Simulators add another dimension to this menagerie. + +Unity is designed to run on almost anything that is targeted by a C compiler. It +would be awesome if this could be done with zero configuration. While there are +some targets that come close to this dream, it is sadly not universal. It is +likely that you are going to need at least a couple of the configuration options +described in this document. + +All of Unity's configuration options are `#defines`. Most of these are simple +definitions. A couple are macros with arguments. They live inside the +unity_internals.h header file. We don't necessarily recommend opening that file +unless you really need to. That file is proof that a cross-platform library is +challenging to build. From a more positive perspective, it is also proof that a +great deal of complexity can be centralized primarily to one place in order to +provide a more consistent and simple experience elsewhere. + + +### Using These Options + +It doesn't matter if you're using a target-specific compiler and a simulator or +a native compiler. In either case, you've got a couple choices for configuring +these options: + +1. Because these options are specified via C defines, you can pass most of these +options to your compiler through command line compiler flags. Even if you're +using an embedded target that forces you to use their overbearing IDE for all +configuration, there will be a place somewhere in your project to configure +defines for your compiler. +2. You can create a custom `unity_config.h` configuration file (present in your +toolchain's search paths). In this file, you will list definitions and macros +specific to your target. All you must do is define `UNITY_INCLUDE_CONFIG_H` and +Unity will rely on `unity_config.h` for any further definitions it may need. + + +## The Options + +### Integer Types + +If you've been a C developer for long, you probably already know that C's +concept of an integer varies from target to target. The C Standard has rules +about the `int` matching the register size of the target microprocessor. It has +rules about the `int` and how its size relates to other integer types. An `int` +on one target might be 16 bits while on another target it might be 64. There are +more specific types in compilers compliant with C99 or later, but that's +certainly not every compiler you are likely to encounter. Therefore, Unity has a +number of features for helping to adjust itself to match your required integer +sizes. It starts off by trying to do it automatically. + + +##### `UNITY_EXCLUDE_STDINT_H` + +The first thing that Unity does to guess your types is check `stdint.h`. +This file includes defines like `UINT_MAX` that Unity can make use of to +learn a lot about your system. It's possible you don't want it to do this +(um. why not?) or (more likely) it's possible that your system doesn't +support `stdint.h`. If that's the case, you're going to want to define this. +That way, Unity will know to skip the inclusion of this file and you won't +be left with a compiler error. + +_Example:_ + #define UNITY_EXCLUDE_STDINT_H + + +##### `UNITY_EXCLUDE_LIMITS_H` + +The second attempt to guess your types is to check `limits.h`. Some compilers +that don't support `stdint.h` could include `limits.h` instead. If you don't +want Unity to check this file either, define this to make it skip the inclusion. + +_Example:_ + #define UNITY_EXCLUDE_LIMITS_H + + +If you've disabled both of the automatic options above, you're going to have to +do the configuration yourself. Don't worry. Even this isn't too bad... there are +just a handful of defines that you are going to specify if you don't like the +defaults. + + +##### `UNITY_INT_WIDTH` + +Define this to be the number of bits an `int` takes up on your system. The +default, if not autodetected, is 32 bits. + +_Example:_ + #define UNITY_INT_WIDTH 16 + + +##### `UNITY_LONG_WIDTH` + +Define this to be the number of bits a `long` takes up on your system. The +default, if not autodetected, is 32 bits. This is used to figure out what kind +of 64-bit support your system can handle. Does it need to specify a `long` or a +`long long` to get a 64-bit value. On 16-bit systems, this option is going to be +ignored. + +_Example:_ + #define UNITY_LONG_WIDTH 16 + + +##### `UNITY_POINTER_WIDTH` + +Define this to be the number of bits a pointer takes up on your system. The +default, if not autodetected, is 32-bits. If you're getting ugly compiler +warnings about casting from pointers, this is the one to look at. + +_Example:_ + #define UNITY_POINTER_WIDTH 64 + + +##### `UNITY_SUPPORT_64` + +Unity will automatically include 64-bit support if it auto-detects it, or if +your `int`, `long`, or pointer widths are greater than 32-bits. Define this to +enable 64-bit support if none of the other options already did it for you. There +can be a significant size and speed impact to enabling 64-bit support on small +targets, so don't define it if you don't need it. + +_Example:_ + #define UNITY_SUPPORT_64 + + +### Floating Point Types + +In the embedded world, it's not uncommon for targets to have no support for +floating point operations at all or to have support that is limited to only +single precision. We are able to guess integer sizes on the fly because integers +are always available in at least one size. Floating point, on the other hand, is +sometimes not available at all. Trying to include `float.h` on these platforms +would result in an error. This leaves manual configuration as the only option. + + +##### `UNITY_INCLUDE_FLOAT` + +##### `UNITY_EXCLUDE_FLOAT` + +##### `UNITY_INCLUDE_DOUBLE` + +##### `UNITY_EXCLUDE_DOUBLE` + +By default, Unity guesses that you will want single precision floating point +support, but not double precision. It's easy to change either of these using the +include and exclude options here. You may include neither, either, or both, as +suits your needs. For features that are enabled, the following floating point +options also become available. + +_Example:_ + + //what manner of strange processor is this? + #define UNITY_EXCLUDE_FLOAT + #define UNITY_INCLUDE_DOUBLE + + +##### `UNITY_EXCLUDE_FLOAT_PRINT` + +Unity aims for as small of a footprint as possible and avoids most standard +library calls (some embedded platforms don’t have a standard library!). Because +of this, its routines for printing integer values are minimalist and hand-coded. +Therefore, the display of floating point values during a failure are optional. +By default, Unity will print the actual results of floating point assertion +failure (e.g. ”Expected 4.56 Was 4.68”). To not include this extra support, you +can use this define to instead respond to a failed assertion with a message like +”Values Not Within Delta”. If you would like verbose failure messages for floating +point assertions, use these options to give more explicit failure messages. + +_Example:_ + #define UNITY_EXCLUDE_FLOAT_PRINT + + +##### `UNITY_FLOAT_TYPE` + +If enabled, Unity assumes you want your `FLOAT` asserts to compare standard C +floats. If your compiler supports a specialty floating point type, you can +always override this behavior by using this definition. + +_Example:_ + #define UNITY_FLOAT_TYPE float16_t + + +##### `UNITY_DOUBLE_TYPE` + +If enabled, Unity assumes you want your `DOUBLE` asserts to compare standard C +doubles. If you would like to change this, you can specify something else by +using this option. For example, defining `UNITY_DOUBLE_TYPE` to `long double` +could enable gargantuan floating point types on your 64-bit processor instead of +the standard `double`. + +_Example:_ + #define UNITY_DOUBLE_TYPE long double + + +##### `UNITY_FLOAT_PRECISION` + +##### `UNITY_DOUBLE_PRECISION` + +If you look up `UNITY_ASSERT_EQUAL_FLOAT` and `UNITY_ASSERT_EQUAL_DOUBLE` as +documented in the big daddy Unity Assertion Guide, you will learn that they are +not really asserting that two values are equal but rather that two values are +"close enough" to equal. "Close enough" is controlled by these precision +configuration options. If you are working with 32-bit floats and/or 64-bit +doubles (the normal on most processors), you should have no need to change these +options. They are both set to give you approximately 1 significant bit in either +direction. The float precision is 0.00001 while the double is 10-12. +For further details on how this works, see the appendix of the Unity Assertion +Guide. + +_Example:_ + #define UNITY_FLOAT_PRECISION 0.001f + + +### Toolset Customization + +In addition to the options listed above, there are a number of other options +which will come in handy to customize Unity's behavior for your specific +toolchain. It is possible that you may not need to touch any of these... but +certain platforms, particularly those running in simulators, may need to jump +through extra hoops to operate properly. These macros will help in those +situations. + + +##### `UNITY_OUTPUT_CHAR(a)` + +##### `UNITY_OUTPUT_FLUSH()` + +##### `UNITY_OUTPUT_START()` + +##### `UNITY_OUTPUT_COMPLETE()` + +By default, Unity prints its results to `stdout` as it runs. This works +perfectly fine in most situations where you are using a native compiler for +testing. It works on some simulators as well so long as they have `stdout` +routed back to the command line. There are times, however, where the simulator +will lack support for dumping results or you will want to route results +elsewhere for other reasons. In these cases, you should define the +`UNITY_OUTPUT_CHAR` macro. This macro accepts a single character at a time (as +an `int`, since this is the parameter type of the standard C `putchar` function +most commonly used). You may replace this with whatever function call you like. + +_Example:_ +Say you are forced to run your test suite on an embedded processor with no +`stdout` option. You decide to route your test result output to a custom serial +`RS232_putc()` function you wrote like thus: + + #define UNITY_OUTPUT_CHAR(a) RS232_putc(a) + #define UNITY_OUTPUT_START() RS232_config(115200,1,8,0) + #define UNITY_OUTPUT_FLUSH() RS232_flush() + #define UNITY_OUTPUT_COMPLETE() RS232_close() + +_Note:_ +`UNITY_OUTPUT_FLUSH()` can be set to the standard out flush function simply by +specifying `UNITY_USE_FLUSH_STDOUT`. No other defines are required. If you +specify a custom flush function instead with `UNITY_OUTPUT_FLUSH` directly, it +will declare an instance of your function by default. If you want to disable +this behavior, add `UNITY_OMIT_OUTPUT_FLUSH_HEADER_DECLARATION`. + + +##### `UNITY_WEAK_ATTRIBUTE` + +##### `UNITY_WEAK_PRAGMA` + +##### `UNITY_NO_WEAK` + +For some targets, Unity can make the otherwise required setUp() and tearDown() +functions optional. This is a nice convenience for test writers since setUp and +tearDown don’t often actually do anything. If you’re using gcc or clang, this +option is automatically defined for you. Other compilers can also support this +behavior, if they support a C feature called weak functions. A weak function is +a function that is compiled into your executable unless a non-weak version of +the same function is defined elsewhere. If a non-weak version is found, the weak +version is ignored as if it never existed. If your compiler supports this feature, +you can let Unity know by defining UNITY_WEAK_ATTRIBUTE or UNITY_WEAK_PRAGMA as +the function attributes that would need to be applied to identify a function as +weak. If your compiler lacks support for weak functions, you will always need to +define setUp and tearDown functions (though they can be and often will be just +empty). You can also force Unity to NOT use weak functions by defining +UNITY_NO_WEAK. The most common options for this feature are: + +_Example:_ + #define UNITY_WEAK_ATTRIBUTE weak + #define UNITY_WEAK_ATTRIBUTE __attribute__((weak)) + #define UNITY_WEAK_PRAGMA + #define UNITY_NO_WEAK + + +##### `UNITY_PTR_ATTRIBUTE` + +Some compilers require a custom attribute to be assigned to pointers, like +`near` or `far`. In these cases, you can give Unity a safe default for these by +defining this option with the attribute you would like. + +_Example:_ + #define UNITY_PTR_ATTRIBUTE __attribute__((far)) + #define UNITY_PTR_ATTRIBUTE near + + +##### `UNITY_PRINT_EOL` + +By default, Unity outputs \n at the end of each line of output. This is easy +to parse by the scripts, by Ceedling, etc, but it might not be ideal for YOUR +system. Feel free to override this and to make it whatever you wish. + +_Example:_ + #define UNITY_PRINT_EOL { UNITY_OUTPUT_CHAR('\r'); UNITY_OUTPUT_CHAR('\n') } + + + +##### `UNITY_EXCLUDE_DETAILS` + +This is an option for if you absolutely must squeeze every byte of memory out of +your system. Unity stores a set of internal scratchpads which are used to pass +extra detail information around. It's used by systems like CMock in order to +report which function or argument flagged an error. If you're not using CMock and +you're not using these details for other things, then you can exclude them. + +_Example:_ + #define UNITY_EXCLUDE_DETAILS + + + +##### `UNITY_EXCLUDE_SETJMP` + +If your embedded system doesn't support the standard library setjmp, you can +exclude Unity's reliance on this by using this define. This dropped dependence +comes at a price, though. You will be unable to use custom helper functions for +your tests, and you will be unable to use tools like CMock. Very likely, if your +compiler doesn't support setjmp, you wouldn't have had the memory space for those +things anyway, though... so this option exists for those situations. + +_Example:_ + #define UNITY_EXCLUDE_SETJMP + +##### `UNITY_OUTPUT_COLOR` + +If you want to add color using ANSI escape codes you can use this define. +t +_Example:_ + #define UNITY_OUTPUT_COLOR + + + +## Getting Into The Guts + +There will be cases where the options above aren't quite going to get everything +perfect. They are likely sufficient for any situation where you are compiling +and executing your tests with a native toolchain (e.g. clang on Mac). These +options may even get you through the majority of cases encountered in working +with a target simulator run from your local command line. But especially if you +must run your test suite on your target hardware, your Unity configuration will +require special help. This special help will usually reside in one of two +places: the `main()` function or the `RUN_TEST` macro. Let's look at how these +work. + + +##### `main()` + +Each test module is compiled and run on its own, separate from the other test +files in your project. Each test file, therefore, has a `main` function. This +`main` function will need to contain whatever code is necessary to initialize +your system to a workable state. This is particularly true for situations where +you must set up a memory map or initialize a communication channel for the +output of your test results. + +A simple main function looks something like this: + + int main(void) { + UNITY_BEGIN(); + RUN_TEST(test_TheFirst); + RUN_TEST(test_TheSecond); + RUN_TEST(test_TheThird); + return UNITY_END(); + } + +You can see that our main function doesn't bother taking any arguments. For our +most barebones case, we'll never have arguments because we just run all the +tests each time. Instead, we start by calling `UNITY_BEGIN`. We run each test +(in whatever order we wish). Finally, we call `UNITY_END`, returning its return +value (which is the total number of failures). + +It should be easy to see that you can add code before any test cases are run or +after all the test cases have completed. This allows you to do any needed +system-wide setup or teardown that might be required for your special +circumstances. + + +##### `RUN_TEST` + +The `RUN_TEST` macro is called with each test case function. Its job is to +perform whatever setup and teardown is necessary for executing a single test +case function. This includes catching failures, calling the test module's +`setUp()` and `tearDown()` functions, and calling `UnityConcludeTest()`. If +using CMock or test coverage, there will be additional stubs in use here. A +simple minimalist RUN_TEST macro looks something like this: + + #define RUN_TEST(testfunc) \ + UNITY_NEW_TEST(#testfunc) \ + if (TEST_PROTECT()) { \ + setUp(); \ + testfunc(); \ + } \ + if (TEST_PROTECT() && (!TEST_IS_IGNORED)) \ + tearDown(); \ + UnityConcludeTest(); + +So that's quite a macro, huh? It gives you a glimpse of what kind of stuff Unity +has to deal with for every single test case. For each test case, we declare that +it is a new test. Then we run `setUp` and our test function. These are run +within a `TEST_PROTECT` block, the function of which is to handle failures that +occur during the test. Then, assuming our test is still running and hasn't been +ignored, we run `tearDown`. No matter what, our last step is to conclude this +test before moving on to the next. + +Let's say you need to add a call to `fsync` to force all of your output data to +flush to a file after each test. You could easily insert this after your +`UnityConcludeTest` call. Maybe you want to write an xml tag before and after +each result set. Again, you could do this by adding lines to this macro. Updates +to this macro are for the occasions when you need an action before or after +every single test case throughout your entire suite of tests. + + +## Happy Porting + +The defines and macros in this guide should help you port Unity to just about +any C target we can imagine. If you run into a snag or two, don't be afraid of +asking for help on the forums. We love a good challenge! + + +*Find The Latest of This And More at [ThrowTheSwitch.org](https://throwtheswitch.org)* diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityGettingStartedGuide.md b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityGettingStartedGuide.md new file mode 100644 index 0000000..08888a1 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityGettingStartedGuide.md @@ -0,0 +1,191 @@ +# Unity - Getting Started + +## Welcome + +Congratulations. You're now the proud owner of your very own pile of bits! What +are you going to do with all these ones and zeros? This document should be able +to help you decide just that. + +Unity is a unit test framework. The goal has been to keep it small and +functional. The core Unity test framework is three files: a single C file and a +couple header files. These team up to provide functions and macros to make +testing easier. + +Unity was designed to be cross platform. It works hard to stick with C standards +while still providing support for the many embedded C compilers that bend the +rules. Unity has been used with many compilers, including GCC, IAR, Clang, +Green Hills, Microchip, and MS Visual Studio. It's not much work to get it to +work with a new target. + + +### Overview of the Documents + +#### Unity Assertions reference + +This document will guide you through all the assertion options provided by +Unity. This is going to be your unit testing bread and butter. You'll spend more +time with assertions than any other part of Unity. + + +#### Unity Assertions Cheat Sheet + +This document contains an abridged summary of the assertions described in the +previous document. It's perfect for printing and referencing while you +familiarize yourself with Unity's options. + + +#### Unity Configuration Guide + +This document is the one to reference when you are going to use Unity with a new +target or compiler. It'll guide you through the configuration options and will +help you customize your testing experience to meet your needs. + + +#### Unity Helper Scripts + +This document describes the helper scripts that are available for simplifying +your testing workflow. It describes the collection of optional Ruby scripts +included in the auto directory of your Unity installation. Neither Ruby nor +these scripts are necessary for using Unity. They are provided as a convenience +for those who wish to use them. + + +#### Unity License + +What's an open source project without a license file? This brief document +describes the terms you're agreeing to when you use this software. Basically, we +want it to be useful to you in whatever context you want to use it, but please +don't blame us if you run into problems. + + +### Overview of the Folders + +If you have obtained Unity through Github or something similar, you might be +surprised by just how much stuff you suddenly have staring you in the face. +Don't worry, Unity itself is very small. The rest of it is just there to make +your life easier. You can ignore it or use it at your convenience. Here's an +overview of everything in the project. + +- `src` - This is the code you care about! This folder contains a C file and two +header files. These three files _are_ Unity. +- `docs` - You're reading this document, so it's possible you have found your way +into this folder already. This is where all the handy documentation can be +found. +- `examples` - This contains a few examples of using Unity. +- `extras` - These are optional addons to Unity that are not part of the core +project. If you've reached us through James Grenning's book, you're going to +want to look here. +- `test` - This is how Unity and its scripts are all tested. If you're just using +Unity, you'll likely never need to go in here. If you are the lucky team member +who gets to port Unity to a new toolchain, this is a good place to verify +everything is configured properly. +- `auto` - Here you will find helpful Ruby scripts for simplifying your test +workflow. They are purely optional and are not required to make use of Unity. + + +## How to Create A Test File + +Test files are C files. Most often you will create a single test file for each C +module that you want to test. The test file should include unity.h and the +header for your C module to be tested. + +Next, a test file will include a `setUp()` and `tearDown()` function. The setUp +function can contain anything you would like to run before each test. The +tearDown function can contain anything you would like to run after each test. +Both functions accept no arguments and return nothing. You may leave either or +both of these blank if you have no need for them. If you're using a compiler +that is configured to make these functions optional, you may leave them off +completely. Not sure? Give it a try. If you compiler complains that it can't +find setUp or tearDown when it links, you'll know you need to at least include +an empty function for these. + +The majority of the file will be a series of test functions. Test functions +follow the convention of starting with the word "test" or "spec". You don't HAVE +to name them this way, but it makes it clear what functions are tests for other +developers. Test functions take no arguments and return nothing. All test +accounting is handled internally in Unity. + +Finally, at the bottom of your test file, you will write a `main()` function. +This function will call `UNITY_BEGIN()`, then `RUN_TEST` for each test, and +finally `UNITY_END()`.This is what will actually trigger each of those test +functions to run, so it is important that each function gets its own `RUN_TEST` +call. + +Remembering to add each test to the main function can get to be tedious. If you +enjoy using helper scripts in your build process, you might consider making use +of our handy generate_test_runner.rb script. This will create the main function +and all the calls for you, assuming that you have followed the suggested naming +conventions. In this case, there is no need for you to include the main function +in your test file at all. + +When you're done, your test file will look something like this: + +```C +#include "unity.h" +#include "file_to_test.h" + +void setUp(void) { + // set stuff up here +} + +void tearDown(void) { + // clean stuff up here +} + +void test_function_should_doBlahAndBlah(void) { + //test stuff +} + +void test_function_should_doAlsoDoBlah(void) { + //more test stuff +} + +int main(void) { + UNITY_BEGIN(); + RUN_TEST(test_function_should_doBlahAndBlah); + RUN_TEST(test_function_should_doAlsoDoBlah); + return UNITY_END(); +} +``` + +It's possible that you will require more customization than this, eventually. +For that sort of thing, you're going to want to look at the configuration guide. +This should be enough to get you going, though. + + +## How to Build and Run A Test File + +This is the single biggest challenge to picking up a new unit testing framework, +at least in a language like C or C++. These languages are REALLY good at getting +you "close to the metal" (why is the phrase metal? Wouldn't it be more accurate +to say "close to the silicon"?). While this feature is usually a good thing, it +can make testing more challenging. + +You have two really good options for toolchains. Depending on where you're +coming from, it might surprise you that neither of these options is running the +unit tests on your hardware. +There are many reasons for this, but here's a short version: +- On hardware, you have too many constraints (processing power, memory, etc), +- On hardware, you don't have complete control over all registers, +- On hardware, unit testing is more challenging, +- Unit testing isn't System testing. Keep them separate. + +Instead of running your tests on your actual hardware, most developers choose to +develop them as native applications (using gcc or MSVC for example) or as +applications running on a simulator. Either is a good option. Native apps have +the advantages of being faster and easier to set up. Simulator apps have the +advantage of working with the same compiler as your target application. The +options for configuring these are discussed in the configuration guide. + +To get either to work, you might need to make a few changes to the file +containing your register set (discussed later). + +In either case, a test is built by linking unity, the test file, and the C +file(s) being tested. These files create an executable which can be run as the +test set for that module. Then, this process is repeated for the next test file. +This flexibility of separating tests into individual executables allows us to +much more thoroughly unit test our system and it keeps all the test code out of +our final release! + + +*Find The Latest of This And More at [ThrowTheSwitch.org](https://throwtheswitch.org)* diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityHelperScriptsGuide.md b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityHelperScriptsGuide.md new file mode 100644 index 0000000..4242990 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/UnityHelperScriptsGuide.md @@ -0,0 +1,254 @@ +# Unity Helper Scripts + +## With a Little Help From Our Friends + +Sometimes what it takes to be a really efficient C programmer is a little non-C. +The Unity project includes a couple Ruby scripts for making your life just a tad +easier. They are completely optional. If you choose to use them, you'll need a +copy of Ruby, of course. Just install whatever the latest version is, and it is +likely to work. You can find Ruby at [ruby-lang.org](https://ruby-labg.org/). + + +### `generate_test_runner.rb` + +Are you tired of creating your own `main` function in your test file? Do you +keep forgetting to add a `RUN_TEST` call when you add a new test case to your +suite? Do you want to use CMock or other fancy add-ons but don't want to figure +out how to create your own `RUN_TEST` macro? + +Well then we have the perfect script for you! + +The `generate_test_runner` script processes a given test file and automatically +creates a separate test runner file that includes ?main?to execute the test +cases within the scanned test file. All you do then is add the generated runner +to your list of files to be compiled and linked, and presto you're done! + +This script searches your test file for void function signatures having a +function name beginning with "test" or "spec". It treats each of these +functions as a test case and builds up a test suite of them. For example, the +following includes three test cases: + +```C +void testVerifyThatUnityIsAwesomeAndWillMakeYourLifeEasier(void) +{ + ASSERT_TRUE(1); +} +void test_FunctionName_should_WorkProperlyAndReturn8(void) { + ASSERT_EQUAL_INT(8, FunctionName()); +} +void spec_Function_should_DoWhatItIsSupposedToDo(void) { + ASSERT_NOT_NULL(Function(5)); +} +``` + +You can run this script a couple of ways. The first is from the command line: + +```Shell +ruby generate_test_runner.rb TestFile.c NameOfRunner.c +``` + +Alternatively, if you include only the test file parameter, the script will copy +the name of the test file and automatically append "_Runner" to the name of the +generated file. The example immediately below will create TestFile_Runner.c. + +```Shell +ruby generate_test_runner.rb TestFile.c +``` + +You can also add a [YAML](http://www.yaml.org/) file to configure extra options. +Conveniently, this YAML file is of the same format as that used by Unity and +CMock. So if you are using YAML files already, you can simply pass the very same +file into the generator script. + +```Shell +ruby generate_test_runner.rb TestFile.c my_config.yml +``` + +The contents of the YAML file `my_config.yml` could look something like the +example below. If you're wondering what some of these options do, you're going +to love the next section of this document. + +```YAML +:unity: + :includes: + - stdio.h + - microdefs.h + :cexception: 1 + :suit_setup: "blah = malloc(1024);" + :suite_teardown: "free(blah);" +``` + +If you would like to force your generated test runner to include one or more +header files, you can just include those at the command line too. Just make sure +these are _after_ the YAML file, if you are using one: + +```Shell +ruby generate_test_runner.rb TestFile.c my_config.yml extras.h +``` + +Another option, particularly if you are already using Ruby to orchestrate your +builds - or more likely the Ruby-based build tool Rake - is requiring this +script directly. Anything that you would have specified in a YAML file can be +passed to the script as part of a hash. Let's push the exact same requirement +set as we did above but this time through Ruby code directly: + +```Ruby +require "generate_test_runner.rb" +options = { + :includes => ["stdio.h", "microdefs.h"], + :cexception => 1, + :suite_setup => "blah = malloc(1024);", + :suite_teardown => "free(blah);" +} +UnityTestRunnerGenerator.new.run(testfile, runner_name, options) +``` + +If you have multiple files to generate in a build script (such as a Rakefile), +you might want to instantiate a generator object with your options and call it +to generate each runner thereafter. Like thus: + +```Ruby +gen = UnityTestRunnerGenerator.new(options) +test_files.each do |f| + gen.run(f, File.basename(f,'.c')+"Runner.c" +end +``` + +#### Options accepted by generate_test_runner.rb: + +The following options are available when executing `generate_test_runner`. You +may pass these as a Ruby hash directly or specify them in a YAML file, both of +which are described above. In the `examples` directory, Example 3's Rakefile +demonstrates using a Ruby hash. + + +##### `:includes` + +This option specifies an array of file names to be `#include`'d at the top of +your runner C file. You might use it to reference custom types or anything else +universally needed in your generated runners. + + +##### `:suite_setup` + +Define this option with C code to be executed _before any_ test cases are run. + +Alternatively, if your C compiler supports weak symbols, you can leave this +option unset and instead provide a `void suiteSetUp(void)` function in your test +suite. The linker will look for this symbol and fall back to a Unity-provided +stub if it is not found. + + +##### `:suite_teardown` + +Define this option with C code to be executed _after all_ test cases have +finished. An integer variable `num_failures` is available for diagnostics. +The code should end with a `return` statement; the value returned will become +the exit code of `main`. You can normally just return `num_failures`. + +Alternatively, if your C compiler supports weak symbols, you can leave this +option unset and instead provide a `int suiteTearDown(int num_failures)` +function in your test suite. The linker will look for this symbol and fall +back to a Unity-provided stub if it is not found. + + +##### `:enforce_strict_ordering` + +This option should be defined if you have the strict order feature enabled in +CMock (see CMock documentation). This generates extra variables required for +everything to run smoothly. If you provide the same YAML to the generator as +used in CMock's configuration, you've already configured the generator properly. + + +##### `:plugins` + +This option specifies an array of plugins to be used (of course, the array can +contain only a single plugin). This is your opportunity to enable support for +CException support, which will add a check for unhandled exceptions in each +test, reporting a failure if one is detected. To enable this feature using Ruby: + +```Ruby +:plugins => [ :cexception ] +``` + +Or as a yaml file: + +```YAML +:plugins: + -:cexception +``` + +If you are using CMock, it is very likely that you are already passing an array +of plugins to CMock. You can just use the same array here. This script will just +ignore the plugins that don't require additional support. + + +### `unity_test_summary.rb` + +A Unity test file contains one or more test case functions. Each test case can +pass, fail, or be ignored. Each test file is run individually producing results +for its collection of test cases. A given project will almost certainly be +composed of multiple test files. Therefore, the suite of tests is comprised of +one or more test cases spread across one or more test files. This script +aggregates individual test file results to generate a summary of all executed +test cases. The output includes how many tests were run, how many were ignored, +and how many failed. In addition, the output includes a listing of which +specific tests were ignored and failed. A good example of the breadth and +details of these results can be found in the `examples` directory. Intentionally +ignored and failing tests in this project generate corresponding entries in the +summary report. + +If you're interested in other (prettier?) output formats, check into the +Ceedling build tool project (ceedling.sourceforge.net) that works with Unity and +CMock and supports xunit-style xml as well as other goodies. + +This script assumes the existence of files ending with the extensions +`.testpass` and `.testfail`.The contents of these files includes the test +results summary corresponding to each test file executed with the extension set +according to the presence or absence of failures for that test file. The script +searches a specified path for these files, opens each one it finds, parses the +results, and aggregates and prints a summary. Calling it from the command line +looks like this: + +```Shell +ruby unity_test_summary.rb build/test/ +``` + +You can optionally specify a root path as well. This is really helpful when you +are using relative paths in your tools' setup, but you want to pull the summary +into an IDE like Eclipse for clickable shortcuts. + +```Shell +ruby unity_test_summary.rb build/test/ ~/projects/myproject/ +``` + +Or, if you're more of a Windows sort of person: + +```Shell +ruby unity_test_summary.rb build\teat\ C:\projects\myproject\ +``` + +When configured correctly, you'll see a final summary, like so: + +```Shell +-------------------------- +UNITY IGNORED TEST SUMMARY +-------------------------- +blah.c:22:test_sandwiches_should_HaveBreadOnTwoSides:IGNORE + +------------------------- +UNITY FAILED TEST SUMMARY +------------------------- +blah.c:87:test_sandwiches_should_HaveCondiments:FAIL:Expected 1 was 0 +meh.c:38:test_soda_should_BeCalledPop:FAIL:Expected "pop" was "coke" + +-------------------------- +OVERALL UNITY TEST SUMMARY +-------------------------- +45 TOTAL TESTS 2 TOTAL FAILURES 1 IGNORED +``` + +How convenient is that? + + +*Find The Latest of This And More at [ThrowTheSwitch.org](https://throwtheswitch.org)* diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/docs/license.txt b/managed_components/espressif__cjson/cJSON/tests/unity/docs/license.txt new file mode 100644 index 0000000..d66fba5 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/docs/license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/makefile b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/makefile new file mode 100644 index 0000000..cca79b4 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/makefile @@ -0,0 +1,71 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +#We try to detect the OS we are running on, and adjust commands as needed +ifeq ($(OS),Windows_NT) + ifeq ($(shell uname -s),) # not in a bash-like shell + CLEANUP = del /F /Q + MKDIR = mkdir + else # in a bash-like shell, like msys + CLEANUP = rm -f + MKDIR = mkdir -p + endif + TARGET_EXTENSION=.exe +else + CLEANUP = rm -f + MKDIR = mkdir -p + TARGET_EXTENSION=.out +endif + +C_COMPILER=gcc +ifeq ($(shell uname -s), Darwin) +C_COMPILER=clang +endif + +UNITY_ROOT=../.. + +CFLAGS=-std=c89 +CFLAGS += -Wall +CFLAGS += -Wextra +CFLAGS += -Wpointer-arith +CFLAGS += -Wcast-align +CFLAGS += -Wwrite-strings +CFLAGS += -Wswitch-default +CFLAGS += -Wunreachable-code +CFLAGS += -Winit-self +CFLAGS += -Wmissing-field-initializers +CFLAGS += -Wno-unknown-pragmas +CFLAGS += -Wstrict-prototypes +CFLAGS += -Wundef +CFLAGS += -Wold-style-definition + +TARGET_BASE1=test1 +TARGET_BASE2=test2 +TARGET1 = $(TARGET_BASE1)$(TARGET_EXTENSION) +TARGET2 = $(TARGET_BASE2)$(TARGET_EXTENSION) +SRC_FILES1=$(UNITY_ROOT)/src/unity.c src/ProductionCode.c test/TestProductionCode.c test/test_runners/TestProductionCode_Runner.c +SRC_FILES2=$(UNITY_ROOT)/src/unity.c src/ProductionCode2.c test/TestProductionCode2.c test/test_runners/TestProductionCode2_Runner.c +INC_DIRS=-Isrc -I$(UNITY_ROOT)/src +SYMBOLS= + +all: clean default + +default: $(SRC_FILES1) $(SRC_FILES2) + $(C_COMPILER) $(CFLAGS) $(INC_DIRS) $(SYMBOLS) $(SRC_FILES1) -o $(TARGET1) + $(C_COMPILER) $(CFLAGS) $(INC_DIRS) $(SYMBOLS) $(SRC_FILES2) -o $(TARGET2) + - ./$(TARGET1) + ./$(TARGET2) + +test/test_runners/TestProductionCode_Runner.c: test/TestProductionCode.c + ruby $(UNITY_ROOT)/auto/generate_test_runner.rb test/TestProductionCode.c test/test_runners/TestProductionCode_Runner.c +test/test_runners/TestProductionCode2_Runner.c: test/TestProductionCode2.c + ruby $(UNITY_ROOT)/auto/generate_test_runner.rb test/TestProductionCode2.c test/test_runners/TestProductionCode2_Runner.c + +clean: + $(CLEANUP) $(TARGET1) $(TARGET2) + +ci: CFLAGS += -Werror +ci: default diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/readme.txt b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/readme.txt new file mode 100644 index 0000000..dfed815 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/readme.txt @@ -0,0 +1,5 @@ +Example 1 +========= + +Close to the simplest possible example of Unity, using only basic features. +Run make to build & run the example tests. \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.c new file mode 100644 index 0000000..d039c3e --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.c @@ -0,0 +1,24 @@ + +#include "ProductionCode.h" + +int Counter = 0; +int NumbersToFind[9] = { 0, 34, 55, 66, 32, 11, 1, 77, 888 }; /* some obnoxious array to search that is 1-based indexing instead of 0. */ + +/* This function is supposed to search through NumbersToFind and find a particular number. + * If it finds it, the index is returned. Otherwise 0 is returned which sorta makes sense since + * NumbersToFind is indexed from 1. Unfortunately it's broken + * (and should therefore be caught by our tests) */ +int FindFunction_WhichIsBroken(int NumberToFind) +{ + int i = 0; + while (i <= 8) /* Notice I should have been in braces */ + i++; + if (NumbersToFind[i] == NumberToFind) /* Yikes! I'm getting run after the loop finishes instead of during it! */ + return i; + return 0; +} + +int FunctionWhichReturnsLocalVariable(void) +{ + return Counter; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.h new file mode 100644 index 0000000..250ca0d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.c new file mode 100644 index 0000000..98ee7ee --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.c @@ -0,0 +1,11 @@ + +#include "ProductionCode2.h" + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction) +{ + (void)Poor; + (void)LittleFunction; + /* Since There Are No Tests Yet, This Function Could Be Empty For All We Know. + * Which isn't terribly useful... but at least we put in a TEST_IGNORE so we won't forget */ + return (char*)0; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.h new file mode 100644 index 0000000..34ae980 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_1/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/makefile b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/makefile new file mode 100644 index 0000000..99d8d96 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/makefile @@ -0,0 +1,70 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +#We try to detect the OS we are running on, and adjust commands as needed +ifeq ($(OS),Windows_NT) + ifeq ($(shell uname -s),) # not in a bash-like shell + CLEANUP = del /F /Q + MKDIR = mkdir + else # in a bash-like shell, like msys + CLEANUP = rm -f + MKDIR = mkdir -p + endif + TARGET_EXTENSION=.exe +else + CLEANUP = rm -f + MKDIR = mkdir -p + TARGET_EXTENSION=.out +endif + +C_COMPILER=gcc +ifeq ($(shell uname -s), Darwin) +C_COMPILER=clang +endif + +UNITY_ROOT=../.. + +CFLAGS=-std=c99 +CFLAGS += -Wall +CFLAGS += -Wextra +CFLAGS += -Wpointer-arith +CFLAGS += -Wcast-align +CFLAGS += -Wwrite-strings +CFLAGS += -Wswitch-default +CFLAGS += -Wunreachable-code +CFLAGS += -Winit-self +CFLAGS += -Wmissing-field-initializers +CFLAGS += -Wno-unknown-pragmas +CFLAGS += -Wstrict-prototypes +CFLAGS += -Wundef +CFLAGS += -Wold-style-definition + +TARGET_BASE1=all_tests +TARGET1 = $(TARGET_BASE1)$(TARGET_EXTENSION) +SRC_FILES1=\ + $(UNITY_ROOT)/src/unity.c \ + $(UNITY_ROOT)/extras/fixture/src/unity_fixture.c \ + src/ProductionCode.c \ + src/ProductionCode2.c \ + test/TestProductionCode.c \ + test/TestProductionCode2.c \ + test/test_runners/TestProductionCode_Runner.c \ + test/test_runners/TestProductionCode2_Runner.c \ + test/test_runners/all_tests.c +INC_DIRS=-Isrc -I$(UNITY_ROOT)/src -I$(UNITY_ROOT)/extras/fixture/src +SYMBOLS= + +all: clean default + +default: + $(C_COMPILER) $(CFLAGS) $(INC_DIRS) $(SYMBOLS) $(SRC_FILES1) -o $(TARGET1) + - ./$(TARGET1) -v + +clean: + $(CLEANUP) $(TARGET1) + +ci: CFLAGS += -Werror +ci: default diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/readme.txt b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/readme.txt new file mode 100644 index 0000000..f0fce65 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/readme.txt @@ -0,0 +1,5 @@ +Example 2 +========= + +Same as the first example, but now using Unity's test fixture to group tests +together. Using the test fixture also makes writing test runners much easier. \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.c new file mode 100644 index 0000000..500b44b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.c @@ -0,0 +1,24 @@ + +#include "ProductionCode.h" + +int Counter = 0; +int NumbersToFind[9] = { 0, 34, 55, 66, 32, 11, 1, 77, 888 }; //some obnoxious array to search that is 1-based indexing instead of 0. + +// This function is supposed to search through NumbersToFind and find a particular number. +// If it finds it, the index is returned. Otherwise 0 is returned which sorta makes sense since +// NumbersToFind is indexed from 1. Unfortunately it's broken +// (and should therefore be caught by our tests) +int FindFunction_WhichIsBroken(int NumberToFind) +{ + int i = 0; + while (i <= 8) //Notice I should have been in braces + i++; + if (NumbersToFind[i] == NumberToFind) //Yikes! I'm getting run after the loop finishes instead of during it! + return i; + return 0; +} + +int FunctionWhichReturnsLocalVariable(void) +{ + return Counter; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.h new file mode 100644 index 0000000..250ca0d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.c new file mode 100644 index 0000000..77c969f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.c @@ -0,0 +1,11 @@ + +#include "ProductionCode2.h" + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction) +{ + (void)Poor; + (void)LittleFunction; + //Since There Are No Tests Yet, This Function Could Be Empty For All We Know. + // Which isn't terribly useful... but at least we put in a TEST_IGNORE so we won't forget + return (char*)0; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.h new file mode 100644 index 0000000..34ae980 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_2/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.c new file mode 100644 index 0000000..9cf42c6 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.c @@ -0,0 +1,10 @@ +#include "unity.h" +#include "UnityHelper.h" +#include +#include + +void AssertEqualExampleStruct(const EXAMPLE_STRUCT_T expected, const EXAMPLE_STRUCT_T actual, const unsigned short line) +{ + UNITY_TEST_ASSERT_EQUAL_INT(expected.x, actual.x, line, "Example Struct Failed For Field x"); + UNITY_TEST_ASSERT_EQUAL_INT(expected.y, actual.y, line, "Example Struct Failed For Field y"); +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.h new file mode 100644 index 0000000..1516111 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/helper/UnityHelper.h @@ -0,0 +1,12 @@ +#ifndef _TESTHELPER_H +#define _TESTHELPER_H + +#include "Types.h" + +void AssertEqualExampleStruct(const EXAMPLE_STRUCT_T expected, const EXAMPLE_STRUCT_T actual, const unsigned short line); + +#define UNITY_TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual, line, message) AssertEqualExampleStruct(expected, actual, line); + +#define TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual) UNITY_TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual, __LINE__, NULL); + +#endif // _TESTHELPER_H diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile.rb b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile.rb new file mode 100644 index 0000000..bf9f42b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile.rb @@ -0,0 +1,43 @@ +HERE = File.expand_path(File.dirname(__FILE__)) + '/' +UNITY_ROOT = File.expand_path(File.dirname(__FILE__)) + '/../..' + +require 'rake' +require 'rake/clean' +require HERE + 'rakefile_helper' + +TEMP_DIRS = [ + File.join(HERE, 'build') +].freeze + +TEMP_DIRS.each do |dir| + directory(dir) + CLOBBER.include(dir) +end + +task prepare_for_tests: TEMP_DIRS + +include RakefileHelpers + +# Load default configuration, for now +DEFAULT_CONFIG_FILE = 'target_gcc_32.yml'.freeze +configure_toolchain(DEFAULT_CONFIG_FILE) + +task unit: [:prepare_for_tests] do + run_tests unit_test_files +end + +desc 'Generate test summary' +task :summary do + report_summary +end + +desc 'Build and test Unity' +task all: %i(clean unit summary) +task default: %i(clobber all) +task ci: [:default] +task cruise: [:default] + +desc 'Load configuration' +task :config, :config_file do |_t, args| + configure_toolchain(args[:config_file]) +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile_helper.rb b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile_helper.rb new file mode 100644 index 0000000..a186cf0 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/rakefile_helper.rb @@ -0,0 +1,249 @@ +require 'yaml' +require 'fileutils' +require UNITY_ROOT + '/auto/unity_test_summary' +require UNITY_ROOT + '/auto/generate_test_runner' +require UNITY_ROOT + '/auto/colour_reporter' + +module RakefileHelpers + C_EXTENSION = '.c'.freeze + + def load_configuration(config_file) + $cfg_file = config_file + $cfg = YAML.load(File.read($cfg_file)) + end + + def configure_clean + CLEAN.include($cfg['compiler']['build_path'] + '*.*') unless $cfg['compiler']['build_path'].nil? + end + + def configure_toolchain(config_file = DEFAULT_CONFIG_FILE) + config_file += '.yml' unless config_file =~ /\.yml$/ + load_configuration(config_file) + configure_clean + end + + def unit_test_files + path = $cfg['compiler']['unit_tests_path'] + 'Test*' + C_EXTENSION + path.tr!('\\', '/') + FileList.new(path) + end + + def local_include_dirs + include_dirs = $cfg['compiler']['includes']['items'].dup + include_dirs.delete_if { |dir| dir.is_a?(Array) } + include_dirs + end + + def extract_headers(filename) + includes = [] + lines = File.readlines(filename) + lines.each do |line| + m = line.match(/^\s*#include\s+\"\s*(.+\.[hH])\s*\"/) + includes << m[1] unless m.nil? + end + includes + end + + def find_source_file(header, paths) + paths.each do |dir| + src_file = dir + header.ext(C_EXTENSION) + return src_file if File.exist?(src_file) + end + nil + end + + def tackit(strings) + result = if strings.is_a?(Array) + "\"#{strings.join}\"" + else + strings + end + result + end + + def squash(prefix, items) + result = '' + items.each { |item| result += " #{prefix}#{tackit(item)}" } + result + end + + def build_compiler_fields + command = tackit($cfg['compiler']['path']) + defines = if $cfg['compiler']['defines']['items'].nil? + '' + else + squash($cfg['compiler']['defines']['prefix'], $cfg['compiler']['defines']['items']) + end + options = squash('', $cfg['compiler']['options']) + includes = squash($cfg['compiler']['includes']['prefix'], $cfg['compiler']['includes']['items']) + includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR) + + { command: command, defines: defines, options: options, includes: includes } + end + + def compile(file, _defines = []) + compiler = build_compiler_fields + cmd_str = "#{compiler[:command]}#{compiler[:defines]}#{compiler[:options]}#{compiler[:includes]} #{file} " \ + "#{$cfg['compiler']['object_files']['prefix']}#{$cfg['compiler']['object_files']['destination']}" + obj_file = "#{File.basename(file, C_EXTENSION)}#{$cfg['compiler']['object_files']['extension']}" + execute(cmd_str + obj_file) + obj_file + end + + def build_linker_fields + command = tackit($cfg['linker']['path']) + options = if $cfg['linker']['options'].nil? + '' + else + squash('', $cfg['linker']['options']) + end + includes = if $cfg['linker']['includes'].nil? || $cfg['linker']['includes']['items'].nil? + '' + else + squash($cfg['linker']['includes']['prefix'], $cfg['linker']['includes']['items']) + end.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR) + + { command: command, options: options, includes: includes } + end + + def link_it(exe_name, obj_list) + linker = build_linker_fields + cmd_str = "#{linker[:command]}#{linker[:options]}#{linker[:includes]} " + + (obj_list.map { |obj| "#{$cfg['linker']['object_files']['path']}#{obj} " }).join + + $cfg['linker']['bin_files']['prefix'] + ' ' + + $cfg['linker']['bin_files']['destination'] + + exe_name + $cfg['linker']['bin_files']['extension'] + execute(cmd_str) + end + + def build_simulator_fields + return nil if $cfg['simulator'].nil? + command = if $cfg['simulator']['path'].nil? + '' + else + (tackit($cfg['simulator']['path']) + ' ') + end + pre_support = if $cfg['simulator']['pre_support'].nil? + '' + else + squash('', $cfg['simulator']['pre_support']) + end + post_support = if $cfg['simulator']['post_support'].nil? + '' + else + squash('', $cfg['simulator']['post_support']) + end + + { command: command, pre_support: pre_support, post_support: post_support } + end + + def execute(command_string, verbose = true, raise_on_fail = true) + report command_string + output = `#{command_string}`.chomp + report(output) if verbose && !output.nil? && !output.empty? + if !$?.exitstatus.zero? && raise_on_fail + raise "Command failed. (Returned #{$?.exitstatus})" + end + output + end + + def report_summary + summary = UnityTestSummary.new + summary.root = HERE + results_glob = "#{$cfg['compiler']['build_path']}*.test*" + results_glob.tr!('\\', '/') + results = Dir[results_glob] + summary.targets = results + summary.run + fail_out 'FAIL: There were failures' if summary.failures > 0 + end + + def run_tests(test_files) + report 'Running system tests...' + + # Tack on TEST define for compiling unit tests + load_configuration($cfg_file) + test_defines = ['TEST'] + $cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil? + $cfg['compiler']['defines']['items'] << 'TEST' + + include_dirs = local_include_dirs + + # Build and execute each unit test + test_files.each do |test| + obj_list = [] + + # Detect dependencies and build required required modules + extract_headers(test).each do |header| + # Compile corresponding source file if it exists + src_file = find_source_file(header, include_dirs) + obj_list << compile(src_file, test_defines) unless src_file.nil? + end + + # Build the test runner (generate if configured to do so) + test_base = File.basename(test, C_EXTENSION) + runner_name = test_base + '_Runner.c' + if $cfg['compiler']['runner_path'].nil? + runner_path = $cfg['compiler']['build_path'] + runner_name + test_gen = UnityTestRunnerGenerator.new($cfg_file) + test_gen.run(test, runner_path) + else + runner_path = $cfg['compiler']['runner_path'] + runner_name + end + + obj_list << compile(runner_path, test_defines) + + # Build the test module + obj_list << compile(test, test_defines) + + # Link the test executable + link_it(test_base, obj_list) + + # Execute unit test and generate results file + simulator = build_simulator_fields + executable = $cfg['linker']['bin_files']['destination'] + test_base + $cfg['linker']['bin_files']['extension'] + cmd_str = if simulator.nil? + executable + else + "#{simulator[:command]} #{simulator[:pre_support]} #{executable} #{simulator[:post_support]}" + end + output = execute(cmd_str, true, false) + test_results = $cfg['compiler']['build_path'] + test_base + test_results += if output.match(/OK$/m).nil? + '.testfail' + else + '.testpass' + end + File.open(test_results, 'w') { |f| f.print output } + end + end + + def build_application(main) + report 'Building application...' + + obj_list = [] + load_configuration($cfg_file) + main_path = $cfg['compiler']['source_path'] + main + C_EXTENSION + + # Detect dependencies and build required required modules + include_dirs = get_local_include_dirs + extract_headers(main_path).each do |header| + src_file = find_source_file(header, include_dirs) + obj_list << compile(src_file) unless src_file.nil? + end + + # Build the main source file + main_base = File.basename(main_path, C_EXTENSION) + obj_list << compile(main_path) + + # Create the executable + link_it(main_base, obj_list) + end + + def fail_out(msg) + puts msg + puts 'Not returning exit code so continuous integration can pass' + # exit(-1) # Only removed to pass example_3, which has failing tests on purpose. + # Still fail if the build fails for any other reason. + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/readme.txt b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/readme.txt new file mode 100644 index 0000000..7371fea --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/readme.txt @@ -0,0 +1,13 @@ +Example 3 +========= + +This example project gives an example of some passing, ignored, and failing tests. +It's simple and meant for you to look over and get an idea for what all of this stuff does. + +You can build and test using rake. The rake version will let you test with gcc or a couple +versions of IAR. You can tweak the yaml files to get those versions running. + +Ruby is required if you're using the rake version (obviously). This version shows off most of +Unity's advanced features (automatically creating test runners, fancy summaries, etc.) +Without ruby, you have to maintain your own test runners. Do that for a while and you'll learn +why you really want to start using the Ruby tools. diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.c new file mode 100644 index 0000000..500b44b --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.c @@ -0,0 +1,24 @@ + +#include "ProductionCode.h" + +int Counter = 0; +int NumbersToFind[9] = { 0, 34, 55, 66, 32, 11, 1, 77, 888 }; //some obnoxious array to search that is 1-based indexing instead of 0. + +// This function is supposed to search through NumbersToFind and find a particular number. +// If it finds it, the index is returned. Otherwise 0 is returned which sorta makes sense since +// NumbersToFind is indexed from 1. Unfortunately it's broken +// (and should therefore be caught by our tests) +int FindFunction_WhichIsBroken(int NumberToFind) +{ + int i = 0; + while (i <= 8) //Notice I should have been in braces + i++; + if (NumbersToFind[i] == NumberToFind) //Yikes! I'm getting run after the loop finishes instead of during it! + return i; + return 0; +} + +int FunctionWhichReturnsLocalVariable(void) +{ + return Counter; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.h new file mode 100644 index 0000000..250ca0d --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.c b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.c new file mode 100644 index 0000000..77c969f --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.c @@ -0,0 +1,11 @@ + +#include "ProductionCode2.h" + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction) +{ + (void)Poor; + (void)LittleFunction; + //Since There Are No Tests Yet, This Function Could Be Empty For All We Know. + // Which isn't terribly useful... but at least we put in a TEST_IGNORE so we won't forget + return (char*)0; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.h new file mode 100644 index 0000000..34ae980 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/target_gcc_32.yml b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/target_gcc_32.yml new file mode 100644 index 0000000..f155508 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/example_3/target_gcc_32.yml @@ -0,0 +1,46 @@ +# Copied from ~Unity/targets/gcc_32.yml +unity_root: &unity_root '../..' +compiler: + path: gcc + source_path: 'src/' + unit_tests_path: &unit_tests_path 'test/' + build_path: &build_path 'build/' + options: + - '-c' + - '-m32' + - '-Wall' + - '-Wno-address' + - '-std=c99' + - '-pedantic' + includes: + prefix: '-I' + items: + - 'src/' + - '../../src/' + - *unit_tests_path + defines: + prefix: '-D' + items: + - UNITY_INCLUDE_DOUBLE + - UNITY_SUPPORT_TEST_CASES + object_files: + prefix: '-o' + extension: '.o' + destination: *build_path +linker: + path: gcc + options: + - -lm + - '-m32' + includes: + prefix: '-I' + object_files: + path: *build_path + extension: '.o' + bin_files: + prefix: '-o' + extension: '.exe' + destination: *build_path +colour: true +:unity: + :plugins: [] diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/examples/unity_config.h b/managed_components/espressif__cjson/cJSON/tests/unity/examples/unity_config.h new file mode 100644 index 0000000..a2f161a --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/examples/unity_config.h @@ -0,0 +1,239 @@ +/* Unity Configuration + * As of May 11th, 2016 at ThrowTheSwitch/Unity commit 837c529 + * Update: December 29th, 2016 + * See Also: Unity/docs/UnityConfigurationGuide.pdf + * + * Unity is designed to run on almost anything that is targeted by a C compiler. + * It would be awesome if this could be done with zero configuration. While + * there are some targets that come close to this dream, it is sadly not + * universal. It is likely that you are going to need at least a couple of the + * configuration options described in this document. + * + * All of Unity's configuration options are `#defines`. Most of these are simple + * definitions. A couple are macros with arguments. They live inside the + * unity_internals.h header file. We don't necessarily recommend opening that + * file unless you really need to. That file is proof that a cross-platform + * library is challenging to build. From a more positive perspective, it is also + * proof that a great deal of complexity can be centralized primarily to one + * place in order to provide a more consistent and simple experience elsewhere. + * + * Using These Options + * It doesn't matter if you're using a target-specific compiler and a simulator + * or a native compiler. In either case, you've got a couple choices for + * configuring these options: + * + * 1. Because these options are specified via C defines, you can pass most of + * these options to your compiler through command line compiler flags. Even + * if you're using an embedded target that forces you to use their + * overbearing IDE for all configuration, there will be a place somewhere in + * your project to configure defines for your compiler. + * 2. You can create a custom `unity_config.h` configuration file (present in + * your toolchain's search paths). In this file, you will list definitions + * and macros specific to your target. All you must do is define + * `UNITY_INCLUDE_CONFIG_H` and Unity will rely on `unity_config.h` for any + * further definitions it may need. + */ + +#ifndef UNITY_CONFIG_H +#define UNITY_CONFIG_H + +/* ************************* AUTOMATIC INTEGER TYPES *************************** + * C's concept of an integer varies from target to target. The C Standard has + * rules about the `int` matching the register size of the target + * microprocessor. It has rules about the `int` and how its size relates to + * other integer types. An `int` on one target might be 16 bits while on another + * target it might be 64. There are more specific types in compilers compliant + * with C99 or later, but that's certainly not every compiler you are likely to + * encounter. Therefore, Unity has a number of features for helping to adjust + * itself to match your required integer sizes. It starts off by trying to do it + * automatically. + **************************************************************************** */ + +/* The first attempt to guess your types is to check `limits.h`. Some compilers + * that don't support `stdint.h` could include `limits.h`. If you don't + * want Unity to check this file, define this to make it skip the inclusion. + * Unity looks at UINT_MAX & ULONG_MAX, which were available since C89. + */ +/* #define UNITY_EXCLUDE_LIMITS_H */ + +/* The second thing that Unity does to guess your types is check `stdint.h`. + * This file defines `UINTPTR_MAX`, since C99, that Unity can make use of to + * learn about your system. It's possible you don't want it to do this or it's + * possible that your system doesn't support `stdint.h`. If that's the case, + * you're going to want to define this. That way, Unity will know to skip the + * inclusion of this file and you won't be left with a compiler error. + */ +/* #define UNITY_EXCLUDE_STDINT_H */ + +/* ********************** MANUAL INTEGER TYPE DEFINITION *********************** + * If you've disabled all of the automatic options above, you're going to have + * to do the configuration yourself. There are just a handful of defines that + * you are going to specify if you don't like the defaults. + **************************************************************************** */ + + /* Define this to be the number of bits an `int` takes up on your system. The + * default, if not auto-detected, is 32 bits. + * + * Example: + */ +/* #define UNITY_INT_WIDTH 16 */ + +/* Define this to be the number of bits a `long` takes up on your system. The + * default, if not autodetected, is 32 bits. This is used to figure out what + * kind of 64-bit support your system can handle. Does it need to specify a + * `long` or a `long long` to get a 64-bit value. On 16-bit systems, this option + * is going to be ignored. + * + * Example: + */ +/* #define UNITY_LONG_WIDTH 16 */ + +/* Define this to be the number of bits a pointer takes up on your system. The + * default, if not autodetected, is 32-bits. If you're getting ugly compiler + * warnings about casting from pointers, this is the one to look at. + * + * Example: + */ +/* #define UNITY_POINTER_WIDTH 64 */ + +/* Unity will automatically include 64-bit support if it auto-detects it, or if + * your `int`, `long`, or pointer widths are greater than 32-bits. Define this + * to enable 64-bit support if none of the other options already did it for you. + * There can be a significant size and speed impact to enabling 64-bit support + * on small targets, so don't define it if you don't need it. + */ +/* #define UNITY_INCLUDE_64 */ + + +/* *************************** FLOATING POINT TYPES **************************** + * In the embedded world, it's not uncommon for targets to have no support for + * floating point operations at all or to have support that is limited to only + * single precision. We are able to guess integer sizes on the fly because + * integers are always available in at least one size. Floating point, on the + * other hand, is sometimes not available at all. Trying to include `float.h` on + * these platforms would result in an error. This leaves manual configuration as + * the only option. + **************************************************************************** */ + + /* By default, Unity guesses that you will want single precision floating point + * support, but not double precision. It's easy to change either of these using + * the include and exclude options here. You may include neither, just float, + * or both, as suits your needs. + */ +/* #define UNITY_EXCLUDE_FLOAT */ +#define UNITY_INCLUDE_DOUBLE +/* #define UNITY_EXCLUDE_DOUBLE */ + +/* For features that are enabled, the following floating point options also + * become available. + */ + +/* Unity aims for as small of a footprint as possible and avoids most standard + * library calls (some embedded platforms don't have a standard library!). + * Because of this, its routines for printing integer values are minimalist and + * hand-coded. To keep Unity universal, though, we eventually chose to develop + * our own floating point print routines. Still, the display of floating point + * values during a failure are optional. By default, Unity will print the + * actual results of floating point assertion failures. So a failed assertion + * will produce a message like "Expected 4.0 Was 4.25". If you would like less + * verbose failure messages for floating point assertions, use this option to + * give a failure message `"Values Not Within Delta"` and trim the binary size. + */ +/* #define UNITY_EXCLUDE_FLOAT_PRINT */ + +/* If enabled, Unity assumes you want your `FLOAT` asserts to compare standard C + * floats. If your compiler supports a specialty floating point type, you can + * always override this behavior by using this definition. + * + * Example: + */ +/* #define UNITY_FLOAT_TYPE float16_t */ + +/* If enabled, Unity assumes you want your `DOUBLE` asserts to compare standard + * C doubles. If you would like to change this, you can specify something else + * by using this option. For example, defining `UNITY_DOUBLE_TYPE` to `long + * double` could enable gargantuan floating point types on your 64-bit processor + * instead of the standard `double`. + * + * Example: + */ +/* #define UNITY_DOUBLE_TYPE long double */ + +/* If you look up `UNITY_ASSERT_EQUAL_FLOAT` and `UNITY_ASSERT_EQUAL_DOUBLE` as + * documented in the Unity Assertion Guide, you will learn that they are not + * really asserting that two values are equal but rather that two values are + * "close enough" to equal. "Close enough" is controlled by these precision + * configuration options. If you are working with 32-bit floats and/or 64-bit + * doubles (the normal on most processors), you should have no need to change + * these options. They are both set to give you approximately 1 significant bit + * in either direction. The float precision is 0.00001 while the double is + * 10^-12. For further details on how this works, see the appendix of the Unity + * Assertion Guide. + * + * Example: + */ +/* #define UNITY_FLOAT_PRECISION 0.001f */ +/* #define UNITY_DOUBLE_PRECISION 0.001f */ + + +/* *************************** TOOLSET CUSTOMIZATION *************************** + * In addition to the options listed above, there are a number of other options + * which will come in handy to customize Unity's behavior for your specific + * toolchain. It is possible that you may not need to touch any of these but + * certain platforms, particularly those running in simulators, may need to jump + * through extra hoops to operate properly. These macros will help in those + * situations. + **************************************************************************** */ + +/* By default, Unity prints its results to `stdout` as it runs. This works + * perfectly fine in most situations where you are using a native compiler for + * testing. It works on some simulators as well so long as they have `stdout` + * routed back to the command line. There are times, however, where the + * simulator will lack support for dumping results or you will want to route + * results elsewhere for other reasons. In these cases, you should define the + * `UNITY_OUTPUT_CHAR` macro. This macro accepts a single character at a time + * (as an `int`, since this is the parameter type of the standard C `putchar` + * function most commonly used). You may replace this with whatever function + * call you like. + * + * Example: + * Say you are forced to run your test suite on an embedded processor with no + * `stdout` option. You decide to route your test result output to a custom + * serial `RS232_putc()` function you wrote like thus: + */ +/* #define UNITY_OUTPUT_CHAR(a) RS232_putc(a) */ +/* #define UNITY_OUTPUT_CHAR_HEADER_DECLARATION RS232_putc(int) */ +/* #define UNITY_OUTPUT_FLUSH() RS232_flush() */ +/* #define UNITY_OUTPUT_FLUSH_HEADER_DECLARATION RS232_flush(void) */ +/* #define UNITY_OUTPUT_START() RS232_config(115200,1,8,0) */ +/* #define UNITY_OUTPUT_COMPLETE() RS232_close() */ + +/* For some targets, Unity can make the otherwise required `setUp()` and + * `tearDown()` functions optional. This is a nice convenience for test writers + * since `setUp` and `tearDown` don't often actually _do_ anything. If you're + * using gcc or clang, this option is automatically defined for you. Other + * compilers can also support this behavior, if they support a C feature called + * weak functions. A weak function is a function that is compiled into your + * executable _unless_ a non-weak version of the same function is defined + * elsewhere. If a non-weak version is found, the weak version is ignored as if + * it never existed. If your compiler supports this feature, you can let Unity + * know by defining `UNITY_SUPPORT_WEAK` as the function attributes that would + * need to be applied to identify a function as weak. If your compiler lacks + * support for weak functions, you will always need to define `setUp` and + * `tearDown` functions (though they can be and often will be just empty). The + * most common options for this feature are: + */ +/* #define UNITY_SUPPORT_WEAK weak */ +/* #define UNITY_SUPPORT_WEAK __attribute__((weak)) */ +/* #define UNITY_NO_WEAK */ + +/* Some compilers require a custom attribute to be assigned to pointers, like + * `near` or `far`. In these cases, you can give Unity a safe default for these + * by defining this option with the attribute you would like. + * + * Example: + */ +/* #define UNITY_PTR_ATTRIBUTE __attribute__((far)) */ +/* #define UNITY_PTR_ATTRIBUTE near */ + +#endif /* UNITY_CONFIG_H */ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/eclipse/error_parsers.txt b/managed_components/espressif__cjson/cJSON/tests/unity/extras/eclipse/error_parsers.txt new file mode 100644 index 0000000..f7ce8bd --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/eclipse/error_parsers.txt @@ -0,0 +1,26 @@ +Eclipse error parsers +===================== + +These are a godsend for extracting & quickly navigating to +warnings & error messages from console output. Unfortunately +I don't know how to write an Eclipse plugin so you'll have +to add them manually. + +To add a console parser to Eclipse, go to Window --> Preferences +--> C/C++ --> Build --> Settings. Click on the 'Error Parsers' +tab and then click the 'Add...' button. See the table below for +the parser fields to add. + +Eclipse will only parse the console output during a build, so +running your unit tests must be part of your build process. +Either add this to your make/rakefile, or add it as a post- +build step in your Eclipse project settings. + + +Unity unit test error parsers +----------------------------- +Severity Pattern File Line Description +------------------------------------------------------------------------------- +Error (\.+)(.*?):(\d+):(.*?):FAIL: (.*) $2 $3 $5 +Warning (\.+)(.*?):(\d+):(.*?):IGNORE: (.*) $2 $3 $5 +Warning (\.+)(.*?):(\d+):(.*?):IGNORE\s*$ $2 $3 Ignored test diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile.rb b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile.rb new file mode 100644 index 0000000..7603e57 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile.rb @@ -0,0 +1,48 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +HERE = File.expand_path(File.dirname(__FILE__)) + '/' + +require 'rake' +require 'rake/clean' +require 'rake/testtask' +require HERE + 'rakefile_helper' + +TEMP_DIRS = [ + File.join(HERE, 'build') +].freeze + +TEMP_DIRS.each do |dir| + directory(dir) + CLOBBER.include(dir) +end + +task prepare_for_tests: TEMP_DIRS + +include RakefileHelpers + +# Load default configuration, for now +DEFAULT_CONFIG_FILE = 'gcc_auto_stdint.yml'.freeze +configure_toolchain(DEFAULT_CONFIG_FILE) + +task unit: [:prepare_for_tests] do + run_tests +end + +desc 'Build and test Unity Framework' +task all: %i(clean unit) +task default: %i(clobber all) +task ci: %i(no_color default) +task cruise: %i(no_color default) + +desc 'Load configuration' +task :config, :config_file do |_t, args| + configure_toolchain(args[:config_file]) +end + +task :no_color do + $colour_output = false +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile_helper.rb b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile_helper.rb new file mode 100644 index 0000000..c45b239 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/rakefile_helper.rb @@ -0,0 +1,178 @@ +# ========================================== +# Unity Project - A Test Framework for C +# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +# [Released under MIT License. Please refer to license.txt for details] +# ========================================== + +require 'yaml' +require 'fileutils' +require HERE + '../../auto/unity_test_summary' +require HERE + '../../auto/generate_test_runner' +require HERE + '../../auto/colour_reporter' + +module RakefileHelpers + C_EXTENSION = '.c'.freeze + + def load_configuration(config_file) + return if $configured + + $cfg_file = HERE + "../../test/targets/#{config_file}" unless config_file =~ /[\\|\/]/ + $cfg = YAML.load(File.read($cfg_file)) + $colour_output = false unless $cfg['colour'] + $configured = true if config_file != DEFAULT_CONFIG_FILE + end + + def configure_clean + CLEAN.include($cfg['compiler']['build_path'] + '*.*') unless $cfg['compiler']['build_path'].nil? + end + + def configure_toolchain(config_file = DEFAULT_CONFIG_FILE) + config_file += '.yml' unless config_file =~ /\.yml$/ + config_file = config_file unless config_file =~ /[\\|\/]/ + load_configuration(config_file) + configure_clean + end + + def tackit(strings) + result = if strings.is_a?(Array) + "\"#{strings.join}\"" + else + strings + end + result + end + + def squash(prefix, items) + result = '' + items.each { |item| result += " #{prefix}#{tackit(item)}" } + result + end + + def build_compiler_fields + command = tackit($cfg['compiler']['path']) + defines = if $cfg['compiler']['defines']['items'].nil? + '' + else + squash($cfg['compiler']['defines']['prefix'], $cfg['compiler']['defines']['items'] + ['UNITY_OUTPUT_CHAR=UnityOutputCharSpy_OutputChar'] + ['UNITY_OUTPUT_CHAR_HEADER_DECLARATION=UnityOutputCharSpy_OutputChar\(int\)']) + end + options = squash('', $cfg['compiler']['options']) + includes = squash($cfg['compiler']['includes']['prefix'], $cfg['compiler']['includes']['items']) + includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR) + + { command: command, defines: defines, options: options, includes: includes } + end + + def compile(file, _defines = []) + compiler = build_compiler_fields + unity_include = $cfg['compiler']['includes']['prefix'] + '../../src' + cmd_str = "#{compiler[:command]}#{compiler[:defines]}#{compiler[:options]}#{compiler[:includes]} #{unity_include} #{file} " \ + "#{$cfg['compiler']['object_files']['prefix']}#{$cfg['compiler']['object_files']['destination']}" \ + "#{File.basename(file, C_EXTENSION)}#{$cfg['compiler']['object_files']['extension']}" + + execute(cmd_str) + end + + def build_linker_fields + command = tackit($cfg['linker']['path']) + options = if $cfg['linker']['options'].nil? + '' + else + squash('', $cfg['linker']['options']) + end + includes = if $cfg['linker']['includes'].nil? || $cfg['linker']['includes']['items'].nil? + '' + else + squash($cfg['linker']['includes']['prefix'], $cfg['linker']['includes']['items']) + end.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR) + + { command: command, options: options, includes: includes } + end + + def link_it(exe_name, obj_list) + linker = build_linker_fields + cmd_str = "#{linker[:command]}#{linker[:options]}#{linker[:includes]} " + + (obj_list.map { |obj| "#{$cfg['linker']['object_files']['path']}#{obj} " }).join + + $cfg['linker']['bin_files']['prefix'] + ' ' + + $cfg['linker']['bin_files']['destination'] + + exe_name + $cfg['linker']['bin_files']['extension'] + execute(cmd_str) + end + + def build_simulator_fields + return nil if $cfg['simulator'].nil? + command = if $cfg['simulator']['path'].nil? + '' + else + (tackit($cfg['simulator']['path']) + ' ') + end + pre_support = if $cfg['simulator']['pre_support'].nil? + '' + else + squash('', $cfg['simulator']['pre_support']) + end + post_support = if $cfg['simulator']['post_support'].nil? + '' + else + squash('', $cfg['simulator']['post_support']) + end + { command: command, pre_support: pre_support, post_support: post_support } + end + + def execute(command_string, verbose = true) + report command_string + output = `#{command_string}`.chomp + report(output) if verbose && !output.nil? && !output.empty? + raise "Command failed. (Returned #{$?.exitstatus})" if $?.exitstatus != 0 + output + end + + def report_summary + summary = UnityTestSummary.new + summary.root = HERE + results_glob = "#{$cfg['compiler']['build_path']}*.test*" + results_glob.tr!('\\', '/') + results = Dir[results_glob] + summary.targets = results + summary.run + end + + def run_tests + report 'Running Unity system tests...' + + # Tack on TEST define for compiling unit tests + load_configuration($cfg_file) + test_defines = ['TEST'] + $cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil? + + # Get a list of all source files needed + src_files = Dir[HERE + 'src/*.c'] + src_files += Dir[HERE + 'test/*.c'] + src_files += Dir[HERE + 'test/main/*.c'] + src_files << '../../src/unity.c' + + # Build object files + src_files.each { |f| compile(f, test_defines) } + obj_list = src_files.map { |f| File.basename(f.ext($cfg['compiler']['object_files']['extension'])) } + + # Link the test executable + test_base = 'framework_test' + link_it(test_base, obj_list) + + # Execute unit test and generate results file + simulator = build_simulator_fields + executable = $cfg['linker']['bin_files']['destination'] + test_base + $cfg['linker']['bin_files']['extension'] + cmd_str = if simulator.nil? + executable + ' -v -r' + else + "#{simulator[:command]} #{simulator[:pre_support]} #{executable} #{simulator[:post_support]}" + end + output = execute(cmd_str) + test_results = $cfg['compiler']['build_path'] + test_base + test_results += if output.match(/OK$/m).nil? + '.testfail' + else + '.testpass' + end + File.open(test_results, 'w') { |f| f.print output } + end +end diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/readme.txt b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/readme.txt new file mode 100644 index 0000000..6b9a78c --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/readme.txt @@ -0,0 +1,9 @@ +Copyright (c) 2010 James Grenning and Contributed to Unity Project + +Unity Project - A Test Framework for C +Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams +[Released under MIT License. Please refer to license.txt for details] + +This Framework is an optional add-on to Unity. By including unity_framework.h in place of unity.h, +you may now work with Unity in a manner similar to CppUTest. This framework adds the concepts of +test groups and gives finer control of your tests over the command line. \ No newline at end of file diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.c b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.c new file mode 100644 index 0000000..3872bd8 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.c @@ -0,0 +1,432 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#include "unity_fixture.h" +#include "unity_internals.h" +#include + +struct UNITY_FIXTURE_T UnityFixture; + +/* If you decide to use the function pointer approach. + * Build with -D UNITY_OUTPUT_CHAR=outputChar and include + * int (*outputChar)(int) = putchar; */ + +#if !defined(UNITY_WEAK_ATTRIBUTE) && !defined(UNITY_WEAK_PRAGMA) +void setUp(void) { /*does nothing*/ } +void tearDown(void) { /*does nothing*/ } +#endif + +static void announceTestRun(unsigned int runNumber) +{ + UnityPrint("Unity test run "); + UnityPrintNumberUnsigned(runNumber+1); + UnityPrint(" of "); + UnityPrintNumberUnsigned(UnityFixture.RepeatCount); + UNITY_PRINT_EOL(); +} + +int UnityMain(int argc, const char* argv[], void (*runAllTests)(void)) +{ + int result = UnityGetCommandLineOptions(argc, argv); + unsigned int r; + if (result != 0) + return result; + + for (r = 0; r < UnityFixture.RepeatCount; r++) + { + UnityBegin(argv[0]); + announceTestRun(r); + runAllTests(); + if (!UnityFixture.Verbose) UNITY_PRINT_EOL(); + UnityEnd(); + } + + return (int)Unity.TestFailures; +} + +static int selected(const char* filter, const char* name) +{ + if (filter == 0) + return 1; + return strstr(name, filter) ? 1 : 0; +} + +static int testSelected(const char* test) +{ + return selected(UnityFixture.NameFilter, test); +} + +static int groupSelected(const char* group) +{ + return selected(UnityFixture.GroupFilter, group); +} + +void UnityTestRunner(unityfunction* setup, + unityfunction* testBody, + unityfunction* teardown, + const char* printableName, + const char* group, + const char* name, + const char* file, + unsigned int line) +{ + if (testSelected(name) && groupSelected(group)) + { + Unity.TestFile = file; + Unity.CurrentTestName = printableName; + Unity.CurrentTestLineNumber = line; + if (!UnityFixture.Verbose) + UNITY_OUTPUT_CHAR('.'); + else + { + UnityPrint(printableName); + #ifndef UNITY_REPEAT_TEST_NAME + Unity.CurrentTestName = NULL; + #endif + } + + Unity.NumberOfTests++; + UnityMalloc_StartTest(); + UnityPointer_Init(); + + if (TEST_PROTECT()) + { + setup(); + testBody(); + } + if (TEST_PROTECT()) + { + teardown(); + } + if (TEST_PROTECT()) + { + UnityPointer_UndoAllSets(); + if (!Unity.CurrentTestFailed) + UnityMalloc_EndTest(); + } + UnityConcludeFixtureTest(); + } +} + +void UnityIgnoreTest(const char* printableName, const char* group, const char* name) +{ + if (testSelected(name) && groupSelected(group)) + { + Unity.NumberOfTests++; + Unity.TestIgnores++; + if (!UnityFixture.Verbose) + UNITY_OUTPUT_CHAR('!'); + else + { + UnityPrint(printableName); + UNITY_PRINT_EOL(); + } + } +} + + +/*------------------------------------------------- */ +/* Malloc and free stuff */ +#define MALLOC_DONT_FAIL -1 +static int malloc_count; +static int malloc_fail_countdown = MALLOC_DONT_FAIL; + +void UnityMalloc_StartTest(void) +{ + malloc_count = 0; + malloc_fail_countdown = MALLOC_DONT_FAIL; +} + +void UnityMalloc_EndTest(void) +{ + malloc_fail_countdown = MALLOC_DONT_FAIL; + if (malloc_count != 0) + { + UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "This test leaks!"); + } +} + +void UnityMalloc_MakeMallocFailAfterCount(int countdown) +{ + malloc_fail_countdown = countdown; +} + +/* These definitions are always included from unity_fixture_malloc_overrides.h */ +/* We undef to use them or avoid conflict with per the C standard */ +#undef malloc +#undef free +#undef calloc +#undef realloc + +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC +static unsigned char unity_heap[UNITY_INTERNAL_HEAP_SIZE_BYTES]; +static size_t heap_index; +#else +#include +#endif + +typedef struct GuardBytes +{ + size_t size; + size_t guard_space; +} Guard; + + +static const char end[] = "END"; + +void* unity_malloc(size_t size) +{ + char* mem; + Guard* guard; + size_t total_size = size + sizeof(Guard) + sizeof(end); + + if (malloc_fail_countdown != MALLOC_DONT_FAIL) + { + if (malloc_fail_countdown == 0) + return NULL; + malloc_fail_countdown--; + } + + if (size == 0) return NULL; +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC + if (heap_index + total_size > UNITY_INTERNAL_HEAP_SIZE_BYTES) + { + guard = NULL; + } + else + { + guard = (Guard*)&unity_heap[heap_index]; + heap_index += total_size; + } +#else + guard = (Guard*)UNITY_FIXTURE_MALLOC(total_size); +#endif + if (guard == NULL) return NULL; + malloc_count++; + guard->size = size; + guard->guard_space = 0; + mem = (char*)&(guard[1]); + memcpy(&mem[size], end, sizeof(end)); + + return (void*)mem; +} + +static int isOverrun(void* mem) +{ + Guard* guard = (Guard*)mem; + char* memAsChar = (char*)mem; + guard--; + + return guard->guard_space != 0 || strcmp(&memAsChar[guard->size], end) != 0; +} + +static void release_memory(void* mem) +{ + Guard* guard = (Guard*)mem; + guard--; + + malloc_count--; +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC + if (mem == unity_heap + heap_index - guard->size - sizeof(end)) + { + heap_index -= (guard->size + sizeof(Guard) + sizeof(end)); + } +#else + UNITY_FIXTURE_FREE(guard); +#endif +} + +void unity_free(void* mem) +{ + int overrun; + + if (mem == NULL) + { + return; + } + + overrun = isOverrun(mem); + release_memory(mem); + if (overrun) + { + UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "Buffer overrun detected during free()"); + } +} + +void* unity_calloc(size_t num, size_t size) +{ + void* mem = unity_malloc(num * size); + if (mem == NULL) return NULL; + memset(mem, 0, num * size); + return mem; +} + +void* unity_realloc(void* oldMem, size_t size) +{ + Guard* guard = (Guard*)oldMem; + void* newMem; + + if (oldMem == NULL) return unity_malloc(size); + + guard--; + if (isOverrun(oldMem)) + { + release_memory(oldMem); + UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "Buffer overrun detected during realloc()"); + } + + if (size == 0) + { + release_memory(oldMem); + return NULL; + } + + if (guard->size >= size) return oldMem; + +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC /* Optimization if memory is expandable */ + if (oldMem == unity_heap + heap_index - guard->size - sizeof(end) && + heap_index + size - guard->size <= UNITY_INTERNAL_HEAP_SIZE_BYTES) + { + release_memory(oldMem); /* Not thread-safe, like unity_heap generally */ + return unity_malloc(size); /* No memcpy since data is in place */ + } +#endif + newMem = unity_malloc(size); + if (newMem == NULL) return NULL; /* Do not release old memory */ + memcpy(newMem, oldMem, guard->size); + release_memory(oldMem); + return newMem; +} + + +/*-------------------------------------------------------- */ +/*Automatic pointer restoration functions */ +struct PointerPair +{ + void** pointer; + void* old_value; +}; + +static struct PointerPair pointer_store[UNITY_MAX_POINTERS]; +static int pointer_index = 0; + +void UnityPointer_Init(void) +{ + pointer_index = 0; +} + +void UnityPointer_Set(void** pointer, void* newValue, UNITY_LINE_TYPE line) +{ + if (pointer_index >= UNITY_MAX_POINTERS) + { + UNITY_TEST_FAIL(line, "Too many pointers set"); + } + else + { + pointer_store[pointer_index].pointer = pointer; + pointer_store[pointer_index].old_value = *pointer; + *pointer = newValue; + pointer_index++; + } +} + +void UnityPointer_UndoAllSets(void) +{ + while (pointer_index > 0) + { + pointer_index--; + *(pointer_store[pointer_index].pointer) = + pointer_store[pointer_index].old_value; + } +} + +int UnityGetCommandLineOptions(int argc, const char* argv[]) +{ + int i; + UnityFixture.Verbose = 0; + UnityFixture.GroupFilter = 0; + UnityFixture.NameFilter = 0; + UnityFixture.RepeatCount = 1; + + if (argc == 1) + return 0; + + for (i = 1; i < argc; ) + { + if (strcmp(argv[i], "-v") == 0) + { + UnityFixture.Verbose = 1; + i++; + } + else if (strcmp(argv[i], "-g") == 0) + { + i++; + if (i >= argc) + return 1; + UnityFixture.GroupFilter = argv[i]; + i++; + } + else if (strcmp(argv[i], "-n") == 0) + { + i++; + if (i >= argc) + return 1; + UnityFixture.NameFilter = argv[i]; + i++; + } + else if (strcmp(argv[i], "-r") == 0) + { + UnityFixture.RepeatCount = 2; + i++; + if (i < argc) + { + if (*(argv[i]) >= '0' && *(argv[i]) <= '9') + { + unsigned int digit = 0; + UnityFixture.RepeatCount = 0; + while (argv[i][digit] >= '0' && argv[i][digit] <= '9') + { + UnityFixture.RepeatCount *= 10; + UnityFixture.RepeatCount += (unsigned int)argv[i][digit++] - '0'; + } + i++; + } + } + } + else + { + /* ignore unknown parameter */ + i++; + } + } + return 0; +} + +void UnityConcludeFixtureTest(void) +{ + if (Unity.CurrentTestIgnored) + { + Unity.TestIgnores++; + UNITY_PRINT_EOL(); + } + else if (!Unity.CurrentTestFailed) + { + if (UnityFixture.Verbose) + { + UnityPrint(" PASS"); + UNITY_PRINT_EOL(); + } + } + else /* Unity.CurrentTestFailed */ + { + Unity.TestFailures++; + UNITY_PRINT_EOL(); + } + + Unity.CurrentTestFailed = 0; + Unity.CurrentTestIgnored = 0; +} diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.h b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.h new file mode 100644 index 0000000..6f8d623 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture.h @@ -0,0 +1,83 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_H_ +#define UNITY_FIXTURE_H_ + +#include "unity.h" +#include "unity_internals.h" +#include "unity_fixture_malloc_overrides.h" +#include "unity_fixture_internals.h" + +int UnityMain(int argc, const char* argv[], void (*runAllTests)(void)); + + +#define TEST_GROUP(group)\ + static const char* TEST_GROUP_##group = #group + +#define TEST_SETUP(group) void TEST_##group##_SETUP(void);\ + void TEST_##group##_SETUP(void) + +#define TEST_TEAR_DOWN(group) void TEST_##group##_TEAR_DOWN(void);\ + void TEST_##group##_TEAR_DOWN(void) + + +#define TEST(group, name) \ + void TEST_##group##_##name##_(void);\ + void TEST_##group##_##name##_run(void);\ + void TEST_##group##_##name##_run(void)\ + {\ + UnityTestRunner(TEST_##group##_SETUP,\ + TEST_##group##_##name##_,\ + TEST_##group##_TEAR_DOWN,\ + "TEST(" #group ", " #name ")",\ + TEST_GROUP_##group, #name,\ + __FILE__, __LINE__);\ + }\ + void TEST_##group##_##name##_(void) + +#define IGNORE_TEST(group, name) \ + void TEST_##group##_##name##_(void);\ + void TEST_##group##_##name##_run(void);\ + void TEST_##group##_##name##_run(void)\ + {\ + UnityIgnoreTest("IGNORE_TEST(" #group ", " #name ")", TEST_GROUP_##group, #name);\ + }\ + void TEST_##group##_##name##_(void) + +/* Call this for each test, insider the group runner */ +#define RUN_TEST_CASE(group, name) \ + { void TEST_##group##_##name##_run(void);\ + TEST_##group##_##name##_run(); } + +/* This goes at the bottom of each test file or in a separate c file */ +#define TEST_GROUP_RUNNER(group)\ + void TEST_##group##_GROUP_RUNNER(void);\ + void TEST_##group##_GROUP_RUNNER(void) + +/* Call this from main */ +#define RUN_TEST_GROUP(group)\ + { void TEST_##group##_GROUP_RUNNER(void);\ + TEST_##group##_GROUP_RUNNER(); } + +/* CppUTest Compatibility Macros */ +#ifndef UNITY_EXCLUDE_CPPUTEST_ASSERTS +/* Sets a pointer and automatically restores it to its old value after teardown */ +#define UT_PTR_SET(ptr, newPointerValue) UnityPointer_Set((void**)&(ptr), (void*)(newPointerValue), __LINE__) +#define TEST_ASSERT_POINTERS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_PTR((expected), (actual)) +#define TEST_ASSERT_BYTES_EQUAL(expected, actual) TEST_ASSERT_EQUAL_HEX8(0xff & (expected), 0xff & (actual)) +#define FAIL(message) TEST_FAIL_MESSAGE((message)) +#define CHECK(condition) TEST_ASSERT_TRUE((condition)) +#define LONGS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_INT((expected), (actual)) +#define STRCMP_EQUAL(expected, actual) TEST_ASSERT_EQUAL_STRING((expected), (actual)) +#define DOUBLES_EQUAL(expected, actual, delta) TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual)) +#endif + +/* You must compile with malloc replacement, as defined in unity_fixture_malloc_overrides.h */ +void UnityMalloc_MakeMallocFailAfterCount(int count); + +#endif /* UNITY_FIXTURE_H_ */ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_internals.h b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_internals.h new file mode 100644 index 0000000..aa0d9e7 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_internals.h @@ -0,0 +1,51 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_INTERNALS_H_ +#define UNITY_FIXTURE_INTERNALS_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +struct UNITY_FIXTURE_T +{ + int Verbose; + unsigned int RepeatCount; + const char* NameFilter; + const char* GroupFilter; +}; +extern struct UNITY_FIXTURE_T UnityFixture; + +typedef void unityfunction(void); +void UnityTestRunner(unityfunction* setup, + unityfunction* body, + unityfunction* teardown, + const char* printableName, + const char* group, + const char* name, + const char* file, unsigned int line); + +void UnityIgnoreTest(const char* printableName, const char* group, const char* name); +void UnityMalloc_StartTest(void); +void UnityMalloc_EndTest(void); +int UnityGetCommandLineOptions(int argc, const char* argv[]); +void UnityConcludeFixtureTest(void); + +void UnityPointer_Set(void** ptr, void* newValue, UNITY_LINE_TYPE line); +void UnityPointer_UndoAllSets(void); +void UnityPointer_Init(void); +#ifndef UNITY_MAX_POINTERS +#define UNITY_MAX_POINTERS 5 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* UNITY_FIXTURE_INTERNALS_H_ */ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h new file mode 100644 index 0000000..7daba50 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_MALLOC_OVERRIDES_H_ +#define UNITY_FIXTURE_MALLOC_OVERRIDES_H_ + +#include + +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC +/* Define this macro to remove the use of stdlib.h, malloc, and free. + * Many embedded systems do not have a heap or malloc/free by default. + * This internal unity_malloc() provides allocated memory deterministically from + * the end of an array only, unity_free() only releases from end-of-array, + * blocks are not coalesced, and memory not freed in LIFO order is stranded. */ + #ifndef UNITY_INTERNAL_HEAP_SIZE_BYTES + #define UNITY_INTERNAL_HEAP_SIZE_BYTES 256 + #endif +#endif + +/* These functions are used by the Unity Fixture to allocate and release memory + * on the heap and can be overridden with platform-specific implementations. + * For example, when using FreeRTOS UNITY_FIXTURE_MALLOC becomes pvPortMalloc() + * and UNITY_FIXTURE_FREE becomes vPortFree(). */ +#if !defined(UNITY_FIXTURE_MALLOC) || !defined(UNITY_FIXTURE_FREE) + #include + #define UNITY_FIXTURE_MALLOC(size) malloc(size) + #define UNITY_FIXTURE_FREE(ptr) free(ptr) +#else + extern void* UNITY_FIXTURE_MALLOC(size_t size); + extern void UNITY_FIXTURE_FREE(void* ptr); +#endif + +#define malloc unity_malloc +#define calloc unity_calloc +#define realloc unity_realloc +#define free unity_free + +void* unity_malloc(size_t size); +void* unity_calloc(size_t num, size_t size); +void* unity_realloc(void * oldMem, size_t size); +void unity_free(void * mem); + +#endif /* UNITY_FIXTURE_MALLOC_OVERRIDES_H_ */ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/release/build.info b/managed_components/espressif__cjson/cJSON/tests/unity/release/build.info new file mode 100644 index 0000000..56d5912 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/release/build.info @@ -0,0 +1,2 @@ +122 + diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/release/version.info b/managed_components/espressif__cjson/cJSON/tests/unity/release/version.info new file mode 100644 index 0000000..cf12b30 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/release/version.info @@ -0,0 +1,2 @@ +2.4.3 + diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.c b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.c new file mode 100644 index 0000000..eee6f96 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.c @@ -0,0 +1,1570 @@ +/* ========================================================================= + Unity Project - A Test Framework for C + Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +============================================================================ */ + +#define UNITY_INCLUDE_SETUP_STUBS +#include "unity.h" +#include + +/* If omitted from header, declare overridable prototypes here so they're ready for use */ +#ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION +void UNITY_OUTPUT_CHAR(int); +#endif + +/* Helpful macros for us to use here in Assert functions */ +#define UNITY_FAIL_AND_BAIL { Unity.CurrentTestFailed = 1; TEST_ABORT(); } +#define UNITY_IGNORE_AND_BAIL { Unity.CurrentTestIgnored = 1; TEST_ABORT(); } +#define RETURN_IF_FAIL_OR_IGNORE if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) return + +struct UNITY_STORAGE_T Unity; + +#ifdef UNITY_OUTPUT_COLOR +static const char UnityStrOk[] = "\033[42mOK\033[00m"; +static const char UnityStrPass[] = "\033[42mPASS\033[00m"; +static const char UnityStrFail[] = "\033[41mFAIL\033[00m"; +static const char UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; +#else +static const char UnityStrOk[] = "OK"; +static const char UnityStrPass[] = "PASS"; +static const char UnityStrFail[] = "FAIL"; +static const char UnityStrIgnore[] = "IGNORE"; +#endif +static const char UnityStrNull[] = "NULL"; +static const char UnityStrSpacer[] = ". "; +static const char UnityStrExpected[] = " Expected "; +static const char UnityStrWas[] = " Was "; +static const char UnityStrGt[] = " to be greater than "; +static const char UnityStrLt[] = " to be less than "; +static const char UnityStrOrEqual[] = "or equal to "; +static const char UnityStrElement[] = " Element "; +static const char UnityStrByte[] = " Byte "; +static const char UnityStrMemory[] = " Memory Mismatch."; +static const char UnityStrDelta[] = " Values Not Within Delta "; +static const char UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; +static const char UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; +static const char UnityStrNullPointerForActual[] = " Actual pointer was NULL"; +#ifndef UNITY_EXCLUDE_FLOAT +static const char UnityStrNot[] = "Not "; +static const char UnityStrInf[] = "Infinity"; +static const char UnityStrNegInf[] = "Negative Infinity"; +static const char UnityStrNaN[] = "NaN"; +static const char UnityStrDet[] = "Determinate"; +static const char UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; +#endif +const char UnityStrErrFloat[] = "Unity Floating Point Disabled"; +const char UnityStrErrDouble[] = "Unity Double Precision Disabled"; +const char UnityStrErr64[] = "Unity 64-bit Support Disabled"; +static const char UnityStrBreaker[] = "-----------------------"; +static const char UnityStrResultsTests[] = " Tests "; +static const char UnityStrResultsFailures[] = " Failures "; +static const char UnityStrResultsIgnored[] = " Ignored "; +static const char UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; +static const char UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; + +/*----------------------------------------------- + * Pretty Printers & Test Result Output Handlers + *-----------------------------------------------*/ + +void UnityPrint(const char* string) +{ + const char* pch = string; + + if (pch != NULL) + { + while (*pch) + { + /* printable characters plus CR & LF are printed */ + if ((*pch <= 126) && (*pch >= 32)) + { + UNITY_OUTPUT_CHAR(*pch); + } + /* write escaped carriage returns */ + else if (*pch == 13) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (*pch == 10) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } +#ifdef UNITY_OUTPUT_COLOR + /* print ANSI escape code */ + else if (*pch == 27 && *(pch + 1) == '[') + { + while (*pch && *pch != 'm') + { + UNITY_OUTPUT_CHAR(*pch); + pch++; + } + UNITY_OUTPUT_CHAR('m'); + } +#endif + /* unprintable characters are shown as codes */ + else + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)*pch, 2); + } + pch++; + } + } +} + +void UnityPrintLen(const char* string, const UNITY_UINT32 length) +{ + const char* pch = string; + + if (pch != NULL) + { + while (*pch && (UNITY_UINT32)(pch - string) < length) + { + /* printable characters plus CR & LF are printed */ + if ((*pch <= 126) && (*pch >= 32)) + { + UNITY_OUTPUT_CHAR(*pch); + } + /* write escaped carriage returns */ + else if (*pch == 13) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (*pch == 10) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)*pch, 2); + } + pch++; + } + } +} + +/*-----------------------------------------------*/ +void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style) +{ + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) + { + UnityPrintNumber(number); + } + else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT) + { + UnityPrintNumberUnsigned((UNITY_UINT)number); + } + else + { + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)number, (char)((style & 0xF) * 2)); + } +} + +/*-----------------------------------------------*/ +void UnityPrintNumber(const UNITY_INT number_to_print) +{ + UNITY_UINT number = (UNITY_UINT)number_to_print; + + if (number_to_print < 0) + { + /* A negative number, including MIN negative */ + UNITY_OUTPUT_CHAR('-'); + number = (UNITY_UINT)(-number_to_print); + } + UnityPrintNumberUnsigned(number); +} + +/*----------------------------------------------- + * basically do an itoa using as little ram as possible */ +void UnityPrintNumberUnsigned(const UNITY_UINT number) +{ + UNITY_UINT divisor = 1; + + /* figure out initial divisor */ + while (number / divisor > 9) + { + divisor *= 10; + } + + /* now mod and print, then divide divisor */ + do + { + UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10))); + divisor /= 10; + } while (divisor > 0); +} + +/*-----------------------------------------------*/ +void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print) +{ + int nibble; + char nibbles = nibbles_to_print; + if ((unsigned)nibbles > (2 * sizeof(number))) + nibbles = 2 * sizeof(number); + + while (nibbles > 0) + { + nibbles--; + nibble = (int)(number >> (nibbles * 4)) & 0x0F; + if (nibble <= 9) + { + UNITY_OUTPUT_CHAR((char)('0' + nibble)); + } + else + { + UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble)); + } + } +} + +/*-----------------------------------------------*/ +void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) +{ + UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1); + UNITY_INT32 i; + + for (i = 0; i < UNITY_INT_WIDTH; i++) + { + if (current_bit & mask) + { + if (current_bit & number) + { + UNITY_OUTPUT_CHAR('1'); + } + else + { + UNITY_OUTPUT_CHAR('0'); + } + } + else + { + UNITY_OUTPUT_CHAR('X'); + } + current_bit = current_bit >> 1; + } +} + +/*-----------------------------------------------*/ +#ifndef UNITY_EXCLUDE_FLOAT_PRINT +/* This function prints a floating-point value in a format similar to + * printf("%.6g"). It can work with either single- or double-precision, + * but for simplicity, it prints only 6 significant digits in either case. + * Printing more than 6 digits accurately is hard (at least in the single- + * precision case) and isn't attempted here. */ +void UnityPrintFloat(const UNITY_DOUBLE input_number) +{ + UNITY_DOUBLE number = input_number; + + /* print minus sign (including for negative zero) */ + if (number < (double)0.0f || (number == (double)0.0f && (double)1.0f / number < (double)0.0f)) + { + UNITY_OUTPUT_CHAR('-'); + number = -number; + } + + /* handle zero, NaN, and +/- infinity */ + if (number == (double)0.0f) UnityPrint("0"); + else if (isnan(number)) UnityPrint("nan"); + else if (isinf(number)) UnityPrint("inf"); + else + { + int exponent = 0; + int decimals, digits; + UNITY_INT32 n; + char buf[16]; + + /* scale up or down by powers of 10 */ + while (number < (double)(100000.0f / 1e6f)) { number *= (double)1e6f; exponent -= 6; } + while (number < (double)100000.0f) { number *= (double)10.0f; exponent--; } + while (number > (double)(1000000.0f * 1e6f)) { number /= (double)1e6f; exponent += 6; } + while (number > (double)1000000.0f) { number /= (double)10.0f; exponent++; } + + /* round to nearest integer */ + n = ((UNITY_INT32)(number + number) + 1) / 2; + if (n > 999999) + { + n = 100000; + exponent++; + } + + /* determine where to place decimal point */ + decimals = (exponent <= 0 && exponent >= -9) ? -exponent : 5; + exponent += decimals; + + /* truncate trailing zeroes after decimal point */ + while (decimals > 0 && n % 10 == 0) + { + n /= 10; + decimals--; + } + + /* build up buffer in reverse order */ + digits = 0; + while (n != 0 || digits < decimals + 1) + { + buf[digits++] = (char)('0' + n % 10); + n /= 10; + } + while (digits > 0) + { + if(digits == decimals) UNITY_OUTPUT_CHAR('.'); + UNITY_OUTPUT_CHAR(buf[--digits]); + } + + /* print exponent if needed */ + if (exponent != 0) + { + UNITY_OUTPUT_CHAR('e'); + + if(exponent < 0) + { + UNITY_OUTPUT_CHAR('-'); + exponent = -exponent; + } + else + { + UNITY_OUTPUT_CHAR('+'); + } + + digits = 0; + while (exponent != 0 || digits < 2) + { + buf[digits++] = (char)('0' + exponent % 10); + exponent /= 10; + } + while (digits > 0) + { + UNITY_OUTPUT_CHAR(buf[--digits]); + } + } + } +} +#endif /* ! UNITY_EXCLUDE_FLOAT_PRINT */ + +/*-----------------------------------------------*/ +static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) +{ + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(':'); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); +} + +/*-----------------------------------------------*/ +static void UnityTestResultsFailBegin(const UNITY_LINE_TYPE line) +{ + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrFail); + UNITY_OUTPUT_CHAR(':'); +} + +/*-----------------------------------------------*/ +void UnityConcludeTest(void) +{ + if (Unity.CurrentTestIgnored) + { + Unity.TestIgnores++; + } + else if (!Unity.CurrentTestFailed) + { + UnityTestResultsBegin(Unity.TestFile, Unity.CurrentTestLineNumber); + UnityPrint(UnityStrPass); + } + else + { + Unity.TestFailures++; + } + + Unity.CurrentTestFailed = 0; + Unity.CurrentTestIgnored = 0; + UNITY_PRINT_EOL(); + UNITY_FLUSH_CALL(); +} + +/*-----------------------------------------------*/ +static void UnityAddMsgIfSpecified(const char* msg) +{ + if (msg) + { + UnityPrint(UnityStrSpacer); +#ifndef UNITY_EXCLUDE_DETAILS + if (Unity.CurrentDetail1) + { + UnityPrint(UnityStrDetail1Name); + UnityPrint(Unity.CurrentDetail1); + if (Unity.CurrentDetail2) + { + UnityPrint(UnityStrDetail2Name); + UnityPrint(Unity.CurrentDetail2); + } + UnityPrint(UnityStrSpacer); + } +#endif + UnityPrint(msg); + } +} + +/*-----------------------------------------------*/ +static void UnityPrintExpectedAndActualStrings(const char* expected, const char* actual) +{ + UnityPrint(UnityStrExpected); + if (expected != NULL) + { + UNITY_OUTPUT_CHAR('\''); + UnityPrint(expected); + UNITY_OUTPUT_CHAR('\''); + } + else + { + UnityPrint(UnityStrNull); + } + UnityPrint(UnityStrWas); + if (actual != NULL) + { + UNITY_OUTPUT_CHAR('\''); + UnityPrint(actual); + UNITY_OUTPUT_CHAR('\''); + } + else + { + UnityPrint(UnityStrNull); + } +} + +/*-----------------------------------------------*/ +static void UnityPrintExpectedAndActualStringsLen(const char* expected, + const char* actual, + const UNITY_UINT32 length) +{ + UnityPrint(UnityStrExpected); + if (expected != NULL) + { + UNITY_OUTPUT_CHAR('\''); + UnityPrintLen(expected, length); + UNITY_OUTPUT_CHAR('\''); + } + else + { + UnityPrint(UnityStrNull); + } + UnityPrint(UnityStrWas); + if (actual != NULL) + { + UNITY_OUTPUT_CHAR('\''); + UnityPrintLen(actual, length); + UNITY_OUTPUT_CHAR('\''); + } + else + { + UnityPrint(UnityStrNull); + } +} + +/*----------------------------------------------- + * Assertion & Control Helpers + *-----------------------------------------------*/ + +static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_LINE_TYPE lineNumber, + const char* msg) +{ + if (expected == actual) return 0; /* Both are NULL or same pointer */ + + /* print and return true if just expected is NULL */ + if (expected == NULL) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrNullPointerForExpected); + UnityAddMsgIfSpecified(msg); + return 1; + } + + /* print and return true if just actual is NULL */ + if (actual == NULL) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrNullPointerForActual); + UnityAddMsgIfSpecified(msg); + return 1; + } + + return 0; /* return false if neither is NULL */ +} + +/*----------------------------------------------- + * Assertion Functions + *-----------------------------------------------*/ + +void UnityAssertBits(const UNITY_INT mask, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber) +{ + RETURN_IF_FAIL_OR_IGNORE; + + if ((mask & expected) != (mask & actual)) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected); + UnityPrint(UnityStrWas); + UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertEqualNumber(const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) +{ + RETURN_IF_FAIL_OR_IGNORE; + + if (expected != actual) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expected, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, + const UNITY_INT actual, + const UNITY_COMPARISON_T compare, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) +{ + int failed = 0; + RETURN_IF_FAIL_OR_IGNORE; + + if (threshold == actual && compare & UNITY_EQUAL_TO) return; + if (threshold == actual) failed = 1; + + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) + { + if (actual > threshold && compare & UNITY_SMALLER_THAN) failed = 1; + if (actual < threshold && compare & UNITY_GREATER_THAN) failed = 1; + } + else /* UINT or HEX */ + { + if ((UNITY_UINT)actual > (UNITY_UINT)threshold && compare & UNITY_SMALLER_THAN) failed = 1; + if ((UNITY_UINT)actual < (UNITY_UINT)threshold && compare & UNITY_GREATER_THAN) failed = 1; + } + + if (failed) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(actual, style); + if (compare & UNITY_GREATER_THAN) UnityPrint(UnityStrGt); + if (compare & UNITY_SMALLER_THAN) UnityPrint(UnityStrLt); + if (compare & UNITY_EQUAL_TO) UnityPrint(UnityStrOrEqual); + UnityPrintNumberByStyle(threshold, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +#define UnityPrintPointlessAndBail() \ +{ \ + UnityTestResultsFailBegin(lineNumber); \ + UnityPrint(UnityStrPointless); \ + UnityAddMsgIfSpecified(msg); \ + UNITY_FAIL_AND_BAIL; } + +/*-----------------------------------------------*/ +void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags) +{ + UNITY_UINT32 elements = num_elements; + unsigned int length = style & 0xF; + + RETURN_IF_FAIL_OR_IGNORE; + + if (num_elements == 0) + { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) return; /* Both are NULL or same pointer */ + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) + UNITY_FAIL_AND_BAIL; + + while (elements--) + { + UNITY_INT expect_val; + UNITY_INT actual_val; + switch (length) + { + case 1: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; + break; + case 2: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; + break; +#ifdef UNITY_SUPPORT_64 + case 8: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; + break; +#endif + default: /* length 4 bytes */ + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; + length = 4; + break; + } + + if (expect_val != actual_val) + { + if (style & UNITY_DISPLAY_RANGE_UINT && length < sizeof(expect_val)) + { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ + UNITY_INT mask = 1; + mask = (mask << 8 * length) - 1; + expect_val &= mask; + actual_val &= mask; + } + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expect_val, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual_val, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + if (flags == UNITY_ARRAY_TO_ARRAY) + { + expected = (UNITY_INTERNAL_PTR)(length + (const char*)expected); + } + actual = (UNITY_INTERNAL_PTR)(length + (const char*)actual); + } +} + +/*-----------------------------------------------*/ +#ifndef UNITY_EXCLUDE_FLOAT +/* Wrap this define in a function with variable types as float or double */ +#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \ + if (isinf(expected) && isinf(actual) && ((expected < 0) == (actual < 0))) return 1; \ + if (UNITY_NAN_CHECK) return 1; \ + diff = actual - expected; \ + if (diff < 0) diff = -diff; \ + if (delta < 0) delta = -delta; \ + return !(isnan(diff) || isinf(diff) || (diff > delta)) + /* This first part of this condition will catch any NaN or Infinite values */ +#ifndef UNITY_NAN_NOT_EQUAL_NAN + #define UNITY_NAN_CHECK isnan(expected) && isnan(actual) +#else + #define UNITY_NAN_CHECK 0 +#endif + +#ifndef UNITY_EXCLUDE_FLOAT_PRINT + #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ + { \ + UnityPrint(UnityStrExpected); \ + UnityPrintFloat(expected); \ + UnityPrint(UnityStrWas); \ + UnityPrintFloat(actual); } +#else + #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ + UnityPrint(UnityStrDelta) +#endif /* UNITY_EXCLUDE_FLOAT_PRINT */ + +static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual) +{ + UNITY_FLOAT diff; + UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); +} + +void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) +{ + UNITY_UINT32 elements = num_elements; + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_expected = expected; + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_actual = actual; + + RETURN_IF_FAIL_OR_IGNORE; + + if (elements == 0) + { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) return; /* Both are NULL or same pointer */ + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) + UNITY_FAIL_AND_BAIL; + + while (elements--) + { + if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, *ptr_expected, *ptr_actual)) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)*ptr_expected, (UNITY_DOUBLE)*ptr_actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + if (flags == UNITY_ARRAY_TO_ARRAY) + { + ptr_expected++; + } + ptr_actual++; + } +} + +/*-----------------------------------------------*/ +void UnityAssertFloatsWithin(const UNITY_FLOAT delta, + const UNITY_FLOAT expected, + const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber) +{ + RETURN_IF_FAIL_OR_IGNORE; + + + if (!UnityFloatsWithin(delta, expected, actual)) + { + UnityTestResultsFailBegin(lineNumber); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertFloatSpecial(const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style) +{ + const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; + UNITY_INT should_be_trait = ((UNITY_INT)style & 1); + UNITY_INT is_trait = !should_be_trait; + UNITY_INT trait_index = (UNITY_INT)(style >> 1); + + RETURN_IF_FAIL_OR_IGNORE; + + switch (style) + { + case UNITY_FLOAT_IS_INF: + case UNITY_FLOAT_IS_NOT_INF: + is_trait = isinf(actual) && (actual > 0); + break; + case UNITY_FLOAT_IS_NEG_INF: + case UNITY_FLOAT_IS_NOT_NEG_INF: + is_trait = isinf(actual) && (actual < 0); + break; + + case UNITY_FLOAT_IS_NAN: + case UNITY_FLOAT_IS_NOT_NAN: + is_trait = isnan(actual) ? 1 : 0; + break; + + case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ + case UNITY_FLOAT_IS_NOT_DET: + is_trait = !isinf(actual) && !isnan(actual); + break; + + default: + trait_index = 0; + trait_names[0] = UnityStrInvalidFloatTrait; + break; + } + + if (is_trait != should_be_trait) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + if (!should_be_trait) + UnityPrint(UnityStrNot); + UnityPrint(trait_names[trait_index]); + UnityPrint(UnityStrWas); +#ifndef UNITY_EXCLUDE_FLOAT_PRINT + UnityPrintFloat((UNITY_DOUBLE)actual); +#else + if (should_be_trait) + UnityPrint(UnityStrNot); + UnityPrint(trait_names[trait_index]); +#endif + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +#endif /* not UNITY_EXCLUDE_FLOAT */ + +/*-----------------------------------------------*/ +#ifndef UNITY_EXCLUDE_DOUBLE +static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_DOUBLE actual) +{ + UNITY_DOUBLE diff; + UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); +} + +void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) +{ + UNITY_UINT32 elements = num_elements; + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_expected = expected; + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_actual = actual; + + RETURN_IF_FAIL_OR_IGNORE; + + if (elements == 0) + { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) return; /* Both are NULL or same pointer */ + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) + UNITY_FAIL_AND_BAIL; + + while (elements--) + { + if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, *ptr_expected, *ptr_actual)) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, *ptr_actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + if (flags == UNITY_ARRAY_TO_ARRAY) + { + ptr_expected++; + } + ptr_actual++; + } +} + +/*-----------------------------------------------*/ +void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, + const UNITY_DOUBLE expected, + const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber) +{ + RETURN_IF_FAIL_OR_IGNORE; + + if (!UnityDoublesWithin(delta, expected, actual)) + { + UnityTestResultsFailBegin(lineNumber); + UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ + +void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style) +{ + const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; + UNITY_INT should_be_trait = ((UNITY_INT)style & 1); + UNITY_INT is_trait = !should_be_trait; + UNITY_INT trait_index = (UNITY_INT)(style >> 1); + + RETURN_IF_FAIL_OR_IGNORE; + + switch (style) + { + case UNITY_FLOAT_IS_INF: + case UNITY_FLOAT_IS_NOT_INF: + is_trait = isinf(actual) && (actual > 0); + break; + case UNITY_FLOAT_IS_NEG_INF: + case UNITY_FLOAT_IS_NOT_NEG_INF: + is_trait = isinf(actual) && (actual < 0); + break; + + case UNITY_FLOAT_IS_NAN: + case UNITY_FLOAT_IS_NOT_NAN: + is_trait = isnan(actual) ? 1 : 0; + break; + + case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ + case UNITY_FLOAT_IS_NOT_DET: + is_trait = !isinf(actual) && !isnan(actual); + break; + + default: + trait_index = 0; + trait_names[0] = UnityStrInvalidFloatTrait; + break; + } + + if (is_trait != should_be_trait) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrExpected); + if (!should_be_trait) + UnityPrint(UnityStrNot); + UnityPrint(trait_names[trait_index]); + UnityPrint(UnityStrWas); +#ifndef UNITY_EXCLUDE_FLOAT_PRINT + UnityPrintFloat(actual); +#else + if (should_be_trait) + UnityPrint(UnityStrNot); + UnityPrint(trait_names[trait_index]); +#endif + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +#endif /* not UNITY_EXCLUDE_DOUBLE */ + +/*-----------------------------------------------*/ +void UnityAssertNumbersWithin(const UNITY_UINT delta, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style) +{ + RETURN_IF_FAIL_OR_IGNORE; + + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) + { + if (actual > expected) + Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(actual - expected) > delta); + else + Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(expected - actual) > delta); + } + else + { + if ((UNITY_UINT)actual > (UNITY_UINT)expected) + Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(actual - expected) > delta); + else + Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(expected - actual) > delta); + } + + if (Unity.CurrentTestFailed) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrDelta); + UnityPrintNumberByStyle((UNITY_INT)delta, style); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expected, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertEqualString(const char* expected, + const char* actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber) +{ + UNITY_UINT32 i; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if both pointers not null compare the strings */ + if (expected && actual) + { + for (i = 0; expected[i] || actual[i]; i++) + { + if (expected[i] != actual[i]) + { + Unity.CurrentTestFailed = 1; + break; + } + } + } + else + { /* handle case of one pointers being null (if both null, test should pass) */ + if (expected != actual) + { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrintExpectedAndActualStrings(expected, actual); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertEqualStringLen(const char* expected, + const char* actual, + const UNITY_UINT32 length, + const char* msg, + const UNITY_LINE_TYPE lineNumber) +{ + UNITY_UINT32 i; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if both pointers not null compare the strings */ + if (expected && actual) + { + for (i = 0; (i < length) && (expected[i] || actual[i]); i++) + { + if (expected[i] != actual[i]) + { + Unity.CurrentTestFailed = 1; + break; + } + } + } + else + { /* handle case of one pointers being null (if both null, test should pass) */ + if (expected != actual) + { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrintExpectedAndActualStringsLen(expected, actual, length); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } +} + +/*-----------------------------------------------*/ +void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected, + const char** actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) +{ + UNITY_UINT32 i = 0; + UNITY_UINT32 j = 0; + const char* expd = NULL; + const char* act = NULL; + + RETURN_IF_FAIL_OR_IGNORE; + + /* if no elements, it's an error */ + if (num_elements == 0) + { + UnityPrintPointlessAndBail(); + } + + if ((const void*)expected == (const void*)actual) + { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) + { + UNITY_FAIL_AND_BAIL; + } + + if (flags != UNITY_ARRAY_TO_ARRAY) + { + expd = (const char*)expected; + } + + do + { + act = actual[j]; + if (flags == UNITY_ARRAY_TO_ARRAY) + { + expd = ((const char* const*)expected)[j]; + } + + /* if both pointers not null compare the strings */ + if (expd && act) + { + for (i = 0; expd[i] || act[i]; i++) + { + if (expd[i] != act[i]) + { + Unity.CurrentTestFailed = 1; + break; + } + } + } + else + { /* handle case of one pointers being null (if both null, test should pass) */ + if (expd != act) + { + Unity.CurrentTestFailed = 1; + } + } + + if (Unity.CurrentTestFailed) + { + UnityTestResultsFailBegin(lineNumber); + if (num_elements > 1) + { + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(j); + } + UnityPrintExpectedAndActualStrings(expd, act); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + } while (++j < num_elements); +} + +/*-----------------------------------------------*/ +void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 length, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags) +{ + UNITY_PTR_ATTRIBUTE const unsigned char* ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; + UNITY_PTR_ATTRIBUTE const unsigned char* ptr_act = (UNITY_PTR_ATTRIBUTE const unsigned char*)actual; + UNITY_UINT32 elements = num_elements; + UNITY_UINT32 bytes; + + RETURN_IF_FAIL_OR_IGNORE; + + if ((elements == 0) || (length == 0)) + { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) return; /* Both are NULL or same pointer */ + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) + UNITY_FAIL_AND_BAIL; + + while (elements--) + { + bytes = length; + while (bytes--) + { + if (*ptr_exp != *ptr_act) + { + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrMemory); + if (num_elements > 1) + { + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + } + UnityPrint(UnityStrByte); + UnityPrintNumberUnsigned(length - bytes - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(*ptr_exp, UNITY_DISPLAY_STYLE_HEX8); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(*ptr_act, UNITY_DISPLAY_STYLE_HEX8); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + ptr_exp++; + ptr_act++; + } + if (flags == UNITY_ARRAY_TO_VAL) + { + ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; + } + } +} + +/*-----------------------------------------------*/ + +static union +{ + UNITY_INT8 i8; + UNITY_INT16 i16; + UNITY_INT32 i32; +#ifdef UNITY_SUPPORT_64 + UNITY_INT64 i64; +#endif +#ifndef UNITY_EXCLUDE_FLOAT + float f; +#endif +#ifndef UNITY_EXCLUDE_DOUBLE + double d; +#endif +} UnityQuickCompare; + +UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size) +{ + switch(size) + { + case 1: + UnityQuickCompare.i8 = (UNITY_INT8)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); + + case 2: + UnityQuickCompare.i16 = (UNITY_INT16)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); + +#ifdef UNITY_SUPPORT_64 + case 8: + UnityQuickCompare.i64 = (UNITY_INT64)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); +#endif + default: /* 4 bytes */ + UnityQuickCompare.i32 = (UNITY_INT32)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); + } +} + +#ifndef UNITY_EXCLUDE_FLOAT +UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) +{ + UnityQuickCompare.f = num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f); +} +#endif + +#ifndef UNITY_EXCLUDE_DOUBLE +UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) +{ + UnityQuickCompare.d = num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d); +} +#endif + +/*----------------------------------------------- + * Control Functions + *-----------------------------------------------*/ + +void UnityFail(const char* msg, const UNITY_LINE_TYPE line) +{ + RETURN_IF_FAIL_OR_IGNORE; + + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrFail); + if (msg != NULL) + { + UNITY_OUTPUT_CHAR(':'); + +#ifndef UNITY_EXCLUDE_DETAILS + if (Unity.CurrentDetail1) + { + UnityPrint(UnityStrDetail1Name); + UnityPrint(Unity.CurrentDetail1); + if (Unity.CurrentDetail2) + { + UnityPrint(UnityStrDetail2Name); + UnityPrint(Unity.CurrentDetail2); + } + UnityPrint(UnityStrSpacer); + } +#endif + if (msg[0] != ' ') + { + UNITY_OUTPUT_CHAR(' '); + } + UnityPrint(msg); + } + + UNITY_FAIL_AND_BAIL; +} + +/*-----------------------------------------------*/ +void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line) +{ + RETURN_IF_FAIL_OR_IGNORE; + + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint(UnityStrIgnore); + if (msg != NULL) + { + UNITY_OUTPUT_CHAR(':'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(msg); + } + UNITY_IGNORE_AND_BAIL; +} + +/*-----------------------------------------------*/ +void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) +{ + Unity.CurrentTestName = FuncName; + Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; + Unity.NumberOfTests++; + UNITY_CLR_DETAILS(); + if (TEST_PROTECT()) + { + setUp(); + Func(); + } + if (TEST_PROTECT()) + { + tearDown(); + } + UnityConcludeTest(); +} + +/*-----------------------------------------------*/ +void UnityBegin(const char* filename) +{ + Unity.TestFile = filename; + Unity.CurrentTestName = NULL; + Unity.CurrentTestLineNumber = 0; + Unity.NumberOfTests = 0; + Unity.TestFailures = 0; + Unity.TestIgnores = 0; + Unity.CurrentTestFailed = 0; + Unity.CurrentTestIgnored = 0; + + UNITY_CLR_DETAILS(); + UNITY_OUTPUT_START(); +} + +/*-----------------------------------------------*/ +int UnityEnd(void) +{ + UNITY_PRINT_EOL(); + UnityPrint(UnityStrBreaker); + UNITY_PRINT_EOL(); + UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests)); + UnityPrint(UnityStrResultsTests); + UnityPrintNumber((UNITY_INT)(Unity.TestFailures)); + UnityPrint(UnityStrResultsFailures); + UnityPrintNumber((UNITY_INT)(Unity.TestIgnores)); + UnityPrint(UnityStrResultsIgnored); + UNITY_PRINT_EOL(); + if (Unity.TestFailures == 0U) + { + UnityPrint(UnityStrOk); + } + else + { + UnityPrint(UnityStrFail); +#ifdef UNITY_DIFFERENTIATE_FINAL_FAIL + UNITY_OUTPUT_CHAR('E'); UNITY_OUTPUT_CHAR('D'); +#endif + } + UNITY_PRINT_EOL(); + UNITY_FLUSH_CALL(); + UNITY_OUTPUT_COMPLETE(); + return (int)(Unity.TestFailures); +} + +/*----------------------------------------------- + * Command Line Argument Support + *-----------------------------------------------*/ +#ifdef UNITY_USE_COMMAND_LINE_ARGS + +char* UnityOptionIncludeNamed = NULL; +char* UnityOptionExcludeNamed = NULL; +int UnityVerbosity = 1; + +int UnityParseOptions(int argc, char** argv) +{ + UnityOptionIncludeNamed = NULL; + UnityOptionExcludeNamed = NULL; + + for (int i = 1; i < argc; i++) + { + if (argv[i][0] == '-') + { + switch (argv[i][1]) + { + case 'l': /* list tests */ + return -1; + case 'n': /* include tests with name including this string */ + case 'f': /* an alias for -n */ + if (argv[i][2] == '=') + UnityOptionIncludeNamed = &argv[i][3]; + else if (++i < argc) + UnityOptionIncludeNamed = argv[i]; + else + { + UnityPrint("ERROR: No Test String to Include Matches For"); + UNITY_PRINT_EOL(); + return 1; + } + break; + case 'q': /* quiet */ + UnityVerbosity = 0; + break; + case 'v': /* verbose */ + UnityVerbosity = 2; + break; + case 'x': /* exclude tests with name including this string */ + if (argv[i][2] == '=') + UnityOptionExcludeNamed = &argv[i][3]; + else if (++i < argc) + UnityOptionExcludeNamed = argv[i]; + else + { + UnityPrint("ERROR: No Test String to Exclude Matches For"); + UNITY_PRINT_EOL(); + return 1; + } + break; + default: + UnityPrint("ERROR: Unknown Option "); + UNITY_OUTPUT_CHAR(argv[i][1]); + UNITY_PRINT_EOL(); + return 1; + } + } + } + + return 0; +} + +int IsStringInBiggerString(const char* longstring, const char* shortstring) +{ + const char* lptr = longstring; + const char* sptr = shortstring; + const char* lnext = lptr; + + if (*sptr == '*') + return 1; + + while (*lptr) + { + lnext = lptr + 1; + + /* If they current bytes match, go on to the next bytes */ + while (*lptr && *sptr && (*lptr == *sptr)) + { + lptr++; + sptr++; + + /* We're done if we match the entire string or up to a wildcard */ + if (*sptr == '*') + return 1; + if (*sptr == ',') + return 1; + if (*sptr == '"') + return 1; + if (*sptr == '\'') + return 1; + if (*sptr == ':') + return 2; + if (*sptr == 0) + return 1; + } + + /* Otherwise we start in the long pointer 1 character further and try again */ + lptr = lnext; + sptr = shortstring; + } + return 0; +} + +int UnityStringArgumentMatches(const char* str) +{ + int retval; + const char* ptr1; + const char* ptr2; + const char* ptrf; + + /* Go through the options and get the substrings for matching one at a time */ + ptr1 = str; + while (ptr1[0] != 0) + { + if ((ptr1[0] == '"') || (ptr1[0] == '\'')) + ptr1++; + + /* look for the start of the next partial */ + ptr2 = ptr1; + ptrf = 0; + do + { + ptr2++; + if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')) + ptrf = &ptr2[1]; + } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')); + while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ','))) + ptr2++; + + /* done if complete filename match */ + retval = IsStringInBiggerString(Unity.TestFile, ptr1); + if (retval == 1) + return retval; + + /* done if testname match after filename partial match */ + if ((retval == 2) && (ptrf != 0)) + { + if (IsStringInBiggerString(Unity.CurrentTestName, ptrf)) + return 1; + } + + /* done if complete testname match */ + if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) + return 1; + + ptr1 = ptr2; + } + + /* we couldn't find a match for any substrings */ + return 0; +} + +int UnityTestMatches(void) +{ + /* Check if this test name matches the included test pattern */ + int retval; + if (UnityOptionIncludeNamed) + { + retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); + } + else + retval = 1; + + /* Check if this test name matches the excluded test pattern */ + if (UnityOptionExcludeNamed) + { + if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) + retval = 0; + } + return retval; +} + +#endif /* UNITY_USE_COMMAND_LINE_ARGS */ +/*-----------------------------------------------*/ diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.h b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.h new file mode 100644 index 0000000..32ff0e6 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity.h @@ -0,0 +1,503 @@ +/* ========================================== + Unity Project - A Test Framework for C + Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef UNITY_FRAMEWORK_H +#define UNITY_FRAMEWORK_H +#define UNITY + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "unity_internals.h" + +/*------------------------------------------------------- + * Test Setup / Teardown + *-------------------------------------------------------*/ + +/* These functions are intended to be called before and after each test. */ +void setUp(void); +void tearDown(void); + +/* These functions are intended to be called at the beginning and end of an + * entire test suite. suiteTearDown() is passed the number of tests that + * failed, and its return value becomes the exit code of main(). */ +void suiteSetUp(void); +int suiteTearDown(int num_failures); + +/* If the compiler supports it, the following block provides stub + * implementations of the above functions as weak symbols. Note that on + * some platforms (MinGW for example), weak function implementations need + * to be in the same translation unit they are called from. This can be + * achieved by defining UNITY_INCLUDE_SETUP_STUBS before including unity.h. */ +#ifdef UNITY_INCLUDE_SETUP_STUBS + #ifdef UNITY_WEAK_ATTRIBUTE + UNITY_WEAK_ATTRIBUTE void setUp(void) { } + UNITY_WEAK_ATTRIBUTE void tearDown(void) { } + UNITY_WEAK_ATTRIBUTE void suiteSetUp(void) { } + UNITY_WEAK_ATTRIBUTE int suiteTearDown(int num_failures) { return num_failures; } + #elif defined(UNITY_WEAK_PRAGMA) + #pragma weak setUp + void setUp(void) { } + #pragma weak tearDown + void tearDown(void) { } + #pragma weak suiteSetUp + void suiteSetUp(void) { } + #pragma weak suiteTearDown + int suiteTearDown(int num_failures) { return num_failures; } + #endif +#endif + +/*------------------------------------------------------- + * Configuration Options + *------------------------------------------------------- + * All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above. + + * Integers/longs/pointers + * - Unity attempts to automatically discover your integer sizes + * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in + * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in + * - If you cannot use the automatic methods above, you can force Unity by using these options: + * - define UNITY_SUPPORT_64 + * - set UNITY_INT_WIDTH + * - set UNITY_LONG_WIDTH + * - set UNITY_POINTER_WIDTH + + * Floats + * - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons + * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT + * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats + * - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons + * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default) + * - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE + * - define UNITY_DOUBLE_TYPE to specify something other than double + * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors + + * Output + * - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired + * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure + + * Optimization + * - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge + * - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests. + + * Test Cases + * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script + + * Parameterized Tests + * - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing + + * Tests with Arguments + * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity + + *------------------------------------------------------- + * Basic Fail and Ignore + *-------------------------------------------------------*/ + +#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) +#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) +#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) +#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) +#define TEST_ONLY() + +/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. + * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ +#define TEST_PASS() TEST_ABORT() + +/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out + * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ +#define TEST_FILE(a) + +/*------------------------------------------------------- + * Test Asserts (simple) + *-------------------------------------------------------*/ + +/* Boolean */ +#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE") +#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE") +#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE") +#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE") +#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL") +#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") + +/* Integers (of all sizes) */ +#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, NULL) +#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) +#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, NULL) + +/* Integer Greater Than/ Less Than (of all sizes) */ +#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) + +/* Integer Ranges (of all sizes) */ +#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) + +/* Structs and Strings */ +#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL) + +/* Arrays */ +#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) + +/* Arrays Compared To Single Value */ +#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) + +/* Floating Point (If Enabled) */ +#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) + +/* Double (If Enabled) */ +#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) + +/*------------------------------------------------------- + * Test Asserts (with additional messages) + *-------------------------------------------------------*/ + +/* Boolean */ +#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) +#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) +#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) +#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) +#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message)) +#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) + +/* Integers (of all sizes) */ +#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) +#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) +#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) + +/* Integer Greater Than/ Less Than (of all sizes) */ +#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +/* Integer Ranges (of all sizes) */ +#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) + +/* Structs and Strings */ +#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message)) + +/* Arrays */ +#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) + +/* Arrays Compared To Single Value*/ +#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) + +/* Floating Point (If Enabled) */ +#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message)) + +/* Double (If Enabled) */ +#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) + +/* end of UNITY_FRAMEWORK_H */ +#ifdef __cplusplus +} +#endif +#endif diff --git a/managed_components/espressif__cjson/cJSON/tests/unity/src/unity_internals.h b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity_internals.h new file mode 100644 index 0000000..f78ceba --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity/src/unity_internals.h @@ -0,0 +1,870 @@ +/* ========================================== + Unity Project - A Test Framework for C + Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef UNITY_INTERNALS_H +#define UNITY_INTERNALS_H + +#include "../examples/unity_config.h" + +#ifndef UNITY_EXCLUDE_SETJMP_H +#include +#endif + +#ifndef UNITY_EXCLUDE_MATH_H +#include +#endif + +/* Unity Attempts to Auto-Detect Integer Types + * Attempt 1: UINT_MAX, ULONG_MAX in , or default to 32 bits + * Attempt 2: UINTPTR_MAX in , or default to same size as long + * The user may override any of these derived constants: + * UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */ +#ifndef UNITY_EXCLUDE_STDINT_H +#include +#endif + +#ifndef UNITY_EXCLUDE_LIMITS_H +#include +#endif + +/*------------------------------------------------------- + * Guess Widths If Not Specified + *-------------------------------------------------------*/ + +/* Determine the size of an int, if not already specified. + * We cannot use sizeof(int), because it is not yet defined + * at this stage in the translation of the C program. + * Therefore, infer it from UINT_MAX if possible. */ +#ifndef UNITY_INT_WIDTH + #ifdef UINT_MAX + #if (UINT_MAX == 0xFFFF) + #define UNITY_INT_WIDTH (16) + #elif (UINT_MAX == 0xFFFFFFFF) + #define UNITY_INT_WIDTH (32) + #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) + #define UNITY_INT_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_INT_WIDTH (32) + #endif /* UINT_MAX */ +#endif + +/* Determine the size of a long, if not already specified. */ +#ifndef UNITY_LONG_WIDTH + #ifdef ULONG_MAX + #if (ULONG_MAX == 0xFFFF) + #define UNITY_LONG_WIDTH (16) + #elif (ULONG_MAX == 0xFFFFFFFF) + #define UNITY_LONG_WIDTH (32) + #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) + #define UNITY_LONG_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_LONG_WIDTH (32) + #endif /* ULONG_MAX */ +#endif + +/* Determine the size of a pointer, if not already specified. */ +#ifndef UNITY_POINTER_WIDTH + #ifdef UINTPTR_MAX + #if (UINTPTR_MAX <= 0xFFFF) + #define UNITY_POINTER_WIDTH (16) + #elif (UINTPTR_MAX <= 0xFFFFFFFF) + #define UNITY_POINTER_WIDTH (32) + #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) + #define UNITY_POINTER_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH + #endif /* UINTPTR_MAX */ +#endif + +/*------------------------------------------------------- + * Int Support (Define types based on detected sizes) + *-------------------------------------------------------*/ + +#if (UNITY_INT_WIDTH == 32) + typedef unsigned char UNITY_UINT8; + typedef unsigned short UNITY_UINT16; + typedef unsigned int UNITY_UINT32; + typedef signed char UNITY_INT8; + typedef signed short UNITY_INT16; + typedef signed int UNITY_INT32; +#elif (UNITY_INT_WIDTH == 16) + typedef unsigned char UNITY_UINT8; + typedef unsigned int UNITY_UINT16; + typedef unsigned long UNITY_UINT32; + typedef signed char UNITY_INT8; + typedef signed int UNITY_INT16; + typedef signed long UNITY_INT32; +#else + #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) +#endif + +/*------------------------------------------------------- + * 64-bit Support + *-------------------------------------------------------*/ + +#ifndef UNITY_SUPPORT_64 + #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 + #define UNITY_SUPPORT_64 + #endif +#endif + +#ifndef UNITY_SUPPORT_64 + /* No 64-bit Support */ + typedef UNITY_UINT32 UNITY_UINT; + typedef UNITY_INT32 UNITY_INT; +#else + + /* 64-bit Support */ + #if (UNITY_LONG_WIDTH == 32) + typedef unsigned long long UNITY_UINT64; + typedef signed long long UNITY_INT64; + #elif (UNITY_LONG_WIDTH == 64) + typedef unsigned long UNITY_UINT64; + typedef signed long UNITY_INT64; + #else + #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) + #endif + typedef UNITY_UINT64 UNITY_UINT; + typedef UNITY_INT64 UNITY_INT; + +#endif + +/*------------------------------------------------------- + * Pointer Support + *-------------------------------------------------------*/ + +#if (UNITY_POINTER_WIDTH == 32) +#define UNITY_PTR_TO_INT UNITY_INT32 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 +#elif (UNITY_POINTER_WIDTH == 64) +#define UNITY_PTR_TO_INT UNITY_INT64 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 +#elif (UNITY_POINTER_WIDTH == 16) +#define UNITY_PTR_TO_INT UNITY_INT16 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 +#else + #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) +#endif + +#ifndef UNITY_PTR_ATTRIBUTE +#define UNITY_PTR_ATTRIBUTE +#endif + +#ifndef UNITY_INTERNAL_PTR +#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* +#endif + +/*------------------------------------------------------- + * Float Support + *-------------------------------------------------------*/ + +#ifdef UNITY_EXCLUDE_FLOAT + +/* No Floating Point Support */ +#ifndef UNITY_EXCLUDE_DOUBLE +#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */ +#endif +#ifndef UNITY_EXCLUDE_FLOAT_PRINT +#define UNITY_EXCLUDE_FLOAT_PRINT +#endif + +#else + +/* Floating Point Support */ +#ifndef UNITY_FLOAT_PRECISION +#define UNITY_FLOAT_PRECISION (0.00001f) +#endif +#ifndef UNITY_FLOAT_TYPE +#define UNITY_FLOAT_TYPE float +#endif +typedef UNITY_FLOAT_TYPE UNITY_FLOAT; + +/* isinf & isnan macros should be provided by math.h */ +#ifndef isinf +/* The value of Inf - Inf is NaN */ +#define isinf(n) (isnan((n) - (n)) && !isnan(n)) +#endif + +#ifndef isnan +/* NaN is the only floating point value that does NOT equal itself. + * Therefore if n != n, then it is NaN. */ +#define isnan(n) ((n != n) ? 1 : 0) +#endif + +#endif + +/*------------------------------------------------------- + * Double Float Support + *-------------------------------------------------------*/ + +/* unlike float, we DON'T include by default */ +#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) + + /* No Floating Point Support */ + #ifndef UNITY_EXCLUDE_DOUBLE + #define UNITY_EXCLUDE_DOUBLE + #else + #undef UNITY_INCLUDE_DOUBLE + #endif + + #ifndef UNITY_EXCLUDE_FLOAT + #ifndef UNITY_DOUBLE_TYPE + #define UNITY_DOUBLE_TYPE double + #endif + typedef UNITY_FLOAT UNITY_DOUBLE; + /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ + #endif + +#else + + /* Double Floating Point Support */ + #ifndef UNITY_DOUBLE_PRECISION + #define UNITY_DOUBLE_PRECISION (1e-12) + #endif + + #ifndef UNITY_DOUBLE_TYPE + #define UNITY_DOUBLE_TYPE double + #endif + typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; + +#endif + +/*------------------------------------------------------- + * Output Method: stdout (DEFAULT) + *-------------------------------------------------------*/ +#ifndef UNITY_OUTPUT_CHAR +/* Default to using putchar, which is defined in stdio.h */ +#include +#define UNITY_OUTPUT_CHAR(a) (void)putchar(a) +#else + /* If defined as something else, make sure we declare it here so it's ready for use */ + #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION +extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; + #endif +#endif + +#ifndef UNITY_OUTPUT_FLUSH +#ifdef UNITY_USE_FLUSH_STDOUT +/* We want to use the stdout flush utility */ +#include +#define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) +#else +/* We've specified nothing, therefore flush should just be ignored */ +#define UNITY_OUTPUT_FLUSH() +#endif +#else +/* We've defined flush as something else, so make sure we declare it here so it's ready for use */ +#ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION +extern void UNITY_OMIT_OUTPUT_FLUSH_HEADER_DECLARATION; +#endif +#endif + +#ifndef UNITY_OUTPUT_FLUSH +#define UNITY_FLUSH_CALL() +#else +#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH() +#endif + +#ifndef UNITY_PRINT_EOL +#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') +#endif + +#ifndef UNITY_OUTPUT_START +#define UNITY_OUTPUT_START() +#endif + +#ifndef UNITY_OUTPUT_COMPLETE +#define UNITY_OUTPUT_COMPLETE() +#endif + +/*------------------------------------------------------- + * Footprint + *-------------------------------------------------------*/ + +#ifndef UNITY_LINE_TYPE +#define UNITY_LINE_TYPE UNITY_UINT +#endif + +#ifndef UNITY_COUNTER_TYPE +#define UNITY_COUNTER_TYPE UNITY_UINT +#endif + +/*------------------------------------------------------- + * Language Features Available + *-------------------------------------------------------*/ +#if !defined(UNITY_WEAK_ATTRIBUTE) && !defined(UNITY_WEAK_PRAGMA) +# if defined(__GNUC__) || defined(__ghs__) /* __GNUC__ includes clang */ +# if !(defined(__WIN32__) && defined(__clang__)) && !defined(__TMS470__) +# define UNITY_WEAK_ATTRIBUTE __attribute__((weak)) +# endif +# endif +#endif + +#ifdef UNITY_NO_WEAK +# undef UNITY_WEAK_ATTRIBUTE +# undef UNITY_WEAK_PRAGMA +#endif + + +/*------------------------------------------------------- + * Internal Structs Needed + *-------------------------------------------------------*/ + +typedef void (*UnityTestFunction)(void); + +#define UNITY_DISPLAY_RANGE_INT (0x10) +#define UNITY_DISPLAY_RANGE_UINT (0x20) +#define UNITY_DISPLAY_RANGE_HEX (0x40) + +typedef enum +{ +UNITY_DISPLAY_STYLE_INT = sizeof(int)+ UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, +#endif + +UNITY_DISPLAY_STYLE_UINT = sizeof(unsigned) + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, +#endif + + UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, +#endif + + UNITY_DISPLAY_STYLE_UNKNOWN +} UNITY_DISPLAY_STYLE_T; + +typedef enum +{ + UNITY_EQUAL_TO = 1, + UNITY_GREATER_THAN = 2, + UNITY_GREATER_OR_EQUAL = 2 + UNITY_EQUAL_TO, + UNITY_SMALLER_THAN = 4, + UNITY_SMALLER_OR_EQUAL = 4 + UNITY_EQUAL_TO +} UNITY_COMPARISON_T; + +#ifndef UNITY_EXCLUDE_FLOAT +typedef enum UNITY_FLOAT_TRAIT +{ + UNITY_FLOAT_IS_NOT_INF = 0, + UNITY_FLOAT_IS_INF, + UNITY_FLOAT_IS_NOT_NEG_INF, + UNITY_FLOAT_IS_NEG_INF, + UNITY_FLOAT_IS_NOT_NAN, + UNITY_FLOAT_IS_NAN, + UNITY_FLOAT_IS_NOT_DET, + UNITY_FLOAT_IS_DET, + UNITY_FLOAT_INVALID_TRAIT +} UNITY_FLOAT_TRAIT_T; +#endif + +typedef enum +{ + UNITY_ARRAY_TO_VAL = 0, + UNITY_ARRAY_TO_ARRAY +} UNITY_FLAGS_T; + +struct UNITY_STORAGE_T +{ + const char* TestFile; + const char* CurrentTestName; +#ifndef UNITY_EXCLUDE_DETAILS + const char* CurrentDetail1; + const char* CurrentDetail2; +#endif + UNITY_LINE_TYPE CurrentTestLineNumber; + UNITY_COUNTER_TYPE NumberOfTests; + UNITY_COUNTER_TYPE TestFailures; + UNITY_COUNTER_TYPE TestIgnores; + UNITY_COUNTER_TYPE CurrentTestFailed; + UNITY_COUNTER_TYPE CurrentTestIgnored; +#ifndef UNITY_EXCLUDE_SETJMP_H + jmp_buf AbortFrame; +#endif +}; + +extern struct UNITY_STORAGE_T Unity; + +/*------------------------------------------------------- + * Test Suite Management + *-------------------------------------------------------*/ + +void UnityBegin(const char* filename); +int UnityEnd(void); +void UnityConcludeTest(void); +void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); + +/*------------------------------------------------------- + * Details Support + *-------------------------------------------------------*/ + +#ifdef UNITY_EXCLUDE_DETAILS +#define UNITY_CLR_DETAILS() +#define UNITY_SET_DETAIL(d1) +#define UNITY_SET_DETAILS(d1,d2) +#else +#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } +#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = 0; } +#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = d2; } + +#ifndef UNITY_DETAIL1_NAME +#define UNITY_DETAIL1_NAME "Function" +#endif + +#ifndef UNITY_DETAIL2_NAME +#define UNITY_DETAIL2_NAME "Argument" +#endif +#endif + +/*------------------------------------------------------- + * Test Output + *-------------------------------------------------------*/ + +void UnityPrint(const char* string); +void UnityPrintLen(const char* string, const UNITY_UINT32 length); +void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); +void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); +void UnityPrintNumber(const UNITY_INT number); +void UnityPrintNumberUnsigned(const UNITY_UINT number); +void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles); + +#ifndef UNITY_EXCLUDE_FLOAT_PRINT +void UnityPrintFloat(const UNITY_DOUBLE input_number); +#endif + +/*------------------------------------------------------- + * Test Assertion Functions + *------------------------------------------------------- + * Use the macros below this section instead of calling + * these directly. The macros have a consistent naming + * convention and will pull in file and line information + * for you. */ + +void UnityAssertEqualNumber(const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, + const UNITY_INT actual, + const UNITY_COMPARISON_T compare, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags); + +void UnityAssertBits(const UNITY_INT mask, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualString(const char* expected, + const char* actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringLen(const char* expected, + const char* actual, + const UNITY_UINT32 length, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, + const char** actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 length, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertNumbersWithin(const UNITY_UINT delta, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityFail(const char* message, const UNITY_LINE_TYPE line); + +void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); + +#ifndef UNITY_EXCLUDE_FLOAT +void UnityAssertFloatsWithin(const UNITY_FLOAT delta, + const UNITY_FLOAT expected, + const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertFloatSpecial(const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); +#endif + +#ifndef UNITY_EXCLUDE_DOUBLE +void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, + const UNITY_DOUBLE expected, + const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); +#endif + +/*------------------------------------------------------- + * Helpers + *-------------------------------------------------------*/ + +UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size); +#ifndef UNITY_EXCLUDE_FLOAT +UNITY_INTERNAL_PTR UnityFloatToPtr(const float num); +#endif +#ifndef UNITY_EXCLUDE_DOUBLE +UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); +#endif + +/*------------------------------------------------------- + * Error Strings We Might Need + *-------------------------------------------------------*/ + +extern const char UnityStrErrFloat[]; +extern const char UnityStrErrDouble[]; +extern const char UnityStrErr64[]; + +/*------------------------------------------------------- + * Test Running Macros + *-------------------------------------------------------*/ + +#ifndef UNITY_EXCLUDE_SETJMP_H +#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0) +#define TEST_ABORT() longjmp(Unity.AbortFrame, 1) +#else +#define TEST_PROTECT() 1 +#define TEST_ABORT() return +#endif + +/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ +#ifndef RUN_TEST +#ifdef __STDC_VERSION__ +#if __STDC_VERSION__ >= 199901L +#define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__)) +#define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway) +#define RUN_TEST_FIRST_HELPER(first, ...) (first), #first +#define RUN_TEST_SECOND(...) RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway) +#define RUN_TEST_SECOND_HELPER(first, second, ...) (second) +#endif +#endif +#endif + +/* If we can't do the tricky version, we'll just have to require them to always include the line number */ +#ifndef RUN_TEST +#ifdef CMOCK +#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) +#else +#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) +#endif +#endif + +#define TEST_LINE_NUM (Unity.CurrentTestLineNumber) +#define TEST_IS_IGNORED (Unity.CurrentTestIgnored) +#define UNITY_NEW_TEST(a) \ + Unity.CurrentTestName = (a); \ + Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ + Unity.NumberOfTests++; + +#ifndef UNITY_BEGIN +#define UNITY_BEGIN() UnityBegin(__FILE__) +#endif + +#ifndef UNITY_END +#define UNITY_END() UnityEnd() +#endif + +/*----------------------------------------------- + * Command Line Argument Support + *-----------------------------------------------*/ + +#ifdef UNITY_USE_COMMAND_LINE_ARGS +int UnityParseOptions(int argc, char** argv); +int UnityTestMatches(void); +#endif + +/*------------------------------------------------------- + * Basic Fail and Ignore + *-------------------------------------------------------*/ + +#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) + +/*------------------------------------------------------- + * Test Asserts + *-------------------------------------------------------*/ + +#define UNITY_TEST_ASSERT(condition, line, message) if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));} +#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) + +#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) + +#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) +#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(unsigned int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) expected, sizeof(int*)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) + +#ifdef UNITY_SUPPORT_64 +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#else +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#endif + +#ifdef UNITY_EXCLUDE_FLOAT +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#else +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#endif + +#ifdef UNITY_EXCLUDE_DOUBLE +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#else +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)line) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual, (UNITY_LINE_TYPE)(line), message) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#endif + +/* End of UNITY_INTERNALS_H */ +#endif diff --git a/managed_components/espressif__cjson/cJSON/tests/unity_setup.c b/managed_components/espressif__cjson/cJSON/tests/unity_setup.c new file mode 100644 index 0000000..1d828b0 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/tests/unity_setup.c @@ -0,0 +1,3 @@ +// msvc doesn't support weak-linking, so we need to define these functions. +void setUp(void) { } +void tearDown(void) { } diff --git a/managed_components/espressif__cjson/cJSON/valgrind.supp b/managed_components/espressif__cjson/cJSON/valgrind.supp new file mode 100644 index 0000000..79b55c6 --- /dev/null +++ b/managed_components/espressif__cjson/cJSON/valgrind.supp @@ -0,0 +1,6 @@ +{ + suppress_ld_on_armv7 + Memcheck:Cond + ... + obj:*/ld-*.so +} diff --git a/managed_components/espressif__cjson/idf_component.yml b/managed_components/espressif__cjson/idf_component.yml new file mode 100644 index 0000000..48193d3 --- /dev/null +++ b/managed_components/espressif__cjson/idf_component.yml @@ -0,0 +1,9 @@ +dependencies: + idf: '>=5.0' +description: 'cJSON: Ultralightweight JSON parser in ANSI C' +repository: git://github.com/espressif/idf-extra-components.git +repository_info: + commit_sha: 1387cec28a9b40654be7892114bd7d26fcd3869c + path: cjson +url: https://github.com/espressif/idf-extra-components/tree/master/cjson +version: 1.7.19~2 diff --git a/managed_components/espressif__cjson/sbom_cJSON.yml b/managed_components/espressif__cjson/sbom_cJSON.yml new file mode 100644 index 0000000..f3142b0 --- /dev/null +++ b/managed_components/espressif__cjson/sbom_cJSON.yml @@ -0,0 +1,9 @@ +name: cJSON +version: "1.7.19" +cpe: + - cpe:2.3:a:cjson_project:cjson:{}:*:*:*:*:*:*:* + - cpe:2.3:a:davegamble:cjson:{}:*:*:*:*:*:*:* +supplier: 'Person: Dave Gamble' +description: "cJSON: Ultralightweight JSON parser in ANSI C" +url: https://github.com/DaveGamble/cJSON +hash: b2890c8d76bbb64e710585ebc0a917196b9c67e7 diff --git a/managed_components/espressif__mdns/.component_hash b/managed_components/espressif__mdns/.component_hash new file mode 100644 index 0000000..68f19b9 --- /dev/null +++ b/managed_components/espressif__mdns/.component_hash @@ -0,0 +1 @@ +2fa43caa78cc170842255bc7bf71f306bc815cae12e9496bfb12372423019ac7 \ No newline at end of file diff --git a/managed_components/espressif__mdns/.cz.yaml b/managed_components/espressif__mdns/.cz.yaml new file mode 100644 index 0000000..20573c9 --- /dev/null +++ b/managed_components/espressif__mdns/.cz.yaml @@ -0,0 +1,8 @@ +--- +commitizen: + bump_message: 'bump(mdns): $current_version -> $new_version' + pre_bump_hooks: python ../../ci/changelog.py mdns + tag_format: mdns-v$version + version: 1.15.1 + version_files: + - idf_component.yml diff --git a/managed_components/espressif__mdns/CHANGELOG.md b/managed_components/espressif__mdns/CHANGELOG.md new file mode 100644 index 0000000..0833f11 --- /dev/null +++ b/managed_components/espressif__mdns/CHANGELOG.md @@ -0,0 +1,781 @@ +# Changelog + +## [1.15.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.15.1) + +### Bug Fixes + +- Fix gcc stringop-truncation warning ([7cb5e9db](https://github.com/espressif/esp-protocols/commit/7cb5e9db)) + +## [1.15.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.15.0) + +### Features + +- support subtype browsing (RFC 6763 Section 7.1) ([19a0c32c](https://github.com/espressif/esp-protocols/commit/19a0c32c)) +- clean up unsubscribed cache records in defined grace time ([951b9d56](https://github.com/espressif/esp-protocols/commit/951b9d56)) + +### Bug Fixes + +- Fix app partition is nearly full warning in CI ([708a6de2](https://github.com/espressif/esp-protocols/commit/708a6de2)) +- Fix console strict discard-qualifiers warning ([2b7db98a](https://github.com/espressif/esp-protocols/commit/2b7db98a)) +- Don't free a queued TX packet when cleaning up its action ([30c8d501](https://github.com/espressif/esp-protocols/commit/30c8d501)) +- avoid stack overflow in SRV and TXT collision checks ([e594544c](https://github.com/espressif/esp-protocols/commit/e594544c)) +- Require console directly under IDF build system v2 ([6aa13b72](https://github.com/espressif/esp-protocols/commit/6aa13b72)) +- Only depend on console when the CLI is enabled ([4e62c23d](https://github.com/espressif/esp-protocols/commit/4e62c23d)) + +### Updated + +- test(mdns): cover subtype cache expiry and browsing ([c17fb015](https://github.com/espressif/esp-protocols/commit/c17fb015)) + +## [1.14.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.14.1) + +### Bug Fixes + +- Fix OOB access in mdns debug logs ([397820ad](https://github.com/espressif/esp-protocols/commit/397820ad)) + +## [1.14.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.14.0) + +### Features + +- mdns cache natrual TTL expiration ([be666607](https://github.com/espressif/esp-protocols/commit/be666607)) +- Add subtype-aware local service lookup APIs ([65a3a57b](https://github.com/espressif/esp-protocols/commit/65a3a57b)) + +### Bug Fixes + +- Enable IPv6 on the right interface for GOT_IP6 ([eb5d2f36](https://github.com/espressif/esp-protocols/commit/eb5d2f36)) +- Don't advertise A record with 0.0.0.0 address ([76760948](https://github.com/espressif/esp-protocols/commit/76760948)) +- Distinguish TXT item with no value and empty value in responder ([47f8ab48](https://github.com/espressif/esp-protocols/commit/47f8ab48)) +- Distinguish TXT item with no value and empty value in cache ([95a1f604](https://github.com/espressif/esp-protocols/commit/95a1f604)) + +### Updated + +- test(mdns): update host unit tests for cache expiry ([d9fb726f](https://github.com/espressif/esp-protocols/commit/d9fb726f)) +- test(mdns): Add host unit tests for mdns_browse ([ee59cf7b](https://github.com/espressif/esp-protocols/commit/ee59cf7b)) +- test(mdns): Added host unit tests for mdns_cache ([63be8715](https://github.com/espressif/esp-protocols/commit/63be8715)) + +## [1.13.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.13.1) + +### Bug Fixes + +- Completely remove test_apps ([19cc175e](https://github.com/espressif/esp-protocols/commit/19cc175e)) +- Migrate test_apps to host tests ([9cdec857](https://github.com/espressif/esp-protocols/commit/9cdec857)) +- Ensure buffer is always NUL-terminated in rx_staged_ip_add() ([b370a9ab](https://github.com/espressif/esp-protocols/commit/b370a9ab)) + +## [1.13.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.13.0) + +### Features + +- Use mdns_cache for browse notifications ([ff5bf666](https://github.com/espressif/esp-protocols/commit/ff5bf666)) + +### Bug Fixes + +- Fix mdns parser to expand per one service question ([c56c725d](https://github.com/espressif/esp-protocols/commit/c56c725d)) +- Fix mdns_mem_strndup() in host unit test stub ([18d5421d](https://github.com/espressif/esp-protocols/commit/18d5421d)) + +## [1.12.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.12.0) + +### Features + +- add hostname change callback ([c2cd90b0](https://github.com/espressif/esp-protocols/commit/c2cd90b0)) +- Make mDNS browse feature optional ([2e0c2540](https://github.com/espressif/esp-protocols/commit/2e0c2540)) + +### Bug Fixes + +- Update supported/tested IDF version matrix ([e8427217](https://github.com/espressif/esp-protocols/commit/e8427217)) +- Fix mdns browse SYNC vs. END race ([1b83e978](https://github.com/espressif/esp-protocols/commit/1b83e978)) +- Only depend on esp_wifi when Wi-Fi is enabled ([47724b7d](https://github.com/espressif/esp-protocols/commit/47724b7d), [#835](https://github.com/espressif/esp-protocols/issues/835)) +- Update host test to check goodbye and browse dupl ([ab03980d](https://github.com/espressif/esp-protocols/commit/ab03980d)) +- Fix mdns_browse_new() return dangling pointer on duplicated browsers ([e063449c](https://github.com/espressif/esp-protocols/commit/e063449c)) +- Create static task only when SPIRAM-task-alloc is ON ([6f31f27f](https://github.com/espressif/esp-protocols/commit/6f31f27f)) +- validate subtype label position ([a09b24fe](https://github.com/espressif/esp-protocols/commit/a09b24fe)) +- ignore subtype SRV and TXT questions ([7910501d](https://github.com/espressif/esp-protocols/commit/7910501d)) +- distinguish subtype queries from instances ([b9103169](https://github.com/espressif/esp-protocols/commit/b9103169)) +- Don't free a browse result already freed by an earlier sync batch ([9057f2d9](https://github.com/espressif/esp-protocols/commit/9057f2d9)) + +### Updated + +- test(mdns): add hostname callback target test ([4c8b76dd](https://github.com/espressif/esp-protocols/commit/4c8b76dd)) +- test(mdns): add hostname callback host test ([1f35d5f3](https://github.com/espressif/esp-protocols/commit/1f35d5f3)) +- test(mdns): cover subtype query handling ([c14ed4fc](https://github.com/espressif/esp-protocols/commit/c14ed4fc)) +- refactor(mdns): share debug name formatting ([8c7bc865](https://github.com/espressif/esp-protocols/commit/8c7bc865)) + +## [1.11.3](https://github.com/espressif/esp-protocols/commits/mdns-v1.11.3) + +### Features + +- Add a structure and APIs for allocating TXT items with given value length ([234f9f00](https://github.com/espressif/esp-protocols/commit/234f9f00)) + +### Bug Fixes + +- Fix potential browse null instance crash caught by fuzzer ([953c3a78](https://github.com/espressif/esp-protocols/commit/953c3a78)) +- fix deadlock caused by re-acquiring the service lock ([88c68330](https://github.com/espressif/esp-protocols/commit/88c68330)) +- free dropped TXT query results when max results reached ([f81720b7](https://github.com/espressif/esp-protocols/commit/f81720b7)) + +## [1.11.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.11.2) + +### Bug Fixes + +- Fix Unbounded recursion in mDNS name decompression ([95c882c7](https://github.com/espressif/esp-protocols/commit/95c882c7)) +- Fix wrong "truncated AAAA" error ([fc5e6787](https://github.com/espressif/esp-protocols/commit/fc5e6787)) +- Add unit tests for fa84ee6e4 ([8d7b9432](https://github.com/espressif/esp-protocols/commit/8d7b9432)) +- guard null TXT values in browse TXT comparison ([1b4fcb0c](https://github.com/espressif/esp-protocols/commit/1b4fcb0c)) +- plug fuzz harness and browse sync memory leaks ([a8c1dad3](https://github.com/espressif/esp-protocols/commit/a8c1dad3)) +- bounds-copy browse service/proto when parsing packets ([429d7b91](https://github.com/espressif/esp-protocols/commit/429d7b91)) +- reject packets shorter than the DNS header ([b556327e](https://github.com/espressif/esp-protocols/commit/b556327e)) +- Add support for fuzzing browses ([7ec95d04](https://github.com/espressif/esp-protocols/commit/7ec95d04)) +- Fix browse to stage A/AAAA to match PTRs records ([26bfcd14](https://github.com/espressif/esp-protocols/commit/26bfcd14), [#1064](https://github.com/espressif/esp-protocols/issues/1064)) +- queue browse send and trigger per-family browse on GOT_IP events ([26e8dd1e](https://github.com/espressif/esp-protocols/commit/26e8dd1e)) + +## [1.11.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.11.1) + +### Bug Fixes + +- Remove IDF tracker from sources/comments ([4870186b](https://github.com/espressif/esp-protocols/commit/4870186b)) +- Bounds check RR header and NSEC length in debug parser ([c10eb9ac](https://github.com/espressif/esp-protocols/commit/c10eb9ac)) +- Validate RDATA length for A/AAAA records ([df9644aa](https://github.com/espressif/esp-protocols/commit/df9644aa)) +- Validate second byte of DNS compression pointer ([6dd051a1](https://github.com/espressif/esp-protocols/commit/6dd051a1)) +- Minor cleanup in mdns socket layer ([37b8a7ca](https://github.com/espressif/esp-protocols/commit/37b8a7ca)) +- Fix parsing of mdns.txt records containing booleans ([a6e09518](https://github.com/espressif/esp-protocols/commit/a6e09518)) +- race conditions in async query lifecycle (IDFGH-17246) ([ab5aeaf8](https://github.com/espressif/esp-protocols/commit/ab5aeaf8), [#1010](https://github.com/espressif/esp-protocols/issues/1010)) + +## [1.11.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.11.0) + +### Features + +- Add support for mdns service discovery ([a0af8449](https://github.com/espressif/esp-protocols/commit/a0af8449)) + +### Bug Fixes + +- Use python implementation of dig utility ([0104a14a](https://github.com/espressif/esp-protocols/commit/0104a14a)) +- Fix null pointer exception in mdns_parse_packet ([56812092](https://github.com/espressif/esp-protocols/commit/56812092)) + +### Updated + +- Add null check for netif in mDNS networking ([d5a393f6](https://github.com/espressif/esp-protocols/commit/d5a393f6)) + +## [1.10.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.10.1) + +### Bug Fixes + +- correct server initialization condition in mdns_browse_new ([dcc33d69](https://github.com/espressif/esp-protocols/commit/dcc33d69)) + +## [1.10.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.10.0) + +### Features + +- support null value for boolean txt records ([63082b99](https://github.com/espressif/esp-protocols/commit/63082b99)) +- Refactor mdns library (stage #1) ([bed116d9](https://github.com/espressif/esp-protocols/commit/bed116d9)) + +### Bug Fixes + +- Fix the bug where closing the socket did not update to -1. ([6b9c5128](https://github.com/espressif/esp-protocols/commit/6b9c5128)) +- Fix to keep TXT/SRV in answers to queries ([0f6235f1](https://github.com/espressif/esp-protocols/commit/0f6235f1)) +- Create a test to check answer section for PTR/ANY ([6c2c2cd2](https://github.com/espressif/esp-protocols/commit/6c2c2cd2)) +- Fix unused variable `dcst` warning for wifi-remote chips ([f20a234f](https://github.com/espressif/esp-protocols/commit/f20a234f)) +- put srv/txt records in additional section for ptr queries ([27d43277](https://github.com/espressif/esp-protocols/commit/27d43277)) +- Host test to use hw_support include dir ([4d8d25a3](https://github.com/espressif/esp-protocols/commit/4d8d25a3)) + +## [1.9.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.9.1) + +### Bug Fixes + +- Fix to use tagged AFL image + minor format fix ([2b2f009a](https://github.com/espressif/esp-protocols/commit/2b2f009a)) +- Fix unused variable `dcst` warning for wifi-remote chips ([081eef88](https://github.com/espressif/esp-protocols/commit/081eef88)) + +## [1.9.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.9.0) + +### Features + +- support null value for boolean txt records ([fa96de3b](https://github.com/espressif/esp-protocols/commit/fa96de3b)) + +### Bug Fixes + +- Add test case for bool/NULL txt handling ([5068f221](https://github.com/espressif/esp-protocols/commit/5068f221)) +- Temporary fix for build issues on IDF master ([0197c994](https://github.com/espressif/esp-protocols/commit/0197c994)) +- Add tests for delegated answers ([487a746d](https://github.com/espressif/esp-protocols/commit/487a746d)) +- Add fuzzing into mdns CI ([af6bb1b5](https://github.com/espressif/esp-protocols/commit/af6bb1b5)) +- Host test to use hw_support include dir ([8bba3a97](https://github.com/espressif/esp-protocols/commit/8bba3a97)) +- Fixes case where we create our own malloc/free allocators, therefore we need to call mdns_mem_free and not free ([63bf7091](https://github.com/espressif/esp-protocols/commit/63bf7091)) +- put srv/txt records in additional section for ptr queries ([b7b8c5db](https://github.com/espressif/esp-protocols/commit/b7b8c5db)) + +### Updated + +- ci(common): Update test component dir for IDFv6.0 ([18418c83](https://github.com/espressif/esp-protocols/commit/18418c83)) + +## [1.8.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.8.2) + +### Bug Fixes + +- Fix parsing incorrect txt records ([8fd2c99f](https://github.com/espressif/esp-protocols/commit/8fd2c99f)) + +## [1.8.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.8.1) + +### Bug Fixes + +- Fix potential task delete race ([8ca45f34](https://github.com/espressif/esp-protocols/commit/8ca45f34)) + +## [1.8.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.8.0) + +### Features + +- Add version keys ([e01e67e7](https://github.com/espressif/esp-protocols/commit/e01e67e7)) + +### Bug Fixes + +- Reformat mdns sources per indent-cont=120 ([c7663cde](https://github.com/espressif/esp-protocols/commit/c7663cde)) + +## [1.7.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.7.0) + +### Features + +- Support user defined allocators ([88162d1f](https://github.com/espressif/esp-protocols/commit/88162d1f)) +- Allow allocate memory with configured caps ([7d29b476](https://github.com/espressif/esp-protocols/commit/7d29b476)) + +### Bug Fixes + +- Adjust some formatting per indent-cont=120 ([5b2077e3](https://github.com/espressif/esp-protocols/commit/5b2077e3)) + +## [1.6.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.6.0) + +### Features + +- support allocating mDNS task from SPIRAM ([8fcad10c](https://github.com/espressif/esp-protocols/commit/8fcad10c)) + +### Bug Fixes + +- Use correct task delete function ([eb4ab524](https://github.com/espressif/esp-protocols/commit/eb4ab524)) + +### Updated + +- ci(mdns): Fix mdns host test layers with static task creation ([0690eba3](https://github.com/espressif/esp-protocols/commit/0690eba3)) + +## [1.5.3](https://github.com/espressif/esp-protocols/commits/mdns-v1.5.3) + +### Bug Fixes + +- Fix responder to ignore only invalid queries ([cd07228f](https://github.com/espressif/esp-protocols/commit/cd07228f), [#754](https://github.com/espressif/esp-protocols/issues/754)) + +## [1.5.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.5.2) + +### Bug Fixes + +- Fix potential NULL deref when sending sub-buy ([e7273c46](https://github.com/espressif/esp-protocols/commit/e7273c46)) +- Fix _mdns_append_fqdn excessive stack usage ([bd23c233](https://github.com/espressif/esp-protocols/commit/bd23c233)) + +## [1.5.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.5.1) + +### Bug Fixes + +- Fix incorrect memory free for mdns browse ([4451a8c5](https://github.com/espressif/esp-protocols/commit/4451a8c5)) + +## [1.5.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.5.0) + +### Features + +- supported removal of subtype when updating service ([4ad88e29](https://github.com/espressif/esp-protocols/commit/4ad88e29)) + +### Bug Fixes + +- Fix zero-sized VLA clang-tidy warnings ([196198ec](https://github.com/espressif/esp-protocols/commit/196198ec)) +- Remove dead store to arg variable shared ([e838bf03](https://github.com/espressif/esp-protocols/commit/e838bf03)) +- Fix name mangling not to use strcpy() ([99b54ac3](https://github.com/espressif/esp-protocols/commit/99b54ac3)) +- Fix potential null derefernce in _mdns_execute_action() ([f5be2f41](https://github.com/espressif/esp-protocols/commit/f5be2f41)) +- Fix AFL test mock per espressif/esp-idf@a5bc08fb55c ([3d8835cf](https://github.com/espressif/esp-protocols/commit/3d8835cf)) +- Fixed potential out-of-bound interface error ([24f55ce9](https://github.com/espressif/esp-protocols/commit/24f55ce9)) +- Fixed incorrect error conversion ([8f8516cc](https://github.com/espressif/esp-protocols/commit/8f8516cc)) +- Fixed potential overflow when allocating txt data ([75a8e864](https://github.com/espressif/esp-protocols/commit/75a8e864)) +- Move MDNS_NAME_BUF_LEN to public headers ([907087c0](https://github.com/espressif/esp-protocols/commit/907087c0), [#724](https://github.com/espressif/esp-protocols/issues/724)) +- Cleanup includes in mdns.c ([68a9e148](https://github.com/espressif/esp-protocols/commit/68a9e148), [#725](https://github.com/espressif/esp-protocols/issues/725)) +- Allow advertizing service with port==0 ([827ea65f](https://github.com/espressif/esp-protocols/commit/827ea65f)) +- Fixed complier warning if MDNS_MAX_SERVICES==0 ([95377216](https://github.com/espressif/esp-protocols/commit/95377216), [#611](https://github.com/espressif/esp-protocols/issues/611)) + +## [1.4.3](https://github.com/espressif/esp-protocols/commits/mdns-v1.4.3) + +### Features + +- support zero item when update subtype ([5bd82c01](https://github.com/espressif/esp-protocols/commit/5bd82c01)) + +## [1.4.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.4.2) + +### Features + +- support update subtype ([062b8dca](https://github.com/espressif/esp-protocols/commit/062b8dca)) + +### Updated + +- chore(mdns): Add more info to idf_component.yml ([4a1cb65c](https://github.com/espressif/esp-protocols/commit/4a1cb65c)) + +## [1.4.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.4.1) + +### Features + +- Send PTR query for mdns browse when interface is ready ([010a404a](https://github.com/espressif/esp-protocols/commit/010a404a)) + +### Bug Fixes + +- Prevent deadlock when deleting a browse request ([3f48f9ea](https://github.com/espressif/esp-protocols/commit/3f48f9ea)) +- Fix use after free reported by coverity ([25b3d5fd](https://github.com/espressif/esp-protocols/commit/25b3d5fd)) +- Fixed dead-code reported by coverity ([11846c7d](https://github.com/espressif/esp-protocols/commit/11846c7d)) + +## [1.4.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.4.0) + +### Major changes + +- Fixed mdns API issues when add/remove/update records from multiple threads ([Fix services API races to directly add/remove services](https://github.com/espressif/esp-protocols/commit/8a690503)) + +### Features + +- Unit tests for add/remove/update deleg/selfhosted services ([0660ece1](https://github.com/espressif/esp-protocols/commit/0660ece1)) +- Add console command for mdns browsing ([1e8ede33](https://github.com/espressif/esp-protocols/commit/1e8ede33)) +- Console test: set instance for service ([f107dcd1](https://github.com/espressif/esp-protocols/commit/f107dcd1)) +- Console test: add subtype for service ([ee00e97b](https://github.com/espressif/esp-protocols/commit/ee00e97b)) +- Console test: set port for (delegated) srvs ([07b79abf](https://github.com/espressif/esp-protocols/commit/07b79abf)) +- Console test: add/remove TXT recs for delegated srvs ([c9a58d73](https://github.com/espressif/esp-protocols/commit/c9a58d73)) +- Console test for changing TXT records ([6b9a6ce6](https://github.com/espressif/esp-protocols/commit/6b9a6ce6)) +- Console test for add/remove delegated service APIs ([43de7e5c](https://github.com/espressif/esp-protocols/commit/43de7e5c)) +- Console test for add/remove delegated host APIs ([ce7f326a](https://github.com/espressif/esp-protocols/commit/ce7f326a)) +- Console test for lookup service APIs ([a91ead8e](https://github.com/espressif/esp-protocols/commit/a91ead8e)) +- Add linux console functional tests ([50d059af](https://github.com/espressif/esp-protocols/commit/50d059af)) +- check if the txt items is changed when browsing ([e2f0477a](https://github.com/espressif/esp-protocols/commit/e2f0477a)) + +### Bug Fixes + +- Fix mdns_delegate_hostname_add() to block until done ([2c1b1661](https://github.com/espressif/esp-protocols/commit/2c1b1661)) +- Fix API races when removing all services ([169405b5](https://github.com/espressif/esp-protocols/commit/169405b5)) +- Fix API races setting instance name for services ([643dc6d4](https://github.com/espressif/esp-protocols/commit/643dc6d4)) +- Fix API races while adding subtypes for services ([f9f234c4](https://github.com/espressif/esp-protocols/commit/f9f234c4)) +- Fix API races removing txt item for services ([3f97a822](https://github.com/espressif/esp-protocols/commit/3f97a822)) +- Fix API races adding txt item for services ([c62b920b](https://github.com/espressif/esp-protocols/commit/c62b920b)) +- Fix API races while setting txt for services ([a927bf3a](https://github.com/espressif/esp-protocols/commit/a927bf3a)) +- Fix API races while setting port for services ([99d5fb27](https://github.com/espressif/esp-protocols/commit/99d5fb27)) +- Fix services API races to directly add/remove services ([8a690503](https://github.com/espressif/esp-protocols/commit/8a690503)) +- Fix mdns mdns_lookup_service() to handle empty TXT ([d4da9cb0](https://github.com/espressif/esp-protocols/commit/d4da9cb0)) + +## [1.3.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.3.2) + +### Features + +- add check of instance when handling PTR query ([6af6ca5](https://github.com/espressif/esp-protocols/commit/6af6ca5)) + +### Bug Fixes + +- Fix of mdns afl tests ([139166c](https://github.com/espressif/esp-protocols/commit/139166c)) +- remove same protocol services with different instances ([042533a](https://github.com/espressif/esp-protocols/commit/042533a)) + +## [1.3.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.3.1) + +### Bug Fixes + +- free txt value len ([afd98bb](https://github.com/espressif/esp-protocols/commit/afd98bb)) + +## [1.3.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.3.0) + +### Features + +- add a new mdns query mode `browse` ([af330b6](https://github.com/espressif/esp-protocols/commit/af330b6)) +- Make including mdns_console KConfigurable ([27adbfe](https://github.com/espressif/esp-protocols/commit/27adbfe)) + +### Bug Fixes + +- Schedule all queued Tx packets from timer task ([d4e693e](https://github.com/espressif/esp-protocols/commit/d4e693e)) +- add lock for some common apis ([21c84bf](https://github.com/espressif/esp-protocols/commit/21c84bf)) +- fix mdns answer append while host is invalid ([7be16bc](https://github.com/espressif/esp-protocols/commit/7be16bc)) + +## [1.2.5](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.5) + +### Bug Fixes + +- Fixed build issues for targets without WiFi caps ([302b46f](https://github.com/espressif/esp-protocols/commit/302b46f)) + +## [1.2.4](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.4) + +### Bug Fixes + +- Correction on 6d2c475 MDNS_PREDEF_NETIF_ETH fix ([fc59f87c4e](https://github.com/espressif/esp-protocols/commit/fc59f87c4e)) +- fix the logic of creating pcb for networking socket ([5000a9a20a](https://github.com/espressif/esp-protocols/commit/5000a9a20a)) +- fix compiling issue when disabling IPv4 ([2646dcd23a](https://github.com/espressif/esp-protocols/commit/2646dcd23a)) +- Fix compile error when MDNS_PREDEF_NETIF_ETH is defined, but ETH_ENABLED is not (#459) ([6d2c475c20](https://github.com/espressif/esp-protocols/commit/6d2c475c20)) + +## [1.2.3](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.3) + +### Bug Fixes + +- fixed CI issues for host and afl tests ([4be5efc84e](https://github.com/espressif/esp-protocols/commit/4be5efc84e)) +- fix copy delegated host addr ([19fb36000c](https://github.com/espressif/esp-protocols/commit/19fb36000c)) +- enable CONFIG_ESP_WIFI_ENABLED if CONFIG_SOC_WIFI_SUPPORTED is also enabled (for ESP-IDF <= 5.1) ([d20a718320](https://github.com/espressif/esp-protocols/commit/d20a718320)) +- remove protocol_examples_common ([1ee9dae6bf](https://github.com/espressif/esp-protocols/commit/1ee9dae6bf)) +- move the example into a subdirectory ([d28232b9f8](https://github.com/espressif/esp-protocols/commit/d28232b9f8)) +- reference protocol_examples_common from IDF ([c83b76ea8f](https://github.com/espressif/esp-protocols/commit/c83b76ea8f)) + +## [1.2.2](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.2) + +### Bug Fixes + +- add terminator for the getting host name ([b6a4d94](https://github.com/espressif/esp-protocols/commit/b6a4d94)) +- Enable ESP_WIFI_CONFIG when ESP-IDF <= 5.1 ([0b783c0](https://github.com/espressif/esp-protocols/commit/0b783c0)) +- set host list NULL on destroy ([ea54eef](https://github.com/espressif/esp-protocols/commit/ea54eef)) +- removed Wno-format flag and fixed formatting warnings ([c48e442](https://github.com/espressif/esp-protocols/commit/c48e442)) +- remove the the range of MDNS_MAX_SERVICES and fix issues of string functions ([3dadce2](https://github.com/espressif/esp-protocols/commit/3dadce2)) + +## [1.2.1](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.1) + +### Features + +- Allow setting length of mDNS action queue in menuconfig ([28cd898](https://github.com/espressif/esp-protocols/commit/28cd898)) + +### Bug Fixes + +- fix build issue if CONFIG_ESP_WIFI_ENABLED disabled ([24f7031](https://github.com/espressif/esp-protocols/commit/24f7031)) +- added idf_component.yml for examples ([d273e10](https://github.com/espressif/esp-protocols/commit/d273e10)) +- added guard check for null pointer ([71bb461](https://github.com/espressif/esp-protocols/commit/71bb461)) + +## [1.2.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.2.0) + +### Features + +- add an API for setting address to a delegated host ([ddc3eb6](https://github.com/espressif/esp-protocols/commit/ddc3eb6)) +- Add support for lwip build under linux ([588465d](https://github.com/espressif/esp-protocols/commit/588465d)) +- Allow for adding a delegated host with no address ([c562461](https://github.com/espressif/esp-protocols/commit/c562461)) +- Add APIs for looking up self hosted services and getting the self hostname ([f0df12d](https://github.com/espressif/esp-protocols/commit/f0df12d)) + +### Bug Fixes + +- Refactor freertos linux compat layers ([79a0e57](https://github.com/espressif/esp-protocols/commit/79a0e57)) +- Fix delegated service PTR response ([cab0e1d](https://github.com/espressif/esp-protocols/commit/cab0e1d)) +- Added unit tests to CI + minor fix to pass it ([c974c14](https://github.com/espressif/esp-protocols/commit/c974c14)) + +### Updated + +- docs: update documentation links ([4de5298](https://github.com/espressif/esp-protocols/commit/4de5298)) + +## [1.1.0](https://github.com/espressif/esp-protocols/commits/mdns-v1.1.0) + +### Features + +- Decouple main module from mdns-networking ([d238e93](https://github.com/espressif/esp-protocols/commit/d238e93)) + +### Bug Fixes + +- Use idf-build-apps package for building mdns ([1a0a41f](https://github.com/espressif/esp-protocols/commit/1a0a41f)) +- socket networking to init interfaces properly ([ee9b04f](https://github.com/espressif/esp-protocols/commit/ee9b04f)) +- Removed unused internal lock from mdns_server struct ([a06fb77](https://github.com/espressif/esp-protocols/commit/a06fb77)) +- Resolve conflicts only on self hosted items ([e69a9eb](https://github.com/espressif/esp-protocols/commit/e69a9eb), [#185](https://github.com/espressif/esp-protocols/issues/185)) +- Fix memory issues reported by valgrind ([0a682e7](https://github.com/espressif/esp-protocols/commit/0a682e7)) + +### Updated + +- docs(common): updated component and example links ([f48d9b2](https://github.com/espressif/esp-protocols/commit/f48d9b2)) +- Add APIs to look up delegated services ([87dcd7d](https://github.com/espressif/esp-protocols/commit/87dcd7d)) +- Fix deadly mdns crash ([4fa3023](https://github.com/espressif/esp-protocols/commit/4fa3023)) +- docs(common): improving documentation ([ca3fce0](https://github.com/espressif/esp-protocols/commit/ca3fce0)) +- append all ipv6 address in mdns answer ([5ed3e9a](https://github.com/espressif/esp-protocols/commit/5ed3e9a)) +- test(mdns): Host tests to use IDF's esp_event_stub ([537d170](https://github.com/espressif/esp-protocols/commit/537d170)) + +## [1.0.9](https://github.com/espressif/esp-protocols/commits/mdns-v1.0.9) + +### Features + +- Add reverse lookup to the example and test ([d464ed7](https://github.com/espressif/esp-protocols/commit/d464ed7)) +- Add support for IPv6 reverse query ([d4825f5](https://github.com/espressif/esp-protocols/commit/d4825f5)) + +### Bug Fixes + +- Reintroduce missing CHANGELOGs ([200cbb3](https://github.com/espressif/esp-protocols/commit/200cbb3)) +- use semaphore instead of task notification bits (IDFGH-9380) ([73f2800](https://github.com/espressif/esp-protocols/commit/73f2800), [IDF#10754](https://github.com/espressif/esp-idf/issues/10754)) + +### Updated + +- ci(common): force scoping commit messages with components ([c55fcc0](https://github.com/espressif/esp-protocols/commit/c55fcc0)) +- Add homepage URL and License to all components ([ef3f0ee](https://github.com/espressif/esp-protocols/commit/ef3f0ee)) +- docs: fix of mdns link translation ([1c850dd](https://github.com/espressif/esp-protocols/commit/1c850dd)) +- unite all tags under common structure py test: update tags under common structure ([c6db3ea](https://github.com/espressif/esp-protocols/commit/c6db3ea)) + +## [1.0.8](https://github.com/espressif/esp-protocols/commits/b9b4a75) + +### Features + +- Add support for IPv4 reverse query ([b87bef5](https://github.com/espressif/esp-protocols/commit/b87bef5)) + +### Bug Fixes + +- Host test with IDFv5.1 ([fb8a2f0](https://github.com/espressif/esp-protocols/commit/fb8a2f0)) +- Remove strict mode as it's invalid ([d0c9070](https://github.com/espressif/esp-protocols/commit/d0c9070)) +- Allow setting instance name only after hostname set ([a8339e4](https://github.com/espressif/esp-protocols/commit/a8339e4), [#190](https://github.com/espressif/esp-protocols/issues/190)) +- Make unit test executable with pytest ([12cfcb5](https://github.com/espressif/esp-protocols/commit/12cfcb5)) +- AFL port layer per IDF-latest changes ([0247926](https://github.com/espressif/esp-protocols/commit/0247926)) + +### Updated + +- bump the component version to 1.0.8 ([b9b4a75](https://github.com/espressif/esp-protocols/commit/b9b4a75)) +- Make reverse query conditional per Kconfig ([91134f1](https://github.com/espressif/esp-protocols/commit/91134f1)) +- Added badges with version of components to the respective README files ([e4c8a59](https://github.com/espressif/esp-protocols/commit/e4c8a59)) +- fix some coverity reported issues ([c73c797](https://github.com/espressif/esp-protocols/commit/c73c797)) +- Examples: using pytest.ini from top level directory ([aee016d](https://github.com/espressif/esp-protocols/commit/aee016d)) +- mDNS: test_app pytest migration ([f71f61f](https://github.com/espressif/esp-protocols/commit/f71f61f)) +- CI: fixing the files to be complient with pre-commit hooks ([945bd17](https://github.com/espressif/esp-protocols/commit/945bd17)) +- prevent crash when hostname is null ([3498e86](https://github.com/espressif/esp-protocols/commit/3498e86)) +- Example tests integration ([a045c1c](https://github.com/espressif/esp-protocols/commit/a045c1c)) +- Replace hardcoded TTL values with named defines ([bb4c002](https://github.com/espressif/esp-protocols/commit/bb4c002)) +- Fix add_service() to report error if no-hostname ([656ab21](https://github.com/espressif/esp-protocols/commit/656ab21)) + + +## [1.0.7](https://github.com/espressif/esp-protocols/commits/088f7ac) + +### Updated + +- bump up the component version ([088f7ac](https://github.com/espressif/esp-protocols/commit/088f7ac)) +- fix IPV4 only build and also update CI configuration ([e079f8b](https://github.com/espressif/esp-protocols/commit/e079f8b)) +- add test configuration for IPV6 disabled build ([330332a](https://github.com/espressif/esp-protocols/commit/330332a)) + + +## [1.0.6](https://github.com/espressif/esp-protocols/commits/48c157b) + +### Bug Fixes + +- Example makefile to add only mdns as extra comps ([d74c296](https://github.com/espressif/esp-protocols/commit/d74c296)) +- ignore authoritative flag on reception ([415e04a](https://github.com/espressif/esp-protocols/commit/415e04a)) + +### Updated + +- fix build issue with CONFIG_LWIP_IPV6 disabled ([48c157b](https://github.com/espressif/esp-protocols/commit/48c157b)) +- fix bit order issue in DNS header flags ([c4e85bd](https://github.com/espressif/esp-protocols/commit/c4e85bd)) +- updated package version to 0.1.19 ([469f953](https://github.com/espressif/esp-protocols/commit/469f953)) + + +## [1.0.5](https://github.com/espressif/esp-protocols/commits/36de9af) + +### Features + +- Define explicit dependencies on esp-wifi ([36de9af](https://github.com/espressif/esp-protocols/commit/36de9af)) + +### Updated + +- bugfix: mdns IPv6 address convert error ([238ee96](https://github.com/espressif/esp-protocols/commit/238ee96)) + + +## [1.0.4](https://github.com/espressif/esp-protocols/commits/57afa38) + +### Updated + +- Bump asio/mdns/esp_websocket_client versions ([57afa38](https://github.com/espressif/esp-protocols/commit/57afa38)) +- ignore format warnings ([d66f9dc](https://github.com/espressif/esp-protocols/commit/d66f9dc)) +- Fix test_app build ([0b102f6](https://github.com/espressif/esp-protocols/commit/0b102f6)) + + +## [1.0.3](https://github.com/espressif/esp-protocols/commits/4868689) + +### Updated + +- Updated mDNS to explicitely use esp-eth dependency if needed ([4868689](https://github.com/espressif/esp-protocols/commit/4868689), [IDF@5e19b9c](https://github.com/espressif/esp-idf/commit/5e19b9c9518ae253d82400ab24b86af8af832425)) + + +## [1.0.2](https://github.com/espressif/esp-protocols/commits/8fe2a3a) + +### Features + +- fix bug when clean action memory ([81c219d](https://github.com/espressif/esp-protocols/commit/81c219d), [IDF@3d4deb9](https://github.com/espressif/esp-idf/commit/3d4deb972620cae8e8ce4d0050153cc6f39db372)) + +### Bug Fixes + +- add the maximum number of services ([0191d6f](https://github.com/espressif/esp-protocols/commit/0191d6f), [IDF@ba458c6](https://github.com/espressif/esp-idf/commit/ba458c69cfb2f18478d73690c289b09641c62004)) +- fix the exception when remove one of multiple service ([b26c866](https://github.com/espressif/esp-protocols/commit/b26c866), [IDF@696d733](https://github.com/espressif/esp-idf/commit/696d733eb04ee98f764dffdc82bcef51a724c9c6)) + +### Updated + +- Minor fixes here and there ([8fe2a3a](https://github.com/espressif/esp-protocols/commit/8fe2a3a)) +- mDNS: Initial version based on IDF 5.0 ([b6b20ad](https://github.com/espressif/esp-protocols/commit/b6b20ad)) +- soc: moved kconfig options out of the target component. ([4a52cf2](https://github.com/espressif/esp-protocols/commit/4a52cf2), [IDF@d287209](https://github.com/espressif/esp-idf/commit/d2872095f93ed82fb91c776081bc1d032493d93e)) +- cmake: fix issue with passing cxx_std option for GCC 11, a common workaround ([87c2699](https://github.com/espressif/esp-protocols/commit/87c2699), [IDF@ea0d212](https://github.com/espressif/esp-idf/commit/ea0d2123c806bd0ad77bc49843ee905cf9be65ff)) +- kconfig: Changed default values of bool configs - Some bool configs were using default values true and false, instead of y and n. ([eb536a7](https://github.com/espressif/esp-protocols/commit/eb536a7), [IDF@25c5c21](https://github.com/espressif/esp-idf/commit/25c5c214f38ca690b03533e12fb5a4d774c7eae0)) +- esp_netif: Remove tcpip_adapter compatibility layer ([3e93ea9](https://github.com/espressif/esp-protocols/commit/3e93ea9), [IDF@795b7ed](https://github.com/espressif/esp-idf/commit/795b7ed993784e3134195e12b0978504d83dfd56)) +- Fix copyright messages, update API descrition ([2c764b1](https://github.com/espressif/esp-protocols/commit/2c764b1), [IDF@42ba8a8](https://github.com/espressif/esp-idf/commit/42ba8a8338fd5efd82498a5989fc5c105938d447)) +- Add API to control custom network interfaces ([f836ae7](https://github.com/espressif/esp-protocols/commit/f836ae7), [IDF@b02468d](https://github.com/espressif/esp-idf/commit/b02468dc98d614f931d14cd8b5e2373ca51fb18d)) +- CI/mdns: Fix fuzzer build ([4b5f24f](https://github.com/espressif/esp-protocols/commit/4b5f24f), [IDF@98e9426](https://github.com/espressif/esp-idf/commit/98e9426b660a6e825f811cccd45a0722cc801ccd)) +- Add support for registering custom netif ([30f37c0](https://github.com/espressif/esp-protocols/commit/30f37c0), [IDF@bec42ff](https://github.com/espressif/esp-idf/commit/bec42ff85d5091d71e1cb1063bea20d7c6ac8c76)) +- Indicate interface using esp_netif in search results ([ddc58e8](https://github.com/espressif/esp-protocols/commit/ddc58e8), [IDF@f8495f1](https://github.com/espressif/esp-idf/commit/f8495f1e86de9a8e7d046bf13d0ca04775041b4c)) +- Use predefined interfaces to prepare for custom netifs ([fa951bf](https://github.com/espressif/esp-protocols/commit/fa951bf), [IDF@f90b3b7](https://github.com/espressif/esp-idf/commit/f90b3b798b446382d848f8c55c5e1653c81871cd)) +- Prepare for dynamic esp-netif support ([605d1fa](https://github.com/espressif/esp-protocols/commit/605d1fa), [IDF@f9892f7](https://github.com/espressif/esp-idf/commit/f9892f77b88ba77dc6608ba746175f6dc64a7607)) +- esp_hw_support/esp_system: Re-evaluate header inclusions and include directories ([58bf218](https://github.com/espressif/esp-protocols/commit/58bf218), [IDF@a9fda54](https://github.com/espressif/esp-idf/commit/a9fda54d39d1321005c3bc9b3cc268d0b7e9f052)) +- system: move kconfig options out of target component ([ec491ec](https://github.com/espressif/esp-protocols/commit/ec491ec), [IDF@bb88338](https://github.com/espressif/esp-idf/commit/bb88338118957c2214a4c0a33cd4a152e2e1f8ba)) +- Update to drop our own packet if bounced back ([94ae672](https://github.com/espressif/esp-protocols/commit/94ae672), [IDF@b5149e3](https://github.com/espressif/esp-idf/commit/b5149e3ee73728f790798e6757d732fe426e21c7)) +- Fix potential read behind parsed packet ([e5a3a3d](https://github.com/espressif/esp-protocols/commit/e5a3a3d), [IDF@51a5de2](https://github.com/espressif/esp-idf/commit/51a5de2525d0e82adea2e298a0edcc9b2dee5edd)) +- Fix memleak when adding delegated host ([7710ea9](https://github.com/espressif/esp-protocols/commit/7710ea9), [IDF@9cbdb87](https://github.com/espressif/esp-idf/commit/9cbdb8767bdf6e9745e895b2c5af74d0376965e7)) +- Fix null-service issue when parsing packets ([034c55e](https://github.com/espressif/esp-protocols/commit/034c55e), [IDF#8307](https://github.com/espressif/esp-idf/issues/8307), [IDF@a57be7b](https://github.com/espressif/esp-idf/commit/a57be7b7d1135ddb29f9da636e9ad315f7fa1fa7)) +- Update fuzzer test (add delegation, check memory) ([ec03fec](https://github.com/espressif/esp-protocols/commit/ec03fec), [IDF@2c10071](https://github.com/espressif/esp-idf/commit/2c1007156e01b4707b5c89d73cad05c0eef0264f)) +- Remove legacy esp_event API ([5909e9e](https://github.com/espressif/esp-protocols/commit/5909e9e), [IDF@e46aa51](https://github.com/espressif/esp-idf/commit/e46aa515bdf5606a3d868f1034774d5fc96904b8)) +- added missing includes ([82e2a5d](https://github.com/espressif/esp-protocols/commit/82e2a5d), [IDF@28d09c7](https://github.com/espressif/esp-idf/commit/28d09c7dbe145ffa6a7dd90531062d4f7669a9c8)) +- Clear notification value in mdns_hostname_set ([48e4d40](https://github.com/espressif/esp-protocols/commit/48e4d40), [IDF@83a4ddb](https://github.com/espressif/esp-idf/commit/83a4ddbd250e2b386bccabb4705d4c58c1a22bcb)) +- esp_timer: remove legacy ESP32 FRC timer implementation. ([ac6dcb6](https://github.com/espressif/esp-protocols/commit/ac6dcb6), [IDF@edb76f1](https://github.com/espressif/esp-idf/commit/edb76f14d6b3e925568ff04a87befe733ecc4517)) +- freertos: Remove legacy data types ([085dbd8](https://github.com/espressif/esp-protocols/commit/085dbd8), [IDF@57fd78f](https://github.com/espressif/esp-idf/commit/57fd78f5baf93a368a82cf4b2e00ca17ffc09115)) +- Tools: Custom baud-rate setup is not possible for IDF Monitor from menuconfig anymore ([f78e8cf](https://github.com/espressif/esp-protocols/commit/f78e8cf), [IDF@36a4011](https://github.com/espressif/esp-idf/commit/36a4011ff8985bfbae08ba0272194e6c3ef93bbf)) +- Use memcpy() for copy to support non-text TXTs ([6cdf5ee](https://github.com/espressif/esp-protocols/commit/6cdf5ee), [IDF@6aefe9c](https://github.com/espressif/esp-idf/commit/6aefe9c18563ed567d384a956cf02b6f57d6894c)) +- Support for null-value TXT records ([fcb5515](https://github.com/espressif/esp-protocols/commit/fcb5515), [IDF#8267](https://github.com/espressif/esp-idf/issues/8267), [IDF@23c2db4](https://github.com/espressif/esp-idf/commit/23c2db406dee8df09dbdba21cb7eef9fbca8bf27)) +- Fix alloc issue if TXT has empty value ([9fdbe5f](https://github.com/espressif/esp-protocols/commit/9fdbe5f), [IDF@205f6ba](https://github.com/espressif/esp-idf/commit/205f6ba8541e12d958c7c56af5a7136090f12a0e)) +- Fix random crash when defalt service instance queried ([20e6e9e](https://github.com/espressif/esp-protocols/commit/20e6e9e), [IDF@f46dffc](https://github.com/espressif/esp-idf/commit/f46dffca627e9578e49a510580f9754ec1e27e2e)) +- Fix minor memory leaks when creating services ([c588263](https://github.com/espressif/esp-protocols/commit/c588263), [IDF@fad62cc](https://github.com/espressif/esp-idf/commit/fad62cc1ed3dce63b58297172a72a489d7af2d9d)) +- Fix mDNS memory leak ([6258edf](https://github.com/espressif/esp-protocols/commit/6258edf), [IDF@119b4a9](https://github.com/espressif/esp-idf/commit/119b4a9dd12cf89cc5eaf63f8aa19730607ef30b)) +- Fix mDNS memory leak ([c8b0d5e](https://github.com/espressif/esp-protocols/commit/c8b0d5e), [IDF@f5ffd53](https://github.com/espressif/esp-idf/commit/f5ffd53aeb402afc1333a98168bb2fa35d7cdc77)) +- Use multi/uni-cast types in API ([5252b1d](https://github.com/espressif/esp-protocols/commit/5252b1d), [IDF@125c312](https://github.com/espressif/esp-idf/commit/125c3125524c71f4f48f635eda12e22fa3bca500)) +- Allow for unicast PTR queries ([4e11cc8](https://github.com/espressif/esp-protocols/commit/4e11cc8), [IDF@7eeeb01](https://github.com/espressif/esp-idf/commit/7eeeb01ea705745b027bd8bc11d2b142418e9927)) +- Fix potential null deref for ANY query type ([7af91ec](https://github.com/espressif/esp-protocols/commit/7af91ec), [IDF@99dd8ee](https://github.com/espressif/esp-idf/commit/99dd8eedb1a0e957f5f74344e3e4172e61c29ef8)) +- Make fuzzer layers compatible with llvm>=6 ([01256d3](https://github.com/espressif/esp-protocols/commit/01256d3), [IDF@1882cbe](https://github.com/espressif/esp-idf/commit/1882cbe44e6140bebb2d27dc18af06dfcb0157f5)) +- Fix copyright ([5a2d4ea](https://github.com/espressif/esp-protocols/commit/5a2d4ea), [IDF@c83678f](https://github.com/espressif/esp-idf/commit/c83678f64fe27844fc28050bde6433ccb04a0704)) +- Add mDNS miss comment ([9de3f53](https://github.com/espressif/esp-protocols/commit/9de3f53), [IDF@08e0813](https://github.com/espressif/esp-idf/commit/08e081340d9d76d1244e9f2dc527e5ae370b1fbe)) +- freertos: remove FREERTOS_ASSERT option ([bcabc8e](https://github.com/espressif/esp-protocols/commit/bcabc8e), [IDF@7255497](https://github.com/espressif/esp-idf/commit/72554971467a5edc9bd6e390cf8fe7b05e6ade81)) +- Minor err print fix in socket-networking layer ([dfb27b3](https://github.com/espressif/esp-protocols/commit/dfb27b3), [IDF@f1b8f5c](https://github.com/espressif/esp-idf/commit/f1b8f5c1023df7d649161bc76f2bcc9a8f8f4d8b)) +- unified errno format ([076c095](https://github.com/espressif/esp-protocols/commit/076c095), [IDF@87506f4](https://github.com/espressif/esp-idf/commit/87506f46e2922710f48a6b96ca75e53543ff45c4)) +- always send A/AAAA records in announcements ([7dd0bc1](https://github.com/espressif/esp-protocols/commit/7dd0bc1), [IDF@456f80b](https://github.com/espressif/esp-idf/commit/456f80b754ebd0bd74e02c7febdf461c6b573b7a)) +- filter instance name for ANY queries ([7e82a7c](https://github.com/espressif/esp-protocols/commit/7e82a7c), [IDF@5d0c473](https://github.com/espressif/esp-idf/commit/5d0c47303dd9ead0f2ad291dca1d4b7ce4e23b2b)) +- Fix potential null deref reported by fuzzer test ([ae381b7](https://github.com/espressif/esp-protocols/commit/ae381b7), [IDF@cb5653f](https://github.com/espressif/esp-idf/commit/cb5653fd940a9cd41e8554a6d753fab46e0459d7)) +- Minor fix of API description and API usage ([941dc5c](https://github.com/espressif/esp-protocols/commit/941dc5c), [IDF@c297301](https://github.com/espressif/esp-idf/commit/c297301ecc350f8315d7eaf78c72b4aba68d422a)) +- Added results count to MDNS ([525c649](https://github.com/espressif/esp-protocols/commit/525c649), [IDF@f391d61](https://github.com/espressif/esp-idf/commit/f391d610e8185631b5361dc6c844c4c04aac30b1)) +- fix mdns server instance mismatch ([f0839d9](https://github.com/espressif/esp-protocols/commit/f0839d9), [IDF@6173dd7](https://github.com/espressif/esp-idf/commit/6173dd78097216261277c20ebd92a53c68c47f89)) +- support multiple instance for mdns service txt set ([69902ea](https://github.com/espressif/esp-protocols/commit/69902ea), [IDF@50f6302](https://github.com/espressif/esp-idf/commit/50f6302c5d7c0498fa1baa6fd6129d8233971a81)) +- fix wrong PTR record count ([d0bbe88](https://github.com/espressif/esp-protocols/commit/d0bbe88), [IDF@5d3f815](https://github.com/espressif/esp-idf/commit/5d3f8157e0e481363ef93d54a29d957fc91cca86)) +- Build & config: Remove leftover files from the unsupported "make" build system ([4a9d55e](https://github.com/espressif/esp-protocols/commit/4a9d55e), [IDF@766aa57](https://github.com/espressif/esp-idf/commit/766aa5708443099f3f033b739cda0e1de101cca6)) +- Build & config: Remove the "make" build system ([be2a924](https://github.com/espressif/esp-protocols/commit/be2a924), [IDF@9c1d4f5](https://github.com/espressif/esp-idf/commit/9c1d4f5b549d6a7125e5c7c323c80d37361991cb)) +- freertos: update freertos folder structure to match upstream ([76fcd41](https://github.com/espressif/esp-protocols/commit/76fcd41), [IDF@4846222](https://github.com/espressif/esp-idf/commit/48462221029c7da4b1ea233e9e781cd57ff91c7e)) +- support service subtype ([fd8499c](https://github.com/espressif/esp-protocols/commit/fd8499c), [IDF#5508](https://github.com/espressif/esp-idf/issues/5508), [IDF@e7e8610](https://github.com/espressif/esp-idf/commit/e7e8610f563e0b8532a093ea8b803f0eb132fd0e)) +- Fix parsing non-standard queries ([38b4fe2](https://github.com/espressif/esp-protocols/commit/38b4fe2), [IDF#7694](https://github.com/espressif/esp-idf/issues/7694), [IDF@d16f9ba](https://github.com/espressif/esp-idf/commit/d16f9bade5beab3785677dd5b39ebc4e9c895008)) +- allow mutiple instances with same service type ([b266062](https://github.com/espressif/esp-protocols/commit/b266062), [IDF@b7a99f4](https://github.com/espressif/esp-idf/commit/b7a99f46587a69a2cd07e7616c3bb30b7b1a6edf)) +- Update copyright header ([5e087d8](https://github.com/espressif/esp-protocols/commit/5e087d8), [IDF@2a2b95b](https://github.com/espressif/esp-idf/commit/2a2b95b9c22bc5090d87a4f4317288b64b14fcd9)) +- Fix potential null dereference identified by fuzzer tests ([91a3d95](https://github.com/espressif/esp-protocols/commit/91a3d95), [IDF@e7dabb1](https://github.com/espressif/esp-idf/commit/e7dabb14f7c8fd9bd2bea55d8f1accc65323a1c0)) +- components/bt: move config BT_RESERVE_DRAM from bluedroid to ESP32 controller ([6d6dd2b](https://github.com/espressif/esp-protocols/commit/6d6dd2b), [IDF@b310c06](https://github.com/espressif/esp-idf/commit/b310c062cd25f249e00dd03dd27baed783921630)) +- add notification callback for async APIs ([52306e9](https://github.com/espressif/esp-protocols/commit/52306e9), [IDF@986603c](https://github.com/espressif/esp-idf/commit/986603cf07413b46c88c76c324bf500edcfb6171)) +- add more mdns result attributes ([d37ab6d](https://github.com/espressif/esp-protocols/commit/d37ab6d), [IDF@76ec76c](https://github.com/espressif/esp-idf/commit/76ec76c12c871554147343bb7141da1e5de58011)) +- Add host test using linux target ([5c55ea6](https://github.com/espressif/esp-protocols/commit/5c55ea6), [IDF@fc7e2d9](https://github.com/espressif/esp-idf/commit/fc7e2d9e908f61fb4b852cfae72aa5ff7c662ebc)) +- Implement mdns_networking using BSD sockets ([0c71c7b](https://github.com/espressif/esp-protocols/commit/0c71c7b), [IDF@73dfe84](https://github.com/espressif/esp-idf/commit/73dfe84bf295a850edfad39b6b097a71f15964dc)) +- fix crash when adding services without hostname set ([4c368c0](https://github.com/espressif/esp-protocols/commit/4c368c0), [IDF@5e98772](https://github.com/espressif/esp-idf/commit/5e98772eaf7e50d96cf2e6ecdfedcd928b61c864)) +- Fix fuzzer IDF-mock layer ([af22753](https://github.com/espressif/esp-protocols/commit/af22753), [IDF@619235c](https://github.com/espressif/esp-idf/commit/619235c2ee5a1fe8411bd2be2de8798209f95902)) +- Clean the main mdns module from lwip dependencies ([b0957e7](https://github.com/espressif/esp-protocols/commit/b0957e7), [IDF@54e3294](https://github.com/espressif/esp-idf/commit/54e329444a5dd19c51e84b5f1e16455a0f1c6225)) +- Add asynchronous query API ([47c7266](https://github.com/espressif/esp-protocols/commit/47c7266), [IDF#7090](https://github.com/espressif/esp-idf/issues/7090), [IDF@d81482d](https://github.com/espressif/esp-idf/commit/d81482d699232b22f4a5cbee2a76199a5285dadb)) +- Fix crashes reported by the fuzzer tests ([40da0d2](https://github.com/espressif/esp-protocols/commit/40da0d2), [IDF@4a2e726](https://github.com/espressif/esp-idf/commit/4a2e72677c6fb7681a7e2acd1a878d3deb114079)) +- mdns/fuzzer: Fix non-instrumentation test to reproduce fuzzer issues ([5f6b6f9](https://github.com/espressif/esp-protocols/commit/5f6b6f9), [IDF@dae8033](https://github.com/espressif/esp-idf/commit/dae803335e6bc6d9751a360cd3f675ce4027853b)) +- return ESP_OK rather than ERR_OK in API functions ([8a12082](https://github.com/espressif/esp-protocols/commit/8a12082), [IDF@2386113](https://github.com/espressif/esp-idf/commit/2386113972ee51ea93e9740d8c34bfe9289ce909)) +- fix memory leak in mdns_free when adding delegated hostnames ([46f28a8](https://github.com/espressif/esp-protocols/commit/46f28a8), [IDF@0baee93](https://github.com/espressif/esp-idf/commit/0baee932111268c4a2103e1c1adeb7d99914a937)) +- Support for One-Shot mDNS queries ([5a81eae](https://github.com/espressif/esp-protocols/commit/5a81eae), [IDF@f167238](https://github.com/espressif/esp-idf/commit/f167238fac37818aed75dc689eed54ad47528ab9)) +- allow explicit txt value length ([2ddaee2](https://github.com/espressif/esp-protocols/commit/2ddaee2), [IDF@b4e0088](https://github.com/espressif/esp-idf/commit/b4e0088b68321acc4698b01faec7e2ffbe1e37c1)) +- Fix crashes reported by the fuzzer ([27fc285](https://github.com/espressif/esp-protocols/commit/27fc285), [IDF@79ba738](https://github.com/espressif/esp-idf/commit/79ba738626d643d8c6f32bdcd455e0d2476f94c7)) +- Minor correction of the test code ([93e6efe](https://github.com/espressif/esp-protocols/commit/93e6efe), [IDF@7d76245](https://github.com/espressif/esp-idf/commit/7d762451731cb305c3b090509827740f0195a496)) +- Fix fuzzer from miss-interpreting adding services as timeouts ([bc4cda8](https://github.com/espressif/esp-protocols/commit/bc4cda8), [IDF@14099fe](https://github.com/espressif/esp-idf/commit/14099fe15efb1b0cde0a8370096c55bba62ff937)) +- fix test script delayed response ([8a8d58d](https://github.com/espressif/esp-protocols/commit/8a8d58d), [IDF@a4f2639](https://github.com/espressif/esp-idf/commit/a4f263948c35c13340b6f4b59a649c5073787d5e)) +- fix wrong SRV/PTR record handling ([402baeb](https://github.com/espressif/esp-protocols/commit/402baeb), [IDF@e613555](https://github.com/espressif/esp-idf/commit/e6135552d26480e39e11632437020535b1667b7a)) +- fix wrong service hostname after mangling ([9fa25ef](https://github.com/espressif/esp-protocols/commit/9fa25ef), [IDF@439b31d](https://github.com/espressif/esp-idf/commit/439b31d065eddfdfb6eb4cf9c00454edfebc3d9b)) +- fix empty address change announce packets ([121b525](https://github.com/espressif/esp-protocols/commit/121b525), [IDF@7bbb72d](https://github.com/espressif/esp-idf/commit/7bbb72d86540f04d37b0e2c4efb6dc66ee9c9ea0)) +- fix mdns probe/reply behavior ([418fb60](https://github.com/espressif/esp-protocols/commit/418fb60), [IDF@d2a5d25](https://github.com/espressif/esp-idf/commit/d2a5d25984432d149ca31aea4a0d177f3509dd7b)) +- make delegate host address a list ([4049b3b](https://github.com/espressif/esp-protocols/commit/4049b3b), [IDF@2d34352](https://github.com/espressif/esp-idf/commit/2d34352f3db0fa71366a838933a29138a90eb2af)) +- add remove delegate host api ([c882119](https://github.com/espressif/esp-protocols/commit/c882119), [IDF@2174693](https://github.com/espressif/esp-idf/commit/2174693096b73ce93261611c44ecba647cd01859)) +- add mdns delegation ([1eb5df9](https://github.com/espressif/esp-protocols/commit/1eb5df9), [IDF@401ff56](https://github.com/espressif/esp-idf/commit/401ff56cc1ad1d11284143a348cc0c0e4a363e98)) +- fix memory free issue when repeating the query in reply ([b62b4b3](https://github.com/espressif/esp-protocols/commit/b62b4b3), [IDF@5f244c8](https://github.com/espressif/esp-idf/commit/5f244c86f29da46c17610563a245d1663a46b439)) +- Fix of crash when wifi interface get deleted and mdns receives the packets ([4d8aec1](https://github.com/espressif/esp-protocols/commit/4d8aec1), [IDF#6973](https://github.com/espressif/esp-idf/issues/6973), [IDF@03de74a](https://github.com/espressif/esp-idf/commit/03de74a728d4b278f55e1fc30e0425483b806e80)) +- Docs: Added README.md for lwip fuzzer tests ([6d64910](https://github.com/espressif/esp-protocols/commit/6d64910), [IDF@53c18a8](https://github.com/espressif/esp-idf/commit/53c18a85db104bb37ebeadec2faf5d42d764d0f9)) +- Fixed the ip header TTL to be correctly set to 255 ([ab3fa69](https://github.com/espressif/esp-protocols/commit/ab3fa69), [IDF@5cce919](https://github.com/espressif/esp-idf/commit/5cce919cbef87f543bb9f5275b77b97b3b1ea67e)) +- Fix parsing answers with questions when instance name not set ([c3a5826](https://github.com/espressif/esp-protocols/commit/c3a5826), [IDF#6598](https://github.com/espressif/esp-idf/issues/6598), [IDF@3404945](https://github.com/espressif/esp-idf/commit/34049454dfaf5132d9b258ef4d04921befc8997b)) +- Fix the resolver to correctly parse it's own non-strict answers ([cbcbe4f](https://github.com/espressif/esp-protocols/commit/cbcbe4f), [IDF@b649603](https://github.com/espressif/esp-idf/commit/b649603a0d70ec804567f57752c3eddaed56198f)) +- Add MDNS_STRICT_MODE config option ([adc3430](https://github.com/espressif/esp-protocols/commit/adc3430), [IDF@0eee315](https://github.com/espressif/esp-idf/commit/0eee31546dd4e6df0d1c1cc2740da0675dffb4bf)) +- freertos: common config header ([c30617d](https://github.com/espressif/esp-protocols/commit/c30617d), [IDF@39cf818](https://github.com/espressif/esp-idf/commit/39cf818838b0259b3e00b3c198ad47b4add41939)) +- Removed freeRTOS dependancies from fuzzer tests ([1e5eeb1](https://github.com/espressif/esp-protocols/commit/1e5eeb1), [IDF@5571694](https://github.com/espressif/esp-idf/commit/55716945a9908e057743d69e1d59399df03e49bd)) +- mDNS: Updated APIs description and shows the warning when hostname contains domain name during the query ([22c7c0a](https://github.com/espressif/esp-protocols/commit/22c7c0a), [IDF#6590](https://github.com/espressif/esp-idf/issues/6590), [IDF@9f8d2b9](https://github.com/espressif/esp-idf/commit/9f8d2b944d2b3736a012e0dff1a8459b6941d295)) +- components: Use CONFIG_LWIP_IPV6 to strip IPv6 function in components ([1623c0e](https://github.com/espressif/esp-protocols/commit/1623c0e), [IDF@da58235](https://github.com/espressif/esp-idf/commit/da58235a0ee262ff552c5f1155d531b5c31e8de6)) +- add bound check when setting interface as duplicate ([b114ed6](https://github.com/espressif/esp-protocols/commit/b114ed6), [IDF@2b9d2c0](https://github.com/espressif/esp-idf/commit/2b9d2c06f54924b680c41ae641978c8d81612f65)) +- mDNS: Fix of text length calculation when detecting a collision ([2ffd223](https://github.com/espressif/esp-protocols/commit/2ffd223), [IDF@be0ae1e](https://github.com/espressif/esp-idf/commit/be0ae1ebbbe9fae6ecf7de09e8d50cba063b61f4)) +- global: fix sign-compare warnings ([1fe901f](https://github.com/espressif/esp-protocols/commit/1fe901f), [IDF@753a929](https://github.com/espressif/esp-idf/commit/753a9295259126217a9fe6ef1c5e9da21e9b4e28)) +- lwip: Moved default SNTP API to esp_sntp.h ([2cf9fd8](https://github.com/espressif/esp-protocols/commit/2cf9fd8), [IDF@76f6dd6](https://github.com/espressif/esp-idf/commit/76f6dd6214ca583b1a94c7c553ccac739a27f6d5)) +- Allow resolve its own non-strict answers ([89439e0](https://github.com/espressif/esp-protocols/commit/89439e0), [IDF#6190](https://github.com/espressif/esp-idf/issues/6190), [IDF@0693e17](https://github.com/espressif/esp-idf/commit/0693e172de392086b9bfd8cf1474d8d133af3298)) +- mDNS: Fix of collision detection during txt length calculation ([becd5d0](https://github.com/espressif/esp-protocols/commit/becd5d0), [IDF#6114](https://github.com/espressif/esp-idf/issues/6114), [IDF@f33772c](https://github.com/espressif/esp-idf/commit/f33772c96037c795366e60082bdbbefe2a69165f)) +- esp32c3: Apply one-liner/small changes for ESP32-C3 ([0d7a309](https://github.com/espressif/esp-protocols/commit/0d7a309), [IDF@5228d9f](https://github.com/espressif/esp-idf/commit/5228d9f9ced16118d87326f94d9f9dfd411e0be9)) +- test: fix several test build error ([1fdffbb](https://github.com/espressif/esp-protocols/commit/1fdffbb), [IDF@b7ecccd](https://github.com/espressif/esp-idf/commit/b7ecccd9010f1deaba83de54374231c3c7f5b472)) +- freertos: Add RISC-V port ([988d120](https://github.com/espressif/esp-protocols/commit/988d120), [IDF@87e13ba](https://github.com/espressif/esp-idf/commit/87e13baaf12fe6deae715d95e912a310fea4ba88)) +- Fix wrong mdns source address if lwIP IPv6 zones disabled ([fd47df3](https://github.com/espressif/esp-protocols/commit/fd47df3), [IDF@7ac9761](https://github.com/espressif/esp-idf/commit/7ac97616c119e4d2f4cdd377dfc5abbf75ec5e30)) +- Whitespace: Automated whitespace fixes (large commit) ([2cb3a6e](https://github.com/espressif/esp-protocols/commit/2cb3a6e), [IDF@66fb5a2](https://github.com/espressif/esp-idf/commit/66fb5a29bbdc2482d67c52e6f66b303378c9b789)) +- test_compile_fuzzers: Fix include paths for host build ([825652f](https://github.com/espressif/esp-protocols/commit/825652f), [IDF@98a0cc7](https://github.com/espressif/esp-idf/commit/98a0cc783f701b238bea232b53250a538d34920a)) +- CI: Add a test to pre-check fuzzer tests compilation before weekly run ([fc53888](https://github.com/espressif/esp-protocols/commit/fc53888), [IDF@637f5c0](https://github.com/espressif/esp-idf/commit/637f5c0a6842c42ee6cf7f41d3c5ae0cb28a68af)) +- soc: descriptive part occupy whole component ([7635c04](https://github.com/espressif/esp-protocols/commit/7635c04), [IDF@79887fd](https://github.com/espressif/esp-idf/commit/79887fdc6c3d9a2e509cc189bb43c998d3f0f4ee)) +- Coredump config option rename throughout IDF ([d5fe42b](https://github.com/espressif/esp-protocols/commit/d5fe42b), [IDF@20af94f](https://github.com/espressif/esp-idf/commit/20af94ff53c5147a76342800d007a6c49be50a7b)) +- mdns, dns, dhcp, dhcps: update fuzzer test to work in CI ([e0bc60a](https://github.com/espressif/esp-protocols/commit/e0bc60a), [IDF@a43c06a](https://github.com/espressif/esp-idf/commit/a43c06a592bcf9404297b22268c33bb7a246632c)) +- cmock: added cmock as component ([9772e49](https://github.com/espressif/esp-protocols/commit/9772e49), [IDF@20c068e](https://github.com/espressif/esp-idf/commit/20c068ef3b49999387896b90f8011b02f718485f)) +- Support queries in responses in mDNS non-strict mode ([6021a88](https://github.com/espressif/esp-protocols/commit/6021a88), [IDF#5521](https://github.com/espressif/esp-idf/issues/5521), [IDF@bcfa36d](https://github.com/espressif/esp-idf/commit/bcfa36db8ffff997f1f95eaf6b011ffc4d46a10f)) +- Fix include query ID in reponses ([78f71ec](https://github.com/espressif/esp-protocols/commit/78f71ec), [IDF#5574](https://github.com/espressif/esp-idf/issues/5574), [IDF@f62e321](https://github.com/espressif/esp-idf/commit/f62e321d87c1d520cccca951715c27730e06607a)) +- Allow config mDNS task stack size ([3319844](https://github.com/espressif/esp-protocols/commit/3319844), [IDF@cf7e48c](https://github.com/espressif/esp-idf/commit/cf7e48c779edd84c3f99d5e8ed81027932302382)) +- Remove mbedtls dependency ([ac70c9a](https://github.com/espressif/esp-protocols/commit/ac70c9a), [IDF@f4a4549](https://github.com/espressif/esp-idf/commit/f4a4549a344e7ff2444a188adbebbc136b47a7bb)) +- limit the GOT_IP6_EVENT to only known network interfaces ([2b7d43e](https://github.com/espressif/esp-protocols/commit/2b7d43e), [IDF@ab8cab1](https://github.com/espressif/esp-idf/commit/ab8cab1c553ee5312ef47a7dea002f2585605006)) +- esp32: add implementation of esp_timer based on TG0 LAC timer ([4eb3e89](https://github.com/espressif/esp-protocols/commit/4eb3e89), [IDF@739eb05](https://github.com/espressif/esp-idf/commit/739eb05bb97736b70507e7ebcfee58e670672d23)) +- fixed typos in the variable names and the comments ([b5e5a64](https://github.com/espressif/esp-protocols/commit/b5e5a64), [IDF@ecca39e](https://github.com/espressif/esp-idf/commit/ecca39e19f663e32e16aef2a09df15443de347e9)) +- fix preset of esp_netif ptr for local interfaces ([6713ffe](https://github.com/espressif/esp-protocols/commit/6713ffe), [IDF@09e36f9](https://github.com/espressif/esp-idf/commit/09e36f9f3354092b2a528baaaaccab28ff4774d6)) +- fixed crash on event during deinit ([817c4fd](https://github.com/espressif/esp-protocols/commit/817c4fd), [IDF@eaa2f12](https://github.com/espressif/esp-idf/commit/eaa2f12d6761710d2633b4934fe09f6f45e20f4f)) +- respond to discovery with the proper pseudo name _services._dns-sd._udp ([8f0dc6d](https://github.com/espressif/esp-protocols/commit/8f0dc6d), [IDF#4369](https://github.com/espressif/esp-idf/issues/4369), [IDF@de17a14](https://github.com/espressif/esp-idf/commit/de17a1487f8ba6f432b06199f2261132ec6e735f)) +- fixed forgotten merge conflicts in debug code ([d20666f](https://github.com/espressif/esp-protocols/commit/d20666f), [IDF@d9433ef](https://github.com/espressif/esp-idf/commit/d9433ef69223a32d05abdca543fb530f2e6679e4)) +- add missing include of esp_task.h ([662a4ce](https://github.com/espressif/esp-protocols/commit/662a4ce), [IDF@5884b80](https://github.com/espressif/esp-idf/commit/5884b80908d680874e27fa0c8b2df85b69d03dd3)) +- add configuration values for task priority, affinity and internal service timeouts ([fb1de80](https://github.com/espressif/esp-protocols/commit/fb1de80), [IDF@c6f38f0](https://github.com/espressif/esp-idf/commit/c6f38f04f8eec1aae937cc87c111609772681cb3)) +- tcpip_adapter: updated tcpip_adapter compatablity layer to include all public API and keep 100% backward compatibility update build of tcpip adapter when ethernet disabled ([1f35e9a](https://github.com/espressif/esp-protocols/commit/1f35e9a), [IDF@7f5cda1](https://github.com/espressif/esp-idf/commit/7f5cda1b825586903f85dc4ad7736b35712e46d7)) +- update mdns to use esp-netif for mdns supported services such as STA, AP, ETH ([48b819b](https://github.com/espressif/esp-protocols/commit/48b819b), [IDF@19e24fe](https://github.com/espressif/esp-idf/commit/19e24fe61ed5ea6698dfd5e1f427e783360aa846)) +- esp_netif: Introduction of esp-netif component as a replacement of tcpip_adpter ([53e2aa3](https://github.com/espressif/esp-protocols/commit/53e2aa3), [IDF@ffe043b](https://github.com/espressif/esp-idf/commit/ffe043b1a81a0f9e1cc2cfa8873e21318ec89143)) +- examples: removed ip4addr_ntoa and used prefered IP2STR for displaying IP addresses ([3cc6446](https://github.com/espressif/esp-protocols/commit/3cc6446), [IDF@ec9f245](https://github.com/espressif/esp-idf/commit/ec9f245dd35d3e8e7b19a8dec5e05e003dc21f39)) +- esp_event, mdns: fixes for CONFIG_ETH_ENABLED=n ([248b11b](https://github.com/espressif/esp-protocols/commit/248b11b), [IDF@569ad75](https://github.com/espressif/esp-idf/commit/569ad7545c32a2f1d0eff3f1e81df70fb76ad125)) +- build and link hello-world for esp32s2beta ([901124b](https://github.com/espressif/esp-protocols/commit/901124b), [IDF@84b2f9f](https://github.com/espressif/esp-idf/commit/84b2f9f14d16533c84db2210f13a24cd817e0b0a)) +- fix crash for hostname queries ([f6ff165](https://github.com/espressif/esp-protocols/commit/f6ff165), [IDF#4224](https://github.com/espressif/esp-idf/issues/4224), [IDF@3d11700](https://github.com/espressif/esp-idf/commit/3d1170031b340a231949fdc0d9c46d87af0d1b5d)) +- fix possible race condition when checking DHCP status on WIFI_EVENT_STA_CONNECTED event. ([f44c569](https://github.com/espressif/esp-protocols/commit/f44c569), [IDF@7f410a0](https://github.com/espressif/esp-idf/commit/7f410a0bcbafa85dba05807c53c3c38999506509)) +- use constant size of AAAA answer in mdns packets instead of deriving from lwip struct size, since the struct could contain also zones ([286c646](https://github.com/espressif/esp-protocols/commit/286c646), [IDF@e5e31c5](https://github.com/espressif/esp-idf/commit/e5e31c5d0172d68fd207fa31cc5d3bba82dad020)) +- esp_wifi: wifi support new event mechanism ([c70d527](https://github.com/espressif/esp-protocols/commit/c70d527), [IDF@003a987](https://github.com/espressif/esp-idf/commit/003a9872b7de69d799e9d37521cfbcaff9b37e85)) +- fix missing bye packet if services removed with mdns_service_remove_all() or mdns_free() ([7cdf96c](https://github.com/espressif/esp-protocols/commit/7cdf96c), [IDF#3660](https://github.com/espressif/esp-idf/issues/3660), [IDF@a001998](https://github.com/espressif/esp-idf/commit/a001998d5283b29ca9a374adf7cef3357b39a03a)) +- mdns_service_remove_all doesn't take an argument ([407875d](https://github.com/espressif/esp-protocols/commit/407875d), [IDF@c2764f6](https://github.com/espressif/esp-idf/commit/c2764f6fe85681cfaf5dbbe168295284f09c09cd)) +- tools: Mass fixing of empty prototypes (for -Wstrict-prototypes) ([3e753f5](https://github.com/espressif/esp-protocols/commit/3e753f5), [IDF@afbaf74](https://github.com/espressif/esp-idf/commit/afbaf74007e89d016dbade4072bf2e7a3874139a)) +- fix ignoring mdns packet with some invalid name entries in question field ([144d4ad](https://github.com/espressif/esp-protocols/commit/144d4ad), [IDF@4bd4c7c](https://github.com/espressif/esp-idf/commit/4bd4c7caf3f9ef8402c5a27ab44561537407eb60)) +- add esp_eth component ([680bad6](https://github.com/espressif/esp-protocols/commit/680bad6), [IDF@90c4827](https://github.com/espressif/esp-idf/commit/90c4827bd22aa61894a5b22b3b39247a7e44d6cf)) +- components: use new component registration api ([7fb6686](https://github.com/espressif/esp-protocols/commit/7fb6686), [IDF@9eccd7c](https://github.com/espressif/esp-idf/commit/9eccd7c0826d6cc2e9de59304d1e5f76c0063ccf)) +- fix static analysis warnings ([4912bef](https://github.com/espressif/esp-protocols/commit/4912bef), [IDF@c34de4c](https://github.com/espressif/esp-idf/commit/c34de4cba658e8331f8a3ab2f466190c7640595b)) +- added initial suite of api unit tests ([181a22e](https://github.com/espressif/esp-protocols/commit/181a22e), [IDF@e680191](https://github.com/espressif/esp-idf/commit/e6801912c5c4861f828ab1f447280628bba9a5d7)) +- mdns tests: adapt mdns fuzzer test to compile with event loop library ([4172219](https://github.com/espressif/esp-protocols/commit/4172219), [IDF@38d15cb](https://github.com/espressif/esp-idf/commit/38d15cbd637e8b8baacda9fc43e8e99d224530f5)) +- fixed mdns crashing on reception of txt packet without a corresponding service closes #2866 ([98d2c1a](https://github.com/espressif/esp-protocols/commit/98d2c1a), [IDF@af48977](https://github.com/espressif/esp-idf/commit/af48977f21cea6b18dae10b2c8b64a78acfc647f)) +- use const char* for mdns txt items types to remove warning when assigning ([84cbb1f](https://github.com/espressif/esp-protocols/commit/84cbb1f), [IDF@c050a75](https://github.com/espressif/esp-idf/commit/c050a75616803c7871ef11c060e440fae09000d9)) +- updated doxygen comments documenting mdns api ([4c6818e](https://github.com/espressif/esp-protocols/commit/4c6818e), [IDF#1718](https://github.com/espressif/esp-idf/issues/1718), [IDF@a851aac](https://github.com/espressif/esp-idf/commit/a851aac255311124529f504486ca55bad15c1951)) +- update mdns_out_question_s to be in line with mdns_parsed_question_s struct ([c440114](https://github.com/espressif/esp-protocols/commit/c440114), [IDF#1568]( https://github.com/espressif/esp-idf/issues/1568), [IDF@eddd5c4](https://github.com/espressif/esp-idf/commit/eddd5c4f2c686d9a1d6d3258569cc33752e78880)) +- use esp_event library to handle events ([6ea0ea9](https://github.com/espressif/esp-protocols/commit/6ea0ea9), [IDF@a2d5952](https://github.com/espressif/esp-idf/commit/a2d59525e53099ee1ad63c3d60ff853f573ab535)) +- fuzzer tests: update of mdns and lwip host compilation for fuzzer testing ([d9aec9f](https://github.com/espressif/esp-protocols/commit/d9aec9f), [IDF@bc60bbb](https://github.com/espressif/esp-idf/commit/bc60bbbeaf89f2bbfc5db4bd4f1e7ace81a2ab37)) +- fix possible crash when probing on particular interface with duplicated service instances due to naming conflicts on network ([985e691](https://github.com/espressif/esp-protocols/commit/985e691), [IDF@265e983](https://github.com/espressif/esp-idf/commit/265e983a452a7eaefc1662cdc0e6ed839a37fe1a)) +- enable pcbs before starting service thread to avoid updating pcb's internal variables from concurent tasks ([75deebb](https://github.com/espressif/esp-protocols/commit/75deebb), [IDF@c87f0cb](https://github.com/espressif/esp-idf/commit/c87f0cb6cad3c36b077f4aaeb1ca52fe6ed0cdaf)) +- fix possible deadlock on mdns deinit calling mdns_free() ([fdd27dc](https://github.com/espressif/esp-protocols/commit/fdd27dc), [IDF#1696](https://github.com/espressif/esp-idf/issues/1696), [IDF@48b5501](https://github.com/espressif/esp-idf/commit/48b5501c250ed90da51a55ad4fc18e09f466a517)) +- mdsn: fix race condition in updating packet data from user task when failed to allocate or queue a new service ([2ec3b55](https://github.com/espressif/esp-protocols/commit/2ec3b55), [IDF@021dc5d](https://github.com/espressif/esp-idf/commit/021dc5d453e21e2d1707f194668e69cf63ef4e84)) +- fix possible crash when packet scheduled to transmit contained service which might have been already removed ([450cbf0](https://github.com/espressif/esp-protocols/commit/450cbf0), [IDF@67051a2](https://github.com/espressif/esp-idf/commit/67051a286ba60a01d4755c3682129153c2f95953)) +- use binary semaphore instead of mutex when searching ([34f6d8d](https://github.com/espressif/esp-protocols/commit/34f6d8d), [IDF@eef0b50](https://github.com/espressif/esp-idf/commit/eef0b5090aee87efef1a6a37772b3b88c9ce8df8)) +- fix memory leak in pbuf if tcpipadapter failed to get netif ([b6efc68](https://github.com/espressif/esp-protocols/commit/b6efc68), [IDF@8462751](https://github.com/espressif/esp-idf/commit/8462751f95a3ff18bdc1b01d02fabd1829fd9135)) +- fix malfuctional query_txt ([90e4bab](https://github.com/espressif/esp-protocols/commit/90e4bab), [IDF@1a02773](https://github.com/espressif/esp-idf/commit/1a027734af06abf08fcb1c34ee65bdf50d12be4d)) +- fix possible crash when mdns_free called while action queue not empty ([c546ab8](https://github.com/espressif/esp-protocols/commit/c546ab8), [IDF@206b47c](https://github.com/espressif/esp-idf/commit/206b47c03aca0acdf40d1d9c250e18aeddfe1bd7)) +- fix memory leak when query for service receives multiple ptr entries for one instance ([6582b41](https://github.com/espressif/esp-protocols/commit/6582b41), [IDF@9a4da97](https://github.com/espressif/esp-idf/commit/9a4da97fb4b3c241998cb969a08c3a917ffb4cd1)) +- fix crash after init if no memory for task ([358d26c](https://github.com/espressif/esp-protocols/commit/358d26c), [IDF@a47768d](https://github.com/espressif/esp-idf/commit/a47768dc4e4750fd7e1c29b15d6e2dd3c76e6591)) +- fixed crash on free undefined ptr after skipped strdup ([2ac83d0](https://github.com/espressif/esp-protocols/commit/2ac83d0), [IDF@e0a8044](https://github.com/espressif/esp-idf/commit/e0a8044a16907e642001b883469618a999dbe6db)) +- Correct Kconfigs according to the coding style ([98e3171](https://github.com/espressif/esp-protocols/commit/98e3171), [IDF@37126d3](https://github.com/espressif/esp-idf/commit/37126d3451eabb44eeeb48b8e2ee554dc233e2a8)) +- fix networking running udp_sendif from lwip thread ([2f85c07](https://github.com/espressif/esp-protocols/commit/2f85c07), [IDF@f7d4a4b](https://github.com/espressif/esp-idf/commit/f7d4a4be6a9e0b0ac5edb9400d3b123dbbed2ffc)) +- fixed static memory leak ([b30a7fe](https://github.com/espressif/esp-protocols/commit/b30a7fe), [IDF@6bb68a5](https://github.com/espressif/esp-idf/commit/6bb68a5a7567a94c3605136d44960ff060c74663)) +- check all mallocs for failure and add default hook to log error with free heap ([7a4fdad](https://github.com/espressif/esp-protocols/commit/7a4fdad), [IDF@c8cb4cd](https://github.com/espressif/esp-idf/commit/c8cb4cd3c8eb56d5901ade03302ad1231d7f3de5)) +- resolve memory leak when txt record received multiple times ([b4e5742](https://github.com/espressif/esp-protocols/commit/b4e5742), [IDF@a6b2b73](https://github.com/espressif/esp-idf/commit/a6b2b73f03bbb75a39685ddba6cf877fd1e5e6d7)) +- skip sending search when finished, not properly locked timer task ([2763bcd](https://github.com/espressif/esp-protocols/commit/2763bcd), [IDF@31163f0](https://github.com/espressif/esp-idf/commit/31163f02d5c414d8b492dce6f729b43a0061581b)) +- sending search packets also in probing and announcing state ([8cd0e8a](https://github.com/espressif/esp-protocols/commit/8cd0e8a), [IDF@d16762a](https://github.com/espressif/esp-idf/commit/d16762a036e35ce86ece86bb44e6e99f9cc7c431)) +- fixed crashes on network changes ([9b3b41c](https://github.com/espressif/esp-protocols/commit/9b3b41c), [IDF@097282a](https://github.com/espressif/esp-idf/commit/097282a8e3f85958747430d9931ce0a545d37700)) +- Update network code for mDNS to work with newest LwIP ([ea23007](https://github.com/espressif/esp-protocols/commit/ea23007), [IDF@3ec0e7e](https://github.com/espressif/esp-idf/commit/3ec0e7e2d2ddea70e9f8fb5025664d0fe24c301a)) +- bugfix: mdns_service_txt_set() wasn't allocating memory for TXT records ([0c17121](https://github.com/espressif/esp-protocols/commit/0c17121), [IDF@e5e2702](https://github.com/espressif/esp-idf/commit/e5e2702ca3f63a29da57eb138f75a20c74fb2a94)) +- cmake: make main a component again ([67173f6](https://github.com/espressif/esp-protocols/commit/67173f6), [IDF@d9939ce](https://github.com/espressif/esp-idf/commit/d9939cedd9b44d63dc148354c3a0a139b9c7113d)) +- Feature/sync lwip as submodule ([fed787f](https://github.com/espressif/esp-protocols/commit/fed787f), [IDF@3578fe3](https://github.com/espressif/esp-idf/commit/3578fe39e01ba0c2d54824ac70c3276502661c6b)) +- Fix a portion of the queries are issued with the wildcard query type ([b4ab30b](https://github.com/espressif/esp-protocols/commit/b4ab30b), [IDF@f3f0445](https://github.com/espressif/esp-idf/commit/f3f0445f4db7c9ad97ae10a9728767337aa7bb62)) +- added CI job for AFL fuzzer tests ([dd71494](https://github.com/espressif/esp-protocols/commit/dd71494), [IDF@0c14764](https://github.com/espressif/esp-idf/commit/0c147648f7642d058b63fbe2ddd5de31c2326304)) +- Minor fix for mdns_service_remove() ([39de491](https://github.com/espressif/esp-protocols/commit/39de491), [IDF@5c7eb7e](https://github.com/espressif/esp-idf/commit/5c7eb7e27be7508130459d896cf7d13ffefda87f)) +- Replace all DOS line endings with Unix ([19acac7](https://github.com/espressif/esp-protocols/commit/19acac7), [IDF@a67d5d8](https://github.com/espressif/esp-idf/commit/a67d5d89e0e90390fa7ff02816a6a79008d75d40)) +- remove executable permission from source files ([98069f9](https://github.com/espressif/esp-protocols/commit/98069f9), [IDF@cb649e4](https://github.com/espressif/esp-idf/commit/cb649e452f3c64a7db1f4a61e162a16b70248204)) +- Fixed nullptr dereference in MDNS.c ([ad29d34](https://github.com/espressif/esp-protocols/commit/ad29d34), [IDF@fffbf7b](https://github.com/espressif/esp-idf/commit/fffbf7b75065b5852e064e04b0c5102dd0fc2244)) +- MDNS-Fuzzer: AFL fuzzer tests for mdsn packet parser ([9f1be36](https://github.com/espressif/esp-protocols/commit/9f1be36), [IDF@e983230](https://github.com/espressif/esp-idf/commit/e983230be933fb83cebdd1945ba6539a7dc99b28)) +- cmake: Add component dependency support ([c7701d4](https://github.com/espressif/esp-protocols/commit/c7701d4), [IDF@1cb5712](https://github.com/espressif/esp-idf/commit/1cb5712463a8963cd3e8331da90fb5e03f13575f)) +- cmake: Remove defaults for COMPONENT_SRCDIRS, COMPONENT_SRCS, COMPONENT_ADD_INCLUDEDIRS ([f1ccc40](https://github.com/espressif/esp-protocols/commit/f1ccc40), [IDF@4f1a856](https://github.com/espressif/esp-idf/commit/4f1a856dbfd752336cd71730105e02ad8c045541)) +- build system: Initial cmake support, work in progress ([84bd1d7](https://github.com/espressif/esp-protocols/commit/84bd1d7), [IDF@c671a0c](https://github.com/espressif/esp-idf/commit/c671a0c3ebf90f18576d6db55b51b62730c58301)) +- fix the bug that in mdns test code redefine esp_err_t to uint32_t, which should be int32_t ([259d3fc](https://github.com/espressif/esp-protocols/commit/259d3fc), [IDF@81e4cad](https://github.com/espressif/esp-idf/commit/81e4cad61593cde879a5c44a08060d9d336e5a3f)) +- Fix exception when service is removed while there are pending packets that depend on it ([7784d00](https://github.com/espressif/esp-protocols/commit/7784d00), [IDF@421c6f1](https://github.com/espressif/esp-idf/commit/421c6f154b10d9253b78875ab28ee6bdcaaaf3c0)) +- Fix case where service is NULL and that will cause exception ([bce7d52](https://github.com/espressif/esp-protocols/commit/bce7d52), [IDF@4fa130a](https://github.com/espressif/esp-idf/commit/4fa130ae4fb5de99ddddc5a7bed7e26ae645591c)) +- Fix issue with some mDNS parsers ([ef924f1](https://github.com/espressif/esp-protocols/commit/ef924f1), [IDF@51dde19](https://github.com/espressif/esp-idf/commit/51dde19a765533af67fc7be21f116641773a9be4)) +- Import mDNS changes ([ad8c92d](https://github.com/espressif/esp-protocols/commit/ad8c92d), [IDF@4bddbc0](https://github.com/espressif/esp-idf/commit/4bddbc031cee83935c0e4df1dc72cc7000c97ba5)) +- Fix compilation errors when using gcc-7.2.0 for the crosstool-ng toolchain ([3aa605f](https://github.com/espressif/esp-protocols/commit/3aa605f), [IDF@519edc3](https://github.com/espressif/esp-idf/commit/519edc332dae0160069fd790467cde8de78f1a0e)) +- components/mdns: wrong Message compression detect ([00a72b8](https://github.com/espressif/esp-protocols/commit/00a72b8), [IDF@6e24566](https://github.com/espressif/esp-idf/commit/6e24566186c52dc5432b6b25c81abda577c21e85)) +- fix leak after _mdns_create_service if we have a malloc error. ([907e7ee](https://github.com/espressif/esp-protocols/commit/907e7ee), [IDF@b6b36bd](https://github.com/espressif/esp-idf/commit/b6b36bd9ddf169039a5528f8b766048d97b975f7)) +- Use LwIP IPC for low-level API calls ([b367484](https://github.com/espressif/esp-protocols/commit/b367484), [IDF@713964f](https://github.com/espressif/esp-idf/commit/713964fe9e98b4fa34145c497b7ab638dc57614c)) +- Add AFL fuzz test ([4a8582f](https://github.com/espressif/esp-protocols/commit/4a8582f), [IDF@4c26227](https://github.com/espressif/esp-idf/commit/4c2622755d92efa1818d062d433725553437993c)) +- implement fixes for issues found while fuzz testing ([75de31c](https://github.com/espressif/esp-protocols/commit/75de31c), [IDF@99d3990](https://github.com/espressif/esp-idf/commit/99d39909c4f19c63909d663e927ac0a8933a3ed5)) +- add simple dns-sd meta query support ([4acf639](https://github.com/espressif/esp-protocols/commit/4acf639), [IDF@96e8a3c](https://github.com/espressif/esp-idf/commit/96e8a3c725095562d2725aaefa15adcfc5d78dd5)) +- address security issues with mDNS ([91bb509](https://github.com/espressif/esp-protocols/commit/91bb509), [IDF@c89e11c](https://github.com/espressif/esp-idf/commit/c89e11c8fa64641edddf9a055745d825ae3fab9d)) +- Initial mDNS component and example ([7fbf8e5](https://github.com/espressif/esp-protocols/commit/7fbf8e5), [IDF@dd3f18d](https://github.com/espressif/esp-idf/commit/dd3f18d2d88ee78909d4af2840dfdf0b9f715f28)) diff --git a/managed_components/espressif__mdns/CHECKSUMS.json b/managed_components/espressif__mdns/CHECKSUMS.json new file mode 100644 index 0000000..92e4671 --- /dev/null +++ b/managed_components/espressif__mdns/CHECKSUMS.json @@ -0,0 +1 @@ +{"version":"1.0","algorithm":"sha256","created_at":"2026-11-03T11:50:56.436943+00:00","files":[{"path":"README.md","size":673,"hash":"05ae92097f344b060cbf90ae21c9fe9953d53188a363f45f3ce2af945a8b6244"},{"path":"mdns_service.c","size":14856,"hash":"c58a60d91334b5989d078c349338a42fa3b483b6d54eedd9e0fb50f26ca373e9"},{"path":".cz.yaml","size":217,"hash":"79b320234fc267c09c84759d3be73040d33c108cee30228d2f490953e724bc64"},{"path":"refactor_2025.md","size":5631,"hash":"00b1c0714818028776bdd4ca9112b2982ea1e8e402e8295d59b5eaa48db87881"},{"path":"mdns_querier.c","size":31746,"hash":"08eda4456d3523c8ed991b6752dcdc8122bebd2d75b981ae0a503750f5e68cfe"},{"path":"mdns_pcb.c","size":15269,"hash":"0d87034a1cbdfa290460a14417f58895e477a4b358752b99dbab56afa4018d38"},{"path":"mdns_debug.c","size":16436,"hash":"ce32e571ddd1fbdbea6f27c5849a2a79b92caf7e5d74e69becd2dee6c4bd487d"},{"path":"mdns_responder.c","size":59343,"hash":"8f554157bc7d5beef8c51f254d2ccdc46d37bab2848c0f06044e7b65689d3a99"},{"path":"mdns_cache.c","size":44917,"hash":"bc3dd1a404267b905b4a1284e01eaacd67b2c2f3608abe506c82fad93bd04286"},{"path":"LICENSE","size":11358,"hash":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},{"path":"Kconfig","size":8100,"hash":"451ee022b744ff092e76ca1b237eb9f03cb10e15b73f92043db2af20bc91accc"},{"path":"refactoring_details.md","size":161613,"hash":"0ce37336fb27802372c2f8fc3ec452fc321525cbe923251887c302a3d8f17917"},{"path":"CHANGELOG.md","size":79448,"hash":"e83d7b46d6bdc5554c3a95b62ac04fd8b8ab219faabe3ab3aac846ff223d16c3"},{"path":"mdns_diagram.md","size":1508,"hash":"00b0441991d2a8a5a0c60c58ee88cfc32ace635fdf8f2314ad45d0096e0b2a4d"},{"path":"mdns_netif.c","size":15870,"hash":"ea1278096e31ccf09bbf5497559fbd3f7c46928d9a10284eae36a2ce51bb6054"},{"path":"CMakeLists.txt","size":3597,"hash":"82de6109edecbab515be91b7cb393e0a63bb05ed0707d63ffa68dddea06f3517"},{"path":"mdns_receive.c","size":56128,"hash":"dd9a3419df01c7829635b00543b40a0f3ee6dcd9e0cdb2d05f2620af887c6029"},{"path":"mdns_networking_lwip.c","size":11825,"hash":"adc139fa504a925ab644f21f8dce3659927f534e390a176b72b0ae3206c6a3ea"},{"path":"idf_component.yml","size":536,"hash":"5564a4eb583fe68a5a49ccf0491cb891957270bb38a2c11c6c76f85c24a8685a"},{"path":"mdns_networking_socket.c","size":19743,"hash":"84dcefa81cdbc52212a09934bdc7eb3f49fbac24c2679da0bca2103ce84961c7"},{"path":"mdns_utils.c","size":10380,"hash":"7c799fd095d2fe64d58f43efa4cf9ce99eb1b3335c84fdb5c77e36d1fb81d1ba"},{"path":"mdns_mem_caps.c","size":2407,"hash":"eeaf91732c95432c97bd44cd1211e017f5d6e9bf9d52fe13b988099a9c9fc9ad"},{"path":"mdns_console.c","size":50666,"hash":"b50bd20278b7aa7820cb6f26f5aed7171824c802e0ad8e4e889dec9f6f157507"},{"path":"mdns_send.c","size":65815,"hash":"72fb0d7ed3bd17285ec3893efcdbf4ee58bb0acc3bbe97c42de36afe58cafef2"},{"path":"mdns_browser.c","size":16535,"hash":"888b7dadc80e03fed38688524dd760a3f175b6a84142d179de973457abd11a51"},{"path":"mem_prefix_script.py","size":1370,"hash":"5320bff3afb9fca57e5a12a9a217f7d68bccc28300d4a96b6aab8aa648206575"},{"path":"include/mdns_console.h","size":308,"hash":"7b06003a193a2b602dc38e2f8d7b34c4ed3043e02c57345565f06030464d946a"},{"path":"include/mdns.h","size":48307,"hash":"991b80089a9c070fdc247dd29d8b18c0ba9e8840c34748a079efd43eb3fbab53"},{"path":"private_include/mdns_networking.h","size":1392,"hash":"07b4ac8ed569bfb500641afd90808b2988e9dc894044391ae824510a265c45aa"},{"path":"private_include/mdns_receive.h","size":441,"hash":"fff10a3f796db4b7698cef6aae625d3983978790f53730a569bb4f91c91d2d0c"},{"path":"private_include/mdns_cache.h","size":8532,"hash":"a6c5e6c327aa3018bd49dee33931f1d3d313c6341d683f5bef9b661dc1f18e7b"},{"path":"private_include/mdns_private.h","size":15058,"hash":"75301b41fc6cb6daeda2286cbe03bedd6bda87bb44247242ccf5a49296b15624"},{"path":"private_include/mdns_pcb.h","size":3609,"hash":"95bf89b3a83f0fd6f91ee33d70245117fe1788b6ff487120e2aebdf51aefb496"},{"path":"private_include/mdns_mem_caps.h","size":1483,"hash":"67f749086445e9eb9ba8d00120eca699e9b16865c1c8ccdf4449ad9cd6c9076d"},{"path":"private_include/mdns_querier.h","size":3641,"hash":"9c6b62600bca9a9a60a50d63b1ab64bead0e5f3f5f3267ce41cab06d762a3511"},{"path":"private_include/mdns_debug.h","size":1986,"hash":"9885977f8aa428c2741da28e1e0ca54f2b5ed48560b4f3070e1bd6b521f8197e"},{"path":"private_include/mdns_send.h","size":4111,"hash":"4b85ed92b8bcbb9ac2ed9024db0a6fe1bbab115a33609399b60d635de96631f2"},{"path":"private_include/mdns_responder.h","size":2103,"hash":"e1db6cca0a43d1c8f55f432b54f7990b556841b8e44f4735289a879d2a3a158b"},{"path":"private_include/mdns_service.h","size":511,"hash":"330285a5c1e0b62ada683b1ec5f67f2b9946bfb7ab06cec1d8c5dae163ca630a"},{"path":"private_include/mdns_utils.h","size":5208,"hash":"91c78111f2f3b734a7af84fb87cdc4910c79addef390bdc6695fbd63469dffc9"},{"path":"private_include/mdns_browser.h","size":3438,"hash":"867a97ae3d0aeb5e4e5c0e8c12be2b527d7797f522fec0b5a235786d68b83958"},{"path":"private_include/mdns_netif.h","size":1734,"hash":"9ab3c26a5fee95965417dfd8e6d3fa69c4b7480aec51bc19d0f86ff20eba14f2"},{"path":"tests/host_unit_test/README.md","size":2332,"hash":"3ea1496808c0454060da54905203e69bb30f09d47dd8fc81801c58aed3f837f3"},{"path":"tests/host_unit_test/main.c","size":4225,"hash":"368540106a245ec95d53e6c2b6b90a2d72a69badf7b99c32f47b56094a25c672"},{"path":"tests/host_unit_test/CMakeLists.txt","size":3087,"hash":"a8e5c212be33c0a520cebd44eb8f283a5246ea9243fa0fb77ac8c9e0011135dd"},{"path":"tests/host_unit_test/sdkconfig.defaults","size":260,"hash":"c2d9e4cd278769551762ecf101839f8378f3a5e9a6c1bda891fa83b43b01bbd4"},{"path":"tests/host_test/README.md","size":975,"hash":"168820c132bd2c276d22856e5dd533cdc0add8952da06358e19528d4a3dea3a7"},{"path":"tests/host_test/pytest_mdns.py","size":19975,"hash":"f08d7d6d56d1c114fa8995dd644e9cecdc46c7c163ced6b15d3d566e840b98af"},{"path":"tests/host_test/querier_responder.py","size":6040,"hash":"34e9f977483a3dcf13500c059c772f9bc1ebc9a78401bc72ffecb2ad2b042b2c"},{"path":"tests/host_test/sdkconfig.ci.console","size":114,"hash":"36fbd4c9edc43321f412b6704d3b1ad7ad625cf8e12a6881b1ffd09ed8d6fac2"},{"path":"tests/host_test/CMakeLists.txt","size":541,"hash":"d69a08646eb7af5535b1b4fbd78501eb1e8a18086e7db058677139e540fc9440"},{"path":"tests/host_test/bonjour_order_responder.py","size":10296,"hash":"1a96b80a567ac8b40eb06766824cac3d9088153b55d7960e9a9aa3b5461cc497"},{"path":"tests/host_test/sdkconfig.defaults","size":199,"hash":"68e2a590541166d099f182e88bf4e239c259cd79bdf516ce1d08f5a4266e7bf8"},{"path":"tests/host_test/sdkconfig.ci.target","size":26,"hash":"b5cb63deea9b1e4d616752e09fab4ed18fbb039e5f980ea26431acf1307d67cb"},{"path":"tests/host_test/dnsfixture.py","size":6758,"hash":"601e19959ff436ca1b8bea3bd07ffa33024efe67b1b1d62b84dd1e8c7d422a47"},{"path":"tests/host_test/sdkconfig.ci.app","size":127,"hash":"b1a7f50d173e21fcc01d3d45e2698e8840c87d6963e2dbb27e6c5943b9125593"},{"path":"tests/unit_test/sdkconfig.ci","size":94,"hash":"8da7589f815a526c0e9bc8291cd1e58864041b80bec592a91840a5c8847cffa6"},{"path":"tests/unit_test/CMakeLists.txt","size":490,"hash":"f334a8e3913a6da2f0d4dcbe7448c517a50a930a68a89c4a17fdc31b84ad8d2e"},{"path":"tests/unit_test/pytest_app_mdns.py","size":213,"hash":"b15b764b8d0fcf025dbe7ae4d06f0077537749fba52bef09b46ac2ebc12c82a8"},{"path":"tests/unit_test/sdkconfig.defaults","size":68,"hash":"bf225acae456eb714b977921a0e9d29bdce06d7113f5544593758357810adc56"},{"path":"tests/unit_test/main/test_mdns.c","size":19818,"hash":"5a23d7191c6744e8a05133caf567096e01208b01502fa6797450d628eb822dd0"},{"path":"tests/unit_test/main/CMakeLists.txt","size":175,"hash":"45f26ae5395a211f0499ef4dac97d1fc1ddccab75e0b2bd672aade8c170ada45"},{"path":"tests/host_test/main/main.c","size":4640,"hash":"10c3a56036bc089a8436446b20fb16722f9ed80fc4496492543b89e97d6c60ad"},{"path":"tests/host_test/main/CMakeLists.txt","size":147,"hash":"750a466f2ab682e1aff3eea846752dc5148b7e638b14ad6842bae79d96e279c5"},{"path":"tests/host_test/main/idf_component.yml","size":201,"hash":"ba446b66e793f1e609b753740c205d1cf9a7b1bad509bdbec6ef694c8401ecf5"},{"path":"tests/host_test/main/Kconfig.projbuild","size":507,"hash":"43e5370c092dcace9d05489494f8178df02adace71014f025cc465a01e2e8781"},{"path":"tests/host_test/components/esp_netif_linux/esp_netif_linux.c","size":4982,"hash":"0ead2caefe0a8b66196b37236724cb85df69f34ccf14d530fe548ff9d5094aee"},{"path":"tests/host_test/components/esp_netif_linux/Kconfig","size":257,"hash":"ac8bff8c86c8e268c11d1926ed0d70459156e00f48d9f715b856b9dbe8d9511d"},{"path":"tests/host_test/components/esp_netif_linux/CMakeLists.txt","size":314,"hash":"b57723ef05c094444d19dc123ba11aee2a5693d7685c0a5a9aaf7dfaeee7110b"},{"path":"tests/host_test/components/esp_netif_linux/include/esp_wifi_types.h","size":158,"hash":"42b1dd10e6b6a54bc6f2a3f761d096bd5bbdc7c3d0ba122110fbcd879221bd86"},{"path":"tests/host_test/components/esp_netif_linux/include/machine/endian.h","size":161,"hash":"6affb826a6caad86367e44a69e3ea901b19e6589120980ac73e31f076b782610"},{"path":"tests/host_unit_test/input/generate_cases.py","size":6224,"hash":"dceb89dcc6aa3b012bb3b6961c651ddbff09ab03399603ba551e15ccba58f954"},{"path":"tests/host_unit_test/stubs/esp_random.h","size":0,"hash":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},{"path":"tests/host_unit_test/stubs/mdns_networking.c","size":2684,"hash":"0d32592cbaf31a73ce838c9aa69eef5ec9ad93c20d070e56c62881c1021d7911"},{"path":"tests/host_unit_test/stubs/esp_assert.h","size":244,"hash":"ddbfcb413066dfa9acbcb63de0a887d1fb09e4a94cf39ba26f6c22a35b6f0942"},{"path":"tests/host_unit_test/stubs/sdkconfig.h","size":40709,"hash":"67d590c06e0e120bb048166d22236c081b058b23e97862352dc181fa4aa1e5ac"},{"path":"tests/host_unit_test/stubs/mdns_engine.c","size":1421,"hash":"94d99510cbe2ee2072b60edb7c27602ed3b4caadc12de4f8ac219e5aa2bbac06"},{"path":"tests/host_unit_test/stubs/esp_idf.c","size":2036,"hash":"f5a5c3d4ee8cf9f632c94d0194e040813b59f7b2599b07d5470d74b9cbc477a9"},{"path":"tests/host_unit_test/stubs/mdns_mem_caps.c","size":1501,"hash":"eef5e4b30ef56792b2eec00fb1750409e48991617c5e29b06e4311a2a26b3e74"},{"path":"tests/host_unit_test/stubs/mdns_mem_caps_test.h","size":207,"hash":"3c7f5f856a44d638d1ec0f8256e90b0fc5b66413ea9f78ab766479fe537160ba"},{"path":"tests/host_unit_test/stubs/mdns_test_clock.h","size":338,"hash":"2b6a38d6c4ceea52126a7dee692b20aaf07297ee7594722c9c60a77ffadc15e4"},{"path":"tests/host_unit_test/unity/create_test_packet.c","size":4728,"hash":"d7868cf2accf42c8b53334e94815f1045c357e3bb0b7c84af48780fd7571e8f3"},{"path":"tests/host_unit_test/unity/unity_main.h","size":300,"hash":"0e9d96137dfdfc42a4a6ade44e364035d7682e18f07646a093efbb2f2d3c503b"},{"path":"tests/host_unit_test/unity/unit_test.cmake","size":2128,"hash":"a9bc900561e8bc0ceac1f55d26e911b538f3068e1208bbd3f51a703dd7700bae"},{"path":"tests/host_unit_test/unity/enable_testing.cmake","size":422,"hash":"27c5432b363bf7fe61dc45f03f17f41346b3ef615fd0dadfb21c9e7a8c78938d"},{"path":"tests/host_unit_test/unity/unity_main.c","size":5025,"hash":"80397d6913ea5f876ab9815f1f7610b1d2279ee69975d9fc810e818f8aed7d46"},{"path":"tests/host_unit_test/unity/cmock_config.yml","size":285,"hash":"dea71eb95e7afdf259a605f9b8d24286dbe40627ce7cd2b81dae93393bda171d"},{"path":"tests/host_unit_test/unity/create_test_packet.h","size":1027,"hash":"418f8da9cb9d2829568320a2072d6eaf7dfaa3574689c3e7cd8ccdf10f3a1c88"},{"path":"tests/host_unit_test/unity/test_sender/unit_test.cmake","size":132,"hash":"2f59a9a1d5c95be498e367760ba66564eb7f26b6639f85142f50314ae0a7233a"},{"path":"tests/host_unit_test/unity/test_sender/test_sender.c","size":1651,"hash":"ed3514f3b3c58da1424d87ea0f93b39340c16f1a378f765614c4f76578b0ed42"},{"path":"tests/host_unit_test/unity/test_receiver/test_receiver.c","size":7981,"hash":"5250989f1a2799da74ea805ec7a863bcaf244bafe4452735bff2db1274c6bce9"},{"path":"tests/host_unit_test/unity/test_receiver/unit_test.cmake","size":163,"hash":"91c876c76954a0e6d965d0978e5a1db288d87e18a758178493a0fd8362f60da1"},{"path":"tests/host_unit_test/unity/test_browse/test_browse.c","size":12480,"hash":"ec14df28694b5b559c8fd87893de5e4d9619c12e1616d32ed2be4aef8a098165"},{"path":"tests/host_unit_test/unity/test_browse/unit_test.cmake","size":159,"hash":"b8ae91eb5321bccad9cd9c5590c4611d41f0dbece71c9023add31ab7810f759f"},{"path":"tests/host_unit_test/unity/test_cache/unit_test.cmake","size":163,"hash":"6b8d19793208abbdf5c50903de190973ef9c73a1fd64cc981364a070a7616da4"},{"path":"tests/host_unit_test/unity/test_cache/test_cache.c","size":43813,"hash":"cff0c5f7d22c735c578866dc91da1e335bec3647c92eec27cb12906a69080219"},{"path":"examples/query_advertise/sdkconfig.ci.eth_def","size":489,"hash":"e6c46e51ac75407c09b32b6361383727337ddea0275555eb82f4f7908196ca6c"},{"path":"examples/query_advertise/sdkconfig.ci.eth_no_ipv4","size":478,"hash":"e0c9f0ada36d3ede6772e5161293dcabb67aaf13bf3e88255397f435ec07f626"},{"path":"examples/query_advertise/README.md","size":4517,"hash":"6e41319d31b1bc66c4a31d68516a92986ac21beeb56eabcf0c13a5e84466e878"},{"path":"examples/query_advertise/pytest_mdns.py","size":14356,"hash":"bc600dd3ce613fa5803e825eccab4f47f4e4676ce7b977ae294ffbbcf02a837a"},{"path":"examples/query_advertise/sdkconfig.ci.eth_socket","size":521,"hash":"f3bbfa2a648d3908d7b8235d3c3d62714bcadf5aa160ae9347d285e6512e7eb1"},{"path":"examples/query_advertise/CMakeLists.txt","size":239,"hash":"d0442b76ac4c9d8bd895e06b4097d1b5b878fcc5ba5833b04221a8c630bd623c"},{"path":"examples/query_advertise/sdkconfig.ci.eth_no_ipv6","size":508,"hash":"6ec8aff6b96fbc6a3884cc7a24c9e292c7ddda4933ca708359c860d8262d8a4d"},{"path":"examples/query_advertise/sdkconfig.build_only.no_browse","size":517,"hash":"bf4627cd238585caa07e446b6a74dfc9e05a9a58add80d470227be809b365d43"},{"path":"examples/query_advertise/sdkconfig.defaults","size":42,"hash":"6653345afbb8d5c69f9bf91a74b562dd46c294a1c010a588b352e0ee57ddf1c1"},{"path":"examples/query_advertise/sdkconfig.ci.eth_custom_netif","size":683,"hash":"a5a60e353448f411de036bef4eccc399f06280419855f032df5c5d7822847e08"},{"path":"examples/query_advertise/main/mdns_example_main.c","size":14341,"hash":"c12ed545332a730a4da204d27ec47cba762cf6b5c61e49b94056692f864d4528"},{"path":"examples/query_advertise/main/CMakeLists.txt","size":88,"hash":"d02d665083ea78f8aa519b770ea9c4c348889f7c4964b5d224e4898f08fc6adb"},{"path":"examples/query_advertise/main/idf_component.yml","size":169,"hash":"868447bb1d289904ac26b54562bcc208988ac737530fc25ea8e4bef701c966ea"},{"path":"examples/query_advertise/main/Kconfig.projbuild","size":1920,"hash":"544af51bd80b0a8be3930329b3611219e95c54a58ff2947ec22a458bba5e417f"}]} \ No newline at end of file diff --git a/managed_components/espressif__mdns/CMakeLists.txt b/managed_components/espressif__mdns/CMakeLists.txt new file mode 100644 index 0000000..4996b3e --- /dev/null +++ b/managed_components/espressif__mdns/CMakeLists.txt @@ -0,0 +1,92 @@ +if(CONFIG_MDNS_NETWORKING_SOCKET) + set(MDNS_NETWORKING "mdns_networking_socket.c") +else() + set(MDNS_NETWORKING "mdns_networking_lwip.c") +endif() + +if(CONFIG_MDNS_ENABLE_CONSOLE_CLI) + set(MDNS_CONSOLE "mdns_console.c") +else() + set(MDNS_CONSOLE "") +endif() + +set(MDNS_MEMORY "mdns_mem_caps.c") + +set(MDNS_CORE "mdns_responder.c" "mdns_receive.c" "mdns_utils.c" "mdns_debug.c" "mdns_send.c" "mdns_netif.c" + "mdns_querier.c" "mdns_pcb.c" "mdns_service.c") + +if(CONFIG_MDNS_ENABLE_BROWSE) + list(APPEND MDNS_CORE "mdns_browser.c" "mdns_cache.c") +endif() + +idf_build_get_property(target IDF_TARGET) +if(${target} STREQUAL "linux") + set(dependencies esp_netif_linux esp_event) + set(private_dependencies esp_timer esp_system) + set(srcs ${MDNS_CORE} ${MDNS_MEMORY} ${MDNS_NETWORKING} ${MDNS_CONSOLE}) +else() + set(dependencies lwip esp_netif) + set(private_dependencies esp_timer) + set(srcs ${MDNS_CORE} ${MDNS_MEMORY} ${MDNS_NETWORKING} ${MDNS_CONSOLE}) +endif() + +# console is only used by mdns_console.c; declare it only when the CLI is enabled so +# builds without it do not pull console (and esp_gdbstub through it) into the build. +# Build system v2 evaluates components with sdkconfig loaded, so the requirement can +# be declared here; v1 collects requirements before sdkconfig exists, so there the +# dependency is linked after registration (see below). +if(IDF_BUILD_V2 AND CONFIG_MDNS_ENABLE_CONSOLE_CLI) + if(${target} STREQUAL "linux") + list(APPEND private_dependencies console) + else() + list(APPEND dependencies console) + endif() +endif() + +idf_component_register( + SRCS ${srcs} + INCLUDE_DIRS "include" + PRIV_INCLUDE_DIRS "private_include" + REQUIRES ${dependencies} + PRIV_REQUIRES ${private_dependencies}) + +if(${target} STREQUAL "linux") + target_link_libraries(${COMPONENT_LIB} PRIVATE "-lbsd") +endif() + +if(CONFIG_ETH_ENABLED) + idf_component_optional_requires(PRIVATE esp_eth) +endif() + +# esp_wifi is only used by the predefined STA/AP interface event handlers in +# mdns_netif.c; mirror the MDNS_ESP_WIFI_ENABLED condition used there so +# builds without Wi-Fi do not pull the Wi-Fi stack into the build. +if(NOT ${target} STREQUAL "linux") + if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER "5.1") + if(CONFIG_ESP_WIFI_ENABLED OR CONFIG_ESP_WIFI_REMOTE_ENABLED) + idf_component_optional_requires(PRIVATE esp_wifi) + endif() + elseif(CONFIG_SOC_WIFI_SUPPORTED) + # ESP_WIFI_ENABLED is not available on IDF <= 5.1 + idf_component_optional_requires(PRIVATE esp_wifi) + endif() +endif() + +# Build system v1: requirements cannot depend on sdkconfig, so when the CLI is +# enabled the project has to bring console into the build and mdns links it here. +if(CONFIG_MDNS_ENABLE_CONSOLE_CLI AND NOT IDF_BUILD_V2) + idf_build_get_property(build_components BUILD_COMPONENTS) + if(NOT console IN_LIST build_components) + message(FATAL_ERROR "CONFIG_MDNS_ENABLE_CONSOLE_CLI is enabled but the console component " + "is not in the build. Add console to the project's COMPONENTS or to a component's " + "REQUIRES, or disable CONFIG_MDNS_ENABLE_CONSOLE_CLI.") + endif() + if(${target} STREQUAL "linux") + idf_component_optional_requires(PRIVATE console) + else() + idf_component_optional_requires(PUBLIC console) + endif() +endif() + +idf_component_get_property(MDNS_VERSION ${COMPONENT_NAME} COMPONENT_VERSION) +target_compile_definitions(${COMPONENT_LIB} PUBLIC "-DESP_MDNS_VERSION_NUMBER=\"${MDNS_VERSION}\"") diff --git a/managed_components/espressif__mdns/Kconfig b/managed_components/espressif__mdns/Kconfig new file mode 100644 index 0000000..27e8d82 --- /dev/null +++ b/managed_components/espressif__mdns/Kconfig @@ -0,0 +1,218 @@ +menu "mDNS" + + config MDNS_MAX_INTERFACES + int "Max number of interfaces" + range 1 9 + default 3 + help + Number of network interfaces to be served by the mDNS library. + Lowering this number helps to reduce some static RAM usage. + + config MDNS_MAX_SERVICES + int "Max number of services" + default 10 + help + Services take up a certain amount of memory, and allowing fewer + services to be open at the same time conserves memory. Specify + the maximum amount of services here. + + config MDNS_TASK_PRIORITY + int "mDNS task priority" + range 1 255 + default 1 + help + Allows setting mDNS task priority. Please do not set the task priority + higher than priorities of system tasks. Compile time warning/error + would be emitted if the chosen task priority were too high. + + config MDNS_ACTION_QUEUE_LEN + int "Maximum actions pending to the server" + range 8 64 + default 16 + help + Allows setting the length of mDNS action queue. + + config MDNS_TASK_STACK_SIZE + int "mDNS task stack size" + default 4096 + help + Allows setting mDNS task stacksize. + + choice MDNS_TASK_AFFINITY + prompt "mDNS task affinity" + default MDNS_TASK_AFFINITY_CPU0 + help + Allows setting mDNS tasks affinity, i.e. whether the task is pinned to + CPU0, pinned to CPU1, or allowed to run on any CPU. + + config MDNS_TASK_AFFINITY_NO_AFFINITY + bool "No affinity" + config MDNS_TASK_AFFINITY_CPU0 + bool "CPU0" + config MDNS_TASK_AFFINITY_CPU1 + bool "CPU1" + depends on !FREERTOS_UNICORE + + endchoice + + config MDNS_TASK_AFFINITY + hex + default FREERTOS_NO_AFFINITY if MDNS_TASK_AFFINITY_NO_AFFINITY + default 0x0 if MDNS_TASK_AFFINITY_CPU0 + default 0x1 if MDNS_TASK_AFFINITY_CPU1 + + menu "MDNS Memory Configuration" + + choice MDNS_TASK_MEMORY_ALLOC_FROM + prompt "Select mDNS task create on which type of memory" + default MDNS_TASK_CREATE_FROM_INTERNAL + config MDNS_TASK_CREATE_FROM_SPIRAM + bool "mDNS task creates on the SPIRAM (READ HELP)" + depends on (SPIRAM_USE_CAPS_ALLOC || SPIRAM_USE_MALLOC) + help + mDNS task creates on the SPIRAM. + This option requires FreeRTOS component to allow creating + tasks on the external memory. + Please read the documentation about FREERTOS_TASK_CREATE_ALLOW_EXT_MEM + + config MDNS_TASK_CREATE_FROM_INTERNAL + bool "mDNS task creates on the internal RAM" + + endchoice + + choice MDNS_MEMORY_ALLOC_FROM + prompt "Select mDNS memory allocation type" + default MDNS_MEMORY_ALLOC_INTERNAL + + config MDNS_MEMORY_ALLOC_SPIRAM + bool "Allocate mDNS memory from SPIRAM" + depends on (SPIRAM_USE_CAPS_ALLOC || SPIRAM_USE_MALLOC) + + config MDNS_MEMORY_ALLOC_INTERNAL + bool "Allocate mDNS memory from internal RAM" + + endchoice + + config MDNS_MEMORY_CUSTOM_IMPL + bool "Implement custom memory functions" + default n + help + Enable to implement custom memory functions for mDNS library. + This option is useful when the application wants to use custom + memory allocation functions for mDNS library. + + endmenu # MDNS Memory Configuration + + config MDNS_SERVICE_ADD_TIMEOUT_MS + int "mDNS adding service timeout (ms)" + range 10 30000 + default 2000 + help + Configures timeout for adding a new mDNS service. Adding a service + fails if could not be completed within this time. + + config MDNS_TIMER_PERIOD_MS + int "mDNS timer period (ms)" + range 10 10000 + default 100 + help + Configures period of mDNS timer, which periodically transmits packets + and schedules mDNS searches. + + config MDNS_NETWORKING_SOCKET + bool "Use BSD sockets for mDNS networking" + default n + help + Enables optional mDNS networking implementation using BSD sockets + in UDP multicast mode. + This option creates a new thread to serve receiving packets (TODO). + This option uses additional N sockets, where N is number of interfaces. + + config MDNS_SKIP_SUPPRESSING_OWN_QUERIES + bool "Skip suppressing our own packets" + default n + help + Enable only if the querier and the responder share the same IP address. + This usually happens in test mode, where we may run multiple instances of + responders/queriers on the same interface. + + config MDNS_ENABLE_DEBUG_PRINTS + bool "Enable debug prints of mDNS packets" + default n + help + Enable for the library to log received and sent mDNS packets to stdout. + + config MDNS_DEBUG_USE_ESP_LOG + bool "Route debug prints to ESP_LOG" + depends on MDNS_ENABLE_DEBUG_PRINTS + default y + help + Enable this option to route debug prints to ESP_LOG, which allows more flexibility. + + config MDNS_DEBUG_BUFFER_SIZE + int "Size of temporary buffer for debug prints" + depends on MDNS_DEBUG_USE_ESP_LOG + default 1024 + help + This buffer is used to output mDNS packets in debug prints. + + config MDNS_ENABLE_CONSOLE_CLI + bool "Enable Command Line Interface on device console" + default y + help + Enable for the console cli to be available on the device. + When disabled, mdns does not depend on the console component at all. + With the IDF build system v1 the console component has to be part + of the build when this is enabled; projects that trim the component + list (COMPONENTS, EXCLUDE_COMPONENTS or MINIMAL_BUILD) need to + include it or disable this option. With build system v2 mdns + requires console itself when this is enabled. + + config MDNS_ENABLE_BROWSE + bool "Enable mDNS browse (daemon service discovery)" + default y + help + Enable continuous browse APIs (mdns_browse_new / mdns_browse_delete) + and the related receive/send paths. Disable to save ~3–4 KB of flash + when the application only advertises services or uses one-shot queries. + + config MDNS_RESPOND_REVERSE_QUERIES + bool "Enable responding to IPv4 reverse queries" + default n + help + Enables support for IPv4 reverse lookup. If enabled, the mDNS library + response to PTR queries of "A.B.C.D.in-addr.arpa" type. + + config MDNS_MULTIPLE_INSTANCE + bool "Multiple instances under the same service type" + default y + help + Enables adding multiple service instances under the same service type. + + menu "MDNS Predefined interfaces" + + config MDNS_PREDEF_NETIF_STA + bool "Use predefined interface for WiFi Station" + default y + help + Set up mDNS for the default WiFi station. + Disable this option if you do not need mDNS on default WiFi STA. + + config MDNS_PREDEF_NETIF_AP + bool "Use predefined interface for WiFi Access Point" + default y + help + Set up mDNS for the default WiFi Access Point. + Disable this option if you do not need mDNS on default WiFi AP. + + config MDNS_PREDEF_NETIF_ETH + bool "Use predefined interface for Ethernet" + depends on ETH_ENABLED + default y + help + Set up mDNS for the default Ethernet interface. + Disable this option if you do not need mDNS on default Ethernet. + + endmenu # MDNS Predefined interfaces + +endmenu diff --git a/managed_components/espressif__mdns/LICENSE b/managed_components/espressif__mdns/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/managed_components/espressif__mdns/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/managed_components/espressif__mdns/README.md b/managed_components/espressif__mdns/README.md new file mode 100644 index 0000000..a644ad4 --- /dev/null +++ b/managed_components/espressif__mdns/README.md @@ -0,0 +1,14 @@ +# mDNS Service + +[![Component Registry](https://components.espressif.com/components/espressif/mdns/badge.svg)](https://components.espressif.com/components/espressif/mdns) + +mDNS is a multicast UDP service that is used to provide local network service and host discovery. + +## Examples + +Get started with example test [Example](https://github.com/espressif/esp-protocols/tree/master/components/mdns/examples): + +## Documentation + +* View the full [documentation(English)](https://docs.espressif.com/projects/esp-protocols/mdns/docs/latest/en/index.html) +* View the full [documentation(Chinese)](https://docs.espressif.com/projects/esp-protocols/mdns/docs/latest/zh_CN/index.html) diff --git a/managed_components/espressif__mdns/examples/query_advertise/CMakeLists.txt b/managed_components/espressif__mdns/examples/query_advertise/CMakeLists.txt new file mode 100644 index 0000000..9a16f14 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/CMakeLists.txt @@ -0,0 +1,6 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(query_advertise) diff --git a/managed_components/espressif__mdns/examples/query_advertise/README.md b/managed_components/espressif__mdns/examples/query_advertise/README.md new file mode 100644 index 0000000..6ccdef9 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/README.md @@ -0,0 +1,91 @@ +# mDNS example + +Shows how to use mDNS to advertise and query services and hosts + +## Example workflow + +- mDNS is initialized with host name and instance name defined through the project configuration and `_http._tcp` service is added to be advertised +- A delegated host `esp32-delegated._local` is added and another `_http._tcp` service is added for this host. +- WiFi STA is started and trying to connect to the access point defined through the project configuration +- The system event handler is used to pass the network events to mDNS so the service is aware when the interface comes up or down +- GPIO0 (BOOT Button) is initialized as pulled-up input that can be monitored for button press +- Example task is started to check if the button is pressed so it can execute the mDNS queries defined + +### Configure the project + +* Open the project configuration menu (`idf.py menuconfig`) + +* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu +* Set `mDNS Hostname` as host name prefix for the device and its instance name in `mDNS Instance Name` +* Disable `Resolve test services` to prevent the example from querying defined names/services on startup (cause warnings in example logs, as illustrated below) + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +idf.py -p PORT flash monitor +``` + +- Wait for WiFi to connect to your access point +- You can now ping the device at `[board-hostname].local`, where `[board-hostname]` is preconfigured hostname, `esp32-mdns` by default. +- You can also browse for `_http._tcp` on the same network to find the advertised service +- Pressing the BOOT button will start querying the local network for the predefined in `check_button` hosts and services +- Note that for purpose of CI tests, configuration options of `MDNS_RESOLVE_TEST_SERVICES` and `MDNS_ADD_MAC_TO_HOSTNAME` are available, but disabled by default. If enabled, then the hostname suffix of last 3 bytes from device MAC address is added, e.g. `esp32-mdns-80FFFF`, and a query for test service is issued. + + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output +``` +I (0) cpu_start: Starting scheduler on APP CPU. +I (276) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (276) mdns-test: mdns hostname set to: [esp32-mdns] +I (286) wifi: wifi driver task: 3ffc2fa4, prio:23, stack:3584, core=0 +I (286) wifi: wifi firmware version: a3be639 +I (286) wifi: config NVS flash: enabled +I (296) wifi: config nano formating: disabled +I (296) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (306) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (336) wifi: Init dynamic tx buffer num: 32 +I (336) wifi: Init data frame dynamic rx buffer num: 32 +I (336) wifi: Init management frame dynamic rx buffer num: 32 +I (346) wifi: Init static rx buffer size: 1600 +I (346) wifi: Init static rx buffer num: 10 +I (346) wifi: Init dynamic rx buffer num: 32 +I (356) mdns-test: Setting WiFi configuration SSID myssid... +I (426) phy: phy_version: 4000, b6198fa, Sep 3 2018, 15:11:06, 0, 0 +I (426) wifi: mode : sta (30:ae:a4:80:FF:FF) +I (426) gpio: GPIO[0]| InputEn: 1| OutputEn: 0| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0 +I (1756) wifi: n:11 0, o:1 0, ap:255 255, sta:11 0, prof:1 +I (2736) wifi: state: init -> auth (b0) +I (2756) wifi: state: auth -> assoc (0) +I (2766) wifi: state: assoc -> run (10) +I (2786) wifi: connected with myssid, channel 11 +I (2786) wifi: pm start, type: 1 + +I (4786) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2 +I (21126) mdns-test: Query A: esp32.local +W (23176) mdns-test: ESP_ERR_NOT_FOUND: Host was not found! +I (23176) mdns-test: Query PTR: _arduino._tcp.local +W (26276) mdns-test: No results found! +I (26276) mdns-test: Query PTR: _http._tcp.local +1: Interface: STA, Type: V6 + PTR : HP Color LaserJet MFP M277dw (7C2E10) + SRV : NPI7C2E10.local:80 + A : 254.128.0.0 +2: Interface: STA, Type: V4 + PTR : switch4e4919 + SRV : switch4e4919.local:80 + TXT : [1] path=/config/authentication_page.htm; + A : 192.168.0.118 +I (29396) mdns-test: Query PTR: _printer._tcp.local +1: Interface: STA, Type: V6 + PTR : HP Color LaserJet MFP M277dw (7C2E10) + SRV : NPI7C2E10.local:515 + A : 254.128.0.0 +2: Interface: STA, Type: V4 + PTR : HP Color LaserJet MFP M277dw (7C2E10) +``` diff --git a/managed_components/espressif__mdns/examples/query_advertise/main/CMakeLists.txt b/managed_components/espressif__mdns/examples/query_advertise/main/CMakeLists.txt new file mode 100644 index 0000000..eb0e6d9 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "mdns_example_main.c" + INCLUDE_DIRS ".") diff --git a/managed_components/espressif__mdns/examples/query_advertise/main/Kconfig.projbuild b/managed_components/espressif__mdns/examples/query_advertise/main/Kconfig.projbuild new file mode 100644 index 0000000..18e1cc2 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/main/Kconfig.projbuild @@ -0,0 +1,55 @@ +menu "Example Configuration" + + orsource "$IDF_PATH/examples/common_components/env_caps/$IDF_TARGET/Kconfig.env_caps" + + config MDNS_HOSTNAME + string "mDNS Hostname" + default "esp32-mdns" + help + mDNS Hostname for example to use + + config MDNS_INSTANCE + string "mDNS Instance Name" + default "ESP32 with mDNS" + help + mDNS Instance Name for example to use + + config MDNS_PUBLISH_DELEGATE_HOST + bool "Publish a delegated host" + help + Enable publishing a delegated host other than ESP32. + The example will also add a mock service for this host. + + config MDNS_RESOLVE_TEST_SERVICES + bool "Resolve test services" + default n + help + Enable resolving test services on startup. + These services are advertized and evaluated in automated tests. + When executed locally, these will not be resolved and warnings appear in the log. + Please set to false to disable initial querying to avoid warnings. + + config MDNS_ADD_MAC_TO_HOSTNAME + bool "Add mac suffix to hostname" + default n + help + If enabled, a portion of MAC address is added to the hostname, this is used + for evaluation of tests in CI + + config MDNS_BUTTON_GPIO + int "Button GPIO to trigger querries" + range ENV_GPIO_RANGE_MIN ENV_GPIO_IN_RANGE_MAX + default 0 + help + Set the GPIO number used as mDNS test button + + config MDNS_ADD_CUSTOM_NETIF + bool "Add user netif to mdns service" + default n + help + If enabled, we try to add a custom netif to mdns service. + Note that for using with common connection example code, we have to disable + all predefined interfaces in mdns component setup (since we're adding one + of the default interfaces) + +endmenu diff --git a/managed_components/espressif__mdns/examples/query_advertise/main/idf_component.yml b/managed_components/espressif__mdns/examples/query_advertise/main/idf_component.yml new file mode 100644 index 0000000..f7245a2 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/main/idf_component.yml @@ -0,0 +1,6 @@ +dependencies: + espressif/mdns: + version: ^1.0.0 + idf: '>=5.0' + protocol_examples_common: + path: ${IDF_PATH}/examples/common_components/protocol_examples_common diff --git a/managed_components/espressif__mdns/examples/query_advertise/main/mdns_example_main.c b/managed_components/espressif__mdns/examples/query_advertise/main/mdns_example_main.c new file mode 100644 index 0000000..afe256e --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/main/mdns_example_main.c @@ -0,0 +1,423 @@ +/* + * SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +/* + * MDNS-SD Query and advertise Example +*/ +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_netif_ip_addr.h" +#include "esp_mac.h" +#include "esp_event.h" +#include "esp_log.h" +#include "nvs_flash.h" +#include "esp_netif.h" +#include "protocol_examples_common.h" +#include "mdns.h" +#include "driver/gpio.h" +#include "netdb.h" + +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 1, 0) +/* CONFIG_LWIP_IPV4 was introduced in IDF v5.1, set CONFIG_LWIP_IPV4 to 1 by default for IDF v5.0 */ +#ifndef CONFIG_LWIP_IPV4 +#define CONFIG_LWIP_IPV4 1 +#endif // CONFIG_LWIP_IPV4 +#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 1, 0) + +#define EXAMPLE_MDNS_INSTANCE CONFIG_MDNS_INSTANCE +#define EXAMPLE_BUTTON_GPIO CONFIG_MDNS_BUTTON_GPIO + +static const char *TAG = "mdns-test"; +static char *generate_hostname(void); + +#if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1 +static void query_mdns_host_with_gethostbyname(char *host); +static void query_mdns_host_with_getaddrinfo(char *host); +#endif + +static void initialise_mdns(void) +{ + char *hostname = generate_hostname(); + + //initialize mDNS + ESP_ERROR_CHECK(mdns_init()); + //set mDNS hostname (required if you want to advertise services) + ESP_ERROR_CHECK(mdns_hostname_set(hostname)); + ESP_LOGI(TAG, "mdns hostname set to: [%s]", hostname); + //set default mDNS instance name + ESP_ERROR_CHECK(mdns_instance_name_set(EXAMPLE_MDNS_INSTANCE)); + + //structure with TXT records + mdns_txt_item_t serviceTxtData[3] = { + {"board", "esp32"}, + {"u", "user"}, + {"p", "password"} + }; + + //initialize service + ESP_ERROR_CHECK(mdns_service_add("ESP32-WebServer", "_http", "_tcp", 80, serviceTxtData, 3)); + ESP_ERROR_CHECK(mdns_service_subtype_add_for_host("ESP32-WebServer", "_http", "_tcp", NULL, "_server")); +#if CONFIG_MDNS_MULTIPLE_INSTANCE + ESP_ERROR_CHECK(mdns_service_add("ESP32-WebServer1", "_http", "_tcp", 80, NULL, 0)); +#endif + +#if CONFIG_MDNS_PUBLISH_DELEGATE_HOST + char *delegated_hostname; + if (-1 == asprintf(&delegated_hostname, "%s-delegated", hostname)) { + abort(); + } + + mdns_ip_addr_t addr4, addr6; + esp_netif_str_to_ip4("10.0.0.1", &addr4.addr.u_addr.ip4); + addr4.addr.type = ESP_IPADDR_TYPE_V4; + esp_netif_str_to_ip6("fd11:22::1", &addr6.addr.u_addr.ip6); + addr6.addr.type = ESP_IPADDR_TYPE_V6; + addr4.next = &addr6; + addr6.next = NULL; + ESP_ERROR_CHECK(mdns_delegate_hostname_add(delegated_hostname, &addr4)); + ESP_ERROR_CHECK(mdns_service_add_for_host("test0", "_http", "_tcp", delegated_hostname, 1234, serviceTxtData, 3)); + free(delegated_hostname); +#endif // CONFIG_MDNS_PUBLISH_DELEGATE_HOST + + //add another TXT item + ESP_ERROR_CHECK(mdns_service_txt_item_set("_http", "_tcp", "path", "/foobar")); + //change TXT item value + ESP_ERROR_CHECK(mdns_service_txt_item_set_with_explicit_value_len("_http", "_tcp", "u", "admin", strlen("admin"))); + free(hostname); +} + +/* these strings match mdns_ip_protocol_t enumeration */ +static const char *ip_protocol_str[] = {"V4", "V6", "MAX"}; + +static void mdns_print_results(mdns_result_t *results) +{ + mdns_result_t *r = results; + mdns_ip_addr_t *a = NULL; + int i = 1, t; + while (r) { + if (r->esp_netif) { + printf("%d: Interface: %s, Type: %s, TTL: %" PRIu32 "\n", i++, esp_netif_get_ifkey(r->esp_netif), + ip_protocol_str[r->ip_protocol], r->ttl); + } + if (r->instance_name) { + printf(" PTR : %s.%s.%s\n", r->instance_name, r->service_type, r->proto); + } + if (r->hostname) { + printf(" SRV : %s.local:%u\n", r->hostname, r->port); + } + if (r->txt_count) { + printf(" TXT : [%zu] ", r->txt_count); + for (t = 0; t < r->txt_count; t++) { + printf("%s=%s(%d); ", r->txt[t].key, r->txt[t].value ? r->txt[t].value : "NULL", r->txt_value_len[t]); + } + printf("\n"); + } + a = r->addr; + while (a) { + if (a->addr.type == ESP_IPADDR_TYPE_V6) { + printf(" AAAA: " IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6)); + } else { + printf(" A : " IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4))); + } + a = a->next; + } + r = r->next; + } +} + +static void query_mdns_service(const char *service_name, const char *proto) +{ + ESP_LOGI(TAG, "Query PTR: %s.%s.local", service_name, proto); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query_ptr(service_name, proto, 3000, 20, &results); + if (err) { + ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); + return; + } + if (!results) { + ESP_LOGW(TAG, "No results found!"); + return; + } + + mdns_print_results(results); + mdns_query_results_free(results); +} + +#if CONFIG_MDNS_PUBLISH_DELEGATE_HOST +static void lookup_mdns_delegated_service(const char *service_name, const char *proto) +{ + ESP_LOGI(TAG, "Lookup delegated service: %s.%s.local", service_name, proto); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_lookup_delegated_service(NULL, service_name, proto, 20, &results); + if (err) { + ESP_LOGE(TAG, "Lookup Failed: %s", esp_err_to_name(err)); + return; + } + if (!results) { + ESP_LOGW(TAG, "No results found!"); + return; + } + + mdns_print_results(results); + mdns_query_results_free(results); +} +#endif // CONFIG_MDNS_PUBLISH_DELEGATE_HOST + +static void lookup_mdns_selfhosted_service(const char *service_name, const char *proto) +{ + ESP_LOGI(TAG, "Lookup selfhosted service: %s.%s.local", service_name, proto); + mdns_result_t *results = NULL; + esp_err_t err = mdns_lookup_selfhosted_service(NULL, service_name, proto, 20, &results); + if (err) { + ESP_LOGE(TAG, "Lookup Failed: %s", esp_err_to_name(err)); + return; + } + if (!results) { + ESP_LOGW(TAG, "No results found!"); + return; + } + mdns_print_results(results); + mdns_query_results_free(results); +} + +static bool check_and_print_result(mdns_search_once_t *search) +{ + // Check if any result is available + mdns_result_t *result = NULL; + if (!mdns_query_async_get_results(search, 0, &result, NULL)) { + return false; + } + + if (!result) { // search timeout, but no result + return true; + } + + // If yes, print the result + mdns_ip_addr_t *a = result->addr; + while (a) { + if (a->addr.type == ESP_IPADDR_TYPE_V6) { + printf(" AAAA: " IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6)); + } else { + printf(" A : " IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4))); + } + a = a->next; + } + // and free the result + mdns_query_results_free(result); + return true; +} + +static void query_mdns_hosts_async(const char *host_name) +{ + ESP_LOGI(TAG, "Query both A and AAA: %s.local", host_name); + + mdns_search_once_t *s_a = mdns_query_async_new(host_name, NULL, NULL, MDNS_TYPE_A, 1000, 1, NULL); + mdns_search_once_t *s_aaaa = mdns_query_async_new(host_name, NULL, NULL, MDNS_TYPE_AAAA, 1000, 1, NULL); + while (s_a || s_aaaa) { + if (s_a && check_and_print_result(s_a)) { + ESP_LOGI(TAG, "Query A %s.local finished", host_name); + mdns_query_async_delete(s_a); + s_a = NULL; + } + if (s_aaaa && check_and_print_result(s_aaaa)) { + ESP_LOGI(TAG, "Query AAAA %s.local finished", host_name); + mdns_query_async_delete(s_aaaa); + s_aaaa = NULL; + } + vTaskDelay(50 / portTICK_PERIOD_MS); + } +} +#ifdef CONFIG_LWIP_IPV4 +static void query_mdns_host(const char *host_name) +{ + ESP_LOGI(TAG, "Query A: %s.local", host_name); + + struct esp_ip4_addr addr; + addr.addr = 0; + + esp_err_t err = mdns_query_a(host_name, 2000, &addr); + if (err) { + if (err == ESP_ERR_NOT_FOUND) { + ESP_LOGW(TAG, "%s: Host was not found!", esp_err_to_name(err)); + return; + } + ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); + return; + } + + ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr)); +} +#endif // CONFIG_LWIP_IPV4 + +static void initialise_button(void) +{ + gpio_config_t io_conf = {0}; + io_conf.intr_type = GPIO_INTR_DISABLE; + io_conf.pin_bit_mask = BIT64(EXAMPLE_BUTTON_GPIO); + io_conf.mode = GPIO_MODE_INPUT; + io_conf.pull_up_en = 1; + io_conf.pull_down_en = 0; + gpio_config(&io_conf); +} + +static void check_button(void) +{ + static bool old_level = true; + bool new_level = gpio_get_level(EXAMPLE_BUTTON_GPIO); + if (!new_level && old_level) { + query_mdns_hosts_async("esp32-mdns"); +#ifdef CONFIG_LWIP_IPV4 + query_mdns_host("esp32"); +#endif + query_mdns_service("_arduino", "_tcp"); + query_mdns_service("_http", "_tcp"); + query_mdns_service("_printer", "_tcp"); + query_mdns_service("_ipp", "_tcp"); + query_mdns_service("_afpovertcp", "_tcp"); + query_mdns_service("_smb", "_tcp"); + query_mdns_service("_ftp", "_tcp"); + query_mdns_service("_nfs", "_tcp"); +#if CONFIG_MDNS_PUBLISH_DELEGATE_HOST + lookup_mdns_delegated_service("_http", "_tcp"); +#endif // CONFIG_MDNS_PUBLISH_DELEGATE_HOST + lookup_mdns_selfhosted_service("_http", "_tcp"); + } + old_level = new_level; +} + +static void mdns_example_task(void *pvParameters) +{ +#if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1 + /* Send initial queries that are started by CI tester */ +#ifdef CONFIG_LWIP_IPV4 + query_mdns_host("tinytester"); +#endif + query_mdns_host_with_gethostbyname("tinytester-lwip.local"); + query_mdns_host_with_getaddrinfo("tinytester-lwip.local"); +#endif + + while (1) { + check_button(); + vTaskDelay(50 / portTICK_PERIOD_MS); + } +} + +void app_main(void) +{ + ESP_ERROR_CHECK(nvs_flash_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + ESP_LOGI(TAG, "mDNS Ver: %s", ESP_MDNS_VERSION_NUMBER); + + initialise_mdns(); + + /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. + * Read "Establishing Wi-Fi or Ethernet Connection" section in + * examples/protocols/README.md for more information about this function. + */ + ESP_ERROR_CHECK(example_connect()); + +#if defined(CONFIG_MDNS_ADD_CUSTOM_NETIF) && !defined(CONFIG_MDNS_PREDEF_NETIF_STA) && !defined(CONFIG_MDNS_PREDEF_NETIF_ETH) + /* Demonstration of adding a custom netif to mdns service, but we're adding the default example one, + * so we must disable all predefined interfaces (PREDEF_NETIF_STA, AP and ETH) first + */ + ESP_ERROR_CHECK(mdns_register_netif(EXAMPLE_INTERFACE)); + /* It is not enough to just register the interface, we have to enable is manually. + * This is typically performed in "GOT_IP" event handler, but we call it here directly + * since the `EXAMPLE_INTERFACE` netif is connected already, to keep the example simple. + */ + ESP_ERROR_CHECK(mdns_netif_action(EXAMPLE_INTERFACE, MDNS_EVENT_ENABLE_IP4 | MDNS_EVENT_ENABLE_IP6)); + ESP_ERROR_CHECK(mdns_netif_action(EXAMPLE_INTERFACE, MDNS_EVENT_ANNOUNCE_IP4 | MDNS_EVENT_ANNOUNCE_IP6)); + +#if defined(CONFIG_MDNS_RESPOND_REVERSE_QUERIES) + ESP_ERROR_CHECK(mdns_netif_action(EXAMPLE_INTERFACE, MDNS_EVENT_IP4_REVERSE_LOOKUP | MDNS_EVENT_IP6_REVERSE_LOOKUP)); +#endif + +#endif // CONFIG_MDNS_ADD_CUSTOM_NETIF + + initialise_button(); + xTaskCreate(&mdns_example_task, "mdns_example_task", 2048, NULL, 5, NULL); +} + +/** Generate host name based on sdkconfig, optionally adding a portion of MAC address to it. + * @return host name string allocated from the heap + */ +static char *generate_hostname(void) +{ +#ifndef CONFIG_MDNS_ADD_MAC_TO_HOSTNAME + return strdup(CONFIG_MDNS_HOSTNAME); +#else + uint8_t mac[6]; + char *hostname; + esp_read_mac(mac, ESP_MAC_WIFI_STA); + if (-1 == asprintf(&hostname, "%s-%02X%02X%02X", CONFIG_MDNS_HOSTNAME, mac[3], mac[4], mac[5])) { + abort(); + } + return hostname; +#endif +} + +#if CONFIG_MDNS_RESOLVE_TEST_SERVICES == 1 +/** + * @brief Executes gethostbyname and displays list of resolved addresses. + * Note: This function is used only to test advertised mdns hostnames resolution + */ +static void query_mdns_host_with_gethostbyname(char *host) +{ + struct hostent *res = gethostbyname(host); + if (res) { + unsigned int i = 0; + while (res->h_addr_list[i] != NULL) { + ESP_LOGI(TAG, "gethostbyname: %s resolved to: %s", host, +#if defined(CONFIG_LWIP_IPV6) && defined(CONFIG_LWIP_IPV4) + res->h_addrtype == AF_INET ? inet_ntoa(*(struct in_addr *)(res->h_addr_list[i])) : + inet6_ntoa(*(struct in6_addr *)(res->h_addr_list[i])) +#elif defined(CONFIG_LWIP_IPV6) + inet6_ntoa(*(struct in6_addr *)(res->h_addr_list[i])) +#else + inet_ntoa(*(struct in_addr *)(res->h_addr_list[i])) +#endif + ); + i++; + } + } +} + +/** + * @brief Executes getaddrinfo and displays list of resolved addresses. + * Note: This function is used only to test advertised mdns hostnames resolution + */ +static void query_mdns_host_with_getaddrinfo(char *host) +{ + struct addrinfo hints; + struct addrinfo *res; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + if (!getaddrinfo(host, NULL, &hints, &res)) { + while (res) { + char *resolved_addr; +#if defined(CONFIG_LWIP_IPV6) && defined(CONFIG_LWIP_IPV4) + resolved_addr = res->ai_family == AF_INET ? + inet_ntoa(((struct sockaddr_in *) res->ai_addr)->sin_addr) : + inet6_ntoa(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr); +#elif defined(CONFIG_LWIP_IPV6) + resolved_addr = inet6_ntoa(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr); +#else + resolved_addr = inet_ntoa(((struct sockaddr_in *) res->ai_addr)->sin_addr); +#endif // CONFIG_LWIP_IPV6 + ESP_LOGI(TAG, "getaddrinfo: %s resolved to: %s", host, resolved_addr); + res = res->ai_next; + } + } +} +#endif diff --git a/managed_components/espressif__mdns/examples/query_advertise/pytest_mdns.py b/managed_components/espressif__mdns/examples/query_advertise/pytest_mdns.py new file mode 100644 index 0000000..9eb514d --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/pytest_mdns.py @@ -0,0 +1,341 @@ +# SPDX-FileCopyrightText: 2022-2026 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +import ipaddress +import os +import re +import select +import socket +import struct +import time +from threading import Event, Thread + +try: + import dpkt + import dpkt.dns +except ImportError: + pass + + +def _encode_qname(name): + """Encode a DNS QNAME (e.g. 'host.local' or '100.1.168.192.in-addr.arpa').""" + qname = b'' + for label in name.split('.'): + qname += struct.pack('B', len(label)) + label.encode() + qname += b'\x00' + return qname + + +def _decode_dns_name(data, offset, seen=None): + """Decode a DNS name from packet, handling compression. Returns (name, new_offset).""" + if seen is None: + seen = set() + labels = [] + while offset < len(data): + if offset in seen: + break + length = data[offset] + if length == 0: + return ('.'.join(labels), offset + 1) + if (length & 0xC0) == 0xC0: + ptr = struct.unpack('!H', data[offset:offset + 2])[0] & 0x3FFF + if ptr < len(data) and ptr not in seen: + seen.add(ptr) + subname, _ = _decode_dns_name(data, ptr, seen) + return ('.'.join(labels) + ('.' + subname if labels else subname), offset + 2) + return ('.'.join(labels), offset + 2) + seen.add(offset) + offset += 1 + if offset + length <= len(data): + labels.append(data[offset:offset + length].decode('utf-8', errors='replace')) + offset += length + return ('.'.join(labels), offset) + + +def run_one_shot_query(name, qtype='A', server='224.0.0.251', port=5353, timeout=5, retries=3): + """ + Pure-python single-shot DNS query to a multicast address (replaces dig +short). + For qtype='A': name is hostname (e.g. 'esp32.local'), returns bytes with IP(s). + For qtype='PTR': name is reverse format (e.g. '100.1.168.192.in-addr.arpa'), returns bytes with hostname(s). + """ + qtype_val = 1 if qtype == 'A' else 12 # A=1, PTR=12 + tx_id = struct.pack('!H', os.getpid() & 0xFFFF) + flags = struct.pack('!H', 0x0000) + counts = struct.pack('!HHHH', 1, 0, 0, 0) + qname = _encode_qname(name) + qtype_pack = struct.pack('!H', qtype_val) + qclass = struct.pack('!H', 1) # IN + query = tx_id + flags + counts + qname + qtype_pack + qclass + + print('run_one_shot_query: {} qtype={} -> {}:{}'.format(name, qtype, server, port)) + + for attempt in range(1, retries + 1): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + sock.setblocking(False) + sock.bind(('0.0.0.0', 0)) + sock.sendto(query, (server, port)) + + deadline = time.time() + timeout + while time.time() < deadline: + remaining = max(0.1, deadline - time.time()) + ready, _, _ = select.select([sock], [], [], min(remaining, 1.0)) + if not ready: + continue + data, addr = sock.recvfrom(4096) + + if len(data) < 12: + continue + + ancount = struct.unpack('!H', data[6:8])[0] + offset = 12 + qdcount = struct.unpack('!H', data[4:6])[0] + for _ in range(qdcount): + while offset < len(data): + length = data[offset] + if length == 0: + offset += 1 + break + if (length & 0xC0) == 0xC0: + offset += 2 + break + offset += 1 + length + offset += 4 + + results = [] + for _ in range(ancount): + if offset >= len(data): + break + if (data[offset] & 0xC0) == 0xC0: + offset += 2 + else: + while offset < len(data) and data[offset] != 0: + offset += 1 + data[offset] + offset += 1 + + if offset + 10 > len(data): + break + rtype = struct.unpack('!H', data[offset:offset + 2])[0] + rdlength = struct.unpack('!H', data[offset + 8:offset + 10])[0] + offset += 10 + + if qtype == 'A' and rtype == 1 and rdlength == 4 and offset + 4 <= len(data): + ip = socket.inet_ntoa(data[offset:offset + 4]) + results.append(ip) + elif qtype == 'PTR' and rtype == 12 and offset + rdlength <= len(data): + ptr_name, _ = _decode_dns_name(data, offset) + results.append(ptr_name.rstrip('.')) + offset += rdlength + + if results: + if qtype == 'A': + output = '\n'.join(results) + '\n' + else: + output = '\n'.join(results) + '\n' + print(' resolved: {}'.format(', '.join(results))) + return output.encode('utf-8') + + print(' attempt {} timed out after {}s'.format(attempt, timeout)) + except Exception as e: + print(' attempt {} exception: {}'.format(attempt, e)) + finally: + sock.close() + + print(' all {} attempts failed'.format(retries)) + return b'' + + +def _ip_to_reverse_name(ip_address): + """Convert IP address to reverse DNS query name (e.g. 192.168.1.100 -> 100.1.168.192.in-addr.arpa).""" + if ':' in ip_address: + addr = ipaddress.ip_address(ip_address) + rev = addr.reverse_pointer # e.g. 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. + return rev.rstrip('.') + parts = ip_address.split('.') + return '.'.join(reversed(parts)) + '.in-addr.arpa' + + +def get_dns_query_for_esp(esp_host): + dns = dpkt.dns.DNS( + b'\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01' + ) + dns.qd[0].name = esp_host + u'.local' + print('Created query for esp host: {} '.format(dns.__repr__())) + return dns.pack() + + +def get_dns_answer_to_mdns(tester_host): + dns = dpkt.dns.DNS( + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + ) + dns.op = dpkt.dns.DNS_QR | dpkt.dns.DNS_AA + dns.rcode = dpkt.dns.DNS_RCODE_NOERR + arr = dpkt.dns.DNS.RR() + arr.cls = dpkt.dns.DNS_IN + arr.type = dpkt.dns.DNS_A + arr.name = tester_host + arr.ip = socket.inet_aton('127.0.0.1') + dns.an.append(arr) + print('Created answer to mdns query: {} '.format(dns.__repr__())) + return dns.pack() + + +def get_dns_answer_to_mdns_lwip(tester_host, id): + dns = dpkt.dns.DNS( + b'\x5e\x39\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00\x0a\x64\x61\x76\x69\x64' + b'\x2d\x63\x6f\x6d\x70\x05\x6c\x6f\x63\x61\x6c\x00\x00\x01\x00\x01\xc0\x0c' + b'\x00\x01\x00\x01\x00\x00\x00\x0a\x00\x04\xc0\xa8\x0a\x6c') + dns.qd[0].name = tester_host + dns.an[0].name = tester_host + dns.an[0].ip = socket.inet_aton('127.0.0.1') + dns.an[0].rdata = socket.inet_aton('127.0.0.1') + dns.id = id + print('Created answer to mdns (lwip) query: {} '.format(dns.__repr__())) + return dns.pack() + + +def mdns_server(esp_host, events): + UDP_IP = '0.0.0.0' + UDP_PORT = 5353 + MCAST_GRP = '224.0.0.251' + TESTER_NAME = u'tinytester.local' + TESTER_NAME_LWIP = u'tinytester-lwip.local' + QUERY_TIMEOUT = 0.2 + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + sock.setblocking(False) + sock.bind((UDP_IP, UDP_PORT)) + mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) + last_query_timepoint = time.time() + while not events['stop'].is_set(): + try: + current_time = time.time() + if current_time - last_query_timepoint > QUERY_TIMEOUT: + last_query_timepoint = current_time + if not events['esp_answered'].is_set(): + sock.sendto(get_dns_query_for_esp(esp_host), + (MCAST_GRP, UDP_PORT)) + if not events['esp_delegated_answered'].is_set(): + sock.sendto(get_dns_query_for_esp(esp_host + '-delegated'), + (MCAST_GRP, UDP_PORT)) + timeout = max( + 0, QUERY_TIMEOUT - (current_time - last_query_timepoint)) + read_socks, _, _ = select.select([sock], [], [], timeout) + if not read_socks: + continue + data, addr = sock.recvfrom(1024) + dns = dpkt.dns.DNS(data) + if len(dns.qd) > 0: + for dns_query in dns.qd: + if dns_query.type == dpkt.dns.DNS_A: + if dns_query.name == TESTER_NAME: + print('Received query: {} '.format(dns.__repr__())) + sock.sendto(get_dns_answer_to_mdns(TESTER_NAME), + (MCAST_GRP, UDP_PORT)) + elif dns_query.name == TESTER_NAME_LWIP: + print('Received query: {} '.format(dns.__repr__())) + sock.sendto( + get_dns_answer_to_mdns_lwip(TESTER_NAME_LWIP, dns.id), + addr) + if len(dns.an) > 0: + for dns_answer in dns.an: + if dns_answer.type == dpkt.dns.DNS_A: + print('Received answer from {}'.format(dns_answer.name)) + if dns_answer.name == esp_host + u'.local': + print('Received answer to esp32-mdns query: {}'.format( + dns.__repr__())) + events['esp_answered'].set() + if dns_answer.name == esp_host + u'-delegated.local': + print('Received answer to esp32-mdns-delegate query: {}'.format( + dns.__repr__())) + events['esp_delegated_answered'].set() + except socket.timeout: + break + except dpkt.UnpackError: + continue + + +def test_examples_protocol_mdns(dut): + """ + steps: | + 1. obtain IP address + init mdns example + 2. get the dut host name (and IP address) + 3. check the mdns name is accessible + 4. check DUT output if mdns advertized host is resolved + 5. check if DUT responds to dig + 6. check the DUT is searchable via reverse IP lookup + """ + + specific_host = dut.expect(r'mdns hostname set to: \[(.*?)\]')[1].decode() + + mdns_server_events = { + 'stop': Event(), + 'esp_answered': Event(), + 'esp_delegated_answered': Event() + } + mdns_responder = Thread(target=mdns_server, + args=(str(specific_host), mdns_server_events)) + ip_addresses = [] + if dut.app.sdkconfig.get('LWIP_IPV4') is True: + ipv4 = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', + timeout=30)[1].decode() + ip_addresses.append(ipv4) + if dut.app.sdkconfig.get('LWIP_IPV6') is True: + ipv6_r = r':'.join((r'[0-9a-fA-F]{4}', ) * 8) + ipv6 = dut.expect(ipv6_r, timeout=30)[0].decode() + ip_addresses.append(ipv6) + print('Connected with IP addresses: {}'.format(','.join(ip_addresses))) + try: + # TODO: Add test for example disabling IPV4 + mdns_responder.start() + if dut.app.sdkconfig.get('LWIP_IPV4') is True: + # 3. check the mdns name is accessible. + if not mdns_server_events['esp_answered'].wait(timeout=30): + raise ValueError( + 'Test has failed: did not receive mdns answer within timeout') + if not mdns_server_events['esp_delegated_answered'].wait(timeout=30): + raise ValueError( + 'Test has failed: did not receive mdns answer for delegated host within timeout' + ) + # 4. check DUT output if mdns advertized host is resolved + dut.expect( + re.compile( + b'mdns-test: Query A: tinytester.local resolved to: 127.0.0.1') + ) + dut.expect( + re.compile( + b'mdns-test: gethostbyname: tinytester-lwip.local resolved to: 127.0.0.1' + )) + dut.expect( + re.compile( + b'mdns-test: getaddrinfo: tinytester-lwip.local resolved to: 127.0.0.1' + )) + # 5. check the DUT answers to one-shot mDNS query (replaces dig) + dig_output = run_one_shot_query( + '{}.local'.format(specific_host), qtype='A' + ) + print('Resolving {} using one-shot query succeeded with:\n{}'.format( + specific_host, dig_output)) + if not ipv4.encode('utf-8') in dig_output: + raise ValueError( + 'Test has failed: Incorrectly resolved DUT hostname using dig' + "Output should've contained DUT's IP address:{}".format(ipv4)) + # 6. check the DUT reverse lookup + if dut.app.sdkconfig.get('MDNS_RESPOND_REVERSE_QUERIES') is True: + for ip_address in ip_addresses: + reverse_name = _ip_to_reverse_name(ip_address) + dig_output = run_one_shot_query( + reverse_name, qtype='PTR' + ) + print('Reverse lookup for {} using one-shot query succeeded with:\n{}'. + format(ip_address, dig_output)) + if specific_host not in dig_output.decode(): + raise ValueError( + 'Test has failed: Incorrectly resolved DUT IP address using dig' + "Output should've contained DUT's name:{}".format( + specific_host)) + + finally: + mdns_server_events['stop'].set() + mdns_responder.join() diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.build_only.no_browse b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.build_only.no_browse new file mode 100644 index 0000000..d6aedd5 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.build_only.no_browse @@ -0,0 +1,16 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_ENABLE_BROWSE=n +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_EXAMPLE_CONNECT_IPV6=y +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_custom_netif b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_custom_netif new file mode 100644 index 0000000..a8dee3f --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_custom_netif @@ -0,0 +1,21 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_MDNS_PREDEF_NETIF_STA=n +CONFIG_MDNS_PREDEF_NETIF_AP=n +CONFIG_MDNS_PREDEF_NETIF_ETH=n +CONFIG_MDNS_ADD_CUSTOM_NETIF=y +CONFIG_MDNS_RESPOND_REVERSE_QUERIES=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_PHY_GENERIC=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_EXAMPLE_CONNECT_IPV6=y +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_def b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_def new file mode 100644 index 0000000..703b454 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_def @@ -0,0 +1,15 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_EXAMPLE_CONNECT_IPV6=y +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv4 b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv4 new file mode 100644 index 0000000..b77a752 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv4 @@ -0,0 +1,15 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_LWIP_IPV4=n +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv6 b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv6 new file mode 100644 index 0000000..d669ec0 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_no_ipv6 @@ -0,0 +1,16 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_LWIP_IPV6=n +CONFIG_EXAMPLE_CONNECT_IPV6=n +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_socket b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_socket new file mode 100644 index 0000000..5d92405 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.ci.eth_socket @@ -0,0 +1,16 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_MDNS_RESOLVE_TEST_SERVICES=y +CONFIG_MDNS_ADD_MAC_TO_HOSTNAME=y +CONFIG_MDNS_PUBLISH_DELEGATE_HOST=y +CONFIG_MDNS_NETWORKING_SOCKET=y +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +CONFIG_EXAMPLE_CONNECT_ETHERNET=y +CONFIG_EXAMPLE_CONNECT_WIFI=n +CONFIG_EXAMPLE_USE_INTERNAL_ETHERNET=y +CONFIG_EXAMPLE_ETH_PHY_IP101=y +CONFIG_EXAMPLE_ETH_MDC_GPIO=23 +CONFIG_EXAMPLE_ETH_MDIO_GPIO=18 +CONFIG_EXAMPLE_ETH_PHY_RST_GPIO=5 +CONFIG_EXAMPLE_ETH_PHY_ADDR=1 +CONFIG_EXAMPLE_CONNECT_IPV6=y +CONFIG_MDNS_BUTTON_GPIO=32 diff --git a/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.defaults b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.defaults new file mode 100644 index 0000000..1686559 --- /dev/null +++ b/managed_components/espressif__mdns/examples/query_advertise/sdkconfig.defaults @@ -0,0 +1 @@ +CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE=y diff --git a/managed_components/espressif__mdns/idf_component.yml b/managed_components/espressif__mdns/idf_component.yml new file mode 100644 index 0000000..7e37de4 --- /dev/null +++ b/managed_components/espressif__mdns/idf_component.yml @@ -0,0 +1,13 @@ +dependencies: + idf: + version: '>=5.0' +description: Multicast UDP service used to provide local network service and host + discovery. +documentation: https://docs.espressif.com/projects/esp-protocols/mdns/docs/latest/en/index.html +issues: https://github.com/espressif/esp-protocols/issues +repository: git://github.com/espressif/esp-protocols.git +repository_info: + commit_sha: 587888b46aa6a6fd31d69144a6d36079b7adcbb0 + path: components/mdns +url: https://github.com/espressif/esp-protocols/tree/master/components/mdns +version: 1.15.1 diff --git a/managed_components/espressif__mdns/include/mdns.h b/managed_components/espressif__mdns/include/mdns.h new file mode 100644 index 0000000..e74eb5b --- /dev/null +++ b/managed_components/espressif__mdns/include/mdns.h @@ -0,0 +1,1200 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#ifndef ESP_MDNS_H_ +#define ESP_MDNS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" +#include + +#define MDNS_TYPE_A 0x0001 +#define MDNS_TYPE_PTR 0x000C +#define MDNS_TYPE_TXT 0x0010 +#define MDNS_TYPE_AAAA 0x001C +#define MDNS_TYPE_SRV 0x0021 +#define MDNS_TYPE_OPT 0x0029 +#define MDNS_TYPE_NSEC 0x002F +#define MDNS_TYPE_ANY 0x00FF + +#if defined(CONFIG_LWIP_IPV6) && defined(CONFIG_MDNS_RESPOND_REVERSE_QUERIES) +#define MDNS_NAME_MAX_LEN (64+4) // Need to account for IPv6 reverse queries (64 char address + ".ip6" ) +#else +#define MDNS_NAME_MAX_LEN 64 // Maximum string length of hostname, instance, service and proto +#endif +#define MDNS_NAME_BUF_LEN (MDNS_NAME_MAX_LEN+1) // Maximum char buffer size to hold hostname, instance, service or proto + +/** + * @brief Asynchronous query handle + */ +typedef struct mdns_search_once_s mdns_search_once_t; + +/** + * @brief Daemon query handle + */ +typedef struct mdns_browse_s mdns_browse_t; + +typedef enum { + MDNS_EVENT_ENABLE_IP4 = 1 << 1, + MDNS_EVENT_ENABLE_IP6 = 1 << 2, + MDNS_EVENT_ANNOUNCE_IP4 = 1 << 3, + MDNS_EVENT_ANNOUNCE_IP6 = 1 << 4, + MDNS_EVENT_DISABLE_IP4 = 1 << 5, + MDNS_EVENT_DISABLE_IP6 = 1 << 6, + MDNS_EVENT_IP4_REVERSE_LOOKUP = 1 << 7, + MDNS_EVENT_IP6_REVERSE_LOOKUP = 1 << 8, +} mdns_event_actions_t; + +/** + * @brief mDNS enum to specify the ip_protocol type + */ +typedef enum { + MDNS_IP_PROTOCOL_V4, + MDNS_IP_PROTOCOL_V6, + MDNS_IP_PROTOCOL_MAX +} mdns_ip_protocol_t; + +/** + * @brief mDNS basic text item structure + * Used in mdns_service_add() + */ +typedef struct { + const char *key; /*!< item key name */ + const char *value; /*!< item value string */ +} mdns_txt_item_t; + +/** + * @brief mDNS basic text item structure, with length of values + * Suitable for both string and non-string items + * Used in mdns_service_add_with_explicit_txt_item_value_len() + */ +typedef struct { + const char *key; /*!< item key name */ + const uint8_t *value; /*!< item value */ + uint8_t value_len; /*!< item value length */ +} mdns_txt_item_with_value_len_t; + +/** + * @brief mDNS TXT item type, either regular one or with value length + */ +typedef enum { + MDNS_TXT_ITEM, + MDNS_TXT_ITEM_WITH_VALUE_LEN +} mdns_txt_item_type_t; + +/** + * @brief mDNS basic subtype item structure + * Used in mdns_service_subtype_xxx() APIs + */ +typedef struct { + const char *subtype; /*!< subtype name */ +} mdns_subtype_item_t; + +/** + * @brief mDNS query linked list IP item + */ +typedef struct mdns_ip_addr_s { + esp_ip_addr_t addr; /*!< IP address */ + struct mdns_ip_addr_s *next; /*!< next IP, or NULL for the last IP in the list */ +} mdns_ip_addr_t; + +/** + * @brief mDNS query type to be explicitly set to either Unicast or Multicast + */ +typedef enum { + MDNS_QUERY_UNICAST, + MDNS_QUERY_MULTICAST, +} mdns_query_transmission_type_t; + +/** + * @brief mDNS query result structure + */ +typedef struct mdns_result_s { + struct mdns_result_s *next; /*!< next result, or NULL for the last result in the list */ + + esp_netif_t *esp_netif; /*!< ptr to corresponding esp-netif */ + uint32_t ttl; /*!< time to live */ + + mdns_ip_protocol_t ip_protocol; /*!< ip_protocol type of the interface (v4/v6) */ + // PTR + char *instance_name; /*!< instance name */ + char *service_type; /*!< service type */ + char *proto; /*!< srevice protocol */ + // SRV + char *hostname; /*!< hostname */ + uint16_t port; /*!< service port */ + // TXT + mdns_txt_item_t *txt; /*!< txt record */ + uint8_t *txt_value_len; /*!< array of txt value len of each record */ + size_t txt_count; /*!< number of txt items */ + // A and AAAA + mdns_ip_addr_t *addr; /*!< linked list of IP addresses found */ + // Browse only + char *subtype; /*!< browse subtype, or NULL for normal browse */ +} mdns_result_t; + +typedef void (*mdns_query_notify_t)(mdns_search_once_t *search); + +/** + * @brief Browse result change notifier + * + * Called once for every matching browse result changed by a received response, + * or once for every currently cached result when a new browse is registered. + * + * The @p result is a temporary projection of the internal mDNS cache, which is only valid + * during the lifetime of this callback and is freed immediately after the callback returns. + * + * @warning @p result->next is always NULL. Other instances cannot be obtained from @p result. + * + * @warning If handling is deferred outside this callback, applications must make a deep copy + * of @p result with all components, including strings, TXT entries, address list, and subtype. + * + * @warning This callback runs in the mDNS service task and holds the mDNS service lock. + * Users must not call APIs that acquire mDNS service lock in this callback. + * For example, mdns_browse_new() and mdns_browse_delete(). + * + * @param result Temporary result of the browse that changed. + */ +typedef void (*mdns_browse_notify_t)(mdns_result_t *result); + +/** + * @brief Hostname change notifier + * + * Called from the mDNS service task after the hostname changes. + * The @p hostname argument is the new hostname. It remains valid until the + * callback returns. + * + * @warning Do not call mDNS APIs from this callback. The callback runs while + * the mDNS service is processing an action. + * + * @param hostname The new responder hostname. + * @param arg User context supplied when registering the callback. + */ +typedef void (*mdns_hostname_changed_cb_t)(const char *hostname, void *arg); + +/** + * @brief Initialize mDNS on given interface + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE when failed to register event handler + * - ESP_ERR_NO_MEM on memory error + * - ESP_FAIL when failed to start mdns task + */ +esp_err_t mdns_init(void); + +/** + * @brief Stop and free mDNS server + * + */ +void mdns_free(void); + +/** + * @brief Set the hostname for mDNS server + * required if you want to advertise services + * + * @param hostname Hostname to set + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_hostname_set(const char *hostname); + +/** + * @brief Register a callback notified when the hostname changes + * + * Multiple callbacks can be registered. Registering the same callback and + * context more than once has no effect. Callbacks cannot be unregistered and + * remain registered until mdns_free() is called. + * + * @param cb Callback to invoke when the hostname changes. + * @param arg User context passed to @p cb. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE when mDNS is not initialized + * - ESP_ERR_INVALID_ARG when @p cb is NULL + * - ESP_ERR_NO_MEM when the callback cannot be registered + */ +esp_err_t mdns_register_hostname_changed_callback(mdns_hostname_changed_cb_t cb, void *arg); + +/** + * @brief Get the hostname for mDNS server + * + * @param hostname pointer to the hostname, it should be allocated + * and hold at least MDNS_NAME_BUF_LEN chars + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE when mdns is not initialized + */ +esp_err_t mdns_hostname_get(char *hostname); + +/** + * @brief Adds a hostname and address to be delegated + * A/AAAA queries will be replied for the hostname and + * services can be added to this host. + * + * @param hostname Hostname to add + * @param address_list The IP address list of the host + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * + */ +esp_err_t mdns_delegate_hostname_add(const char *hostname, const mdns_ip_addr_t *address_list); + +/** + * @brief Set the address to a delegated hostname + * + * @param hostname Hostname to set + * @param address_list The IP address list of the host + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * + */ +esp_err_t mdns_delegate_hostname_set_address(const char *hostname, const mdns_ip_addr_t *address_list); + +/** + * @brief Remove a delegated hostname + * All the services added to this host will also be removed. + * + * @param hostname Hostname to remove + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * + */ +esp_err_t mdns_delegate_hostname_remove(const char *hostname); + +/** + * @brief Query whether a hostname has been added + * + * @param hostname Hostname to query + * + * @return + * - true The hostname has been added. + * - false The hostname has not been added. + * + */ +bool mdns_hostname_exists(const char *hostname); + +/** + * @brief Set the default instance name for mDNS server + * + * @param instance_name Instance name to set + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_instance_name_set(const char *instance_name); + +/** + * @brief Add service to mDNS server + * + * @note The value length of txt items will be automatically decided by strlen + * + * @param instance_name instance name to set. If NULL, + * global instance name or hostname will be used. + * Note that MDNS_MULTIPLE_INSTANCE config option + * needs to be enabled for adding multiple instances + * with the same instance type. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param port service port + * @param txt string array of TXT data (eg. {{"var","val"},{"other","2"}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * - ESP_FAIL failed to add service + */ +esp_err_t mdns_service_add(const char *instance_name, const char *service_type, const char *proto, uint16_t port, mdns_txt_item_t txt[], size_t num_items); + +/** + * @brief Add service to mDNS server with a delegated hostname + * + * @note The value length of txt items will be automatically decided by strlen + * + * @param instance_name instance name to set. If NULL, + * global instance name or hostname will be used + * Note that MDNS_MULTIPLE_INSTANCE config option + * needs to be enabled for adding multiple instances + * with the same instance type. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param port service port + * @param txt string array of TXT data (eg. {{"var","val"},{"other","2"}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * - ESP_FAIL failed to add service + */ +esp_err_t mdns_service_add_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, uint16_t port, mdns_txt_item_t txt[], size_t num_items); + +/** + * @brief Add service to mDNS server + * + * @note The value length of txt items should be configured in structures + * + * @param instance_name instance name to set. If NULL, + * global instance name or hostname will be used. + * Note that MDNS_MULTIPLE_INSTANCE config option + * needs to be enabled for adding multiple instances + * with the same instance type. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param port service port + * @param txt array of TXT data with value length (eg. {{"var", "val", 3},{"other", "2", 1}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * - ESP_FAIL failed to add service + */ +esp_err_t mdns_service_add_with_explicit_txt_item_value_len(const char *instance_name, const char *service_type, const char *proto, uint16_t port, mdns_txt_item_with_value_len_t txt[], size_t num_items); + +/** + * @brief Add service to mDNS server with a delegated hostname + * + * @note The value length of txt items should be configured in structures + * + * @param instance_name instance name to set. If NULL, + * global instance name or hostname will be used + * Note that MDNS_MULTIPLE_INSTANCE config option + * needs to be enabled for adding multiple instances + * with the same instance type. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param port service port + * @param txt array of TXT data with value length (eg. {{"var", "val", 3},{"other", "2", 1}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM memory error + * - ESP_FAIL failed to add service + */ +esp_err_t mdns_service_add_for_host_with_explicit_txt_item_value_len(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, uint16_t port, mdns_txt_item_with_value_len_t txt[], size_t num_items); + +/** + * @brief Check whether a service has been added. + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, checks for the local hostname. + * + * @return + * - true Correspondding service has been added. + * - false Service not found. + */ +bool mdns_service_exists(const char *service_type, const char *proto, const char *hostname); + +/** + * @brief Check whether a service has been added. + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, checks for the local hostname. + * + * @return + * - true Correspondding service has been added. + * - false Service not found. + */ +bool mdns_service_exists_with_instance(const char *instance, const char *service_type, const char *proto, + const char *hostname); + +/** + * @brief Remove service from mDNS server + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_remove(const char *service_type, const char *proto); + +/** + * @brief Remove service from mDNS server with hostname + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_remove_for_host(const char *instance, const char *service_type, const char *proto, const char *hostname); + +/** + * @brief Set instance name for service + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param instance_name instance name to set + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_instance_name_set(const char *service_type, const char *proto, const char *instance_name); + +/** + * @brief Set instance name for service with hostname + * + * @param instance_old original instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param instance_name instance name to set + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_instance_name_set_for_host(const char *instance_old, const char *service_type, const char *proto, const char *hostname, + const char *instance_name); + +/** + * @brief Set service port + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param port service port + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_port_set(const char *service_type, const char *proto, uint16_t port); + + +/** + * @brief Set service port with hostname + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param port service port + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_port_set_for_host(const char *instance, const char *service_type, const char *proto, const char *hostname, + uint16_t port); + +/** + * @brief Replace all TXT items for service + * + * @note The value length of txt items will be automatically decided by strlen + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param txt array of TXT data (eg. {{"var","val"},{"other","2"}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_set(const char *service_type, const char *proto, mdns_txt_item_t txt[], uint8_t num_items); + +/** + * @brief Replace all TXT items for service with hostname + * + * @note The value length of txt items will be automatically decided by strlen + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param txt array of TXT data (eg. {{"var","val"},{"other","2"}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_set_for_host(const char *instance, const char *service_type, const char *proto, const char *hostname, + mdns_txt_item_t txt[], uint8_t num_items); + +/** + * @brief Replace all TXT items for service + * + * @note The value length of txt items should be configured in structures + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param txt array of TXT data with value length (eg. {{"var", "val", 3},{"other", "2", 1}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_set_with_explicit_txt_item_value_len(const char *service_type, const char *proto, mdns_txt_item_with_value_len_t txt[], uint8_t num_items); + +/** + * @brief Replace all TXT items for service with hostname + * + * @note The value length of txt items should be configured in structures + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param txt array of TXT data with value length (eg. {{"var", "val", 3},{"other", "2", 1}}) + * @param num_items number of items in TXT data + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_set_for_host_with_explicit_txt_item_value_len(const char *instance, const char *service_type, const char *proto, const char *hostname, + mdns_txt_item_with_value_len_t txt[], uint8_t num_items); + +/** + * @brief Set/Add TXT item for service TXT record + * + * @note The value length will be automatically decided by strlen + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param key the key that you want to add/update + * @param value the new value of the key + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_set(const char *service_type, const char *proto, const char *key, const char *value); + +/** + * @brief Set/Add TXT item for service TXT record + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param key the key that you want to add/update + * @param value the new value of the key + * @param value_len the length of the value + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_set_with_explicit_value_len(const char *service_type, const char *proto, + const char *key, const char *value, uint8_t value_len); + +/** + * @brief Set/Add TXT item for service TXT record with hostname + * + * @note The value length will be automatically decided by strlen + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param key the key that you want to add/update + * @param value the new value of the key + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_set_for_host(const char *instance, const char *service_type, const char *proto, const char *hostname, + const char *key, const char *value); + +/** + * @brief Set/Add TXT item for service TXT record with hostname and txt value length + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param key the key that you want to add/update + * @param value the new value of the key + * @param value_len the length of the value + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_set_for_host_with_explicit_value_len(const char *instance, const char *service_type, const char *proto, + const char *hostname, const char *key, + const char *value, uint8_t value_len); + +/** + * @brief Remove TXT item for service TXT record + * + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param key the key that you want to remove + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_remove(const char *service_type, const char *proto, const char *key); + +/** + * @brief Remove TXT item for service TXT record with hostname + * + * @param instance instance name + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param key the key that you want to remove + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_txt_item_remove_for_host(const char *instance, const char *service_type, const char *proto, const char *hostname, + const char *key); + +/** + * @brief Add a subtype for service. + * + * @param instance_name instance name. If NULL, will find the first service with the same service type and protocol. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param subtype The subtype to add. + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_subtype_add_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, const char *subtype); + +/** + * @brief Remove a subtype for service. + * + * @param instance_name instance name. If NULL, will find the first service with the same service type and protocol. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param subtype The subtype to remove. + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + */ +esp_err_t mdns_service_subtype_remove_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, const char *subtype); + +/** + * @brief Add multiple subtypes for service at once. + * + * @param instance_name instance name. If NULL, will find the first service with the same service type and protocol. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param subtype the pointer of subtype array to add. + * @param num_items number of items in subtype array + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_subtype_add_multiple_items_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, mdns_subtype_item_t subtype[], uint8_t num_items); + +/** + * @brief Update subtype for service. + * + * @param instance_name instance name. If NULL, will find the first service with the same service type and protocol. + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param hostname service hostname. If NULL, local hostname will be used. + * @param subtype the pointer of subtype array to add. + * @param num_items number of items in subtype array + * + * @note If `num_items` is 0, then remove all subtypes. + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NOT_FOUND Service not found + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_service_subtype_update_multiple_items_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, mdns_subtype_item_t subtype[], uint8_t num_items); +/** + * @brief Remove and free all services from mDNS server + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t mdns_service_remove_all(void); + +/** + * @brief Deletes the finished query. Call this only after the search has ended! + * + * @param search pointer to search object + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE search has not finished + * - ESP_ERR_INVALID_ARG pointer to search object is NULL + */ +esp_err_t mdns_query_async_delete(mdns_search_once_t *search); + +/** + * @brief Get results from search pointer. Results available as a pointer to the output parameter. + * Pointer to search object has to be deleted via `mdns_query_async_delete` once the query has finished. + * The results although have to be freed manually. + * + * @param search pointer to search object + * @param timeout time in milliseconds to wait for answers + * @param results pointer to the results of the query + * @param num_results pointer to the number of the actual result items (set to NULL to ignore this return value) + * + * @return + * True if search has finished before or at timeout + * False if search timeout is over + */ +bool mdns_query_async_get_results(mdns_search_once_t *search, uint32_t timeout, mdns_result_t **results, uint8_t *num_results); + +/** + * @brief Query mDNS for host or service asynchronousely. + * Search has to be tested for progress and deleted manually! + * + * @param name service instance or host name (NULL for PTR queries) + * @param service_type service type (_http, _arduino, _ftp etc.) (NULL for host queries) + * @param proto service protocol (_tcp, _udp, etc.) (NULL for host queries) + * @param type type of query (MDNS_TYPE_*) + * @param timeout time in milliseconds during which mDNS query is active + * @param max_results maximum results to be collected + * @param notifier Notification function to be called when the result is ready, can be NULL + * + * @return mdns_search_once_s pointer to new search object if query initiated successfully. + * NULL otherwise. + */ +mdns_search_once_t *mdns_query_async_new(const char *name, const char *service_type, const char *proto, uint16_t type, + uint32_t timeout, size_t max_results, mdns_query_notify_t notifier); + +/** + * @brief Generic mDNS query + * All following query methods are derived from this one + * + * @param name service instance or host name (NULL for PTR queries) + * @param service_type service type (_http, _arduino, _ftp etc.) (NULL for host queries) + * @param proto service protocol (_tcp, _udp, etc.) (NULL for host queries) + * @param type type of query (MDNS_TYPE_*) + * @param transmission_type either Unicast query, or Multicast query + * @param timeout time in milliseconds to wait for answers. + * @param max_results maximum results to be collected + * @param results pointer to the results of the query + * results must be freed using mdns_query_results_free below + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG timeout was not given + */ +esp_err_t mdns_query_generic(const char *name, const char *service_type, const char *proto, uint16_t type, + mdns_query_transmission_type_t transmission_type, uint32_t timeout, size_t max_results, mdns_result_t **results); + +/** + * @brief Query mDNS for host or service + * + * Note that querying PTR types sends Multicast query, all other types send Unicast queries + * + * @param name service instance or host name (NULL for PTR queries) + * @param service_type service type (_http, _arduino, _ftp etc.) (NULL for host queries) + * @param proto service protocol (_tcp, _udp, etc.) (NULL for host queries) + * @param type type of query (MDNS_TYPE_*) + * @param timeout time in milliseconds to wait for answers. + * @param max_results maximum results to be collected + * @param results pointer to the results of the query + * results must be freed using mdns_query_results_free below + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG timeout was not given + */ +esp_err_t mdns_query(const char *name, const char *service_type, const char *proto, uint16_t type, uint32_t timeout, size_t max_results, mdns_result_t **results); + +/** + * @brief Free query results + * + * @param results linked list of results to be freed + */ +void mdns_query_results_free(mdns_result_t *results); + +/** + * @brief Query mDNS for service + * + * @param service_type service type (_http, _arduino, _ftp etc.) + * @param proto service protocol (_tcp, _udp, etc.) + * @param timeout time in milliseconds to wait for answer. + * @param max_results maximum results to be collected + * @param results pointer to the results of the query + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_query_ptr(const char *service_type, const char *proto, uint32_t timeout, size_t max_results, mdns_result_t **results); + +/** + * @brief Query mDNS for SRV record + * + * @param instance_name service instance name + * @param service_type service type (_http, _arduino, _ftp etc.) + * @param proto service protocol (_tcp, _udp, etc.) + * @param timeout time in milliseconds to wait for answer. + * @param result pointer to the result of the query + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_query_srv(const char *instance_name, const char *service_type, const char *proto, uint32_t timeout, mdns_result_t **result); + +/** + * @brief Query mDNS for TXT record + * + * @param instance_name service instance name + * @param service_type service type (_http, _arduino, _ftp etc.) + * @param proto service protocol (_tcp, _udp, etc.) + * @param timeout time in milliseconds to wait for answer. + * @param result pointer to the result of the query + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_query_txt(const char *instance_name, const char *service_type, const char *proto, uint32_t timeout, mdns_result_t **result); + +/** + * @brief Look up delegated services. + * + * @param instance instance name (NULL for uncertain instance) + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param max_results maximum results to be collected + * @param result pointer to the result of the search + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_lookup_delegated_service(const char *instance, const char *service_type, const char *proto, size_t max_results, + mdns_result_t **result); + +/** + * @brief Look up delegated services with a particular subtype. + * + * @param instance instance name (NULL for uncertain instance) + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param subtype service subtype (must not be NULL or empty) + * @param max_results maximum results to be collected + * @param result pointer to the result of the search + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_lookup_delegated_service_with_subtype(const char *instance, const char *service_type, const char *proto, + const char *subtype, size_t max_results, mdns_result_t **result); + +/** + * @brief Look up self hosted services. + * + * @param instance instance name (NULL for uncertain instance) + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param max_results maximum results to be collected + * @param result pointer to the result of the search + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_lookup_selfhosted_service(const char *instance, const char *service_type, const char *proto, size_t max_results, + mdns_result_t **result); + +/** + * @brief Look up self hosted services with a particular subtype. + * + * @param instance instance name (NULL for uncertain instance) + * @param service_type service type (_http, _ftp, etc) + * @param proto service protocol (_tcp, _udp) + * @param subtype service subtype (must not be NULL or empty) + * @param max_results maximum results to be collected + * @param result pointer to the result of the search + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_lookup_selfhosted_service_with_subtype(const char *instance, const char *service_type, const char *proto, + const char *subtype, size_t max_results, mdns_result_t **result); + +/** + * @brief Query mDNS for A record + * + * @param host_name host name to look for + * @param timeout time in milliseconds to wait for answer. + * @param addr pointer to the resulting IP4 address + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_query_a(const char *host_name, uint32_t timeout, esp_ip4_addr_t *addr); + +#if CONFIG_LWIP_IPV6 +/** + * @brief Query mDNS for A record + * + * Please note that hostname must not contain domain name, as mDNS uses '.local' domain. + * + * @param host_name host name to look for + * @param timeout time in milliseconds to wait for answer. If 0, max_results needs to be defined + * @param addr pointer to the resulting IP6 address + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NO_MEM memory error + * - ESP_ERR_INVALID_ARG parameter error + */ +esp_err_t mdns_query_aaaa(const char *host_name, uint32_t timeout, esp_ip6_addr_t *addr); +#endif + + +/** + * @brief Register custom esp_netif with mDNS functionality + * mDNS service runs by default on preconfigured interfaces (STA, AP, ETH). + * This API enables running the service on any customized interface, + * either using standard WiFi or Ethernet driver or any kind of user defined driver. + * + * @param esp_netif Pointer to esp-netif interface + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running or this netif is already registered + * - ESP_ERR_NO_MEM not enough memory for this in interface in the netif list (see CONFIG_MDNS_MAX_INTERFACES) + */ +esp_err_t mdns_register_netif(esp_netif_t *esp_netif); + +/** + * @brief Unregister esp-netif already registered in mDNS service + * + * @param esp_netif Pointer to esp-netif interface + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running + * - ESP_ERR_NOT_FOUND this esp-netif was not registered in mDNS service + */ +esp_err_t mdns_unregister_netif(esp_netif_t *esp_netif); + +/** + * @brief Set esp_netif to a desired state, or perform a desired action, such as enable/disable this interface + * or send announcement packets to this netif + * + * * This function is used to enable (probe, resolve conflicts and announce), announce, or disable (send bye) mDNS + * services on the specified network interface. + * * This function must be called if users registers a specific interface using mdns_register_netif() + * to enable mDNS services on that interface. + * * This function could be used in IP/connection event handlers to automatically enable/announce mDNS services + * when network properties change and/or disable them on disconnection. + * + * @param esp_netif Pointer to esp-netif interface + * @param event_action Disable/Enable/Announce on this interface over IPv4/IPv6 protocol. + * Actions enumerated in mdns_event_actions_t type. + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_STATE mDNS is not running or this netif is not registered + * - ESP_ERR_NO_MEM memory error + */ +esp_err_t mdns_netif_action(esp_netif_t *esp_netif, mdns_event_actions_t event_action); + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +/** + * @brief Browse mDNS for a service `_service._proto`. + * + * @param service Pointer to the `_service` which will be browsed. + * @param proto Pointer to the `_proto` which will be browsed. + * @param notifier The callback which will be called when a browse result changes. + * See @ref mdns_browse_notify_t for callback semantics and limitations. + * @return mdns_browse_t pointer to new browse object if initiated successfully. + * NULL otherwise. + * + * @note If matching services already present in the internal mDNS cache, + * the notifier will be called once for each cached service after this browse + * is registered. + * + * @note The notifier receives a temporary result that is valid only during the callback. + * See @ref mdns_browse_notify_t for ownership and lifetime details. + * + * @note Available when CONFIG_MDNS_ENABLE_BROWSE is enabled (default); can be disabled to reduce binary size. + * + * @warning This function acquires the mDNS service lock and must not be called from the mDNS service task. + */ +mdns_browse_t *mdns_browse_new(const char *service, const char *proto, mdns_browse_notify_t notifier); + +/** + * @brief Browse mDNS for a service subtype `_subtype._sub._service._proto` + * (Selective Instance Enumeration per RFC 6763 Section 7.1). + * + * @param service Pointer to the `_service` which will be browsed. + * @param proto Pointer to the `_proto` which will be browsed. + * @param subtype Pointer to the `_subtype` to restrict browsing to. Pass in NULL or empty string for standard browse. + * @param notifier The callback which will be called when the browsing service changed. + * @return mdns_browse_t pointer to new browse object if initiated successfully. + * NULL otherwise. + * + * @note If matching services already present in the internal mDNS cache, + * the notifier will be called once for each cached service after this browse + * is registered. + * + * @note The notifier receives a temporary result that is valid only during the callback. + * See @ref mdns_browse_notify_t for ownership and lifetime details. + * + * @note Passing in "_sub" to `subtype` is currently unsupported due to a limitation in mDNS name parser. + * Browsing this subtype will not obtain PTR record until this issue is fixed. + * + * @note Available when CONFIG_MDNS_ENABLE_BROWSE is enabled (default); can be disabled to reduce binary size. + * + * @warning This function acquires the mDNS service lock and must not be called from the mDNS service task. + */ +mdns_browse_t *mdns_browse_new_with_subtype(const char *service, const char *proto, const char *subtype, mdns_browse_notify_t notifier); + +/** + * @brief Stop the `_service._proto` browse. + * @param service Pointer to the `_service` which will be browsed. + * @param proto Pointer to the `_proto` which will be browsed. + * @return + * - ESP_OK success. + * - ESP_FAIL mDNS is not running or the browsing of `_service._proto` is never started. + * - ESP_ERR_NO_MEM memory error. + * + * @note Available when CONFIG_MDNS_ENABLE_BROWSE is enabled (default); can be disabled to reduce binary size. + * + * @warning This function acquires the mDNS service lock and must not be called from the mDNS service task. + */ +esp_err_t mdns_browse_delete(const char *service, const char *proto); + +/** + * @brief Stop the `_subtype._sub._service._proto` browse. + * @param service Pointer to the `_service` which will be browsed. + * @param proto Pointer to the `_proto` which will be browsed. + * @param subtype Pointer to the `_subtype`. Can be NULL to match a browse without subtype. + * @return + * - ESP_OK success. + * - ESP_FAIL mDNS is not running or the browsing was never started. + * - ESP_ERR_NO_MEM memory error. + * + * @note Available when CONFIG_MDNS_ENABLE_BROWSE is enabled (default); can be disabled to reduce binary size. + * + * @warning This function acquires the mDNS service lock and must not be called from the mDNS service task. + */ +esp_err_t mdns_browse_delete_with_subtype(const char *service, const char *proto, const char *subtype); +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +#ifdef __cplusplus +} +#endif + +#endif /* ESP_MDNS_H_ */ diff --git a/managed_components/espressif__mdns/include/mdns_console.h b/managed_components/espressif__mdns/include/mdns_console.h new file mode 100644 index 0000000..cb28eca --- /dev/null +++ b/managed_components/espressif__mdns/include/mdns_console.h @@ -0,0 +1,14 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#ifndef _MDNS_CONSOLE_H_ +#define _MDNS_CONSOLE_H_ + +/** + * @brief Register MDNS functions with the console component + */ +void mdns_console_register(void); + +#endif /* _MDNS_CONSOLE_H_ */ diff --git a/managed_components/espressif__mdns/mdns_browser.c b/managed_components/espressif__mdns/mdns_browser.c new file mode 100644 index 0000000..00366b3 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_browser.c @@ -0,0 +1,536 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "mdns_private.h" +#include "mdns_browser.h" +#include "mdns_mem_caps.h" +#include "mdns_debug.h" +#include "mdns_utils.h" +#include "mdns_querier.h" +#include "mdns_responder.h" +#include "mdns_netif.h" +#include "mdns_service.h" +#include "esp_log.h" +#include "mdns_cache.h" + +#define MDNS_CACHE_RECORD_BROWSE_SHARED (mdns_cache_record_mask_t) \ + (MDNS_CACHE_RECORD_SRV | MDNS_CACHE_RECORD_TXT | MDNS_CACHE_RECORD_ADDR) +#define MDNS_SUBTYPE_MAX_LEN 63 + +static const char *TAG = "mdns_browser"; + +static mdns_browse_t *s_browse; + +/** + * @brief Browse action + */ +static esp_err_t send_browse_action(mdns_action_type_t type, mdns_browse_t *browse) +{ + mdns_action_t *action = NULL; + + action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + + action->type = type; + action->data.browse_add.browse = browse; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +/** + * @brief Free a browse item (Not free the list). + */ +static void browse_item_free(mdns_browse_t *browse) +{ + if (!browse) { + return; + } + + mdns_mem_free(browse->service); + mdns_mem_free(browse->proto); + mdns_mem_free(browse->subtype); + mdns_mem_free(browse); +} + +/** + * @brief Send PTR query packet to all available interfaces for browsing. + */ +static void browse_send(mdns_browse_t *browse, mdns_if_t interface, mdns_ip_protocol_t ip_protocol) +{ + // Using search once for sending the PTR query + mdns_search_once_t search = {0}; + + search.instance = NULL; + search.service = browse->service; + search.proto = browse->proto; + search.subtype = browse->subtype; + search.type = MDNS_TYPE_PTR; + search.unicast = false; + search.result = NULL; + search.next = NULL; + mdns_priv_query_send(&search, interface, ip_protocol); +} + +void mdns_priv_browse_send_by_ip_protocol(mdns_if_t mdns_if, mdns_ip_protocol_t ip_protocol) +{ + for (mdns_browse_t *browse = s_browse; browse; browse = browse->next) { + if (browse->state == BROWSE_RUNNING) { + browse_send(browse, mdns_if, ip_protocol); + } + } +} + +void mdns_priv_browse_free(void) +{ + while (s_browse) { + mdns_browse_t *b = s_browse; + s_browse = s_browse->next; + browse_item_free(b); + } +} + +/** + * @brief Check if a browse matches a given service and proto. + */ +static bool browse_matches_identity(const mdns_browse_t *browse, const char *service, const char *proto) +{ + return browse && mdns_utils_str_case_equal(browse->service, service) && mdns_utils_str_case_equal(browse->proto, proto); +} + +/** + * @brief Check if a browse matches a given service, proto, and possible subtype. + */ +static bool browse_matches_identity_with_subtype(const mdns_browse_t *browse, const char *service, const char *proto, const char *subtype) +{ + return browse_matches_identity(browse, service, proto) && mdns_utils_str_case_equal_nullable(browse->subtype, subtype); +} + +/** + * @brief Get the non-BROWSE_OFF browse item with the given service, proto, and subtype. + */ +static mdns_browse_t *get_non_off_browse_item(const char *service, const char *proto, const char *subtype) +{ + for (mdns_browse_t *it = s_browse; it; it = it->next) { + if (it->state != BROWSE_OFF && browse_matches_identity_with_subtype(it, service, proto, subtype)) { + return it; + } + } + return NULL; +} + +bool mdns_priv_browse_has_service(const char *service, const char *proto) +{ + for (const mdns_browse_t *it = s_browse; it; it = it->next) { + if (it->state == BROWSE_RUNNING && browse_matches_identity(it, service, proto)) { + return true; + } + } + return false; +} + +bool mdns_priv_browse_has_subtype(const char *service, const char *proto, const char *subtype) +{ + for (const mdns_browse_t *it = s_browse; it; it = it->next) { + if (it->state == BROWSE_RUNNING && browse_matches_identity_with_subtype(it, service, proto, subtype)) { + return true; + } + } + return false; +} + +/** + * @brief Remove and free the browse from browse linked list + */ +static void browse_finish(mdns_browse_t *browse) +{ + if (!browse) { + return; + } + + for (mdns_browse_t *it = s_browse; it; it = it->next) { + if (it == browse) { + queueDetach(mdns_browse_t, s_browse, it); + browse_item_free(it); + mdns_priv_cache_trim_unsubscribed_records(esp_timer_get_time()); + return; + } + } +} + +/** + * @brief Allocate new browse structure + */ +static mdns_browse_t *browse_init(const char *service, const char *proto, const char *subtype, mdns_browse_notify_t notifier) +{ + mdns_browse_t *browse = (mdns_browse_t *)mdns_mem_malloc(sizeof(mdns_browse_t)); + + if (!browse) { + HOOK_MALLOC_FAILED; + return NULL; + } + memset(browse, 0, sizeof(mdns_browse_t)); + + browse->state = BROWSE_INIT; + if (!mdns_utils_str_null_or_empty(service)) { + browse->service = mdns_mem_strndup(service, MDNS_NAME_BUF_LEN - 1); + if (!browse->service) { + browse_item_free(browse); + HOOK_MALLOC_FAILED; + return NULL; + } + } + if (!mdns_utils_str_null_or_empty(proto)) { + browse->proto = mdns_mem_strndup(proto, MDNS_NAME_BUF_LEN - 1); + if (!browse->proto) { + browse_item_free(browse); + return NULL; + } + } + + if (!mdns_utils_str_null_or_empty(subtype)) { + browse->subtype = mdns_mem_strndup(subtype, MDNS_NAME_BUF_LEN - 1); + if (!browse->subtype) { + browse_item_free(browse); + return NULL; + } + } + + browse->notifier = notifier; + return browse; +} + +/** + * @brief Send initial PTR queries for a registered browse. + */ +static void browse_start(mdns_browse_t *browse) +{ + if (!browse || browse->state != BROWSE_INIT) { + return; + } + browse->state = BROWSE_RUNNING; + mdns_priv_cache_notify_browse(browse); + for (uint8_t interface_idx = 0; interface_idx < MDNS_MAX_INTERFACES; interface_idx++) { + for (uint8_t protocol_idx = 0; protocol_idx < MDNS_IP_PROTOCOL_MAX; protocol_idx++) { + browse_send(browse, (mdns_if_t) interface_idx, (mdns_ip_protocol_t) protocol_idx); + } + } +} + +mdns_browse_t *mdns_priv_browse_find_consumer(mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + for (mdns_browse_t *it = s_browse; it; it = it->next) { + if (it->state != BROWSE_RUNNING) { + continue; + } + // For browse, we only care about PTR, SRV, TXT, A and AAAA + switch (type) { + case MDNS_TYPE_PTR: { + bool subtype_matches = name->sub ? mdns_utils_str_case_equal(name->host, it->subtype) : + mdns_utils_str_null_or_empty(it->subtype); + if (mdns_utils_str_case_equal(name->service, it->service) && mdns_utils_str_case_equal(name->proto, it->proto) + && subtype_matches) { + return it; + } + break; + } + case MDNS_TYPE_SRV: + case MDNS_TYPE_TXT: + if (mdns_utils_str_case_equal(name->service, it->service) && mdns_utils_str_case_equal(name->proto, it->proto)) { + return it; + } + break; + case MDNS_TYPE_A: + case MDNS_TYPE_AAAA: + if (mdns_priv_cache_host_has_service(name->host, mdns_priv_get_esp_netif(tcpip_if), + ip_protocol, it->service, it->proto)) { + return it; + } + break; + default: + return NULL; + } + } + return NULL; +} + +void mdns_priv_browse_action(mdns_action_t *action, mdns_action_subtype_t type) +{ + if (type == ACTION_RUN) { + switch (action->type) { + case ACTION_BROWSE_START: + browse_start(action->data.browse_add.browse); + break; + case ACTION_BROWSE_END: + browse_finish(action->data.browse_add.browse); + break; + default: + abort(); + } + return; + } +} + +/** + * @brief Check if a running browse `_service._proto` matches a service cache `_service._proto`. + */ +static bool browse_matches_service_cache(const mdns_browse_t *browse, const mdns_service_cache_t *service) +{ + return browse && service && browse->state == BROWSE_RUNNING && browse->notifier + && mdns_utils_str_case_equal(browse->service, service->service) + && mdns_utils_str_case_equal(browse->proto, service->proto); +} + +/** + * @brief Check if a running browse matches a service cache with service name, proto, and possible subtype. + * If subtype node is found in cache and `out_subtype` is valid, the subtype node in cache will be passed to it. + */ +static bool browse_matches_service_cache_with_subtype(const mdns_browse_t *browse, const mdns_service_cache_t *service, const mdns_cache_subtype_t **out_subtype) +{ + const mdns_cache_subtype_t* subtype_node = NULL; + if (out_subtype) { + *out_subtype = NULL; + } + + if (!browse_matches_service_cache(browse, service)) { + return false; + } + + if (mdns_utils_str_null_or_empty(browse->subtype)) { + return service->ptr_present; + } + + subtype_node = mdns_priv_cache_service_find_subtype(service, browse->subtype); + if (out_subtype) { + *out_subtype = subtype_node; + } + return subtype_node != NULL; +} + +/** + * @brief Build and sync a temporary result for a browse from cache. + */ +static bool browse_build_and_notify_temp_result(mdns_browse_t *browse, const mdns_cache_entry_t *entry, + const mdns_service_cache_t *service, const mdns_cache_subtype_t *subtype, + bool goodbye) +{ + mdns_result_t *result = NULL; + esp_err_t ret = mdns_priv_service_cache_to_result(entry, service, &result); + if (ret != ESP_OK) { + return false; + } + + if (!mdns_utils_str_null_or_empty(browse->subtype)) { + if (subtype) { + result->ttl = subtype->ttl; + } + result->subtype = mdns_mem_strdup(browse->subtype); + if (!result->subtype) { + HOOK_MALLOC_FAILED; + mdns_priv_query_results_free(result); + return false; + } + } + + result->next = NULL; + if (goodbye) { + result->ttl = 0; + } + + DBG_BROWSE_RESULTS(result, browse); + if (browse->notifier) { + browse->notifier(result); + } + + mdns_priv_query_results_free(result); + return true; +} + +static bool browse_need_update(const mdns_browse_t *browse, const mdns_service_cache_t *service, + const mdns_cache_subtype_t *subtype, mdns_cache_record_mask_t records) +{ + if (!browse || !service) { + return false; + } + + // SRV, TXT, A, AAAA changed, notify all browses with identical service and proto. + if (records & MDNS_CACHE_RECORD_BROWSE_SHARED) { + return true; + } + + // Normal PTR update with no subtype, only notify no-subtype browses. + if (mdns_utils_str_null_or_empty(browse->subtype)) { + return (records & MDNS_CACHE_RECORD_PTR) != 0; + } + + // For subtype update, only notify if the subtype in cache is pending sync. + if (!(records & MDNS_CACHE_RECORD_SUBTYPE)) { + return false; + } + return subtype && subtype->pending_sync; +} + +bool mdns_priv_browse_update_from_service_cache(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_cache_record_mask_t records) +{ + if (!entry || !service) { + return false; + } + + bool updated = true; + + for (mdns_browse_t *browse = s_browse; browse; browse = browse->next) { + const mdns_cache_subtype_t *subtype = NULL; + if (!browse_matches_service_cache_with_subtype(browse, service, &subtype)) { + continue; + } + if (!browse_need_update(browse, service, subtype, records)) { + continue; + } + updated &= browse_build_and_notify_temp_result(browse, entry, service, subtype, false); + } + + return updated; +} + +bool mdns_priv_browse_notify_from_service_cache(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_browse_t *browse) +{ + const mdns_cache_subtype_t *subtype = NULL; + + if (!entry || !service || !browse) { + return false; + } + + if (!browse_matches_service_cache_with_subtype(browse, service, &subtype)) { + return true; + } + + return browse_build_and_notify_temp_result(browse, entry, service, subtype, false); +} + +bool mdns_priv_browse_notify_ptr_goodbye_from_service_cache(const mdns_cache_entry_t *entry, + const mdns_service_cache_t *service, + const char *subtype) +{ + if (!entry || !service) { + return false; + } + + bool notified = true; + + for (mdns_browse_t *browse = s_browse; browse; browse = browse->next) { + if (!browse_matches_service_cache(browse, service)) { + continue; + } + + if (!mdns_utils_str_case_equal_nullable(browse->subtype, subtype)) { + continue; + } + + notified &= browse_build_and_notify_temp_result(browse, entry, service, NULL, true); + } + + return notified; +} + + +/** + * @defgroup MDNS_PUBLIC_API + */ +mdns_browse_t *mdns_browse_new(const char *service, const char *proto, mdns_browse_notify_t notifier) +{ + return mdns_browse_new_with_subtype(service, proto, NULL, notifier); +} + +mdns_browse_t *mdns_browse_new_with_subtype(const char *service, const char *proto, const char *subtype, mdns_browse_notify_t notifier) +{ + mdns_browse_t *browse = NULL; + + if (!mdns_priv_is_server_init() || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return NULL; + } + + // Subtype identifier length limit defined in RFC 6763 Section 7.2 + if (subtype && strlen(subtype) > MDNS_SUBTYPE_MAX_LEN) { + ESP_LOGE(TAG, "Subtype string length must not exceed %d bytes", MDNS_SUBTYPE_MAX_LEN); + return NULL; + } + + browse = browse_init(service, proto, subtype, notifier); + if (!browse) { + return NULL; + } + + mdns_priv_service_lock(); + // Check if the browse already exists before sending action + if (get_non_off_browse_item(service, proto, subtype)) { + bool has_subtype = !mdns_utils_str_null_or_empty(subtype); + ESP_LOGW(TAG, "Browse already exists: %s%s%s.%s", has_subtype ? subtype : "", + has_subtype ? "._sub." : "", browse->service, browse->proto); + goto error; + } + + if (send_browse_action(ACTION_BROWSE_START, browse) != ESP_OK) { + ESP_LOGE(TAG, "Failed to send browse start action"); + goto error; + } + + browse->next = s_browse; + s_browse = browse; + mdns_priv_service_unlock(); + return browse; + +error: + browse_item_free(browse); + mdns_priv_service_unlock(); + return NULL; +} + +esp_err_t mdns_browse_delete(const char *service, const char *proto) +{ + return mdns_browse_delete_with_subtype(service, proto, NULL); +} + +esp_err_t mdns_browse_delete_with_subtype(const char *service, const char *proto, const char *subtype) +{ + mdns_browse_t *browse = NULL; + + if (!mdns_priv_is_server_init() || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_FAIL; + } + + // Subtype identifier length limit defined in RFC 6763 Section 7.2 + if (subtype && strlen(subtype) > MDNS_SUBTYPE_MAX_LEN) { + ESP_LOGE(TAG, "Subtype string length must not exceed 63 bytes"); + return ESP_FAIL; + } + + mdns_priv_service_lock(); + browse = get_non_off_browse_item(service, proto, subtype); + if (!browse) { + mdns_priv_service_unlock(); + return ESP_FAIL; + } + + mdns_browse_state_t prev_state = browse->state; + browse->state = BROWSE_OFF; + + if (send_browse_action(ACTION_BROWSE_END, browse) != ESP_OK) { + browse->state = prev_state; + mdns_priv_service_unlock(); + return ESP_ERR_NO_MEM; + } + + mdns_priv_service_unlock(); + return ESP_OK; +} diff --git a/managed_components/espressif__mdns/mdns_cache.c b/managed_components/espressif__mdns/mdns_cache.c new file mode 100644 index 0000000..b147bd1 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_cache.c @@ -0,0 +1,1294 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include "esp_check.h" +#include "esp_log.h" +#include "mdns_browser.h" +#include "mdns_cache.h" +#include "mdns_mem_caps.h" +#include "mdns_querier.h" +#include "mdns_utils.h" + +#define MDNS_CACHE_UNSUBSCRIBED_GRACE_SEC 300 // Maximum lifetime of cache records without consumers + +static const char *TAG = "mdns_cache"; + +static mdns_cache_entry_t *s_cache; +static mdns_cache_expiry_t *s_expiry; +static bool s_sync_pending; + +static inline int64_t calc_expiration_time_us(uint32_t ttl) +{ + return esp_timer_get_time() + (int64_t)ttl * MDNS_US_PER_SEC; +} + +/** + * @brief Insert a new expiry node to the head of `s_expiry` list. + * + * @note Should call `expiry_schedule` after this function to schedule the node to the correct position in the list. + */ +static bool expiry_new(mdns_cache_record_type_t type, mdns_cache_entry_t *entry, + mdns_service_cache_t *service, mdns_cache_addr_t *addr, mdns_cache_subtype_t *subtype) +{ + mdns_cache_expiry_t *node = mdns_mem_calloc(1, sizeof(mdns_cache_expiry_t)); + if (!node) { + HOOK_MALLOC_FAILED; + return false; + } + + node->entry = entry; + node->service = service; + node->addr = addr; + node->subtype = subtype; + node->record_mask = (mdns_cache_record_mask_t)type; + node->queued = false; + node->expires_at_us = INT64_MAX; + node->next = s_expiry; + s_expiry = node; + return true; +} + +static void expiry_schedule(mdns_cache_record_mask_t record_mask, mdns_cache_entry_t *entry, + mdns_service_cache_t *service, mdns_cache_addr_t *addr, mdns_cache_subtype_t *subtype) +{ + if (!entry || (record_mask == MDNS_CACHE_RECORD_ADDR ? !addr : !service) + || (record_mask == MDNS_CACHE_RECORD_SUBTYPE && !subtype)) { + return; + } + + mdns_cache_expiry_t **link = &s_expiry; + mdns_cache_expiry_t *node = NULL; + uint32_t ttl = 0; + + while (*link) { + mdns_cache_expiry_t *it = *link; + if (it->record_mask == record_mask && it->entry == entry + && (record_mask == MDNS_CACHE_RECORD_ADDR ? it->addr == addr : it->service == service) + && (record_mask != MDNS_CACHE_RECORD_SUBTYPE || it->subtype == subtype)) { + node = it; + *link = it->next; + break; + } + link = &it->next; + } + + if (!node) { + ESP_LOGE(TAG, "Cannot find expiry node for cache record"); + return; + } + + switch (record_mask) { + case MDNS_CACHE_RECORD_PTR: + ttl = service->ptr_ttl; + break; + case MDNS_CACHE_RECORD_SRV: + ttl = service->srv_ttl; + break; + case MDNS_CACHE_RECORD_TXT: + ttl = service->txt_ttl; + break; + case MDNS_CACHE_RECORD_ADDR: + ttl = addr->ttl; + break; + case MDNS_CACHE_RECORD_SUBTYPE: + ttl = subtype->ttl; + break; + default: + mdns_mem_free(node); + return; + } + + // If expiration time is extended, we can start the traverse from current node; otherwise start from the beginning. + const int64_t new_expiration_time_us = ttl == 0 ? 0 : calc_expiration_time_us(ttl); + const bool extended = new_expiration_time_us > node->expires_at_us && node->queued; + node->expires_at_us = new_expiration_time_us; + if (!extended) { + link = &s_expiry; + } + + while (*link && (*link)->expires_at_us < new_expiration_time_us) { + link = &(*link)->next; + } + node->next = *link; + *link = node; + node->queued = true; +} + +static bool update_ttl(uint32_t *cached_ttl, uint32_t ttl) +{ + if (*cached_ttl == ttl) { + return false; + } + *cached_ttl = ttl; + return true; +} + +static bool service_match(const mdns_service_cache_t *cache, const char *instance, const char *service, const char *proto) +{ + return mdns_utils_str_case_equal(cache->instance_name, instance) && mdns_utils_str_case_equal(cache->service, service) + && mdns_utils_str_case_equal(cache->proto, proto); +} + +static bool addr_equal(const esp_ip_addr_t *a, const esp_ip_addr_t *b) +{ + if (a->type != b->type) { + return false; + } + +#ifdef CONFIG_LWIP_IPV6 + if (a->type == ESP_IPADDR_TYPE_V6) { + return !memcmp(a->u_addr.ip6.addr, b->u_addr.ip6.addr, sizeof(a->u_addr.ip6.addr)); + } +#endif +#ifdef CONFIG_LWIP_IPV4 + if (a->type == ESP_IPADDR_TYPE_V4) { + return a->u_addr.ip4.addr == b->u_addr.ip4.addr; + } +#endif + + return false; +} + +/** + * @note Ensure service is not NULL before calling this function. + */ +static bool service_cache_is_empty(const mdns_service_cache_t *service) +{ + return service && (!service->ptr_present && !service->srv_present && !service->txt_present && !service->subtype_list); +} + +/** + * @brief Mark sync out flags for a service cache. + * + * @param service_entry Service cache entry to mark sync out flags for. + * @param result Result of the update operation. + * @param records Record types to mark for notification. + * @param consumer Consumer to notify. + */ +static void service_cache_mark_sync_out(mdns_service_cache_t *service_entry, mdns_cache_update_result_t result, + mdns_cache_record_mask_t records, mdns_cache_consumer_mask_t consumer) +{ + if (service_entry && (result == MDNS_CACHE_ADDED || result == MDNS_CACHE_UPDATED)) { + service_entry->sync_records |= records; + service_entry->sync_consumers |= consumer; + s_sync_pending = true; + } +} + +/** + * @brief Clear sync out flags for a service cache. + * + * @note For browsers, only clear MDNS_CACHE_CONSUMER_BROWSE from sync_consumers. + * + * @param service_entry Service cache entry to clear sync out flags for. + * @param consumer Consumer type to clear sync out flags for. + */ +static void service_cache_clear_sync_out(mdns_service_cache_t *service_entry, mdns_cache_consumer_type_t consumer) +{ + if (!service_entry) { + return; + } + + service_entry->sync_consumers &= ~(mdns_cache_consumer_mask_t)consumer; + + if (service_entry->sync_consumers == 0) { + service_entry->sync_records = 0; + + for (mdns_cache_subtype_t *it = service_entry->subtype_list; it; it = it->next) { + it->pending_sync = false; + } + } +} + +/** + * @brief Find a cache entry by hostname, esp_netif, and ip_protocol. + * + * @param hostname The hostname to find. + * @param esp_netif Pointer to the esp_netif to find. + * @param ip_protocol IP protocol to find. + * + * @return Pointer to the cache entry if found, NULL otherwise. + */ +static mdns_cache_entry_t *cache_find_entry(const char *hostname, const esp_netif_t *esp_netif, + mdns_ip_protocol_t ip_protocol) +{ + mdns_cache_entry_t *entry = s_cache; + while (entry) { + if (mdns_utils_str_case_equal_nullable(entry->hostname, hostname) && entry->esp_netif == esp_netif + && entry->ip_protocol == ip_protocol) { + return entry; + } + entry = entry->next; + } + return NULL; +} + +/** + * @brief Find a service cache entry by esp_netif, ip_protocol, instance, service, and proto. + * + * @param esp_netif Pointer to the esp_netif to find. + * @param ip_protocol IP protocol to find. + * @param instance The instance name to find. + * @param service The service name to find. + * @param proto The protocol to find. + * @param owner_entry Receives the pointer to the cache entry that owns the service cache. + * + * @return Pointer to the service cache entry if found, NULL otherwise. + */ +static mdns_service_cache_t *cache_find_service(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *instance, const char *service, const char *proto, + mdns_cache_entry_t **owner_entry) +{ + mdns_cache_entry_t *entry = s_cache; + if (owner_entry) { + *owner_entry = NULL; + } + + while (entry) { + if (entry->esp_netif == esp_netif && entry->ip_protocol == ip_protocol) { + mdns_service_cache_t *service_entry = entry->service_cache_list; + while (service_entry) { + if (service_match(service_entry, instance, service, proto)) { + if (owner_entry) { + *owner_entry = entry; + } + return service_entry; + } + service_entry = service_entry->next; + } + } + entry = entry->next; + } + return NULL; +} + +bool mdns_priv_cache_host_has_service(const char *hostname, const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *service, const char *proto) +{ + mdns_cache_entry_t *entry = cache_find_entry(hostname, esp_netif, ip_protocol); + if (!entry) { + return false; + } + + for (const mdns_service_cache_t *it = entry->service_cache_list; it; it = it->next) { + if (mdns_utils_str_case_equal(it->service, service) && mdns_utils_str_case_equal(it->proto, proto)) { + return true; + } + } + + return false; +} + +static void service_entry_free(mdns_service_cache_t *service_entry) +{ + mdns_mem_free(service_entry->instance_name); + mdns_mem_free(service_entry->service); + mdns_mem_free(service_entry->proto); + while (service_entry->subtype_list) { + mdns_cache_subtype_t *subtype = service_entry->subtype_list; + service_entry->subtype_list = subtype->next; + mdns_mem_free(subtype->subtype); + mdns_mem_free(subtype); + } + while (service_entry->txt_list) { + mdns_txt_linked_item_t *txt = service_entry->txt_list; + service_entry->txt_list = service_entry->txt_list->next; + mdns_mem_free((char *)txt->key); + mdns_mem_free(txt->value); + mdns_mem_free(txt); + } + mdns_mem_free(service_entry); +} + +static void cache_entry_free(mdns_cache_entry_t *entry) +{ + mdns_mem_free(entry->hostname); + while (entry->addr_list) { + mdns_cache_addr_t *addr = entry->addr_list; + entry->addr_list = entry->addr_list->next; + mdns_mem_free(addr); + } + while (entry->service_cache_list) { + mdns_service_cache_t *service_entry = entry->service_cache_list; + entry->service_cache_list = entry->service_cache_list->next; + service_entry_free(service_entry); + } + mdns_mem_free(entry); +} + +static bool cache_remove_entry(mdns_cache_entry_t *entry) +{ + if (!entry) { + return false; + } + + mdns_cache_entry_t **entry_ptr = &s_cache; + while (*entry_ptr) { + if (*entry_ptr == entry) { + *entry_ptr = entry->next; + cache_entry_free(entry); + return true; + } + entry_ptr = &(*entry_ptr)->next; + } + + return false; +} + +static bool cache_remove_entry_if_empty(mdns_cache_entry_t *entry) +{ + if (!entry || entry->addr_list || entry->service_cache_list) { + return false; + } + return cache_remove_entry(entry); +} + +static mdns_cache_entry_t *cache_add_entry(const char *hostname, const esp_netif_t *esp_netif, + mdns_ip_protocol_t ip_protocol) +{ + mdns_cache_entry_t *entry = mdns_mem_calloc(1, sizeof(mdns_cache_entry_t)); + if (!entry) { + HOOK_MALLOC_FAILED; + return NULL; + } + + if (!mdns_utils_str_null_or_empty(hostname)) { + entry->hostname = mdns_mem_strdup(hostname); + if (!entry->hostname) { + HOOK_MALLOC_FAILED; + mdns_mem_free(entry); + return NULL; + } + } + + entry->esp_netif = (esp_netif_t *)esp_netif; + entry->ip_protocol = ip_protocol; + entry->next = s_cache; + s_cache = entry; + return entry; +} + +static mdns_cache_entry_t *cache_get_or_add_entry(const char *hostname, const esp_netif_t *esp_netif, + mdns_ip_protocol_t ip_protocol) +{ + mdns_cache_entry_t *entry = cache_find_entry(hostname, esp_netif, ip_protocol); + return entry ? entry : cache_add_entry(hostname, esp_netif, ip_protocol); +} + +static mdns_service_cache_t *cache_add_service(mdns_cache_entry_t *entry, const char *instance, const char *service, + const char *proto) +{ + if (!entry) { + return NULL; + } + + mdns_service_cache_t *service_entry = mdns_mem_calloc(1, sizeof(mdns_service_cache_t)); + if (!service_entry) { + HOOK_MALLOC_FAILED; + return NULL; + } + + if (!mdns_utils_str_null_or_empty(instance)) { + service_entry->instance_name = mdns_mem_strdup(instance); + if (!service_entry->instance_name) { + HOOK_MALLOC_FAILED; + service_entry_free(service_entry); + return NULL; + } + } + + if (!mdns_utils_str_null_or_empty(service)) { + service_entry->service = mdns_mem_strdup(service); + if (!service_entry->service) { + HOOK_MALLOC_FAILED; + service_entry_free(service_entry); + return NULL; + } + } + + if (!mdns_utils_str_null_or_empty(proto)) { + service_entry->proto = mdns_mem_strdup(proto); + if (!service_entry->proto) { + HOOK_MALLOC_FAILED; + service_entry_free(service_entry); + return NULL; + } + } + + service_entry->next = entry->service_cache_list; + entry->service_cache_list = service_entry; + return service_entry; +} + +/** + * @brief Move a service cache from one cache entry to another. + * + * @param old_entry The old cache entry to move the service from. + * @param new_entry The new cache entry to move the service to. + * @param cache The service cache to move. + * + * @return true if the service cache was moved successfully, false otherwise. + * + * @note This function only moves the service cache and will not create or delete old entries. + */ +static bool cache_move_service(mdns_cache_entry_t *old_entry, mdns_cache_entry_t *new_entry, mdns_service_cache_t *cache) +{ + if (!old_entry || !new_entry || !cache) { + return false; + } + + mdns_service_cache_t **old_entry_cache = &old_entry->service_cache_list; + + while (*old_entry_cache) { + if (*old_entry_cache == cache) { + *old_entry_cache = cache->next; + cache->next = new_entry->service_cache_list; + new_entry->service_cache_list = cache; + + // Update the entry pointer for all expiration nodes of the service cache. + for (mdns_cache_expiry_t *it = s_expiry; it; it = it->next) { + if (it->service == cache) { + it->entry = new_entry; + } + } + return true; + } + old_entry_cache = &(*old_entry_cache)->next; + } + + ESP_LOGE(TAG, "No target service in old entry"); + return false; +} + +static mdns_cache_update_result_t service_cache_update_subtype(mdns_cache_entry_t *entry, mdns_service_cache_t *service_entry, + const char *subtype, uint32_t ttl) +{ + if (!service_entry) { + return MDNS_CACHE_ERROR; + } + if (mdns_utils_str_null_or_empty(subtype)) { + return MDNS_CACHE_NO_CHANGE; + } + + for (mdns_cache_subtype_t *it = service_entry->subtype_list; it; it = it->next) { + if (mdns_utils_str_case_equal(it->subtype, subtype)) { + bool changed = update_ttl(&it->ttl, ttl); + expiry_schedule(MDNS_CACHE_RECORD_SUBTYPE, entry, service_entry, NULL, it); + if (!changed) { + return MDNS_CACHE_NO_CHANGE; + } + it->pending_sync = true; + return MDNS_CACHE_UPDATED; + } + } + + mdns_cache_subtype_t *subtype_entry = mdns_mem_calloc(1, sizeof(mdns_cache_subtype_t)); + if (!subtype_entry) { + HOOK_MALLOC_FAILED; + return MDNS_CACHE_ERROR; + } + subtype_entry->subtype = mdns_mem_strdup(subtype); + if (!subtype_entry->subtype) { + HOOK_MALLOC_FAILED; + mdns_mem_free(subtype_entry); + return MDNS_CACHE_ERROR; + } + + subtype_entry->ttl = ttl; + if (!expiry_new(MDNS_CACHE_RECORD_SUBTYPE, entry, service_entry, NULL, subtype_entry)) { + mdns_mem_free(subtype_entry->subtype); + mdns_mem_free(subtype_entry); + return MDNS_CACHE_ERROR; + } + expiry_schedule(MDNS_CACHE_RECORD_SUBTYPE, entry, service_entry, NULL, subtype_entry); + subtype_entry->pending_sync = true; + subtype_entry->next = service_entry->subtype_list; + service_entry->subtype_list = subtype_entry; + return MDNS_CACHE_UPDATED; +} + +static mdns_cache_subtype_t *service_cache_find_subtype(const mdns_service_cache_t *service_entry, const char *subtype) +{ + if (!service_entry || mdns_utils_str_null_or_empty(subtype)) { + return NULL; + } + + for (mdns_cache_subtype_t *it = service_entry->subtype_list; it; it = it->next) { + if (mdns_utils_str_case_equal(it->subtype, subtype)) { + return it; + } + } + return NULL; +} + +const mdns_cache_subtype_t *mdns_priv_cache_service_find_subtype(const mdns_service_cache_t *service, const char *subtype) +{ + return service_cache_find_subtype(service, subtype); +} + +static void cache_remove_service_if_empty(mdns_cache_entry_t *entry, mdns_service_cache_t *service_entry) +{ + if (!entry || !service_cache_is_empty(service_entry)) { + return; + } + + mdns_service_cache_t **service_entry_ptr = &entry->service_cache_list; + while (*service_entry_ptr) { + if (*service_entry_ptr == service_entry) { + *service_entry_ptr = service_entry->next; + service_entry_free(service_entry); + cache_remove_entry_if_empty(entry); + return; + } + service_entry_ptr = &(*service_entry_ptr)->next; + } +} + +static bool cache_service_has_consumer(const mdns_service_cache_t *service) +{ + return service && mdns_priv_browse_has_service(service->service, service->proto); +} + +static bool cache_record_has_consumer(const mdns_cache_expiry_t *node) +{ + switch (node->record_mask) { + case MDNS_CACHE_RECORD_PTR: + // Base PTR is only consumed by browses without subtype + return node->service && !node->subtype + && mdns_priv_browse_has_subtype(node->service->service, node->service->proto, NULL); + case MDNS_CACHE_RECORD_SUBTYPE: + return node->service && node->subtype + && mdns_priv_browse_has_subtype(node->service->service, node->service->proto, node->subtype->subtype); + case MDNS_CACHE_RECORD_ADDR: + for (const mdns_service_cache_t *it = node->entry->service_cache_list; it; it = it->next) { + if (cache_service_has_consumer(it)) { + return true; + } + } + return false; + default: + return cache_service_has_consumer(node->service); + } +} + +mdns_cache_update_result_t mdns_priv_cache_update_ptr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *instance, const char *service, const char *proto, + const char *subtype, uint32_t ttl) +{ + if (mdns_utils_str_null_or_empty(instance) || mdns_utils_str_null_or_empty(service) + || mdns_utils_str_null_or_empty(proto)) { + return MDNS_CACHE_NO_CHANGE; + } + + mdns_cache_entry_t *owner_entry = NULL; + mdns_service_cache_t *service_entry = cache_find_service(esp_netif, ip_protocol, instance, + service, proto, &owner_entry); + mdns_cache_update_result_t result = MDNS_CACHE_NO_CHANGE; + bool new_service = false; + const bool base_ptr_updated = mdns_utils_str_null_or_empty(subtype); + + if (ttl == 0) { + if (!service_entry) { + return MDNS_CACHE_NO_CHANGE; + } + + if (base_ptr_updated) { + if (!service_entry->ptr_present) { + return MDNS_CACHE_NO_CHANGE; + } + service_entry->ptr_ttl = 0; + expiry_schedule(MDNS_CACHE_RECORD_PTR, owner_entry, service_entry, NULL, NULL); + } else { + mdns_cache_subtype_t *subtype_entry = service_cache_find_subtype(service_entry, subtype); + if (!subtype_entry) { + return MDNS_CACHE_NO_CHANGE; + } + subtype_entry->ttl = 0; + expiry_schedule(MDNS_CACHE_RECORD_SUBTYPE, owner_entry, service_entry, NULL, subtype_entry); + } + return MDNS_CACHE_UPDATED; + } + + if (!service_entry) { + // Uncached PTR records will all be stored in hostname == NULL entry temporarily + owner_entry = cache_get_or_add_entry(NULL, esp_netif, ip_protocol); + if (!owner_entry) { + return MDNS_CACHE_ERROR; + } + + service_entry = cache_add_service(owner_entry, instance, service, proto); + if (!service_entry) { + cache_remove_entry_if_empty(owner_entry); + return MDNS_CACHE_ERROR; + } + new_service = true; + } + + if (base_ptr_updated) { + if (!service_entry->ptr_present && !expiry_new(MDNS_CACHE_RECORD_PTR, owner_entry, service_entry, NULL, NULL)) { + cache_remove_service_if_empty(owner_entry, service_entry); + return MDNS_CACHE_ERROR; + } + bool changed = !service_entry->ptr_present; + service_entry->ptr_present = true; + changed |= update_ttl(&service_entry->ptr_ttl, ttl); + expiry_schedule(MDNS_CACHE_RECORD_PTR, owner_entry, service_entry, NULL, NULL); + if (changed) { + result = MDNS_CACHE_UPDATED; + } + } else { + result = service_cache_update_subtype(owner_entry, service_entry, subtype, ttl); + if (result == MDNS_CACHE_ERROR) { + cache_remove_service_if_empty(owner_entry, service_entry); + return MDNS_CACHE_ERROR; + } + } + + if (new_service) { + result = MDNS_CACHE_ADDED; + } + service_cache_mark_sync_out(service_entry, result, + base_ptr_updated ? MDNS_CACHE_RECORD_PTR : MDNS_CACHE_RECORD_SUBTYPE, + MDNS_CACHE_CONSUMER_BROWSE); + return result; +} + +static mdns_cache_update_result_t service_cache_srv_update(mdns_service_cache_t *cache, uint16_t priority, uint16_t weight, + uint16_t port, uint32_t ttl) +{ + mdns_cache_update_result_t result = MDNS_CACHE_NO_CHANGE; + + if (!cache->srv_present) { + cache->srv_present = true; + result = MDNS_CACHE_UPDATED; + } + if (cache->priority != priority) { + cache->priority = priority; + result = MDNS_CACHE_UPDATED; + } + if (cache->weight != weight) { + cache->weight = weight; + result = MDNS_CACHE_UPDATED; + } + if (cache->port != port) { + cache->port = port; + result = MDNS_CACHE_UPDATED; + } + if (update_ttl(&cache->srv_ttl, ttl)) { + result = MDNS_CACHE_UPDATED; + } + + return result; +} + +mdns_cache_update_result_t mdns_priv_cache_update_srv(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const char *instance, const char *service, + const char *proto, uint16_t priority, uint16_t weight, + uint16_t port, uint32_t ttl) +{ + mdns_cache_entry_t *owner_entry = NULL; + mdns_service_cache_t *service_entry = cache_find_service(esp_netif, ip_protocol, instance, service, + proto, &owner_entry); + mdns_cache_entry_t *host_entry = NULL; + mdns_cache_update_result_t result = MDNS_CACHE_NO_CHANGE; + + if (ttl == 0) { + if (!service_entry || !service_entry->srv_present) { + return MDNS_CACHE_NO_CHANGE; + } + + service_entry->srv_ttl = 0; + expiry_schedule(MDNS_CACHE_RECORD_SRV, owner_entry, service_entry, NULL, NULL); + return MDNS_CACHE_UPDATED; + } + + if (owner_entry && mdns_utils_str_case_equal(owner_entry->hostname, hostname)) { + host_entry = owner_entry; + } else { + host_entry = cache_get_or_add_entry(hostname, esp_netif, ip_protocol); + if (!host_entry) { + return MDNS_CACHE_ERROR; + } + } + + if (!service_entry) { + service_entry = cache_add_service(host_entry, instance, service, proto); + if (!service_entry) { + cache_remove_entry_if_empty(host_entry); + return MDNS_CACHE_ERROR; + } + result = MDNS_CACHE_ADDED; + } else if (owner_entry != host_entry) { + if (!cache_move_service(owner_entry, host_entry, service_entry)) { + cache_remove_entry_if_empty(host_entry); + return MDNS_CACHE_ERROR; + } + result = MDNS_CACHE_UPDATED; + } + + if (!service_entry->srv_present) { + // If the expiry creation failed, move the service cache back if host_entry is not NULL, otherwise remove the service cache. + if (!expiry_new(MDNS_CACHE_RECORD_SRV, host_entry, service_entry, NULL, NULL)) { + ESP_LOGE(TAG, "Failed to create SRV expiry"); + if (owner_entry) { + (void)cache_move_service(host_entry, owner_entry, service_entry); + cache_remove_entry_if_empty(host_entry); + } else { + cache_remove_service_if_empty(host_entry, service_entry); + } + return MDNS_CACHE_ERROR; + } + } + cache_remove_entry_if_empty(owner_entry); + + mdns_cache_update_result_t srv_result = service_cache_srv_update(service_entry, priority, weight, port, ttl); + expiry_schedule(MDNS_CACHE_RECORD_SRV, host_entry, service_entry, NULL, NULL); + if (result == MDNS_CACHE_NO_CHANGE) { + result = srv_result; + } + + service_cache_mark_sync_out(service_entry, result, MDNS_CACHE_RECORD_SRV, MDNS_CACHE_CONSUMER_BROWSE); + return result; +} + +static bool txt_item_equal(const mdns_txt_linked_item_t *a, const mdns_txt_linked_item_t *b) +{ + if (!a || !b || !mdns_utils_str_case_equal(a->key, b->key)) { + return false; + } + if (a->value_len != b->value_len) { + return false; + } + if (!a->value && !b->value) { + return true; + } + return a->value && b->value && memcmp(a->value, b->value, a->value_len) == 0; +} + +static bool txt_list_contains(const mdns_txt_linked_item_t *txt_list, const mdns_txt_linked_item_t *item) +{ + while (txt_list) { + if (txt_item_equal(txt_list, item)) { + return true; + } + txt_list = txt_list->next; + } + return false; +} + +static size_t txt_list_count(const mdns_txt_linked_item_t *txt_list) +{ + size_t count = 0; + while (txt_list) { + count++; + txt_list = txt_list->next; + } + return count; +} + +static bool txt_list_equal(const mdns_txt_linked_item_t *a, const mdns_txt_linked_item_t *b) +{ + if (a == b) { + return true; + } + + if (txt_list_count(a) != txt_list_count(b)) { + return false; + } + + for (const mdns_txt_linked_item_t *it = a; it; it = it->next) { + if (!txt_list_contains(b, it)) { + return false; + } + } + + return true; +} + +static mdns_cache_update_result_t service_cache_txt_update(mdns_service_cache_t *service_entry, + mdns_txt_linked_item_t *new_txt, uint32_t ttl) +{ + if (!service_entry) { + mdns_utils_free_txt_linked_list(new_txt); + return MDNS_CACHE_ERROR; + } + + if (txt_list_equal(service_entry->txt_list, new_txt) && service_entry->txt_present + && !update_ttl(&service_entry->txt_ttl, ttl)) { + mdns_utils_free_txt_linked_list(new_txt); + return MDNS_CACHE_NO_CHANGE; + } + + service_entry->txt_present = true; + service_entry->txt_ttl = ttl; + mdns_txt_linked_item_t *old_txt = service_entry->txt_list; + service_entry->txt_list = new_txt; + mdns_utils_free_txt_linked_list(old_txt); + return MDNS_CACHE_UPDATED; +} + +mdns_cache_update_result_t mdns_priv_cache_update_txt(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *instance, const char *service, const char *proto, + mdns_txt_linked_item_t *txt, uint32_t ttl) +{ + mdns_cache_entry_t *owner_entry = NULL; + mdns_service_cache_t *service_entry = cache_find_service(esp_netif, ip_protocol, instance, + service, proto, &owner_entry); + mdns_cache_update_result_t result = MDNS_CACHE_NO_CHANGE; + bool new_service = false; + + if (ttl == 0) { + mdns_utils_free_txt_linked_list(txt); + if (!service_entry || !service_entry->txt_present) { + return MDNS_CACHE_NO_CHANGE; + } + + service_entry->txt_ttl = 0; + expiry_schedule(MDNS_CACHE_RECORD_TXT, owner_entry, service_entry, NULL, NULL); + return MDNS_CACHE_UPDATED; + } + + if (!service_entry) { + owner_entry = cache_get_or_add_entry(NULL, esp_netif, ip_protocol); + if (!owner_entry) { + mdns_utils_free_txt_linked_list(txt); + return MDNS_CACHE_ERROR; + } + + service_entry = cache_add_service(owner_entry, instance, service, proto); + if (!service_entry) { + cache_remove_entry_if_empty(owner_entry); + mdns_utils_free_txt_linked_list(txt); + return MDNS_CACHE_ERROR; + } + + new_service = true; + } + + if (!service_entry->txt_present) { + if (!expiry_new(MDNS_CACHE_RECORD_TXT, owner_entry, service_entry, NULL, NULL)) { + ESP_LOGE(TAG, "Failed to create TXT expiry"); + cache_remove_service_if_empty(owner_entry, service_entry); + mdns_utils_free_txt_linked_list(txt); + return MDNS_CACHE_ERROR; + } + } + + result = service_cache_txt_update(service_entry, txt, ttl); + expiry_schedule(MDNS_CACHE_RECORD_TXT, owner_entry, service_entry, NULL, NULL); + if (new_service) { + result = MDNS_CACHE_ADDED; + } + + service_cache_mark_sync_out(service_entry, result, MDNS_CACHE_RECORD_TXT, MDNS_CACHE_CONSUMER_BROWSE); + return result; +} + +static mdns_cache_update_result_t cache_update_addr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const esp_ip_addr_t *addr, uint32_t ttl, + bool create_if_absent) +{ + mdns_cache_entry_t *entry = NULL; + bool addr_added = false; + bool ttl_changed = false; + mdns_cache_update_result_t result = MDNS_CACHE_NO_CHANGE; + + if (ttl == 0) { + entry = cache_find_entry(hostname, esp_netif, ip_protocol); + if (!entry) { + return MDNS_CACHE_NO_CHANGE; + } + + // Remove addr + for (mdns_cache_addr_t *it = entry->addr_list; it; it = it->next) { + if (addr_equal(&it->addr, addr)) { + it->ttl = 0; + expiry_schedule(MDNS_CACHE_RECORD_ADDR, entry, NULL, it, NULL); + return MDNS_CACHE_UPDATED; + } + } + + return MDNS_CACHE_NO_CHANGE; + } + + entry = create_if_absent ? cache_get_or_add_entry(hostname, esp_netif, ip_protocol) + : cache_find_entry(hostname, esp_netif, ip_protocol); + if (!entry) { + return create_if_absent ? MDNS_CACHE_ERROR : MDNS_CACHE_NO_CHANGE; + } + + mdns_cache_addr_t **addr_link = &entry->addr_list; + mdns_cache_addr_t *addr_entry = NULL; + while (*addr_link) { + if (addr_equal(&(*addr_link)->addr, addr)) { + addr_entry = *addr_link; + ttl_changed = update_ttl(&(*addr_link)->ttl, ttl); + expiry_schedule(MDNS_CACHE_RECORD_ADDR, entry, NULL, addr_entry, NULL); + break; + } + addr_link = &(*addr_link)->next; + } + + if (!addr_entry) { + mdns_cache_addr_t *new_addr = mdns_mem_calloc(1, sizeof(mdns_cache_addr_t)); + if (!new_addr) { + HOOK_MALLOC_FAILED; + cache_remove_entry_if_empty(entry); + return MDNS_CACHE_ERROR; + } + + if (!expiry_new(MDNS_CACHE_RECORD_ADDR, entry, NULL, new_addr, NULL)) { + ESP_LOGE(TAG, "Failed to create ADDR expiry"); + mdns_mem_free(new_addr); + cache_remove_entry_if_empty(entry); + return MDNS_CACHE_ERROR; + } + new_addr->addr = *addr; + new_addr->ttl = ttl; + expiry_schedule(MDNS_CACHE_RECORD_ADDR, entry, NULL, new_addr, NULL); + new_addr->next = entry->addr_list; + entry->addr_list = new_addr; + addr_added = true; + } + + result = (addr_added || ttl_changed) ? MDNS_CACHE_UPDATED : MDNS_CACHE_NO_CHANGE; + for (mdns_service_cache_t *service = entry->service_cache_list; service; service = service->next) { + service_cache_mark_sync_out(service, result, MDNS_CACHE_RECORD_ADDR, MDNS_CACHE_CONSUMER_BROWSE); + } + + return result; +} + +mdns_cache_update_result_t mdns_priv_cache_update_addr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const esp_ip_addr_t *addr, uint32_t ttl) +{ + return cache_update_addr(esp_netif, ip_protocol, hostname, addr, ttl, true); +} + +mdns_cache_update_result_t mdns_priv_cache_update_existing_addr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const esp_ip_addr_t *addr, uint32_t ttl) +{ + mdns_cache_entry_t *entry = cache_find_entry(hostname, esp_netif, ip_protocol); + if (!entry) { + return MDNS_CACHE_NO_CHANGE; + } + + // Only update ADDR records if consumers exist + for (const mdns_service_cache_t *service = entry->service_cache_list; service; service = service->next) { + if (mdns_priv_browse_has_service(service->service, service->proto)) { + return cache_update_addr(esp_netif, ip_protocol, hostname, addr, ttl, false); + } + } + return MDNS_CACHE_NO_CHANGE; +} + +void mdns_priv_cache_remove_expired_records(int64_t now_us) +{ + if (!s_expiry || s_expiry->expires_at_us > now_us) { + return; + } + + while (s_expiry && s_expiry->expires_at_us <= now_us) { + mdns_cache_expiry_t *node = s_expiry; + mdns_cache_addr_t *addr = node->addr; + mdns_cache_subtype_t *subtype = node->subtype; + mdns_cache_entry_t *entry = node->entry; + mdns_service_cache_t *service = node->service; + mdns_cache_record_mask_t record = node->record_mask; + s_expiry = s_expiry->next; + + switch (record) { + case MDNS_CACHE_RECORD_PTR: + if (!service) { + mdns_mem_free(node); + continue; + } + service->ptr_present = false; + service->ptr_ttl = 0; + if (!mdns_priv_browse_notify_ptr_goodbye_from_service_cache(entry, service, NULL)) { + ESP_LOGE(TAG, "Failed to notify PTR expiration"); + } + break; + case MDNS_CACHE_RECORD_SUBTYPE: { + if (!service || !subtype) { + mdns_mem_free(node); + continue; + } + if (!mdns_priv_browse_notify_ptr_goodbye_from_service_cache(entry, service, subtype->subtype)) { + ESP_LOGE(TAG, "Failed to notify subtype PTR expiration"); + } + queueDetach(mdns_cache_subtype_t, service->subtype_list, subtype); + mdns_mem_free(subtype->subtype); + mdns_mem_free(subtype); + break; + } + case MDNS_CACHE_RECORD_SRV: + if (!service) { + mdns_mem_free(node); + continue; + } + service->srv_present = false; + service->priority = 0; + service->weight = 0; + service->port = 0; + service->srv_ttl = 0; + break; + case MDNS_CACHE_RECORD_TXT: + if (!service) { + mdns_mem_free(node); + continue; + } + service->txt_present = false; + mdns_utils_free_txt_linked_list(service->txt_list); + service->txt_list = NULL; + service->txt_ttl = 0; + break; + case MDNS_CACHE_RECORD_ADDR: + if (!addr) { + mdns_mem_free(node); + continue; + } + queueDetach(mdns_cache_addr_t, entry->addr_list, addr); + mdns_mem_free(addr); + + for (mdns_service_cache_t *it = entry->service_cache_list; it; it = it->next) { + service_cache_mark_sync_out(it, MDNS_CACHE_UPDATED, MDNS_CACHE_RECORD_ADDR, MDNS_CACHE_CONSUMER_BROWSE); + } + cache_remove_entry_if_empty(entry); + break; + } + + if (service && service_cache_is_empty(service)) { + cache_remove_service_if_empty(entry, service); + } else if ((record & (MDNS_CACHE_RECORD_PTR | MDNS_CACHE_RECORD_SUBTYPE)) == 0) { + // PTR removal is already reported through the goodbye path + service_cache_mark_sync_out(service, MDNS_CACHE_UPDATED, record, MDNS_CACHE_CONSUMER_BROWSE); + } + mdns_mem_free(node); + } +} + +void mdns_priv_cache_trim_unsubscribed_records(int64_t now_us) +{ + const int64_t deadline = now_us + (int64_t)MDNS_CACHE_UNSUBSCRIBED_GRACE_SEC * MDNS_US_PER_SEC; + mdns_cache_expiry_t **link = &s_expiry; + + while (*link && (*link)->expires_at_us <= deadline) { + link = &(*link)->next; + } + mdns_cache_expiry_t **insert_link = link; + + // Only scans through nodes with expiry time > deadline + // If record has no consumers, move expiry node to insert_link + while (*link) { + mdns_cache_expiry_t *node = *link; + if (cache_record_has_consumer(node)) { + link = &node->next; + continue; + } + + *link = node->next; + node->expires_at_us = deadline; + node->next = *insert_link; + *insert_link = node; + if (link == insert_link) { + // In case first *link has no consumers, causing link never moves and infinite loop + link = &node->next; + } + } +} + +void mdns_priv_cache_clear(void) +{ + while (s_cache) { + mdns_cache_entry_t *entry = s_cache; + s_cache = s_cache->next; + cache_entry_free(entry); + } + while (s_expiry) { + mdns_cache_expiry_t *node = s_expiry; + s_expiry = s_expiry->next; + mdns_mem_free(node); + } + s_sync_pending = false; +} + +static bool project_txt(const mdns_txt_linked_item_t *txt_list, mdns_txt_item_t **out_txt, uint8_t **out_value_len, + size_t *out_count) +{ + esp_err_t __attribute__((unused))ret = ESP_OK; + *out_txt = NULL; + *out_value_len = NULL; + *out_count = 0; + + size_t count = 0; + for (const mdns_txt_linked_item_t *txt = txt_list; txt; txt = txt->next) { + count++; + } + if (count == 0) { + return true; + } + + mdns_txt_item_t *txt_items = mdns_mem_calloc(count, sizeof(mdns_txt_item_t)); + if (!txt_items) { + HOOK_MALLOC_FAILED; + return false; + } + uint8_t *value_len = mdns_mem_calloc(count, sizeof(uint8_t)); + if (!value_len) { + HOOK_MALLOC_FAILED; + mdns_mem_free(txt_items); + return false; + } + + size_t i = 0; + for (const mdns_txt_linked_item_t *txt = txt_list; txt; txt = txt->next, i++) { + txt_items[i].key = mdns_mem_strdup(txt->key); + ESP_GOTO_ON_FALSE(txt_items[i].key, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate key"); + + value_len[i] = txt->value_len; + if (!txt->value) { + ESP_GOTO_ON_FALSE(txt->value_len == 0, ESP_ERR_INVALID_ARG, cleanup, TAG, "Invalid value"); + continue; + } + + txt_items[i].value = mdns_mem_calloc(txt->value_len + 1, sizeof(char)); + ESP_GOTO_ON_FALSE(txt_items[i].value, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate value"); + memcpy((char *)txt_items[i].value, txt->value, txt->value_len); + } + + *out_value_len = value_len; + *out_count = count; + *out_txt = txt_items; + return true; + +error: + HOOK_MALLOC_FAILED; +cleanup: + for (size_t i = 0; i < count; i++) { + mdns_mem_free((char *)txt_items[i].key); + mdns_mem_free((char *)txt_items[i].value); + } + mdns_mem_free(value_len); + mdns_mem_free(txt_items); + return false; +} + +static bool project_addr(const mdns_cache_addr_t *addr_list, mdns_ip_addr_t **out_addr_list) +{ + mdns_ip_addr_t *head = NULL; + mdns_ip_addr_t **tail = &head; + + *out_addr_list = NULL; + + for (const mdns_cache_addr_t *addr = addr_list; addr; addr = addr->next) { + mdns_ip_addr_t *new_addr = mdns_mem_calloc(1, sizeof(mdns_ip_addr_t)); + if (!new_addr) { + HOOK_MALLOC_FAILED; + while (head) { + mdns_ip_addr_t *next = head->next; + mdns_mem_free(head); + head = next; + } + return false; + } + new_addr->addr = addr->addr; + *tail = new_addr; + tail = &new_addr->next; + } + + *out_addr_list = head; + return true; +} + +esp_err_t mdns_priv_service_cache_to_result(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_result_t **out_result) +{ + esp_err_t ret = ESP_OK; + mdns_result_t *result = mdns_mem_calloc(1, sizeof(mdns_result_t)); + ESP_GOTO_ON_FALSE(result, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate result"); + + result->esp_netif = entry->esp_netif; + result->ttl = service->ptr_ttl; + result->ip_protocol = entry->ip_protocol; + + if (!mdns_utils_str_null_or_empty(service->instance_name)) { + result->instance_name = mdns_mem_strdup(service->instance_name); + ESP_GOTO_ON_FALSE(result->instance_name, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate instance name"); + } + if (!mdns_utils_str_null_or_empty(service->service)) { + result->service_type = mdns_mem_strdup(service->service); + ESP_GOTO_ON_FALSE(result->service_type, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate service type"); + } + if (!mdns_utils_str_null_or_empty(service->proto)) { + result->proto = mdns_mem_strdup(service->proto); + ESP_GOTO_ON_FALSE(result->proto, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate protocol"); + } + + if (service->srv_present) { + if (entry->hostname) { + result->hostname = mdns_mem_strdup(entry->hostname); + ESP_GOTO_ON_FALSE(result->hostname, ESP_ERR_NO_MEM, error, TAG, "Failed to allocate hostname"); + } + result->port = service->port; + // Address list is bound to hostname, so when srv is removed, the address list should not be projected. + ESP_GOTO_ON_FALSE(project_addr(entry->addr_list, &result->addr), ESP_ERR_NO_MEM, error, TAG, + "Failed to project address list"); + } + + if (service->txt_present) { + ESP_GOTO_ON_FALSE(project_txt(service->txt_list, &result->txt, &result->txt_value_len, &result->txt_count), + ESP_ERR_NO_MEM, error, TAG, "Failed to project TXT"); + } + + *out_result = result; + return ret; + +error: + HOOK_MALLOC_FAILED; + mdns_priv_query_results_free(result); + return ret; +} + +void mdns_priv_cache_process_sync(void) +{ + if (!s_sync_pending) { + return; + } + s_sync_pending = false; + + for (mdns_cache_entry_t *entry = s_cache; entry; entry = entry->next) { + for (mdns_service_cache_t *service = entry->service_cache_list; service; service = service->next) { + if (service->sync_consumers & MDNS_CACHE_CONSUMER_BROWSE) { + mdns_cache_record_mask_t records = service->sync_records; + if (!mdns_priv_browse_update_from_service_cache(entry, service, records)) { + ESP_LOGW(TAG, "Failed to notify browse, dropping sync mark"); + } + service_cache_clear_sync_out(service, MDNS_CACHE_CONSUMER_BROWSE); + } + // TODO: When resolver is implemented, add resolver sync processing here. + } + } +} + +bool mdns_priv_cache_notify_browse(mdns_browse_t *browse) +{ + if (!browse) { + return false; + } + + bool notified = true; + + for (mdns_cache_entry_t *entry = s_cache; entry; entry = entry->next) { + for (mdns_service_cache_t *service = entry->service_cache_list; service; service = service->next) { + notified &= mdns_priv_browse_notify_from_service_cache(entry, service, browse); + } + } + + return notified; +} diff --git a/managed_components/espressif__mdns/mdns_console.c b/managed_components/espressif__mdns/mdns_console.c new file mode 100644 index 0000000..c8fe864 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_console.c @@ -0,0 +1,1534 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include "esp_console.h" +#include "argtable3/argtable3.h" +#include "mdns.h" +#include "mdns_private.h" +#include "inttypes.h" +#include "mdns_mem_caps.h" + +static const char *ip_protocol_str[] = {"V4", "V6", "MAX"}; + +static void mdns_print_results(mdns_result_t *results) +{ + mdns_result_t *r = results; + mdns_ip_addr_t *a = NULL; + int i = 1; + while (r) { + if (r->esp_netif) { + printf("%d: Interface: %s, Type: %s, TTL: %" PRIu32 "\n", i++, esp_netif_get_ifkey(r->esp_netif), + ip_protocol_str[r->ip_protocol], r->ttl); + } + if (r->instance_name) { + printf(" PTR : %s\n", r->instance_name); + } + if (r->hostname) { + printf(" SRV : %s.local:%u\n", r->hostname, r->port); + } + if (r->txt_count) { + printf(" TXT : [%u] ", (int)r->txt_count); + for (size_t t = 0; t < r->txt_count; t++) { + printf("%s=%s; ", r->txt[t].key, r->txt[t].value); + } + printf("\n"); + } + a = r->addr; + while (a) { + if (a->addr.type == ESP_IPADDR_TYPE_V6) { + printf(" AAAA: " IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6)); + } else { + printf(" A : " IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4))); + } + a = a->next; + } + r = r->next; + } +} + +static struct { + struct arg_str *hostname; + struct arg_int *timeout; + struct arg_end *end; +} mdns_query_a_args; + +#ifdef CONFIG_LWIP_IPV4 +static int cmd_mdns_query_a(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_a_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_a_args.end, argv[0]); + return 1; + } + + const char *hostname = mdns_query_a_args.hostname->sval[0]; + int timeout = mdns_query_a_args.timeout->ival[0]; + + if (!hostname || !hostname[0]) { + printf("ERROR: Hostname not supplied\n"); + return 1; + } + + if (timeout <= 0) { + timeout = 1000; + } + + printf("Query A: %s.local, Timeout: %d\n", hostname, timeout); + + struct esp_ip4_addr addr; + addr.addr = 0; + + esp_err_t err = mdns_query_a(hostname, timeout, &addr); + if (err) { + if (err == ESP_ERR_NOT_FOUND) { + printf("ERROR: Host was not found!\n"); + return 0; + } + printf("ERROR: Query Failed\n"); + return 1; + } + + printf(IPSTR "\n", IP2STR(&addr)); + + return 0; +} + +static void register_mdns_query_a(void) +{ + mdns_query_a_args.hostname = arg_str1(NULL, NULL, "", "Hostname that is searched for"); + mdns_query_a_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_a_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_a", + .help = "Query MDNS for IPv4", + .hint = NULL, + .func = &cmd_mdns_query_a, + .argtable = &mdns_query_a_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *hostname; + struct arg_int *timeout; + struct arg_end *end; +} mdns_query_a_async_args; + +static int cmd_mdns_query_a_async(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_a_async_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_a_async_args.end, argv[0]); + return 1; + } + + const char *hostname = mdns_query_a_async_args.hostname->sval[0]; + int timeout = mdns_query_a_async_args.timeout->ival[0]; + + if (!hostname || !hostname[0]) { + printf("ERROR: Hostname not supplied\n"); + return 1; + } + + if (timeout <= 0) { + timeout = 1000; + } + + printf("Query A async: %s.local, Timeout: %d\n", hostname, timeout); + + mdns_search_once_t *search = mdns_query_async_new(hostname, NULL, NULL, MDNS_TYPE_A, timeout, 1, NULL); + if (!search) { + printf("ERROR: Failed to start async query\n"); + return 1; + } + + mdns_result_t *result = NULL; + /* Wait past search->timeout so SEARCH_OFF / done_semaphore are set before + * delete. mdns_query_async_delete() requires SEARCH_OFF; a too-short wait + * under timer/action-queue latency would leave the search on the global list. */ + bool done = mdns_query_async_get_results(search, timeout + 1000, &result, NULL); + if (!done || !result) { + printf("ERROR: Host was not found!\n"); + if (!done) { + /* Still running — wait for the search's own timeout to finish. */ + mdns_query_async_get_results(search, 1000, &result, NULL); + } + mdns_query_async_delete(search); + return 0; + } + + for (mdns_ip_addr_t *a = result->addr; a; a = a->next) { + if (a->addr.type == ESP_IPADDR_TYPE_V4) { + printf("Async query resolved to A:" IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4))); + } + } + + mdns_query_results_free(result); + mdns_query_async_delete(search); + return 0; +} + +static void register_mdns_query_a_async(void) +{ + mdns_query_a_async_args.hostname = arg_str1(NULL, NULL, "", "Hostname that is searched for"); + mdns_query_a_async_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_a_async_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_a_async", + .help = "Query MDNS for IPv4 asynchronously", + .hint = NULL, + .func = &cmd_mdns_query_a_async, + .argtable = &mdns_query_a_async_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} +#endif /* CONFIG_LWIP_IPV4 */ + +#ifdef CONFIG_LWIP_IPV6 +static int cmd_mdns_query_aaaa(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_a_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_a_args.end, argv[0]); + return 1; + } + + const char *hostname = mdns_query_a_args.hostname->sval[0]; + int timeout = mdns_query_a_args.timeout->ival[0]; + + if (!hostname || !hostname[0]) { + printf("ERROR: Hostname not supplied\n"); + return 1; + } + + if (timeout <= 0) { + timeout = 1000; + } + + printf("Query AAAA: %s.local, Timeout: %d\n", hostname, timeout); + + struct esp_ip6_addr addr; + memset(addr.addr, 0, 16); + + esp_err_t err = mdns_query_aaaa(hostname, timeout, &addr); + if (err) { + if (err == ESP_ERR_NOT_FOUND) { + printf("Host was not found!\n"); + return 0; + } + printf("ERROR: Query Failed\n"); + return 1; + } + + printf(IPV6STR "\n", IPV62STR(addr)); + + return 0; +} + +static void register_mdns_query_aaaa(void) +{ + mdns_query_a_args.hostname = arg_str1(NULL, NULL, "", "Hostname that is searched for"); + mdns_query_a_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_a_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_aaaa", + .help = "Query MDNS for IPv6", + .hint = NULL, + .func = &cmd_mdns_query_aaaa, + .argtable = &mdns_query_a_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} +#endif /* CONFIG_LWIP_IPV6 */ + +static struct { + struct arg_str *instance; + struct arg_str *service; + struct arg_str *proto; + struct arg_int *timeout; + struct arg_end *end; +} mdns_query_srv_args; + +static int cmd_mdns_query_srv(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_srv_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_srv_args.end, argv[0]); + return 1; + } + + const char *instance = mdns_query_srv_args.instance->sval[0]; + const char *service = mdns_query_srv_args.service->sval[0]; + const char *proto = mdns_query_srv_args.proto->sval[0]; + int timeout = mdns_query_srv_args.timeout->ival[0]; + + if (timeout <= 0) { + timeout = 1000; + } + + printf("Query SRV: %s.%s.%s.local, Timeout: %d\n", instance, service, proto, timeout); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query_srv(instance, service, proto, timeout, &results); + if (err) { + printf("ERROR: Query Failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + mdns_print_results(results); + mdns_query_results_free(results); + return 0; +} + +static void register_mdns_query_srv(void) +{ + mdns_query_srv_args.instance = arg_str1(NULL, NULL, "", "Instance to search for"); + mdns_query_srv_args.service = arg_str1(NULL, NULL, "", "Service to search for (ex. _http, _smb, etc.)"); + mdns_query_srv_args.proto = arg_str1(NULL, NULL, "", "Protocol to search for (_tcp, _udp, etc.)"); + mdns_query_srv_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_srv_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_srv", + .help = "Query MDNS for Service SRV", + .hint = NULL, + .func = &cmd_mdns_query_srv, + .argtable = &mdns_query_srv_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *instance; + struct arg_str *service; + struct arg_str *proto; + struct arg_int *timeout; + struct arg_end *end; +} mdns_query_txt_args; + +static int cmd_mdns_query_txt(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_txt_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_txt_args.end, argv[0]); + return 1; + } + + const char *instance = mdns_query_txt_args.instance->sval[0]; + const char *service = mdns_query_txt_args.service->sval[0]; + const char *proto = mdns_query_txt_args.proto->sval[0]; + int timeout = mdns_query_txt_args.timeout->ival[0]; + + printf("Query TXT: %s.%s.%s.local, Timeout: %d\n", instance, service, proto, timeout); + + if (timeout <= 0) { + timeout = 5000; + } + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query_txt(instance, service, proto, timeout, &results); + if (err) { + printf("ERROR: Query Failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + + mdns_print_results(results); + mdns_query_results_free(results); + return 0; +} + +static void register_mdns_query_txt(void) +{ + mdns_query_txt_args.instance = arg_str1(NULL, NULL, "", "Instance to search for"); + mdns_query_txt_args.service = arg_str1(NULL, NULL, "", "Service to search for (ex. _http, _smb, etc.)"); + mdns_query_txt_args.proto = arg_str1(NULL, NULL, "", "Protocol to search for (_tcp, _udp, etc.)"); + mdns_query_txt_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_txt_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_txt", + .help = "Query MDNS for Service TXT", + .hint = NULL, + .func = &cmd_mdns_query_txt, + .argtable = &mdns_query_txt_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_int *timeout; + struct arg_int *max_results; + struct arg_end *end; +} mdns_query_ptr_args; + +static int cmd_mdns_query_ptr(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_ptr_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_ptr_args.end, argv[0]); + return 1; + } + + const char *service = mdns_query_ptr_args.service->sval[0]; + const char *proto = mdns_query_ptr_args.proto->sval[0]; + int timeout = mdns_query_ptr_args.timeout->ival[0]; + int max_results = mdns_query_ptr_args.max_results->ival[0]; + + if (timeout <= 0) { + timeout = 5000; + } + + if (max_results <= 0 || max_results > 255) { + max_results = 255; + } + + printf("Query PTR: %s.%s.local, Timeout: %d, Max Results: %d\n", service, proto, timeout, max_results); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query_ptr(service, proto, timeout, max_results, &results); + if (err) { + printf("ERROR: Query Failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + + mdns_print_results(results); + mdns_query_results_free(results); + return 0; +} + +static void register_mdns_query_ptr(void) +{ + mdns_query_ptr_args.service = arg_str1(NULL, NULL, "", "Service to search for (ex. _http, _smb, etc.)"); + mdns_query_ptr_args.proto = arg_str1(NULL, NULL, "", "Protocol to search for (_tcp, _udp, etc.)"); + mdns_query_ptr_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_ptr_args.max_results = arg_int0("m", "max_results", "", "Maximum results returned"); + mdns_query_ptr_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_ptr", + .help = "Query MDNS for Service", + .hint = NULL, + .func = &cmd_mdns_query_ptr, + .argtable = &mdns_query_ptr_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *hostname; + struct arg_int *timeout; + struct arg_int *max_results; + struct arg_end *end; +} mdns_query_ip_args; + +static int cmd_mdns_query_ip(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_ip_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_ip_args.end, argv[0]); + return 1; + } + + const char *hostname = mdns_query_ip_args.hostname->sval[0]; + int timeout = mdns_query_ip_args.timeout->ival[0]; + int max_results = mdns_query_ip_args.max_results->ival[0]; + + if (!hostname || !hostname[0]) { + printf("ERROR: Hostname not supplied\n"); + return 1; + } + + if (timeout <= 0) { + timeout = 1000; + } + + if (max_results < 0 || max_results > 255) { + max_results = 255; + } + + printf("Query IP: %s.local, Timeout: %d, Max Results: %d\n", hostname, timeout, max_results); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query(hostname, NULL, NULL, MDNS_TYPE_ANY, timeout, max_results, &results); + if (err) { + printf("ERROR: Query Failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + mdns_print_results(results); + mdns_query_results_free(results); + + return 0; +} + +static void register_mdns_query_ip(void) +{ + mdns_query_ip_args.hostname = arg_str1(NULL, NULL, "", "Hostname that is searched for"); + mdns_query_ip_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_ip_args.max_results = arg_int0("m", "max_results", "", "Maximum results returned"); + mdns_query_ip_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_ip", + .help = "Query MDNS for IP", + .hint = NULL, + .func = &cmd_mdns_query_ip, + .argtable = &mdns_query_ip_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *instance; + struct arg_str *service; + struct arg_str *proto; + struct arg_int *timeout; + struct arg_int *max_results; + struct arg_end *end; +} mdns_query_svc_args; + +static int cmd_mdns_query_svc(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_query_svc_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_query_svc_args.end, argv[0]); + return 1; + } + + const char *instance = mdns_query_svc_args.instance->sval[0]; + const char *service = mdns_query_svc_args.service->sval[0]; + const char *proto = mdns_query_svc_args.proto->sval[0]; + int timeout = mdns_query_svc_args.timeout->ival[0]; + int max_results = mdns_query_svc_args.max_results->ival[0]; + + if (timeout <= 0) { + timeout = 5000; + } + + if (max_results < 0 || max_results > 255) { + max_results = 255; + } + + printf("Query SVC: %s.%s.%s.local, Timeout: %d, Max Results: %d\n", instance, service, proto, timeout, max_results); + + mdns_result_t *results = NULL; + esp_err_t err = mdns_query(instance, service, proto, MDNS_TYPE_ANY, timeout, max_results, &results); + if (err) { + printf("ERROR: Query Failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + + mdns_print_results(results); + mdns_query_results_free(results); + return 0; +} + +static void register_mdns_query_svc(void) +{ + mdns_query_svc_args.instance = arg_str1(NULL, NULL, "", "Instance to search for"); + mdns_query_svc_args.service = arg_str1(NULL, NULL, "", "Service to search for (ex. _http, _smb, etc.)"); + mdns_query_svc_args.proto = arg_str1(NULL, NULL, "", "Protocol to search for (_tcp, _udp, etc.)"); + mdns_query_svc_args.timeout = arg_int0("t", "timeout", "", "Timeout for this query"); + mdns_query_svc_args.max_results = arg_int0("m", "max_results", "", "Maximum results returned"); + mdns_query_svc_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_query_svc", + .help = "Query MDNS for Service TXT & SRV", + .hint = NULL, + .func = &cmd_mdns_query_svc, + .argtable = &mdns_query_svc_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static struct { + struct arg_str *hostname; + struct arg_str *instance; + struct arg_end *end; +} mdns_init_args; + +static int cmd_mdns_init(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_init_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_init_args.end, argv[0]); + return 1; + } + + ESP_ERROR_CHECK(mdns_init()); + + if (mdns_init_args.hostname->sval[0]) { + ESP_ERROR_CHECK(mdns_hostname_set(mdns_init_args.hostname->sval[0])); + printf("MDNS: Hostname: %s\n", mdns_init_args.hostname->sval[0]); + } + + if (mdns_init_args.instance->count) { + ESP_ERROR_CHECK(mdns_instance_name_set(mdns_init_args.instance->sval[0])); + printf("MDNS: Instance: %s\n", mdns_init_args.instance->sval[0]); + } + + return 0; +} + +static void register_mdns_init(void) +{ + mdns_init_args.hostname = arg_str0("h", "hostname", "", "Hostname that the server will advertise"); + mdns_init_args.instance = arg_str0("i", "instance", "", "Default instance name for services"); + mdns_init_args.end = arg_end(2); + + const esp_console_cmd_t cmd_init = { + .command = "mdns_init", + .help = "Start MDNS Server", + .hint = NULL, + .func = &cmd_mdns_init, + .argtable = &mdns_init_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_init)); +} + +static int cmd_mdns_free(int argc, char **argv) +{ + mdns_free(); + return 0; +} + +static void register_mdns_free(void) +{ + const esp_console_cmd_t cmd_free = { + .command = "mdns_free", + .help = "Stop MDNS Server", + .hint = NULL, + .func = &cmd_mdns_free, + .argtable = NULL + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_free)); +} + +static struct { + struct arg_str *hostname; + struct arg_end *end; +} mdns_set_hostname_args; + +static int cmd_mdns_set_hostname(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_set_hostname_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_set_hostname_args.end, argv[0]); + return 1; + } + + if (mdns_set_hostname_args.hostname->sval[0] == NULL) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + ESP_ERROR_CHECK(mdns_hostname_set(mdns_set_hostname_args.hostname->sval[0])); + return 0; +} + +static void register_mdns_set_hostname(void) +{ + mdns_set_hostname_args.hostname = arg_str1(NULL, NULL, "", "Hostname that the server will advertise"); + mdns_set_hostname_args.end = arg_end(2); + + const esp_console_cmd_t cmd_set_hostname = { + .command = "mdns_set_hostname", + .help = "Set MDNS Server hostname", + .hint = NULL, + .func = &cmd_mdns_set_hostname, + .argtable = &mdns_set_hostname_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_set_hostname)); +} + +static struct { + struct arg_str *instance; + struct arg_end *end; +} mdns_set_instance_args; + +static int cmd_mdns_set_instance(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_set_instance_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_set_instance_args.end, argv[0]); + return 1; + } + + if (mdns_set_instance_args.instance->sval[0] == NULL) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + ESP_ERROR_CHECK(mdns_instance_name_set(mdns_set_instance_args.instance->sval[0])); + return 0; +} + +static void register_mdns_set_instance(void) +{ + mdns_set_instance_args.instance = arg_str1(NULL, NULL, "", "Default instance name for services"); + mdns_set_instance_args.end = arg_end(2); + + const esp_console_cmd_t cmd_set_instance = { + .command = "mdns_set_instance", + .help = "Set MDNS Server Istance Name", + .hint = NULL, + .func = &cmd_mdns_set_instance, + .argtable = &mdns_set_instance_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_set_instance)); +} + +static mdns_txt_item_t *_convert_items(const char **values, int count) +{ + int i = 0, e; + const char *value = NULL; + mdns_txt_item_t *items = (mdns_txt_item_t *) mdns_mem_malloc(sizeof(mdns_txt_item_t) * count); + if (!items) { + printf("ERROR: No Memory!\n"); + goto fail; + + } + memset(items, 0, sizeof(mdns_txt_item_t) * count); + + for (i = 0; i < count; i++) { + value = values[i]; + const char *esign = strchr(value, '='); + if (!esign) { + printf("ERROR: Equal sign not found in '%s'!\n", value); + goto fail; + } + int var_len = esign - value; + int val_len = strlen(value) - var_len - 1; + char *var = (char *)mdns_mem_malloc(var_len + 1); + if (var == NULL) { + printf("ERROR: No Memory!\n"); + goto fail; + } + char *val = (char *)mdns_mem_malloc(val_len + 1); + if (val == NULL) { + printf("ERROR: No Memory!\n"); + mdns_mem_free(var); + goto fail; + } + memcpy(var, value, var_len); + var[var_len] = 0; + memcpy(val, esign + 1, val_len); + val[val_len] = 0; + + items[i].key = var; + items[i].value = val; + } + + return items; + +fail: + for (e = 0; e < i; e++) { + mdns_mem_free((char *)items[e].key); + mdns_mem_free((char *)items[e].value); + } + mdns_mem_free(items); + return NULL; +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_int *port; + struct arg_str *instance; + struct arg_str *host; + struct arg_str *txt; + struct arg_end *end; +} mdns_add_args; + +static int cmd_mdns_service_add(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_add_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_add_args.end, argv[0]); + return 1; + } + + if (!mdns_add_args.service->sval[0] || !mdns_add_args.proto->sval[0] || !mdns_add_args.port->ival[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *instance = NULL; + if (mdns_add_args.instance->sval[0] && mdns_add_args.instance->sval[0][0]) { + instance = mdns_add_args.instance->sval[0]; + printf("MDNS: Service Instance: %s\n", instance); + } + const char *host = NULL; + if (mdns_add_args.host->count && mdns_add_args.host->sval[0]) { + host = mdns_add_args.host->sval[0]; + printf("MDNS: Service for delegated host: %s\n", host); + } + mdns_txt_item_t *items = NULL; + if (mdns_add_args.txt->count) { + items = _convert_items(mdns_add_args.txt->sval, mdns_add_args.txt->count); + if (!items) { + printf("ERROR: No Memory!\n"); + return 1; + + } + } + + ESP_ERROR_CHECK(mdns_service_add_for_host(instance, mdns_add_args.service->sval[0], mdns_add_args.proto->sval[0], + host, mdns_add_args.port->ival[0], items, mdns_add_args.txt->count)); + mdns_mem_free(items); + return 0; +} + +static void register_mdns_service_add(void) +{ + mdns_add_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_add_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_add_args.port = arg_int1(NULL, NULL, "", "Service Port"); + mdns_add_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_add_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_add_args.txt = arg_strn(NULL, NULL, "item", 0, 30, "TXT Items (name=value)"); + mdns_add_args.end = arg_end(2); + + const esp_console_cmd_t cmd_add = { + .command = "mdns_service_add", + .help = "Add service to MDNS", + .hint = NULL, + .func = &cmd_mdns_service_add, + .argtable = &mdns_add_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_add)); +} + +static struct { + struct arg_str *instance; + struct arg_str *service; + struct arg_str *proto; + struct arg_str *host; + struct arg_end *end; +} mdns_remove_args; + +static int cmd_mdns_service_remove(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_remove_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_remove_args.end, argv[0]); + return 1; + } + + if (!mdns_remove_args.service->sval[0] || !mdns_remove_args.proto->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + const char *instance = NULL; + if (mdns_remove_args.instance->count && mdns_remove_args.instance->sval[0]) { + instance = mdns_remove_args.instance->sval[0]; + } + const char *host = NULL; + if (mdns_remove_args.host->count && mdns_remove_args.host->sval[0]) { + host = mdns_remove_args.host->sval[0]; + } + + ESP_ERROR_CHECK(mdns_service_remove_for_host(instance, mdns_remove_args.service->sval[0], mdns_remove_args.proto->sval[0], host)); + return 0; +} + +static void register_mdns_service_remove(void) +{ + mdns_remove_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_remove_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_remove_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_remove_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_remove_args.end = arg_end(4); + + const esp_console_cmd_t cmd_remove = { + .command = "mdns_service_remove", + .help = "Remove service from MDNS", + .hint = NULL, + .func = &cmd_mdns_service_remove, + .argtable = &mdns_remove_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_remove)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_str *instance; + struct arg_str *host; + struct arg_str *old_instance; + struct arg_end *end; +} mdns_service_instance_set_args; + +static int cmd_mdns_service_instance_set(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_service_instance_set_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_service_instance_set_args.end, argv[0]); + return 1; + } + + if (!mdns_service_instance_set_args.service->sval[0] || !mdns_service_instance_set_args.proto->sval[0] || !mdns_service_instance_set_args.instance->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *host = NULL; + if (mdns_service_instance_set_args.host->count && mdns_service_instance_set_args.host->sval[0]) { + host = mdns_service_instance_set_args.host->sval[0]; + } + const char *old_instance = NULL; + if (mdns_service_instance_set_args.old_instance->count && mdns_service_instance_set_args.old_instance->sval[0]) { + old_instance = mdns_service_instance_set_args.old_instance->sval[0]; + } + esp_err_t err = mdns_service_instance_name_set_for_host(old_instance, mdns_service_instance_set_args.service->sval[0], mdns_service_instance_set_args.proto->sval[0], host, mdns_service_instance_set_args.instance->sval[0]); + if (err != ESP_OK) { + printf("mdns_service_instance_name_set_for_host() failed with %s\n", esp_err_to_name(err)); + return 1; + } + + return 0; +} + +static void register_mdns_service_instance_set(void) +{ + mdns_service_instance_set_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_service_instance_set_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_service_instance_set_args.instance = arg_str1(NULL, NULL, "", "Instance name"); + mdns_service_instance_set_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_service_instance_set_args.old_instance = arg_str0("i", "old_instance", "", "Instance name before update"); + mdns_service_instance_set_args.end = arg_end(4); + + const esp_console_cmd_t cmd_add = { + .command = "mdns_service_instance_set", + .help = "Set MDNS Service Instance Name", + .hint = NULL, + .func = &cmd_mdns_service_instance_set, + .argtable = &mdns_service_instance_set_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_add)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_int *port; + struct arg_str *host; + struct arg_str *instance; + struct arg_end *end; +} mdns_service_port_set_args; + +static int cmd_mdns_service_port_set(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_service_port_set_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_service_port_set_args.end, argv[0]); + return 1; + } + + if (!mdns_service_port_set_args.service->sval[0] || !mdns_service_port_set_args.proto->sval[0] || !mdns_service_port_set_args.port->ival[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + const char *host = NULL; + if (mdns_service_port_set_args.host->count && mdns_service_port_set_args.host->sval[0]) { + host = mdns_service_port_set_args.host->sval[0]; + } + const char *instance = NULL; + if (mdns_service_port_set_args.instance->count && mdns_service_port_set_args.instance->sval[0]) { + instance = mdns_service_port_set_args.instance->sval[0]; + } + esp_err_t err = mdns_service_port_set_for_host(instance, mdns_service_port_set_args.service->sval[0], mdns_service_port_set_args.proto->sval[0], host, mdns_service_port_set_args.port->ival[0]); + if (err != ESP_OK) { + printf("mdns_service_port_set_for_host() failed with %s\n", esp_err_to_name(err)); + return 1; + } + return 0; +} + +static void register_mdns_service_port_set(void) +{ + mdns_service_port_set_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_service_port_set_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_service_port_set_args.port = arg_int1(NULL, NULL, "", "Service Port"); + mdns_service_port_set_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_service_port_set_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_service_port_set_args.end = arg_end(2); + + const esp_console_cmd_t cmd_add = { + .command = "mdns_service_port_set", + .help = "Set MDNS Service port", + .hint = NULL, + .func = &cmd_mdns_service_port_set, + .argtable = &mdns_service_port_set_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_add)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_str *instance; + struct arg_str *host; + struct arg_str *txt; + struct arg_end *end; +} mdns_txt_replace_args; + +static int cmd_mdns_service_txt_replace(int argc, char **argv) +{ + mdns_txt_item_t *items = NULL; + int nerrors = arg_parse(argc, argv, (void **) &mdns_txt_replace_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_txt_replace_args.end, argv[0]); + return 1; + } + + if (!mdns_txt_replace_args.service->sval[0] || !mdns_txt_replace_args.proto->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *instance = NULL; + if (mdns_txt_replace_args.instance->count && mdns_txt_replace_args.instance->sval[0]) { + instance = mdns_txt_replace_args.instance->sval[0]; + printf("MDNS: Service Instance: %s\n", instance); + } + const char *host = NULL; + if (mdns_txt_replace_args.host->count && mdns_txt_replace_args.host->sval[0]) { + host = mdns_txt_replace_args.host->sval[0]; + printf("MDNS: Service for delegated host: %s\n", host); + } + if (mdns_txt_replace_args.txt->count) { + items = _convert_items(mdns_txt_replace_args.txt->sval, mdns_txt_replace_args.txt->count); + if (!items) { + printf("ERROR: No Memory!\n"); + return 1; + + } + } + ESP_ERROR_CHECK(mdns_service_txt_set_for_host(instance, mdns_txt_replace_args.service->sval[0], mdns_txt_replace_args.proto->sval[0], host, items, mdns_txt_replace_args.txt->count)); + mdns_mem_free(items); + return 0; +} + +static void register_mdns_service_txt_replace(void) +{ + mdns_txt_replace_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_txt_replace_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_txt_replace_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_txt_replace_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_txt_replace_args.txt = arg_strn(NULL, NULL, "item", 0, 30, "TXT Items (name=value)"); + mdns_txt_replace_args.end = arg_end(5); + + const esp_console_cmd_t cmd_txt_set = { + .command = "mdns_service_txt_replace", + .help = "Replace MDNS service TXT items", + .hint = NULL, + .func = &cmd_mdns_service_txt_replace, + .argtable = &mdns_txt_replace_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_txt_set)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_str *instance; + struct arg_str *host; + struct arg_str *var; + struct arg_str *value; + struct arg_end *end; +} mdns_txt_set_args; + +static int cmd_mdns_service_txt_set(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_txt_set_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_txt_set_args.end, argv[0]); + return 1; + } + + if (!mdns_txt_set_args.service->sval[0] || !mdns_txt_set_args.proto->sval[0] || !mdns_txt_set_args.var->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *instance = NULL; + if (mdns_txt_set_args.instance->count && mdns_txt_set_args.instance->sval[0]) { + instance = mdns_txt_set_args.instance->sval[0]; + printf("MDNS: Service Instance: %s\n", instance); + } + const char *host = NULL; + if (mdns_txt_set_args.host->count && mdns_txt_set_args.host->sval[0]) { + host = mdns_txt_set_args.host->sval[0]; + printf("MDNS: Service for delegated host: %s\n", host); + } + + ESP_ERROR_CHECK(mdns_service_txt_item_set_for_host(instance, mdns_txt_set_args.service->sval[0], mdns_txt_set_args.proto->sval[0], host, mdns_txt_set_args.var->sval[0], mdns_txt_set_args.value->sval[0])); + return 0; +} + +static void register_mdns_service_txt_set(void) +{ + mdns_txt_set_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_txt_set_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_txt_set_args.var = arg_str1(NULL, NULL, "", "Item Name"); + mdns_txt_set_args.value = arg_str1(NULL, NULL, "", "Item Value"); + mdns_txt_set_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_txt_set_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_txt_set_args.end = arg_end(6); + + const esp_console_cmd_t cmd_txt_set = { + .command = "mdns_service_txt_set", + .help = "Add/Set MDNS service TXT item", + .hint = NULL, + .func = &cmd_mdns_service_txt_set, + .argtable = &mdns_txt_set_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_txt_set)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_str *var; + struct arg_str *instance; + struct arg_str *host; + struct arg_end *end; +} mdns_txt_remove_args; + +static int cmd_mdns_service_txt_remove(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_txt_remove_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_txt_remove_args.end, argv[0]); + return 1; + } + + if (!mdns_txt_remove_args.service->sval[0] || !mdns_txt_remove_args.proto->sval[0] || !mdns_txt_remove_args.var->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *instance = NULL; + if (mdns_txt_remove_args.instance->count && mdns_txt_remove_args.instance->sval[0]) { + instance = mdns_txt_remove_args.instance->sval[0]; + } + const char *host = NULL; + if (mdns_txt_remove_args.host->count && mdns_txt_remove_args.host->sval[0]) { + host = mdns_txt_remove_args.host->sval[0]; + } + ESP_ERROR_CHECK(mdns_service_txt_item_remove_for_host(instance, mdns_txt_remove_args.service->sval[0], mdns_txt_remove_args.proto->sval[0], host, mdns_txt_remove_args.var->sval[0])); + return 0; +} + +static void register_mdns_service_txt_remove(void) +{ + mdns_txt_remove_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_txt_remove_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_txt_remove_args.var = arg_str1(NULL, NULL, "", "Item Name"); + mdns_txt_remove_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_txt_remove_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_txt_remove_args.end = arg_end(2); + + const esp_console_cmd_t cmd_txt_remove = { + .command = "mdns_service_txt_remove", + .help = "Remove MDNS service TXT item", + .hint = NULL, + .func = &cmd_mdns_service_txt_remove, + .argtable = &mdns_txt_remove_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_txt_remove)); +} + +static int cmd_mdns_service_remove_all(int argc, char **argv) +{ + mdns_service_remove_all(); + return 0; +} + +static void register_mdns_service_remove_all(void) +{ + const esp_console_cmd_t cmd_free = { + .command = "mdns_service_remove_all", + .help = "Remove all MDNS services", + .hint = NULL, + .func = &cmd_mdns_service_remove_all, + .argtable = NULL + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_free)); +} + +#define MDNS_MAX_LOOKUP_RESULTS CONFIG_MDNS_MAX_SERVICES + +static struct { + struct arg_str *instance; + struct arg_str *service; + struct arg_str *proto; + struct arg_lit *delegated; + struct arg_end *end; +} mdns_lookup_service_args; + +static esp_err_t lookup_service(const char *instance, const char *service, const char *proto, size_t max_results, + mdns_result_t **result, bool delegated) +{ + if (delegated) { + return mdns_lookup_delegated_service(instance, service, proto, max_results, result); + } + return mdns_lookup_selfhosted_service(instance, service, proto, max_results, result); +} + +static int cmd_mdns_lookup_service(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_lookup_service_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_lookup_service_args.end, argv[0]); + return 1; + } + + if (!mdns_lookup_service_args.instance->sval[0] || !mdns_lookup_service_args.service->sval[0] || !mdns_lookup_service_args.proto->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + mdns_result_t *results = NULL; + esp_err_t err = lookup_service(mdns_lookup_service_args.instance->count ? mdns_lookup_service_args.instance->sval[0] : NULL, + mdns_lookup_service_args.service->sval[0], mdns_lookup_service_args.proto->sval[0], + MDNS_MAX_LOOKUP_RESULTS, &results, mdns_lookup_service_args.delegated->count); + if (err) { + printf("Service lookup failed\n"); + return 1; + } + if (!results) { + printf("No results found!\n"); + return 0; + } + mdns_print_results(results); + mdns_query_results_free(results); + return 0; +} + +static void register_mdns_lookup_service(void) +{ + mdns_lookup_service_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_lookup_service_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_lookup_service_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_lookup_service_args.delegated = arg_lit0("d", "delegated", "Lookup delegated services"); + mdns_lookup_service_args.end = arg_end(4); + + const esp_console_cmd_t cmd_lookup_service = { + .command = "mdns_service_lookup", + .help = "Lookup registered service", + .hint = NULL, + .func = &cmd_mdns_lookup_service, + .argtable = &mdns_lookup_service_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_lookup_service)); +} + +static struct { + struct arg_str *hostname; + struct arg_str *address; + struct arg_end *end; +} mdns_delegate_host_args; + +static int cmd_mdns_delegate_host(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_delegate_host_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_delegate_host_args.end, argv[0]); + return 1; + } + + if (!mdns_delegate_host_args.hostname->sval[0] || !mdns_delegate_host_args.address->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + mdns_ip_addr_t addr = { .next = NULL}; + esp_netif_str_to_ip4(mdns_delegate_host_args.address->sval[0], &addr.addr.u_addr.ip4); + addr.addr.type = ESP_IPADDR_TYPE_V4; + + esp_err_t err = mdns_delegate_hostname_add(mdns_delegate_host_args.hostname->sval[0], &addr); + if (err) { + printf("mdns_delegate_hostname_add() failed\n"); + return 1; + } + return 0; +} + +static void register_mdns_delegate_host(void) +{ + mdns_delegate_host_args.hostname = arg_str1(NULL, NULL, "", "Delegated hostname"); + mdns_delegate_host_args.address = arg_str1(NULL, NULL, "
", "Delegated hosts address"); + mdns_delegate_host_args.end = arg_end(2); + + const esp_console_cmd_t cmd_delegate_host = { + .command = "mdns_delegate_host", + .help = "Add delegated hostname", + .hint = NULL, + .func = &cmd_mdns_delegate_host, + .argtable = &mdns_delegate_host_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_delegate_host)); +} + +static struct { + struct arg_str *hostname; + struct arg_end *end; +} mdns_undelegate_host_args; + +static int cmd_mdns_undelegate_host(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_undelegate_host_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_undelegate_host_args.end, argv[0]); + return 1; + } + + if (!mdns_undelegate_host_args.hostname->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + + if (mdns_delegate_hostname_remove(mdns_undelegate_host_args.hostname->sval[0]) != ESP_OK) { + printf("mdns_delegate_hostname_remove() failed\n"); + return 1; + } + return 0; +} + +static void register_mdns_undelegate_host(void) +{ + mdns_undelegate_host_args.hostname = arg_str1(NULL, NULL, "", "Delegated hostname"); + mdns_undelegate_host_args.end = arg_end(2); + + const esp_console_cmd_t cmd_undelegate_host = { + .command = "mdns_undelegate_host", + .help = "Remove delegated hostname", + .hint = NULL, + .func = &cmd_mdns_undelegate_host, + .argtable = &mdns_undelegate_host_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_undelegate_host)); +} + +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_str *sub; + struct arg_str *instance; + struct arg_str *host; + struct arg_end *end; +} mdns_service_subtype_args; + +static int cmd_mdns_service_subtype(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_service_subtype_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_service_subtype_args.end, argv[0]); + return 1; + } + + if (!mdns_service_subtype_args.service->sval[0] || !mdns_service_subtype_args.proto->sval[0] || !mdns_service_subtype_args.sub->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + const char *instance = NULL; + if (mdns_service_subtype_args.instance->count && mdns_service_subtype_args.instance->sval[0]) { + instance = mdns_service_subtype_args.instance->sval[0]; + } + const char *host = NULL; + if (mdns_service_subtype_args.host->count && mdns_service_subtype_args.host->sval[0]) { + host = mdns_service_subtype_args.host->sval[0]; + } + ESP_ERROR_CHECK(mdns_service_subtype_add_for_host(instance, mdns_service_subtype_args.service->sval[0], mdns_service_subtype_args.proto->sval[0], host, mdns_service_subtype_args.sub->sval[0])); + return 0; +} + +static void register_mdns_service_subtype_set(void) +{ + mdns_service_subtype_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_service_subtype_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_service_subtype_args.sub = arg_str1(NULL, NULL, "", "Subtype"); + mdns_service_subtype_args.instance = arg_str0("i", "instance", "", "Instance name"); + mdns_service_subtype_args.host = arg_str0("h", "host", "", "Service for this (delegated) host"); + mdns_service_subtype_args.end = arg_end(5); + + const esp_console_cmd_t cmd_service_sub = { + .command = "mdns_service_subtype", + .help = "Adds subtype for service", + .hint = NULL, + .func = &cmd_mdns_service_subtype, + .argtable = &mdns_service_subtype_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_service_sub)); +} + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +static struct { + struct arg_str *service; + struct arg_str *proto; + struct arg_end *end; +} mdns_browse_args; + +static void mdns_browse_notifier(mdns_result_t *result) +{ + if (result) { + mdns_print_results(result); + } +} + +static int cmd_mdns_browse(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_browse_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_browse_args.end, argv[0]); + return 1; + } + + if (!mdns_browse_args.service->sval[0] || !mdns_browse_args.proto->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + mdns_browse_t *handle = mdns_browse_new(mdns_browse_args.service->sval[0], mdns_browse_args.proto->sval[0], mdns_browse_notifier); + return handle ? 0 : 1; +} + +static void register_mdns_browse(void) +{ + mdns_browse_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_browse_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_browse_args.end = arg_end(2); + + const esp_console_cmd_t cmd_browse = { + .command = "mdns_browse", + .help = "Start browsing", + .hint = NULL, + .func = &cmd_mdns_browse, + .argtable = &mdns_browse_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_browse)); +} + +static int cmd_mdns_browse_del(int argc, char **argv) +{ + int nerrors = arg_parse(argc, argv, (void **) &mdns_browse_args); + if (nerrors != 0) { + arg_print_errors(stderr, mdns_browse_args.end, argv[0]); + return 1; + } + + if (!mdns_browse_args.service->sval[0] || !mdns_browse_args.proto->sval[0]) { + printf("ERROR: Bad arguments!\n"); + return 1; + } + esp_err_t err = mdns_browse_delete(mdns_browse_args.service->sval[0], mdns_browse_args.proto->sval[0]); + return err == ESP_OK ? 0 : 1; +} + +static void register_mdns_browse_del(void) +{ + mdns_browse_args.service = arg_str1(NULL, NULL, "", "MDNS Service"); + mdns_browse_args.proto = arg_str1(NULL, NULL, "", "IP Protocol"); + mdns_browse_args.end = arg_end(2); + + const esp_console_cmd_t cmd_browse_del = { + .command = "mdns_browse_del", + .help = "Stop browsing", + .hint = NULL, + .func = &cmd_mdns_browse_del, + .argtable = &mdns_browse_args + }; + + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_browse_del)); +} +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +void mdns_console_register(void) +{ + register_mdns_init(); + register_mdns_free(); + register_mdns_set_hostname(); + register_mdns_set_instance(); + register_mdns_service_add(); + register_mdns_service_remove(); + register_mdns_service_instance_set(); + register_mdns_service_port_set(); + register_mdns_service_txt_replace(); + register_mdns_service_txt_set(); + register_mdns_service_txt_remove(); + register_mdns_service_remove_all(); + + register_mdns_lookup_service(); + register_mdns_delegate_host(); + register_mdns_undelegate_host(); + register_mdns_service_subtype_set(); + +#ifdef CONFIG_MDNS_ENABLE_BROWSE + register_mdns_browse(); + register_mdns_browse_del(); +#endif + +#ifdef CONFIG_LWIP_IPV4 + register_mdns_query_a(); + register_mdns_query_a_async(); +#endif +#ifdef CONFIG_LWIP_IPV6 + register_mdns_query_aaaa(); +#endif + register_mdns_query_txt(); + register_mdns_query_srv(); + register_mdns_query_ptr(); + + register_mdns_query_ip(); + register_mdns_query_svc(); +} diff --git a/managed_components/espressif__mdns/mdns_debug.c b/managed_components/espressif__mdns/mdns_debug.c new file mode 100644 index 0000000..a47b39d --- /dev/null +++ b/managed_components/espressif__mdns/mdns_debug.c @@ -0,0 +1,446 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "mdns_utils.h" + +#ifdef CONFIG_MDNS_DEBUG_USE_ESP_LOG + +#include +#include "esp_log.h" + +#define MDNS_DBG_MAX_LINE CONFIG_MDNS_DEBUG_BUFFER_SIZE + +static char s_mdns_dbg_buf[MDNS_DBG_MAX_LINE]; +static size_t s_mdns_dbg_pos = 0; + +static void mdns_dbg_puts(const char *str) +{ + ESP_LOGI("mdns", "%s", str); +} + +static inline void mdns_dbg_flush(void) +{ + if (s_mdns_dbg_pos > 0) { + s_mdns_dbg_buf[s_mdns_dbg_pos] = '\0'; + mdns_dbg_puts(s_mdns_dbg_buf); + s_mdns_dbg_pos = 0; + } +} + +static void mdns_dbg_vprintf(const char *fmt, va_list args) +{ + // Try to format directly into the buffer + int len = vsnprintf(s_mdns_dbg_buf + s_mdns_dbg_pos, + MDNS_DBG_MAX_LINE - s_mdns_dbg_pos, + fmt, args); + + if (len < 0) { + return; // Error in formatting + } + + // Check if the entire formatted string fit in the buffer + if (len < (MDNS_DBG_MAX_LINE - s_mdns_dbg_pos)) { + // If it fit, just update the position + s_mdns_dbg_pos += len; + } else { + // The formatted string was truncated because it didn't fit + // First, flush what we have (the partial string) + mdns_dbg_flush(); + + // Create a new va_list copy and try again with the full buffer + va_list args_copy; + va_copy(args_copy, args); + + // Format again with the entire buffer available + len = vsnprintf(s_mdns_dbg_buf, MDNS_DBG_MAX_LINE - 1, fmt, args_copy); + va_end(args_copy); + + if (len < 0) { + return; // Error + } + + // Check if content will be lost (true truncation) + if (len >= MDNS_DBG_MAX_LINE - 1) { + // This is when actual content will be lost - log a warning + ESP_LOGW("mdns", "Message truncated: length (%d) exceeds buffer size (%d). Consider increasing CONFIG_MDNS_DEBUG_BUFFER_SIZE.", + len, MDNS_DBG_MAX_LINE - 1); + + // Display what we could fit, then flush and return + s_mdns_dbg_pos = MDNS_DBG_MAX_LINE - 1; + mdns_dbg_flush(); + return; + } + + // If we get here, the whole message fit this time + s_mdns_dbg_pos = len; + } + + // If buffer is nearly full after this operation, flush it + if (s_mdns_dbg_pos >= MDNS_DBG_MAX_LINE - 1) { + mdns_dbg_flush(); + } +} + +static void mdns_dbg_printf(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + mdns_dbg_vprintf(fmt, ap); + va_end(ap); +} + +#define dbg_printf(...) mdns_dbg_printf(__VA_ARGS__) +#else +#define dbg_printf(...) printf(__VA_ARGS__) +#define mdns_dbg_flush() +#endif + +static void dbg_print_name_and_type(const char *prefix, const mdns_name_t *name, uint16_t type) +{ + if (type == MDNS_TYPE_A) { + dbg_printf("%s%s.%s. A ", prefix, name->host, name->domain); + } else if (type == MDNS_TYPE_AAAA) { + dbg_printf("%s%s.%s. AAAA ", prefix, name->host, name->domain); + } else if (type == MDNS_TYPE_OPT) { + dbg_printf("%s. OPT ", prefix); + } else { + const char *type_name = NULL; + if (type == MDNS_TYPE_PTR) { + type_name = "PTR"; + } else if (type == MDNS_TYPE_SRV) { + type_name = "SRV"; + } else if (type == MDNS_TYPE_TXT) { + type_name = "TXT"; + } else if (type == MDNS_TYPE_NSEC) { + type_name = "NSEC"; + } else if (type == MDNS_TYPE_ANY) { + type_name = "ANY"; + } + + dbg_printf("%s%s%s%s%s.%s.%s. ", prefix, name->host, name->host[0] ? "." : "", + name->sub ? "_sub." : "", name->service, name->proto, name->domain); + if (type_name) { + dbg_printf("%s ", type_name); + } else { + dbg_printf("%04X ", type); + } + } +} + +void static dbg_packet(const uint8_t *data, size_t len) +{ + static mdns_name_t n; + mdns_header_t header; + const uint8_t *content = data + MDNS_HEAD_LEN; + uint64_t t = xTaskGetTickCount() * portTICK_PERIOD_MS; + mdns_name_t *name = &n; + memset(name, 0, sizeof(mdns_name_t)); + + dbg_printf("Packet[%" PRIu64 "]: ", t); + + header.id = mdns_utils_read_u16(data, MDNS_HEAD_ID_OFFSET); + header.flags = mdns_utils_read_u16(data, MDNS_HEAD_FLAGS_OFFSET); + header.questions = mdns_utils_read_u16(data, MDNS_HEAD_QUESTIONS_OFFSET); + header.answers = mdns_utils_read_u16(data, MDNS_HEAD_ANSWERS_OFFSET); + header.servers = mdns_utils_read_u16(data, MDNS_HEAD_SERVERS_OFFSET); + header.additional = mdns_utils_read_u16(data, MDNS_HEAD_ADDITIONAL_OFFSET); + + dbg_printf("%s", + (header.flags == MDNS_FLAGS_QR_AUTHORITATIVE) ? "AUTHORITATIVE\n" : + (header.flags == MDNS_FLAGS_DISTRIBUTED) ? "DISTRIBUTED\n" : + (header.flags == 0) ? "\n" : " " + ); + if (header.flags && header.flags != MDNS_FLAGS_QR_AUTHORITATIVE) { + dbg_printf("0x%04X\n", header.flags); + } + + if (header.questions) { + uint8_t qs = header.questions; + + while (qs--) { + content = mdns_utils_parse_fqdn(data, content, name, len); + if (!content || content + MDNS_CLASS_OFFSET + 1 >= data + len) { + header.answers = 0; + header.additional = 0; + header.servers = 0; + dbg_printf("ERROR: parse header questions\n"); + break; + } + + uint16_t type = mdns_utils_read_u16(content, MDNS_TYPE_OFFSET); + uint16_t mdns_class = mdns_utils_read_u16(content, MDNS_CLASS_OFFSET); + bool unicast = !!(mdns_class & 0x8000); + mdns_class &= 0x7FFF; + content = content + 4; + + dbg_printf(" Q: "); + if (unicast) { + dbg_printf("*U* "); + } + dbg_print_name_and_type("", name, type); + + if (mdns_class == 0x0001) { + dbg_printf("IN"); + } else { + dbg_printf("%04X", mdns_class); + } + dbg_printf("\n"); + } + } + + if (header.answers || header.servers || header.additional) { + uint16_t recordIndex = 0; + + while (content < (data + len)) { + + content = mdns_utils_parse_fqdn(data, content, name, len); + if (!content) { + dbg_printf("ERROR: parse mdns records\n"); + break; + } + + if (content + MDNS_LEN_OFFSET + 1 >= data + len) { + // malformed packet, RR header (TYPE/CLASS/TTL/LEN) would read past the buffer + dbg_printf("ERROR: truncated RR header\n"); + break; + } + uint16_t type = mdns_utils_read_u16(content, MDNS_TYPE_OFFSET); + uint16_t mdns_class = mdns_utils_read_u16(content, MDNS_CLASS_OFFSET); + uint32_t ttl = mdns_utils_read_u32(content, MDNS_TTL_OFFSET); + uint16_t data_len = mdns_utils_read_u16(content, MDNS_LEN_OFFSET); + const uint8_t *data_ptr = content + MDNS_DATA_OFFSET; + bool flush = !!(mdns_class & 0x8000); + mdns_class &= 0x7FFF; + + content = data_ptr + data_len; + if (content > (data + len)) { + dbg_printf("ERROR: content length overflow\n"); + break; + } + + mdns_parsed_record_type_t record_type = MDNS_ANSWER; + + if (recordIndex >= (header.answers + header.servers)) { + record_type = MDNS_EXTRA; + } else if (recordIndex >= (header.answers)) { + record_type = MDNS_NS; + } + recordIndex++; + + if (record_type == MDNS_EXTRA) { + dbg_printf(" X"); + } else if (record_type == MDNS_NS) { + dbg_printf(" S"); + } else { + dbg_printf(" A"); + } + + dbg_print_name_and_type(": ", name, type); + + if (mdns_class == 0x0001) { + dbg_printf("IN "); + } else { + dbg_printf("%04X ", mdns_class); + } + if (flush) { + dbg_printf("FLUSH "); + } + dbg_printf("%" PRIu32, ttl); + dbg_printf("[%u] ", data_len); + if (type == MDNS_TYPE_PTR) { + size_t rdata_bound = (size_t)(data_ptr + data_len - data); + if (!mdns_utils_parse_fqdn(data, data_ptr, name, rdata_bound)) { + dbg_printf("ERROR: parse PTR\n"); + continue; + } + dbg_printf("%s.%s.%s.%s.\n", name->host, name->service, name->proto, name->domain); + } else if (type == MDNS_TYPE_SRV) { + // SRV fixed fields are priority/weight/port (6 bytes) before the target FQDN + if (data_len < MDNS_SRV_FQDN_OFFSET) { + dbg_printf("ERROR: truncated SRV\n"); + continue; + } + size_t rdata_bound = (size_t)(data_ptr + data_len - data); + if (!mdns_utils_parse_fqdn(data, data_ptr + MDNS_SRV_FQDN_OFFSET, name, rdata_bound)) { + dbg_printf("ERROR: parse SRV\n"); + continue; + } + uint16_t priority = mdns_utils_read_u16(data_ptr, MDNS_SRV_PRIORITY_OFFSET); + uint16_t weight = mdns_utils_read_u16(data_ptr, MDNS_SRV_WEIGHT_OFFSET); + uint16_t port = mdns_utils_read_u16(data_ptr, MDNS_SRV_PORT_OFFSET); + dbg_printf("%u %u %u %s.%s.\n", priority, weight, port, name->host, name->domain); + } else if (type == MDNS_TYPE_TXT) { + uint16_t i = 0, y; + while (i < data_len) { + uint8_t partLen = data_ptr[i++]; + if ((i + partLen) > data_len) { + dbg_printf("ERROR: parse TXT\n"); + break; + } + char txt[partLen + 1]; + for (y = 0; y < partLen; y++) { + char d = data_ptr[i++]; + txt[y] = d; + } + txt[partLen] = 0; + dbg_printf("%s", txt); + if (i < data_len) { + dbg_printf("; "); + } + } + dbg_printf("\n"); + } else if (type == MDNS_TYPE_AAAA) { + if (data_len < MDNS_ANSWER_AAAA_SIZE) { + dbg_printf("ERROR: truncated AAAA\n"); + continue; + } + esp_ip6_addr_t ip6 = {0}; + memcpy(&ip6.addr, data_ptr, MDNS_ANSWER_AAAA_SIZE); + dbg_printf(IPV6STR "\n", IPV62STR(ip6)); + } else if (type == MDNS_TYPE_A) { + if (data_len < sizeof(esp_ip4_addr_t)) { + dbg_printf("ERROR: truncated A\n"); + continue; + } + esp_ip4_addr_t ip; + memcpy(&ip, data_ptr, sizeof(esp_ip4_addr_t)); + dbg_printf(IPSTR "\n", IP2STR(&ip)); + } else if (type == MDNS_TYPE_NSEC) { + const uint8_t *old_ptr = data_ptr; + const uint8_t *new_ptr = mdns_utils_parse_fqdn(data, data_ptr, name, len); + if (new_ptr) { + dbg_printf("%s.%s.%s.%s. ", name->host, name->service, name->proto, name->domain); + size_t diff = new_ptr - old_ptr; + if (diff > data_len) { + // FQDN parsed past the record boundary; avoid underflowing data_len + dbg_printf("ERROR: parse NSEC\n"); + continue; + } + data_len -= diff; + data_ptr = new_ptr; + } + size_t i; + for (i = 0; i < data_len; i++) { + dbg_printf(" %02x", data_ptr[i]); + } + dbg_printf("\n"); + } else if (type == MDNS_TYPE_OPT) { + // OPT option header is code + length (4 bytes) before option data + if (data_len < 4) { + dbg_printf("ERROR: truncated OPT\n"); + continue; + } + uint16_t opCode = mdns_utils_read_u16(data_ptr, 0); + uint16_t opLen = mdns_utils_read_u16(data_ptr, 2); + dbg_printf(" Code: %04x Data[%u]:", opCode, opLen); + size_t i; + for (i = 4; i < data_len; i++) { + dbg_printf(" %02x", data_ptr[i]); + } + dbg_printf("\n"); + } else { + size_t i; + for (i = 0; i < data_len; i++) { + dbg_printf(" %02x", data_ptr[i]); + } + dbg_printf("\n"); + } + } + } + mdns_dbg_flush(); +} + +void mdns_debug_tx_packet(mdns_tx_packet_t *p, uint8_t packet[MDNS_MAX_PACKET_SIZE], uint16_t index) +{ + dbg_printf("\nTX[%lu][%lu]: ", (unsigned long)p->tcpip_if, (unsigned long)p->ip_protocol); +#ifdef CONFIG_LWIP_IPV4 + if (p->dst.type == ESP_IPADDR_TYPE_V4) { + dbg_printf("To: " IPSTR ":%u, ", IP2STR(&p->dst.u_addr.ip4), p->port); + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (p->dst.type == ESP_IPADDR_TYPE_V6) { + dbg_printf("To: " IPV6STR ":%u, ", IPV62STR(p->dst.u_addr.ip6), p->port); + } +#endif + dbg_packet(packet, index); + mdns_dbg_flush(); +} + +void mdns_debug_rx_packet(mdns_rx_packet_t *packet, const uint8_t* data, uint16_t len) +{ + dbg_printf("\nRX[%lu][%lu]: ", (unsigned long)packet->tcpip_if, (unsigned long)packet->ip_protocol); +#ifdef CONFIG_LWIP_IPV4 + if (packet->src.type == ESP_IPADDR_TYPE_V4) { + dbg_printf("From: " IPSTR ":%u, To: " IPSTR ", ", IP2STR(&packet->src.u_addr.ip4), packet->src_port, IP2STR(&packet->dest.u_addr.ip4)); + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (packet->src.type == ESP_IPADDR_TYPE_V6) { + dbg_printf("From: " IPV6STR ":%u, To: " IPV6STR ", ", IPV62STR(packet->src.u_addr.ip6), packet->src_port, IPV62STR(packet->dest.u_addr.ip6)); + } +#endif + dbg_packet(data, len); + mdns_dbg_flush(); +} + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +static void dbg_printf_result(mdns_result_t *r_t) +{ + mdns_ip_addr_t *r_a = NULL; + int addr_count = 0; + dbg_printf("result esp_netif: %p\n", r_t->esp_netif); + dbg_printf("result ip_protocol: %d\n", r_t->ip_protocol); + dbg_printf("result hostname: %s\n", mdns_utils_str_null_or_empty(r_t->hostname) ? "NULL" : r_t->hostname); + dbg_printf("result instance_name: %s\n", mdns_utils_str_null_or_empty(r_t->instance_name) ? "NULL" : r_t->instance_name); + dbg_printf("result service_type: %s\n", mdns_utils_str_null_or_empty(r_t->service_type) ? "NULL" : r_t->service_type); + dbg_printf("result proto: %s\n", mdns_utils_str_null_or_empty(r_t->proto) ? "NULL" : r_t->proto); + dbg_printf("result port: %d\n", r_t->port); + dbg_printf("result ttl: %" PRIu32 "\n", r_t->ttl); + for (int i = 0; i < r_t->txt_count; i++) { + dbg_printf("result txt item%d, key: %s, value: %s\n", i, r_t->txt[i].key, r_t->txt[i].value); + } + r_a = r_t->addr; + while (r_a) { +#ifdef CONFIG_LWIP_IPV4 + if (r_a->addr.type == ESP_IPADDR_TYPE_V4) { + dbg_printf("Addr%d: " IPSTR "\n", addr_count++, IP2STR(&r_a->addr.u_addr.ip4)); + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (r_a->addr.type == ESP_IPADDR_TYPE_V6) { + dbg_printf("Addr%d: " IPV6STR "\n", addr_count++, IPV62STR(r_a->addr.u_addr.ip6)); + } +#endif + r_a = r_a->next; + } + mdns_dbg_flush(); +} + +void mdns_debug_printf_browse_result(mdns_result_t *r_t, mdns_browse_t *b_t) +{ + dbg_printf("----------------sync browse %s.%s result---------------\n", b_t->service, b_t->proto); + dbg_printf("browse pointer: %p\n", b_t); + dbg_printf_result(r_t); + mdns_dbg_flush(); +} + +void mdns_debug_printf_browse_result_all(mdns_result_t *r_t) +{ + int count = 0; + while (r_t) { + dbg_printf("----------------result %d---------------\n", count++); + dbg_printf_result(r_t); + r_t = r_t->next; + } + mdns_dbg_flush(); +} +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ diff --git a/managed_components/espressif__mdns/mdns_diagram.md b/managed_components/espressif__mdns/mdns_diagram.md new file mode 100644 index 0000000..b17797d --- /dev/null +++ b/managed_components/espressif__mdns/mdns_diagram.md @@ -0,0 +1,51 @@ +```mermaid +graph TB + %% Housekeeping modules at the top + subgraph Housekeeping [Support Modules] + Service[mdns_service.c] + Utils[mdns_utils.c] + MemCaps[mdns_mem_caps.c] + Debug[mdns_debug.c] + end + + %% Switch to LR direction for the main flow + subgraph MainFlow [Main Data Flow] + direction LR + + %% Network on left side + Network((Network)) <--> Networking + + %% Networking layer + subgraph Networking [Networking Layer] + LWIP[mdns_networking_lwip.c] + Socket[mdns_networking_socket.c] + end + + %% Traffic flow + Networking --> |Incoming| Receive[mdns_receive.c] + Send[mdns_send.c] --> |Outgoing| Networking + + %% Core MDNS components + Receive --> Responder[mdns_responder.c] + Receive --> Browser[mdns_browser.c] + Receive --> Querier[mdns_querier.c] + + Responder --> Send + Browser --> Send + Querier --> Send + + PCB[mdns_pcb.c] --> Send + NetIF[mdns_netif.c] + + %% Users on the right side, aligned vertically + Responder --> Advertise((User: Advertising)) + Querier --> Search((User: Searching)) + Browser --> Browse((User: Browsing)) + end + + %% Style user nodes + style Advertise fill:#f9f,stroke:#333,stroke-width:2px + style Search fill:#f9f,stroke:#333,stroke-width:2px + style Browse fill:#f9f,stroke:#333,stroke-width:2px + style Housekeeping fill:#e6f7ff,stroke:#333,stroke-width:1px +``` diff --git a/managed_components/espressif__mdns/mdns_mem_caps.c b/managed_components/espressif__mdns/mdns_mem_caps.c new file mode 100644 index 0000000..78bdbc1 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_mem_caps.c @@ -0,0 +1,96 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "mdns_mem_caps.h" +#include "esp_heap_caps.h" +#include "esp_log.h" + +#if CONFIG_MDNS_MEMORY_CUSTOM_IMPL +#define ALLOW_WEAK __attribute__((weak)) +#else +#define ALLOW_WEAK +#endif + +#if CONFIG_MDNS_TASK_CREATE_FROM_SPIRAM +#define MDNS_TASK_MEMORY_CAPS (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) +#define MDNS_TASK_MEMORY_LOG "SPIRAM" +#endif +#if CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL +#define MDNS_TASK_MEMORY_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) +#define MDNS_TASK_MEMORY_LOG "internal RAM" +#endif + +#if CONFIG_MDNS_MEMORY_ALLOC_SPIRAM +#define MDNS_MEMORY_CAPS (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) +#endif +#if CONFIG_MDNS_MEMORY_ALLOC_INTERNAL +#define MDNS_MEMORY_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) +#endif + +// Allocate memory from internal heap as default. +#ifndef MDNS_MEMORY_CAPS +#warning "No memory allocation method defined, using internal memory" +#define MDNS_MEMORY_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) +#endif +#ifndef MDNS_TASK_MEMORY_CAPS +#define MDNS_TASK_MEMORY_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) +#define MDNS_TASK_MEMORY_LOG "internal RAM" +#endif + +void ALLOW_WEAK *mdns_mem_malloc(size_t size) +{ + return heap_caps_malloc(size, MDNS_MEMORY_CAPS); +} + +void ALLOW_WEAK *mdns_mem_calloc(size_t num, size_t size) +{ + return heap_caps_calloc(num, size, MDNS_MEMORY_CAPS); +} + +void ALLOW_WEAK mdns_mem_free(void *ptr) +{ + heap_caps_free(ptr); +} + +char ALLOW_WEAK *mdns_mem_strdup(const char *s) +{ + if (!s) { + return NULL; + } + size_t len = strlen(s) + 1; + char *copy = (char *)heap_caps_malloc(len, MDNS_MEMORY_CAPS); + if (copy) { + memcpy(copy, s, len); + } + return copy; +} + +char ALLOW_WEAK *mdns_mem_strndup(const char *s, size_t n) +{ + if (!s) { + return NULL; + } + size_t len = strnlen(s, n); + char *copy = (char *)heap_caps_malloc(len + 1, MDNS_MEMORY_CAPS); + if (copy) { + memcpy(copy, s, len); + copy[len] = '\0'; + } + return copy; +} + +void ALLOW_WEAK *mdns_mem_task_malloc(size_t size) +{ + ESP_LOGI("mdns_mem", "mDNS task will be created from %s", MDNS_TASK_MEMORY_LOG); + return heap_caps_malloc(size, MDNS_TASK_MEMORY_CAPS); +} + +void ALLOW_WEAK mdns_mem_task_free(void *ptr) +{ + heap_caps_free(ptr); +} diff --git a/managed_components/espressif__mdns/mdns_netif.c b/managed_components/espressif__mdns/mdns_netif.c new file mode 100644 index 0000000..9a8d1c8 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_netif.c @@ -0,0 +1,467 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "sdkconfig.h" +#include "esp_log.h" +#include "esp_event.h" +#include "mdns.h" +#include "mdns_private.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_debug.h" +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#include "mdns_browser.h" +#endif +#include "mdns_netif.h" +#include "mdns_pcb.h" +#include "mdns_responder.h" +#include "mdns_service.h" + +static const char *TAG = "mdns_netif"; + +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH +#include "esp_eth.h" +#endif + +#if ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(5, 1, 0) +#define MDNS_ESP_WIFI_ENABLED CONFIG_SOC_WIFI_SUPPORTED +#else +#define MDNS_ESP_WIFI_ENABLED (CONFIG_ESP_WIFI_ENABLED || CONFIG_ESP_WIFI_REMOTE_ENABLED) +#endif + +#if MDNS_ESP_WIFI_ENABLED && (CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP) +#include "esp_wifi.h" +#endif + +typedef enum { + MDNS_IF_STA = 0, + MDNS_IF_AP = 1, + MDNS_IF_ETH = 2, +} mdns_predef_if_t; + +typedef struct mdns_interfaces mdns_interfaces_t; + +struct mdns_interfaces { + const bool predefined; + esp_netif_t *netif; + const mdns_predef_if_t predef_if; + mdns_if_t duplicate; +}; + +/* + * @brief Internal collection of mdns supported interfaces + * + */ +static mdns_interfaces_t s_esp_netifs[MDNS_MAX_INTERFACES] = { +#if CONFIG_MDNS_PREDEF_NETIF_STA + { .predefined = true, .netif = NULL, .predef_if = MDNS_IF_STA, .duplicate = MDNS_MAX_INTERFACES }, +#endif +#if CONFIG_MDNS_PREDEF_NETIF_AP + { .predefined = true, .netif = NULL, .predef_if = MDNS_IF_AP, .duplicate = MDNS_MAX_INTERFACES }, +#endif +#if CONFIG_MDNS_PREDEF_NETIF_ETH + { .predefined = true, .netif = NULL, .predef_if = MDNS_IF_ETH, .duplicate = MDNS_MAX_INTERFACES }, +#endif +}; + +/** + * @brief Helper to get either ETH or STA if the other is provided + * Used when two interfaces are on the same subnet + */ +mdns_if_t mdns_priv_netif_get_other_interface(mdns_if_t tcpip_if) +{ + if (tcpip_if < MDNS_MAX_INTERFACES) { + return s_esp_netifs[tcpip_if].duplicate; + } + return MDNS_MAX_INTERFACES; +} + +/** + * @brief Convert Predefined interface to the netif id from the internal netif list + * @param predef_if Predefined interface enum + * @return Ordinal number of internal list of mdns network interface. + * Returns MDNS_MAX_INTERFACES if the predefined interface wasn't found in the list + */ +static mdns_if_t mdns_if_from_preset(mdns_predef_if_t predef_if) +{ + for (int i = 0; i < MDNS_MAX_INTERFACES; ++i) { + if (s_esp_netifs[i].predefined && s_esp_netifs[i].predef_if == predef_if) { + return i; + } + } + return MDNS_MAX_INTERFACES; +} + +/** + * @brief Convert Predefined interface to esp-netif handle + * @param predef_if Predefined interface enum + * @return esp_netif pointer from system list of network interfaces + */ +static inline esp_netif_t *netif_from_preset(mdns_predef_if_t predef_if) +{ + switch (predef_if) { + case MDNS_IF_STA: + return esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); + case MDNS_IF_AP: + return esp_netif_get_handle_from_ifkey("WIFI_AP_DEF"); +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH + case MDNS_IF_ETH: + return esp_netif_get_handle_from_ifkey("ETH_DEF"); +#endif + default: + return NULL; + } +} + +esp_netif_t *mdns_priv_get_esp_netif(mdns_if_t tcpip_if) +{ + if (tcpip_if < MDNS_MAX_INTERFACES) { + if (s_esp_netifs[tcpip_if].netif == NULL && s_esp_netifs[tcpip_if].predefined) { + // If the local copy is NULL and this netif is predefined -> we can find it in the global netif list + s_esp_netifs[tcpip_if].netif = netif_from_preset(s_esp_netifs[tcpip_if].predef_if); + // failing to find it means that the netif is *not* available -> return NULL + } + return s_esp_netifs[tcpip_if].netif; + } + return NULL; +} + +/* + * @brief Clean internal mdns interface's pointer + */ +void mdns_priv_netif_disable(mdns_if_t tcpip_if) +{ + if (tcpip_if < MDNS_MAX_INTERFACES) { + s_esp_netifs[tcpip_if].netif = NULL; + } +} + +/* + * @brief Convert esp-netif handle to mdns if + */ +static mdns_if_t get_if_from_netif(esp_netif_t *esp_netif) +{ + for (int i = 0; i < MDNS_MAX_INTERFACES; ++i) { + // The predefined netifs in the static array are NULL when firstly calling this function + // if IPv4 is disabled. Set these netifs here. + if (s_esp_netifs[i].netif == NULL && s_esp_netifs[i].predefined) { + s_esp_netifs[i].netif = netif_from_preset(s_esp_netifs[i].predef_if); + } + if (esp_netif == s_esp_netifs[i].netif) { + return i; + } + } + return MDNS_MAX_INTERFACES; +} + +static esp_err_t post_custom_action(mdns_if_t mdns_if, mdns_event_actions_t event_action) +{ + if (!mdns_priv_is_server_init() || mdns_if >= MDNS_MAX_INTERFACES) { + return ESP_ERR_INVALID_STATE; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_calloc(1, sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + action->type = ACTION_SYSTEM_EVENT; + action->data.sys_event.event_action = event_action; + action->data.sys_event.interface = mdns_if; + + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + } + return ESP_OK; +} + +#if defined(CONFIG_MDNS_ENABLE_BROWSE) && (CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH) +static esp_err_t post_browse_send_by_ip_protocol_action(mdns_if_t mdns_if, mdns_ip_protocol_t ip_protocol) +{ + if (!mdns_priv_is_server_init() || mdns_if >= MDNS_MAX_INTERFACES) { + return ESP_ERR_INVALID_STATE; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_calloc(1, sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + action->type = ACTION_BROWSE_SEND_BY_IP_PROTOCOL; + action->data.browse_send.interface = mdns_if; + action->data.browse_send.ip_protocol = ip_protocol; + + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + } + return ESP_OK; +} +#endif + +/** + * @brief Dispatch interface changes based on system events + */ +static inline void post_disable_pcb(mdns_predef_if_t preset_if, mdns_ip_protocol_t protocol) +{ + post_custom_action(mdns_if_from_preset(preset_if), + protocol == MDNS_IP_PROTOCOL_V4 ? MDNS_EVENT_DISABLE_IP4 : MDNS_EVENT_DISABLE_IP6); +} + +static inline void post_enable_pcb(mdns_predef_if_t preset_if, mdns_ip_protocol_t protocol) +{ + post_custom_action(mdns_if_from_preset(preset_if), + protocol == MDNS_IP_PROTOCOL_V4 ? MDNS_EVENT_ENABLE_IP4 : MDNS_EVENT_ENABLE_IP6); +} + +static inline void post_announce_pcb(mdns_predef_if_t preset_if, mdns_ip_protocol_t protocol) +{ + post_custom_action(mdns_if_from_preset(preset_if), + protocol == MDNS_IP_PROTOCOL_V4 ? MDNS_EVENT_ANNOUNCE_IP4 : MDNS_EVENT_ANNOUNCE_IP6); +} + +#if CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH +static void handle_system_event_for_preset(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) +{ + if (!mdns_priv_is_server_init()) { + return; + } + +#if MDNS_ESP_WIFI_ENABLED && (CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP) + if (event_base == WIFI_EVENT) { + esp_netif_dhcp_status_t dcst; + switch (event_id) { + case WIFI_EVENT_STA_CONNECTED: + if (!esp_netif_dhcpc_get_status(netif_from_preset(MDNS_IF_STA), &dcst)) { + if (dcst == ESP_NETIF_DHCP_STOPPED) { + post_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); + } + } + break; + case WIFI_EVENT_STA_DISCONNECTED: + post_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); + post_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); + break; + case WIFI_EVENT_AP_START: + post_enable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); + break; + case WIFI_EVENT_AP_STOP: + post_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); + post_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V6); + break; + default: + break; + } + } else +#endif +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH + if (event_base == ETH_EVENT) { + esp_netif_dhcp_status_t dcst; + switch (event_id) { + case ETHERNET_EVENT_CONNECTED: + if (!esp_netif_dhcpc_get_status(netif_from_preset(MDNS_IF_ETH), &dcst)) { + if (dcst == ESP_NETIF_DHCP_STOPPED) { + post_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); + } + } + break; + case ETHERNET_EVENT_DISCONNECTED: + post_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); + post_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V6); + break; + default: + break; + } + } else +#endif + if (event_base == IP_EVENT) { + switch (event_id) { + case IP_EVENT_STA_GOT_IP: + post_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); + post_announce_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + post_browse_send_by_ip_protocol_action(mdns_if_from_preset(MDNS_IF_STA), MDNS_IP_PROTOCOL_V4); +#endif + break; +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH + case IP_EVENT_ETH_GOT_IP: + post_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + post_browse_send_by_ip_protocol_action(mdns_if_from_preset(MDNS_IF_ETH), MDNS_IP_PROTOCOL_V4); +#endif + break; +#endif + case IP_EVENT_GOT_IP6: { + ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data; + mdns_if_t mdns_if = get_if_from_netif(event->esp_netif); + if (mdns_if >= MDNS_MAX_INTERFACES) { + return; + } + // mdns_if is already an internal index, not a predefined interface + post_custom_action(mdns_if, MDNS_EVENT_ENABLE_IP6); + post_custom_action(mdns_if, MDNS_EVENT_ANNOUNCE_IP4); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + post_browse_send_by_ip_protocol_action(mdns_if, MDNS_IP_PROTOCOL_V6); +#endif + + } + break; + default: + break; + } + } +} +#endif /* CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH */ + +static inline void set_default_duplicated_interfaces(void) +{ + mdns_if_t wifi_sta_if = MDNS_MAX_INTERFACES; + mdns_if_t eth_if = MDNS_MAX_INTERFACES; + for (mdns_if_t i = 0; i < MDNS_MAX_INTERFACES; i++) { + if (s_esp_netifs[i].predefined && s_esp_netifs[i].predef_if == MDNS_IF_STA) { + wifi_sta_if = i; + } + if (s_esp_netifs[i].predefined && s_esp_netifs[i].predef_if == MDNS_IF_ETH) { + eth_if = i; + } + } + if (wifi_sta_if != MDNS_MAX_INTERFACES && eth_if != MDNS_MAX_INTERFACES) { + s_esp_netifs[wifi_sta_if].duplicate = eth_if; + s_esp_netifs[eth_if].duplicate = wifi_sta_if; + } +} + +void mdns_priv_netif_unregister_predefined_handlers(void) +{ +#if MDNS_ESP_WIFI_ENABLED && (CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP) + esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset); +#endif +#if CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH + esp_event_handler_unregister(IP_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset); +#endif +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH + esp_event_handler_unregister(ETH_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset); +#endif +} + +esp_err_t mdns_priv_netif_init(void) +{ + esp_err_t err = ESP_OK; + // zero-out local copy of netifs to initiate a fresh search by interface key whenever a netif ptr is needed + for (mdns_if_t i = 0; i < MDNS_MAX_INTERFACES; ++i) { + s_esp_netifs[i].netif = NULL; + } +#if MDNS_ESP_WIFI_ENABLED && (CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP) + if ((err = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset, NULL)) != ESP_OK) { + goto free_event_handlers; + } +#endif +#if CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH + if ((err = esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset, NULL)) != ESP_OK) { + goto free_event_handlers; + } +#endif +#if CONFIG_ETH_ENABLED && CONFIG_MDNS_PREDEF_NETIF_ETH + if ((err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, handle_system_event_for_preset, NULL)) != ESP_OK) { + goto free_event_handlers; + } +#endif + +#if CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH + set_default_duplicated_interfaces(); +#endif + + uint8_t i; +#ifdef CONFIG_LWIP_IPV6 + esp_ip6_addr_t tmp_addr6; +#endif +#ifdef CONFIG_LWIP_IPV4 + esp_netif_ip_info_t if_ip_info; +#endif + + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { +#ifdef CONFIG_LWIP_IPV6 + if (!esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(i), &tmp_addr6) && !mdns_utils_ipv6_address_is_zero(tmp_addr6)) { + mdns_priv_pcb_enable(i, MDNS_IP_PROTOCOL_V6); + } +#endif +#ifdef CONFIG_LWIP_IPV4 + if (!esp_netif_get_ip_info(mdns_priv_get_esp_netif(i), &if_ip_info) && if_ip_info.ip.addr) { + mdns_priv_pcb_enable(i, MDNS_IP_PROTOCOL_V4); + } +#endif + } + return ESP_OK; +#if CONFIG_MDNS_PREDEF_NETIF_STA || CONFIG_MDNS_PREDEF_NETIF_AP || CONFIG_MDNS_PREDEF_NETIF_ETH +free_event_handlers: + mdns_priv_netif_unregister_predefined_handlers(); +#endif + return err; +} + +esp_err_t mdns_priv_netif_deinit(void) +{ + for (int i = 0; i < MDNS_MAX_INTERFACES; i++) { + mdns_priv_pcb_disable(i, MDNS_IP_PROTOCOL_V6); + mdns_priv_pcb_disable(i, MDNS_IP_PROTOCOL_V4); + s_esp_netifs[i].duplicate = MDNS_MAX_INTERFACES; + } + return ESP_OK; +} + +/* + * Public Methods + * */ +esp_err_t mdns_netif_action(esp_netif_t *esp_netif, mdns_event_actions_t event_action) +{ + return post_custom_action(get_if_from_netif(esp_netif), event_action); +} + +esp_err_t mdns_register_netif(esp_netif_t *esp_netif) +{ + if (!mdns_priv_is_server_init()) { + return ESP_ERR_INVALID_STATE; + } + + esp_err_t err = ESP_ERR_NO_MEM; + mdns_priv_service_lock(); + for (mdns_if_t i = 0; i < MDNS_MAX_INTERFACES; ++i) { + if (s_esp_netifs[i].netif == esp_netif) { + mdns_priv_service_unlock(); + return ESP_ERR_INVALID_STATE; + } + } + + for (mdns_if_t i = 0; i < MDNS_MAX_INTERFACES; ++i) { + if (!s_esp_netifs[i].predefined && s_esp_netifs[i].netif == NULL) { + s_esp_netifs[i].netif = esp_netif; + err = ESP_OK; + break; + } + } + mdns_priv_service_unlock(); + return err; +} + +esp_err_t mdns_unregister_netif(esp_netif_t *esp_netif) +{ + if (!mdns_priv_is_server_init()) { + return ESP_ERR_INVALID_STATE; + } + + esp_err_t err = ESP_ERR_NOT_FOUND; + mdns_priv_service_lock(); + for (mdns_if_t i = 0; i < MDNS_MAX_INTERFACES; ++i) { + if (!s_esp_netifs[i].predefined && s_esp_netifs[i].netif == esp_netif) { + s_esp_netifs[i].netif = NULL; + err = ESP_OK; + break; + } + } + mdns_priv_service_unlock(); + return err; +} diff --git a/managed_components/espressif__mdns/mdns_networking_lwip.c b/managed_components/espressif__mdns/mdns_networking_lwip.c new file mode 100644 index 0000000..38752a5 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_networking_lwip.c @@ -0,0 +1,425 @@ +/* + * SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/* + * MDNS Server Networking + * + */ +#include +#include "esp_log.h" +#include "lwip/ip_addr.h" +#include "lwip/pbuf.h" +#include "lwip/igmp.h" +#include "lwip/udp.h" +#include "lwip/mld6.h" +#include "lwip/priv/tcpip_priv.h" +#include "mdns_networking.h" +#include "esp_netif_net_stack.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_netif.h" +#include "mdns_service.h" + +/* + * MDNS Server Networking + * + */ +enum interface_protocol { + PROTO_IPV4 = 1 << MDNS_IP_PROTOCOL_V4, + PROTO_IPV6 = 1 << MDNS_IP_PROTOCOL_V6 +}; + +typedef struct interfaces { + bool ready; + int proto; +} interfaces_t; + +static interfaces_t s_interfaces[MDNS_MAX_INTERFACES]; + +static struct udp_pcb *s_pcb_main = NULL; + +static const char *TAG = "mdns_networking"; + +static void receive(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip_addr_t *raddr, uint16_t rport); + +static esp_err_t send_rx_action(mdns_rx_packet_t *packet) +{ + mdns_action_t *action = NULL; + + action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + + action->type = ACTION_RX_HANDLE; + action->data.rx_handle.packet = packet; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +/** + * @brief Low level UDP PCB Initialize + */ +static esp_err_t pcb_init(void) +{ + if (s_pcb_main) { + return ESP_OK; + } + s_pcb_main = udp_new(); + if (!s_pcb_main) { + return ESP_ERR_NO_MEM; + } + if (udp_bind(s_pcb_main, IP_ANY_TYPE, MDNS_SERVICE_PORT) != 0) { + udp_remove(s_pcb_main); + s_pcb_main = NULL; + return ESP_ERR_INVALID_STATE; + } + s_pcb_main->mcast_ttl = 255; + s_pcb_main->remote_port = MDNS_SERVICE_PORT; + ip_addr_copy(s_pcb_main->remote_ip, *(IP_ANY_TYPE)); + udp_recv(s_pcb_main, receive, NULL); + return ESP_OK; +} + +/** + * @brief Low level UDP PCB Free + */ +static void pcb_deinit(void) +{ + if (s_pcb_main) { + udp_recv(s_pcb_main, NULL, NULL); + udp_disconnect(s_pcb_main); + udp_remove(s_pcb_main); + s_pcb_main = NULL; + } +} + +/** + * @brief Low level UDP Multicast membership control + */ +static esp_err_t join_group(mdns_if_t if_inx, mdns_ip_protocol_t ip_protocol, bool join) +{ + struct netif *netif = NULL; + esp_netif_t *tcpip_if = mdns_priv_get_esp_netif(if_inx); + + if (!tcpip_if) { + // The interface can disappear before mDNS deinit finishes during reboot. + return ESP_ERR_INVALID_STATE; + } + + if (!esp_netif_is_netif_up(tcpip_if)) { + // Network interface went down before event propagated, skipping IGMP config + return ESP_ERR_INVALID_STATE; + } + + netif = esp_netif_get_netif_impl(tcpip_if); + if (!netif) { + return ESP_ERR_INVALID_STATE; + } + +#if LWIP_IPV4 + if (ip_protocol == MDNS_IP_PROTOCOL_V4) { + ip4_addr_t multicast_addr; + IP4_ADDR(&multicast_addr, 224, 0, 0, 251); + + if (join) { + if (igmp_joingroup_netif(netif, &multicast_addr)) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (igmp_leavegroup_netif(netif, &multicast_addr)) { + return ESP_ERR_INVALID_STATE; + } + } + } +#endif // LWIP_IPV4 +#if LWIP_IPV6 + if (ip_protocol == MDNS_IP_PROTOCOL_V6) { + ip_addr_t multicast_addr = IPADDR6_INIT(0x000002ff, 0, 0, 0xfb000000); + + if (join) { + if (mld6_joingroup_netif(netif, ip_2_ip6(&multicast_addr))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (mld6_leavegroup_netif(netif, ip_2_ip6(&multicast_addr))) { + return ESP_ERR_INVALID_STATE; + } + } + } +#endif // LWIP_IPV6 + return ESP_OK; +} + +/** + * @brief the receive callback of the raw udp api. Packets are received here + * + */ +static void receive(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip_addr_t *raddr, uint16_t rport) +{ + + uint8_t i; + while (pb != NULL) { + struct pbuf *this_pb = pb; + pb = pb->next; + this_pb->next = NULL; + + mdns_rx_packet_t *packet = (mdns_rx_packet_t *)mdns_mem_malloc(sizeof(mdns_rx_packet_t)); + if (!packet) { + HOOK_MALLOC_FAILED; + //missed packet - no memory + pbuf_free(this_pb); + continue; + } + + packet->tcpip_if = MDNS_MAX_INTERFACES; + packet->pb = this_pb; + packet->src_port = rport; +#if LWIP_IPV4 && LWIP_IPV6 + packet->src.type = raddr->type; + memcpy(&packet->src.u_addr, &raddr->u_addr, sizeof(raddr->u_addr)); +#elif LWIP_IPV4 + packet->src.type = IPADDR_TYPE_V4; + packet->src.u_addr.ip4.addr = raddr->addr; +#elif LWIP_IPV6 + packet->src.type = IPADDR_TYPE_V6; + memcpy(&packet->src.u_addr.ip6, raddr, sizeof(ip_addr_t)); +#endif + packet->dest.type = packet->src.type; + +#if LWIP_IPV4 + if (packet->src.type == IPADDR_TYPE_V4) { + packet->ip_protocol = MDNS_IP_PROTOCOL_V4; + struct ip_hdr *iphdr = (struct ip_hdr *)(((uint8_t *)(packet->pb->payload)) - UDP_HLEN - IP_HLEN); + packet->dest.u_addr.ip4.addr = iphdr->dest.addr; + packet->multicast = ip4_addr_ismulticast(&(packet->dest.u_addr.ip4)); + } +#endif // LWIP_IPV4 +#if LWIP_IPV6 + if (packet->src.type == IPADDR_TYPE_V6) { + packet->ip_protocol = MDNS_IP_PROTOCOL_V6; + struct ip6_hdr *ip6hdr = (struct ip6_hdr *)(((uint8_t *)(packet->pb->payload)) - UDP_HLEN - IP6_HLEN); + memcpy(&packet->dest.u_addr.ip6.addr, (uint8_t *)ip6hdr->dest.addr, 16); + packet->multicast = ip6_addr_ismulticast(&(packet->dest.u_addr.ip6)); + } +#endif // LWIP_IPV6 + + //lwip does not return the proper pcb if you have more than one for the same multicast address (but different interfaces) + struct netif *netif = NULL; + bool found = false; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + netif = esp_netif_get_netif_impl(mdns_priv_get_esp_netif(i)); + if (s_interfaces[i].proto && netif && netif == ip_current_input_netif()) { +#if LWIP_IPV4 + if (packet->src.type == IPADDR_TYPE_V4) { + if ((packet->src.u_addr.ip4.addr & ip_2_ip4(&netif->netmask)->addr) != (ip_2_ip4(&netif->ip_addr)->addr & ip_2_ip4(&netif->netmask)->addr)) { + //packet source is not in the same subnet + break; + } + } +#endif // LWIP_IPV4 + packet->tcpip_if = i; + found = true; + break; + } + } + + if (!found || send_rx_action(packet) != ESP_OK) { + pbuf_free(this_pb); + mdns_mem_free(packet); + } + } + +} + +bool mdns_priv_if_ready(mdns_if_t netif, mdns_ip_protocol_t ip_proto) +{ + return s_interfaces[netif].ready && + s_interfaces[netif].proto & (ip_proto == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); +} + +/** + * @brief Check if any of the interfaces is up + */ +static bool is_any_pcb_in_use(void) +{ + int i, p; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (p = 0; p < MDNS_IP_PROTOCOL_MAX; p++) { + if (mdns_priv_if_ready(i, p)) { + return true; + } + } + } + return false; +} + +/** + * @brief Stop PCB Main code + */ +static void pcb_if_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + s_interfaces[tcpip_if].proto &= ~(ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); + if (s_interfaces[tcpip_if].proto == 0) { + s_interfaces[tcpip_if].ready = false; + join_group(tcpip_if, ip_protocol, false); + if (!is_any_pcb_in_use()) { + pcb_deinit(); + } + } +} + +/** + * @brief Start PCB Main code + */ +static esp_err_t pcb_if_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + if (mdns_priv_if_ready(tcpip_if, ip_protocol)) { + return ESP_ERR_INVALID_STATE; + } + + esp_err_t err = join_group(tcpip_if, ip_protocol, true); + if (err) { + return err; + } + + err = pcb_init(); + if (err) { + return err; + } + s_interfaces[tcpip_if].proto |= (ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); + s_interfaces[tcpip_if].ready = true; + + return ESP_OK; +} + +typedef struct { + struct tcpip_api_call_data call; + mdns_if_t tcpip_if; + mdns_ip_protocol_t ip_protocol; + struct pbuf *pbt; + const ip_addr_t *ip; + uint16_t port; + esp_err_t err; +} mdns_api_call_t; + +/** + * @brief Start PCB from LwIP thread + */ +static err_t pcb_if_init_lwip(struct tcpip_api_call_data *api_call_msg) +{ + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; + msg->err = pcb_if_init(msg->tcpip_if, msg->ip_protocol); + return msg->err == ESP_OK ? ERR_OK : ERR_IF; +} + +/** + * @brief Stop PCB from LwIP thread + */ +static err_t pcb_if_deinit_lwip(struct tcpip_api_call_data *api_call_msg) +{ + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; + pcb_if_deinit(msg->tcpip_if, msg->ip_protocol); + msg->err = ESP_OK; + return ESP_OK; +} + +/* + * Non-static functions below are + * - _mdns prefixed + * - commented in mdns_networking.h header + */ +esp_err_t mdns_priv_if_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_api_call_t msg = { + .tcpip_if = tcpip_if, + .ip_protocol = ip_protocol + }; + tcpip_api_call(pcb_if_init_lwip, &msg.call); + return msg.err; +} + +esp_err_t mdns_priv_if_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_api_call_t msg = { + .tcpip_if = tcpip_if, + .ip_protocol = ip_protocol + }; + tcpip_api_call(pcb_if_deinit_lwip, &msg.call); + return msg.err; +} + +static err_t write_if_lwip(struct tcpip_api_call_data *api_call_msg) +{ + void *nif = NULL; + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; + nif = esp_netif_get_netif_impl(mdns_priv_get_esp_netif(msg->tcpip_if)); + if (!nif || !mdns_priv_if_ready(msg->tcpip_if, msg->ip_protocol) || s_pcb_main == NULL) { + pbuf_free(msg->pbt); + msg->err = ERR_IF; + return ERR_IF; + } + err_t err = udp_sendto_if(s_pcb_main, msg->pbt, msg->ip, msg->port, (struct netif *)nif); + pbuf_free(msg->pbt); + msg->err = err == ERR_OK ? ESP_OK : ESP_FAIL; + return err; +} + +size_t mdns_priv_if_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, const esp_ip_addr_t *ip, uint16_t port, uint8_t *data, size_t len) +{ + struct pbuf *pbt = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); + if (pbt == NULL) { + return 0; + } + memcpy((uint8_t *)pbt->payload, data, len); + + ip_addr_t ip_add_copy; +#if LWIP_IPV6 && LWIP_IPV4 + ip_add_copy.type = ip->type; + memcpy(&(ip_add_copy.u_addr), &(ip->u_addr), sizeof(ip_add_copy.u_addr)); +#elif LWIP_IPV4 + ip_add_copy.addr = ip->u_addr.ip4.addr; +#elif LWIP_IPV6 +#if LWIP_IPV6_SCOPES + ip_add_copy.zone = ip->u_addr.ip6.zone; +#endif // LWIP_IPV6_SCOPES + memcpy(ip_add_copy.addr, ip->u_addr.ip6.addr, sizeof(ip_add_copy.addr)); +#endif + + mdns_api_call_t msg = { + .tcpip_if = tcpip_if, + .ip_protocol = ip_protocol, + .pbt = pbt, + .ip = &ip_add_copy, + .port = port + }; + tcpip_api_call(write_if_lwip, &msg.call); + + if (msg.err) { + return 0; + } + return len; +} + +void *mdns_priv_get_packet_data(mdns_rx_packet_t *packet) +{ + return packet->pb->payload; +} + +size_t mdns_priv_get_packet_len(mdns_rx_packet_t *packet) +{ + return packet->pb->len; +} + +void mdns_priv_packet_free(mdns_rx_packet_t *packet) +{ + pbuf_free(packet->pb); + mdns_mem_free(packet); +} diff --git a/managed_components/espressif__mdns/mdns_networking_socket.c b/managed_components/espressif__mdns/mdns_networking_socket.c new file mode 100644 index 0000000..4acd3d9 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_networking_socket.c @@ -0,0 +1,576 @@ +/* + * SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @brief MDNS Server Networking module implemented using BSD sockets + */ + +#include +#include "esp_event.h" +#include "mdns_networking.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "esp_log.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_netif.h" +#include "mdns_service.h" + +#if defined(CONFIG_IDF_TARGET_LINUX) +#include +#include +#endif + +enum interface_protocol { + PROTO_IPV4 = 1 << MDNS_IP_PROTOCOL_V4, + PROTO_IPV6 = 1 << MDNS_IP_PROTOCOL_V6 +}; + +typedef struct interfaces { + int sock; + int proto; +} interfaces_t; + +static interfaces_t s_interfaces[MDNS_MAX_INTERFACES]; + +static const char *TAG = "mdns_networking"; +static bool s_run_sock_recv_task = false; +static TaskHandle_t s_sock_recv_task_handle = NULL; +static SemaphoreHandle_t s_sock_recv_task_exit_sem = NULL; +static int create_socket(esp_netif_t *netif); +static int join_mdns_multicast_group(int sock, esp_netif_t *netif, mdns_ip_protocol_t ip_protocol); + +#if defined(CONFIG_IDF_TARGET_LINUX) +// Need to define packet buffer struct on linux +struct pbuf { + struct pbuf *next; + void *payload; + size_t tot_len; + size_t len; +}; +#else +// Compatibility define to access sock-addr struct the same way for lwip and linux +#define s6_addr32 un.u32_addr +#endif // CONFIG_IDF_TARGET_LINUX + +static esp_err_t send_rx_action(mdns_rx_packet_t *packet) +{ + mdns_action_t *action = NULL; + + action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + + action->type = ACTION_RX_HANDLE; + action->data.rx_handle.packet = packet; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + + +static void __attribute__((constructor)) ctor_networking_socket(void) +{ + for (int i = 0; i < sizeof(s_interfaces) / sizeof(s_interfaces[0]); ++i) { + s_interfaces[i].sock = -1; + s_interfaces[i].proto = 0; + } +} + +static void delete_socket(int sock) +{ + if (sock < 0) { + return; + } + + // Best-effort shutdown helps to unblock select()/recvfrom() on some stacks. + shutdown(sock, SHUT_RDWR); + close(sock); +} + +bool mdns_priv_if_ready(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return s_interfaces[tcpip_if].proto & (ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); +} + +void *mdns_priv_get_packet_data(mdns_rx_packet_t *packet) +{ + return packet->pb->payload; +} + +size_t mdns_priv_get_packet_len(mdns_rx_packet_t *packet) +{ + return packet->pb->len; +} + +void mdns_priv_packet_free(mdns_rx_packet_t *packet) +{ + mdns_mem_free(packet->pb->payload); + mdns_mem_free(packet->pb); + mdns_mem_free(packet); +} + +esp_err_t mdns_priv_if_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + s_interfaces[tcpip_if].proto &= ~(ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); + if (s_interfaces[tcpip_if].proto == 0) { + // If the interface for both protocols uninitialized, close the interface socket. + if (s_interfaces[tcpip_if].sock >= 0) { + delete_socket(s_interfaces[tcpip_if].sock); + s_interfaces[tcpip_if].sock = -1; + } + } + + for (int i = 0; i < MDNS_MAX_INTERFACES; i++) { + if (s_interfaces[i].sock >= 0) { + // If any of the interfaces initialized + return ESP_OK; + } + } + + // No interface alive, stop the rx task and wait for it to exit. + if (s_sock_recv_task_handle != NULL) { + s_run_sock_recv_task = false; + if (s_sock_recv_task_exit_sem != NULL) { + xSemaphoreTake(s_sock_recv_task_exit_sem, pdMS_TO_TICKS(2000)); + } + s_sock_recv_task_handle = NULL; + } + + return ESP_OK; +} + +#if defined(CONFIG_IDF_TARGET_LINUX) +#ifdef CONFIG_LWIP_IPV6 +static char *inet6_ntoa_r(struct in6_addr addr, char *ptr, size_t size) +{ + inet_ntop(AF_INET6, &(addr.s6_addr32[0]), ptr, size); + return ptr; +} +#endif // CONFIG_LWIP_IPV6 +static char *inet_ntoa_r(struct in_addr addr, char *ptr, size_t size) +{ + char *res = inet_ntoa(addr); + if (res && strlen(res) < size) { + strcpy(ptr, res); + } + return res; +} +#endif // CONFIG_IDF_TARGET_LINUX + +static inline char *get_string_address(struct sockaddr_storage *source_addr) +{ + static char address_str[40]; // 40=(8*4+7+term) is the max size of ascii IPv6 addr "XXXX:XX...XX:XXXX" + char *res = NULL; + // Convert ip address to string +#ifdef CONFIG_LWIP_IPV4 + if (source_addr->ss_family == PF_INET) { + res = inet_ntoa_r(((struct sockaddr_in *)source_addr)->sin_addr, address_str, sizeof(address_str)); + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (source_addr->ss_family == PF_INET6) { + res = inet6_ntoa_r(((struct sockaddr_in6 *)source_addr)->sin6_addr, address_str, sizeof(address_str)); + } +#endif + if (!res) { + address_str[0] = '\0'; // Returns empty string if conversion didn't succeed + } + return address_str; +} + + +static inline size_t espaddr_to_inet(const esp_ip_addr_t *addr, const uint16_t port, const mdns_ip_protocol_t ip_protocol, struct sockaddr_storage *in_addr) +{ + size_t ss_addr_len = 0; + memset(in_addr, 0, sizeof(struct sockaddr_storage)); +#ifdef CONFIG_LWIP_IPV4 + if (ip_protocol == MDNS_IP_PROTOCOL_V4 && addr->type == ESP_IPADDR_TYPE_V4) { + in_addr->ss_family = PF_INET; +#if !defined(CONFIG_IDF_TARGET_LINUX) + in_addr->s2_len = sizeof(struct sockaddr_in); +#endif + ss_addr_len = sizeof(struct sockaddr_in); + struct sockaddr_in *in_addr_ip4 = (struct sockaddr_in *) in_addr; + in_addr_ip4->sin_port = port; + in_addr_ip4->sin_addr.s_addr = addr->u_addr.ip4.addr; + } +#endif // CONFIG_LWIP_IPV4 +#ifdef CONFIG_LWIP_IPV6 + if (ip_protocol == MDNS_IP_PROTOCOL_V6 && addr->type == ESP_IPADDR_TYPE_V6) { + memset(in_addr, 0, sizeof(struct sockaddr_storage)); + in_addr->ss_family = PF_INET6; +#if !defined(CONFIG_IDF_TARGET_LINUX) + in_addr->s2_len = sizeof(struct sockaddr_in6); +#endif + ss_addr_len = sizeof(struct sockaddr_in6); + struct sockaddr_in6 *in_addr_ip6 = (struct sockaddr_in6 *)in_addr; + uint32_t *u32_addr = in_addr_ip6->sin6_addr.s6_addr32; + in_addr_ip6->sin6_port = port; + u32_addr[0] = addr->u_addr.ip6.addr[0]; + u32_addr[1] = addr->u_addr.ip6.addr[1]; + u32_addr[2] = addr->u_addr.ip6.addr[2]; + u32_addr[3] = addr->u_addr.ip6.addr[3]; + } +#endif // CONFIG_LWIP_IPV6 + return ss_addr_len; +} + +size_t mdns_priv_if_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, const esp_ip_addr_t *ip, uint16_t port, uint8_t *data, size_t len) +{ + if (!(s_interfaces[tcpip_if].proto & (ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6))) { + return 0; + } + int sock = s_interfaces[tcpip_if].sock; + if (sock < 0) { + return 0; + } + struct sockaddr_storage in_addr; + size_t ss_size = espaddr_to_inet(ip, htons(port), ip_protocol, &in_addr); + if (!ss_size) { + ESP_LOGE(TAG, "espaddr_to_inet() failed: Mismatch of IP protocols"); + return 0; + } + ESP_LOGD(TAG, "[sock=%d]: Sending to IP %s port %d", sock, get_string_address(&in_addr), port); + ssize_t actual_len = sendto(sock, data, len, 0, (struct sockaddr *)&in_addr, ss_size); + if (actual_len < 0) { + ESP_LOGE(TAG, "[sock=%d]: mdns_priv_if_write sendto() has failed\n errno=%d: %s", sock, errno, strerror(errno)); + } + return actual_len; +} + +static inline void inet_to_espaddr(const struct sockaddr_storage *in_addr, esp_ip_addr_t *addr, uint16_t *port) +{ +#ifdef CONFIG_LWIP_IPV4 + if (in_addr->ss_family == PF_INET) { + struct sockaddr_in *in_addr_ip4 = (struct sockaddr_in *)in_addr; + memset(addr, 0, sizeof(esp_ip_addr_t)); + *port = in_addr_ip4->sin_port; + addr->u_addr.ip4.addr = in_addr_ip4->sin_addr.s_addr; + addr->type = ESP_IPADDR_TYPE_V4; + } +#endif /* CONFIG_LWIP_IPV4 */ +#ifdef CONFIG_LWIP_IPV6 + if (in_addr->ss_family == PF_INET6) { + struct sockaddr_in6 *in_addr_ip6 = (struct sockaddr_in6 *)in_addr; + memset(addr, 0, sizeof(esp_ip_addr_t)); + *port = in_addr_ip6->sin6_port; + uint32_t *u32_addr = in_addr_ip6->sin6_addr.s6_addr32; + if (u32_addr[0] == 0 && u32_addr[1] == 0 && u32_addr[2] == esp_netif_htonl(0x0000FFFFUL)) { + // Mapped IPv4 address, convert directly to IPv4 + addr->type = ESP_IPADDR_TYPE_V4; + addr->u_addr.ip4.addr = u32_addr[3]; + } else { + addr->type = ESP_IPADDR_TYPE_V6; + addr->u_addr.ip6.addr[0] = u32_addr[0]; + addr->u_addr.ip6.addr[1] = u32_addr[1]; + addr->u_addr.ip6.addr[2] = u32_addr[2]; + addr->u_addr.ip6.addr[3] = u32_addr[3]; + } + } +#endif // CONFIG_LWIP_IPV6 +} + +void sock_recv_task(void *arg) +{ + while (s_run_sock_recv_task) { + struct timeval tv = { + .tv_sec = 1, + .tv_usec = 0, + }; + fd_set rfds; + FD_ZERO(&rfds); + int max_sock = -1; + for (int i = 0; i < MDNS_MAX_INTERFACES; i++) { + int sock = s_interfaces[i].sock; + if (sock >= 0) { + FD_SET(sock, &rfds); + max_sock = MAX(max_sock, sock); + } + } + if (max_sock < 0) { + vTaskDelay(pdMS_TO_TICKS(1000)); + continue; + } + + int s = select(max_sock + 1, &rfds, NULL, NULL, &tv); + if (s < 0) { + if (errno == EINTR) { + continue; + } + ESP_LOGE(TAG, "Select failed. errno=%d: %s", errno, strerror(errno)); + break; + } else if (s > 0) { + for (int tcpip_if = 0; tcpip_if < MDNS_MAX_INTERFACES; tcpip_if++) { + int sock = s_interfaces[tcpip_if].sock; + if (sock < 0) { + continue; + } + if (!FD_ISSET(sock, &rfds)) { + continue; + } + + static char recvbuf[MDNS_MAX_PACKET_SIZE]; + uint16_t port = 0; + + struct sockaddr_storage raddr; // Large enough for both IPv4 or IPv6 + socklen_t socklen = sizeof(struct sockaddr_storage); + esp_ip_addr_t addr = {0}; + int len = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, + (struct sockaddr *) &raddr, &socklen); + if (len < 0) { + // Avoid log-spinning forever if a socket becomes invalid; close and drop it. + ESP_LOGW(TAG, "[sock=%d]: recvfrom failed. errno=%d: %s", sock, errno, strerror(errno)); + delete_socket(sock); + s_interfaces[tcpip_if].sock = -1; + s_interfaces[tcpip_if].proto = 0; + continue; + } + + ESP_LOGD(TAG, "[sock=%d]: Received from IP:%s", sock, get_string_address(&raddr)); + ESP_LOG_BUFFER_HEXDUMP(TAG, recvbuf, len, ESP_LOG_VERBOSE); + inet_to_espaddr(&raddr, &addr, &port); + + // Allocate the packet structure and pass it to the mdns main engine + mdns_rx_packet_t *packet = (mdns_rx_packet_t *) mdns_mem_calloc(1, sizeof(mdns_rx_packet_t)); + struct pbuf *packet_pbuf = mdns_mem_calloc(1, sizeof(struct pbuf)); + uint8_t *buf = mdns_mem_malloc(len); + if (packet == NULL || packet_pbuf == NULL || buf == NULL) { + mdns_mem_free(buf); + mdns_mem_free(packet_pbuf); + mdns_mem_free(packet); + HOOK_MALLOC_FAILED; + ESP_LOGE(TAG, "Failed to allocate the mdns packet"); + continue; + } + memcpy(buf, recvbuf, len); + packet_pbuf->next = NULL; + packet_pbuf->payload = buf; + packet_pbuf->tot_len = len; + packet_pbuf->len = len; + packet->tcpip_if = tcpip_if; + packet->pb = packet_pbuf; + packet->src_port = ntohs(port); + memcpy(&packet->src, &addr, sizeof(esp_ip_addr_t)); + // TODO: Add the correct dest addr -- for mdns to decide multicast/unicast + // Currently it's enough to assume the packet is multicast and mdns to check the source port of the packet + memset(&packet->dest, 0, sizeof(esp_ip_addr_t)); + packet->multicast = 1; + packet->dest.type = packet->src.type; + packet->ip_protocol = + packet->src.type == ESP_IPADDR_TYPE_V4 ? MDNS_IP_PROTOCOL_V4 : MDNS_IP_PROTOCOL_V6; + if (send_rx_action(packet) != ESP_OK) { + ESP_LOGE(TAG, "send_rx_action failed!"); + mdns_mem_free(packet->pb->payload); + mdns_mem_free(packet->pb); + mdns_mem_free(packet); + } + } + } + } + + if (s_sock_recv_task_exit_sem != NULL) { + xSemaphoreGive(s_sock_recv_task_exit_sem); + } + vTaskDelete(NULL); +} + +static esp_err_t networking_init(void) +{ + if (s_sock_recv_task_exit_sem == NULL) { + s_sock_recv_task_exit_sem = xSemaphoreCreateBinary(); + if (s_sock_recv_task_exit_sem == NULL) { + ESP_LOGE(TAG, "Failed to create recv task exit semaphore"); + return ESP_ERR_NO_MEM; + } + } + + if (s_sock_recv_task_handle == NULL) { + s_run_sock_recv_task = true; + xTaskCreate(sock_recv_task, "mdns recv task", 3 * 1024, NULL, 5, &s_sock_recv_task_handle); + } + return ESP_OK; +} + +static bool create_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + const int proto_bit = (ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); + + if (s_interfaces[tcpip_if].proto & proto_bit) { + return true; + } + + int sock = s_interfaces[tcpip_if].sock; + esp_netif_t *netif = mdns_priv_get_esp_netif(tcpip_if); + if (sock < 0) { + sock = create_socket(netif); + } + if (sock < 0) { + ESP_LOGE(TAG, "Failed to create the socket!"); + return false; + } + + int err = join_mdns_multicast_group(sock, netif, ip_protocol); + if (err < 0) { + ESP_LOGE(TAG, "Failed to add multicast group for protocol %d", ip_protocol); + // If this socket is not used by any other protocol, close it. + if (s_interfaces[tcpip_if].sock < 0 && s_interfaces[tcpip_if].proto == 0) { + delete_socket(sock); + } + return false; + } + + s_interfaces[tcpip_if].proto |= proto_bit; + s_interfaces[tcpip_if].sock = sock; + return true; +} + +esp_err_t mdns_priv_if_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + ESP_LOGI(TAG, "mdns_priv_if_init(tcpip_if=%lu, ip_protocol=%lu)", (unsigned long)tcpip_if, (unsigned long)ip_protocol); + if (!create_pcb(tcpip_if, ip_protocol)) { + return ESP_FAIL; + } + + if (networking_init() != ESP_OK) { + s_interfaces[tcpip_if].proto &= ~(ip_protocol == MDNS_IP_PROTOCOL_V4 ? PROTO_IPV4 : PROTO_IPV6); + if (s_interfaces[tcpip_if].proto == 0 && s_interfaces[tcpip_if].sock >= 0) { + delete_socket(s_interfaces[tcpip_if].sock); + s_interfaces[tcpip_if].sock = -1; + } + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +static int create_socket(esp_netif_t *netif) +{ +#ifdef CONFIG_LWIP_IPV6 + int sock = socket(PF_INET6, SOCK_DGRAM, 0); +#else + int sock = socket(PF_INET, SOCK_DGRAM, 0); +#endif + if (sock < 0) { + ESP_LOGE(TAG, "Failed to create socket. errno=%d: %s", errno, strerror(errno)); + return -1; + } + + int on = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) { + ESP_LOGE(TAG, "Failed setsockopt() to set SO_REUSEADDR. errno=%d: %s\n", errno, strerror(errno)); + } + // Bind the socket to any address +#ifdef CONFIG_LWIP_IPV6 + struct sockaddr_in6 saddr = { INADDR_ANY }; + saddr.sin6_family = AF_INET6; + saddr.sin6_port = htons(5353); + bzero(&saddr.sin6_addr.s6_addr, sizeof(saddr.sin6_addr.s6_addr)); + int err = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in6)); + if (err < 0) { + ESP_LOGE(TAG, "Failed to bind socket. errno=%d: %s", errno, strerror(errno)); + goto err; + } +#else + struct sockaddr_in saddr = { 0 }; + saddr.sin_family = AF_INET; + saddr.sin_port = htons(5353); + bzero(&saddr.sin_addr.s_addr, sizeof(saddr.sin_addr.s_addr)); + int err = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in)); + if (err < 0) { + ESP_LOGE(TAG, "Failed to bind socket. errno=%d: %s", errno, strerror(errno)); + goto err; + } +#endif // CONFIG_LWIP_IPV6 + struct ifreq ifr; + esp_netif_get_netif_impl_name(netif, ifr.ifr_name); + int ret = setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(struct ifreq)); + if (ret < 0) { + ESP_LOGE(TAG, "\"%s\" Unable to bind socket to specified interface. errno=%d: %s", esp_netif_get_desc(netif), errno, strerror(errno)); + goto err; + } + + return sock; + +err: + delete_socket(sock); + return -1; +} + +#ifdef CONFIG_LWIP_IPV6 +static int socket_add_ipv6_multicast_group(int sock, esp_netif_t *netif) +{ + int ifindex = esp_netif_get_netif_impl_index(netif); + int err = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifindex, sizeof(ifindex)); + if (err < 0) { + ESP_LOGE(TAG, "Failed to set IPV6_MULTICAST_IF. errno=%d: %s", errno, strerror(errno)); + return err; + } + + struct ipv6_mreq v6imreq = { 0 }; + esp_ip_addr_t multi_addr = ESP_IP6ADDR_INIT(0x000002ff, 0, 0, 0xfb000000); + memcpy(&v6imreq.ipv6mr_multiaddr, &multi_addr.u_addr.ip6.addr, sizeof(v6imreq.ipv6mr_multiaddr)); + v6imreq.ipv6mr_interface = ifindex; + err = setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &v6imreq, sizeof(struct ipv6_mreq)); + if (err < 0) { + ESP_LOGE(TAG, "Failed to set IPV6_ADD_MEMBERSHIP. errno=%d: %s", errno, strerror(errno)); + return err; + } + return err; +} +#endif // CONFIG_LWIP_IPV6 + +#ifdef CONFIG_LWIP_IPV4 +static int socket_add_ipv4_multicast_group(int sock, esp_netif_t *netif) +{ + struct ip_mreq imreq = { 0 }; + int err = 0; + esp_netif_ip_info_t ip_info = { 0 }; + + if (esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) { + ESP_LOGE(TAG, "Failed to esp_netif_get_ip_info()"); + goto err; + } + imreq.imr_interface.s_addr = ip_info.ip.addr; + + esp_ip_addr_t multicast_addr = ESP_IP4ADDR_INIT(224, 0, 0, 251); + imreq.imr_multiaddr.s_addr = multicast_addr.u_addr.ip4.addr; + + err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imreq, sizeof(struct ip_mreq)); + if (err < 0) { + ESP_LOGE(TAG, "[sock=%d] Failed to set IP_ADD_MEMBERSHIP. errno=%d: %s", sock, errno, strerror(errno)); + goto err; + } + +err: + return err; +} +#endif // CONFIG_LWIP_IPV4 + +static int join_mdns_multicast_group(int sock, esp_netif_t *netif, mdns_ip_protocol_t ip_protocol) +{ +#ifdef CONFIG_LWIP_IPV4 + if (ip_protocol == MDNS_IP_PROTOCOL_V4) { + return socket_add_ipv4_multicast_group(sock, netif); + } +#endif // CONFIG_LWIP_IPV4 +#ifdef CONFIG_LWIP_IPV6 + if (ip_protocol == MDNS_IP_PROTOCOL_V6) { + return socket_add_ipv6_multicast_group(sock, netif); + } +#endif // CONFIG_LWIP_IPV6 + return -1; +} diff --git a/managed_components/espressif__mdns/mdns_pcb.c b/managed_components/espressif__mdns/mdns_pcb.c new file mode 100644 index 0000000..f631277 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_pcb.c @@ -0,0 +1,462 @@ +/* + * SPDX-FileCopyrightText: 2015-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "mdns_private.h" +#include "mdns_networking.h" +#include "mdns_pcb.h" +#include "mdns_netif.h" +#include "mdns_utils.h" +#include "mdns_send.h" +#include "mdns_mem_caps.h" +#include "esp_log.h" +#include "esp_random.h" +#include "mdns_responder.h" + +#define PCB_STATE_IS_PROBING(s) (s->state > PCB_OFF && s->state < PCB_ANNOUNCE_1) +#define PCB_STATE_IS_ANNOUNCING(s) (s->state > PCB_PROBE_3 && s->state < PCB_RUNNING) + +typedef enum { + PCB_OFF, PCB_DUP, PCB_INIT, + PCB_PROBE_1, PCB_PROBE_2, PCB_PROBE_3, + PCB_ANNOUNCE_1, PCB_ANNOUNCE_2, PCB_ANNOUNCE_3, + PCB_RUNNING +} mdns_pcb_state_t; + +typedef struct { + mdns_pcb_state_t state; + mdns_srv_item_t **probe_services; + uint8_t probe_services_len; + uint8_t probe_ip; + uint8_t probe_running; + uint16_t failed_probes; +} mdns_pcb_t; + +static const char *TAG = "mdns_pcb"; +static mdns_pcb_t s_pcbs[MDNS_MAX_INTERFACES][MDNS_IP_PROTOCOL_MAX]; + +/** + * @brief Send announcement on particular PCB + */ +void mdns_priv_pcb_announce(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool include_ip) +{ + mdns_pcb_t *_pcb = &s_pcbs[tcpip_if][ip_protocol]; + size_t i; + if (mdns_priv_if_ready(tcpip_if, ip_protocol)) { + if (PCB_STATE_IS_PROBING(_pcb)) { + mdns_priv_init_pcb_probe(tcpip_if, ip_protocol, services, len, include_ip); + } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) { + mdns_tx_packet_t *p = mdns_priv_get_next_packet(tcpip_if, ip_protocol); + if (p) { + for (i = 0; i < len; i++) { + if (!mdns_priv_create_answer(&p->answers, MDNS_TYPE_SDPTR, services[i]->service, NULL, false, false) + || !mdns_priv_create_answer(&p->answers, MDNS_TYPE_PTR, services[i]->service, NULL, false, + false) + || !mdns_priv_create_answer(&p->answers, MDNS_TYPE_SRV, services[i]->service, NULL, true, + false) + || !mdns_priv_create_answer(&p->answers, MDNS_TYPE_TXT, services[i]->service, NULL, true, + false)) { + break; + } + } + if (include_ip) { + mdns_priv_dealloc_answer(&p->additional, MDNS_TYPE_A, NULL); + mdns_priv_dealloc_answer(&p->additional, MDNS_TYPE_AAAA, NULL); + mdns_priv_append_host_list_in_services(&p->answers, services, len, true, false); + } + _pcb->state = PCB_ANNOUNCE_1; + } + } else if (_pcb->state == PCB_RUNNING) { + + if (mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + return; + } + + _pcb->state = PCB_ANNOUNCE_1; + mdns_tx_packet_t *p = mdns_priv_create_announce_packet(tcpip_if, ip_protocol, services, len, include_ip); + if (p) { + mdns_priv_send_after(p, 0); + } + } + } +} + +/** + * @brief Check if interface is duplicate (two interfaces on the same subnet) + */ +bool mdns_priv_pcb_check_for_duplicates(mdns_if_t tcpip_if) +{ + mdns_if_t ifaces[MDNS_MAX_INTERFACES] = {tcpip_if, mdns_priv_netif_get_other_interface(tcpip_if) }; + if (ifaces[1] == MDNS_MAX_INTERFACES) { + return false; + } + // check both this netif and the potential duplicate on all protocols + // if any of them is in duplicate state, return true + for (int i = 0; i < 2; i++) { + for (int proto = 0; proto < MDNS_IP_PROTOCOL_MAX; proto++) { + if (s_pcbs[ifaces[i]][(mdns_ip_protocol_t) proto].state == PCB_DUP) { + return true; + } + } + } + return false; +} + +static esp_err_t deinit_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_proto) +{ + esp_err_t err = mdns_priv_if_deinit(tcpip_if, ip_proto); + mdns_pcb_t *pcb = &s_pcbs[tcpip_if][ip_proto]; + if (pcb == NULL || err != ESP_OK) { + return err; + } + mdns_mem_free(pcb->probe_services); + pcb->state = PCB_OFF; + pcb->probe_ip = false; + pcb->probe_services = NULL; + pcb->probe_services_len = 0; + pcb->probe_running = false; + pcb->failed_probes = 0; + return ESP_OK; +} + +/** + * @brief Restart the responder on particular PCB + */ +static void restart_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + size_t srv_count = 0; + mdns_srv_item_t *a = mdns_priv_get_services(); + while (a) { + srv_count++; + a = a->next; + } + if (srv_count == 0) { + // proble only IP + mdns_priv_init_pcb_probe(tcpip_if, ip_protocol, NULL, 0, true); + return; + } + mdns_srv_item_t *services[srv_count]; + size_t i = 0; + a = mdns_priv_get_services(); + while (a) { + services[i++] = a; + a = a->next; + } + mdns_priv_init_pcb_probe(tcpip_if, ip_protocol, services, srv_count, true); +} + +/** + * @brief Disable mDNS interface + */ +void mdns_priv_pcb_disable(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_priv_netif_disable(tcpip_if); + + if (mdns_priv_if_ready(tcpip_if, ip_protocol)) { + mdns_priv_clear_tx_queue_if(tcpip_if, ip_protocol); + deinit_pcb(tcpip_if, ip_protocol); + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + if (other_if != MDNS_MAX_INTERFACES && s_pcbs[other_if][ip_protocol].state == PCB_DUP) { + s_pcbs[other_if][ip_protocol].state = PCB_OFF; + mdns_priv_pcb_enable(other_if, ip_protocol); + } + } + s_pcbs[tcpip_if][ip_protocol].state = PCB_OFF; +} + +/** + * @brief Enable mDNS interface + */ +void mdns_priv_pcb_enable(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + if (!mdns_priv_if_ready(tcpip_if, ip_protocol)) { + if (mdns_priv_if_init(tcpip_if, ip_protocol)) { + s_pcbs[tcpip_if][ip_protocol].failed_probes = 0; + return; + } + } + restart_pcb(tcpip_if, ip_protocol); +} + +/** + * @brief Set interface as duplicate if another is found on the same subnet + */ +void mdns_priv_pcb_set_duplicate(mdns_if_t tcpip_if) +{ + uint8_t i; + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + if (other_if == MDNS_MAX_INTERFACES) { + return; // no other interface found + } + for (i = 0; i < MDNS_IP_PROTOCOL_MAX; i++) { + if (mdns_priv_if_ready(other_if, i)) { + //stop this interface and mark as dup + if (mdns_priv_if_ready(tcpip_if, i)) { + mdns_priv_clear_tx_queue_if(tcpip_if, i); + deinit_pcb(tcpip_if, i); + } + s_pcbs[tcpip_if][i].state = PCB_DUP; + mdns_priv_pcb_announce(other_if, i, NULL, 0, true); + } + } +} + +bool mdns_priv_pcb_is_off(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return s_pcbs[tcpip_if][ip_protocol].state == PCB_OFF; +} + +void mdns_priv_pcb_schedule_tx_packet(mdns_tx_packet_t *p) +{ + mdns_pcb_t *pcb = &s_pcbs[p->tcpip_if][p->ip_protocol]; + mdns_out_question_t *q = NULL; + mdns_tx_packet_t *a = NULL; + uint32_t send_after = 1000; + switch (pcb->state) { + case PCB_PROBE_1: + q = p->questions; + while (q) { + q->unicast = false; + q = q->next; + } + //fallthrough + case PCB_PROBE_2: + mdns_priv_send_after(p, 250); + pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1); + break; + case PCB_PROBE_3: + a = mdns_priv_create_announce_from_probe(p); + if (!a) { + mdns_priv_send_after(p, 250); + break; + } + pcb->probe_running = false; + pcb->probe_ip = false; + pcb->probe_services_len = 0; + pcb->failed_probes = 0; + mdns_mem_free(pcb->probe_services); + pcb->probe_services = NULL; + mdns_priv_free_tx_packet(p); + p = a; + send_after = 250; + //fallthrough + case PCB_ANNOUNCE_1: + //fallthrough + case PCB_ANNOUNCE_2: + mdns_priv_send_after(p, send_after); + pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1); + break; + case PCB_ANNOUNCE_3: + pcb->state = PCB_RUNNING; + mdns_priv_free_tx_packet(p); + break; + default: + mdns_priv_free_tx_packet(p); + break; + } +} + +void mdns_priv_pcb_check_probing_services(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_service_t *service, bool removed_answers, bool *should_remove_questions) +{ + mdns_pcb_t *_pcb = &s_pcbs[tcpip_if][ip_protocol]; + + if (PCB_STATE_IS_PROBING(_pcb)) { + uint8_t i; + //check if we are probing this service + for (i = 0; i < _pcb->probe_services_len; i++) { + mdns_srv_item_t *s = _pcb->probe_services[i]; + if (s->service == service) { + break; + } + } + if (i < _pcb->probe_services_len) { + if (_pcb->probe_services_len > 1) { + uint8_t n; + for (n = (i + 1); n < _pcb->probe_services_len; n++) { + _pcb->probe_services[n - 1] = _pcb->probe_services[n]; + } + _pcb->probe_services_len--; + } else { + _pcb->probe_services_len = 0; + mdns_mem_free(_pcb->probe_services); + _pcb->probe_services = NULL; + if (!_pcb->probe_ip) { + _pcb->probe_running = false; + _pcb->state = PCB_RUNNING; + } + } + *should_remove_questions = true; + return; + } + } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) { + //if answers were cleared, set to running + if (removed_answers) { + _pcb->state = PCB_RUNNING; + } + } + *should_remove_questions = false; +} + +void mdns_priv_pcb_deinit(void) +{ + for (int i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (int j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + deinit_pcb(i, j); + } + } +} + +bool mdsn_priv_pcb_is_inited(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return mdns_priv_if_ready(tcpip_if, ip_protocol) && s_pcbs[tcpip_if][ip_protocol].state > PCB_INIT; +} + +bool mdns_priv_pcb_is_duplicate(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return s_pcbs[tcpip_if][ip_protocol].state == PCB_DUP; +} + +bool mdns_priv_pcb_is_probing(mdns_rx_packet_t *packet) +{ + return s_pcbs[packet->tcpip_if][packet->ip_protocol].probe_running; +} + +bool mdns_priv_pcb_is_after_probing(mdns_rx_packet_t *packet) +{ + return s_pcbs[packet->tcpip_if][packet->ip_protocol].state > PCB_PROBE_3; +} + +void mdns_priv_pcb_set_probe_failed(mdns_rx_packet_t *packet) +{ + s_pcbs[packet->tcpip_if][packet->ip_protocol].failed_probes++; +} + +/** + * @brief Send probe for additional services on particular PCB + */ +static void init_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool probe_ip) +{ + mdns_pcb_t *pcb = &s_pcbs[tcpip_if][ip_protocol]; + size_t services_final_len = len; + + if (PCB_STATE_IS_PROBING(pcb)) { + services_final_len += pcb->probe_services_len; + } + mdns_srv_item_t **s = NULL; + if (services_final_len) { + s = (mdns_srv_item_t **)mdns_mem_malloc(sizeof(mdns_srv_item_t *) * services_final_len); + if (!s) { + HOOK_MALLOC_FAILED; + return; + } + + size_t i; + for (i = 0; i < len; i++) { + s[i] = services[i]; + } + if (pcb->probe_services) { + for (i = 0; i < pcb->probe_services_len; i++) { + s[len + i] = pcb->probe_services[i]; + } + mdns_mem_free(pcb->probe_services); + } + } + + probe_ip = pcb->probe_ip || probe_ip; + + pcb->probe_ip = false; + pcb->probe_services = NULL; + pcb->probe_services_len = 0; + pcb->probe_running = false; + + mdns_tx_packet_t *packet = mdns_priv_create_probe_packet(tcpip_if, ip_protocol, s, services_final_len, true, + probe_ip); + if (!packet) { + mdns_mem_free(s); + return; + } + + pcb->probe_ip = probe_ip; + pcb->probe_services = s; + pcb->probe_services_len = services_final_len; + pcb->probe_running = true; + mdns_priv_send_after(packet, ((pcb->failed_probes > 5) ? 1000 : 120) + (esp_random() & 0x7F)); + pcb->state = PCB_PROBE_1; +} + +void mdns_priv_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool probe_ip) +{ + mdns_pcb_t *pcb = &s_pcbs[tcpip_if][ip_protocol]; + + mdns_priv_clear_tx_queue_if(tcpip_if, ip_protocol); + + if (mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + pcb->state = PCB_RUNNING; + return; + } + + if (PCB_STATE_IS_PROBING(pcb)) { + // Looking for already probing services to resolve duplications + mdns_srv_item_t *new_probe_services[len]; + int new_probe_service_len = 0; + bool found; + for (size_t j = 0; j < len; ++j) { + found = false; + for (int i = 0; i < pcb->probe_services_len; ++i) { + if (pcb->probe_services[i] == services[j]) { + found = true; + break; + } + } + if (!found) { + new_probe_services[new_probe_service_len++] = services[j]; + } + } + // init probing for newly added services + init_probe_new_service(tcpip_if, ip_protocol, + new_probe_service_len ? new_probe_services : NULL, new_probe_service_len, probe_ip); + } else { + // not probing, so init for all services + init_probe_new_service(tcpip_if, ip_protocol, services, len, probe_ip); + } +} + +/** + * @brief Send by for particular services + */ +void mdns_priv_pcb_send_bye_service(mdns_srv_item_t **services, size_t len, bool include_ip) +{ + uint8_t i, j; + if (mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + return; + } + + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + if (mdns_priv_if_ready(i, j) && s_pcbs[i][j].state == PCB_RUNNING) { + mdns_priv_send_bye((mdns_if_t) i, (mdns_ip_protocol_t) j, services, len, include_ip); + } + } + } +} + +void mdns_priv_probe_all_pcbs(mdns_srv_item_t **services, size_t len, bool probe_ip, bool clear_old_probe) +{ + uint8_t i, j; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + if (mdns_priv_if_ready(i, j)) { + mdns_pcb_t *_pcb = &s_pcbs[i][j]; + if (clear_old_probe) { + mdns_mem_free(_pcb->probe_services); + _pcb->probe_services = NULL; + _pcb->probe_services_len = 0; + _pcb->probe_running = false; + } + mdns_priv_init_pcb_probe((mdns_if_t) i, (mdns_ip_protocol_t) j, services, len, probe_ip); + } + } + } +} diff --git a/managed_components/espressif__mdns/mdns_querier.c b/managed_components/espressif__mdns/mdns_querier.c new file mode 100644 index 0000000..16e9090 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_querier.c @@ -0,0 +1,990 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "mdns_querier.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_send.h" +#include "esp_log.h" +#include "mdns_pcb.h" +#include "mdns_netif.h" +#include "mdns_responder.h" +#include "mdns_service.h" + +static const char *TAG = "mdns_querier"; +static mdns_search_once_t *s_search_once; + +static esp_err_t send_search_action(mdns_action_type_t type, mdns_search_once_t *search); +static void search_free(mdns_search_once_t *search); + +void mdns_priv_query_results_free(mdns_result_t *results) +{ + mdns_result_t *r; + mdns_ip_addr_t *a; + + while (results) { + r = results; + + mdns_mem_free((char *)(r->hostname)); + mdns_mem_free((char *)(r->instance_name)); + mdns_mem_free((char *)(r->service_type)); + mdns_mem_free((char *)(r->proto)); + mdns_mem_free((char *)(r->subtype)); + + for (size_t i = 0; i < r->txt_count; i++) { + mdns_mem_free((char *)(r->txt[i].key)); + mdns_mem_free((char *)(r->txt[i].value)); + } + mdns_mem_free(r->txt); + mdns_mem_free(r->txt_value_len); + + while (r->addr) { + a = r->addr; + r->addr = r->addr->next; + mdns_mem_free(a); + } + + results = results->next; + mdns_mem_free(r); + } +} + +/** + * @brief Check if a search is still in the search_once linked list. + * Must be called with service lock held. + */ +static bool search_is_in_list(mdns_search_once_t *search) +{ + mdns_search_once_t *s = s_search_once; + while (s) { + if (s == search) { + return true; + } + s = s->next; + } + return false; +} + +/** + * @brief Mark search as finished and remove it from search chain. + * + * Guards against stale pointers: mdns_query_async_delete() may have already + * detached and freed this search while an ACTION_SEARCH_END was still queued. + * The notifier is cleared before calling to prevent double-invocation if + * search_finish() is reached from both mdns_priv_query_done() (max results) + * and ACTION_SEARCH_END (timeout) for the same search. + */ +static void search_finish(mdns_search_once_t *search) +{ + if (!search_is_in_list(search)) { + return; /* Already freed by mdns_query_async_delete() */ + } + search->state = SEARCH_OFF; + queueDetach(mdns_search_once_t, s_search_once, search); + if (search->notifier) { + mdns_query_notify_t notifier = search->notifier; + search->notifier = NULL; + notifier(search); + } + xSemaphoreGive(search->done_semaphore); +} + +/** + * @brief Add new search to the search chain + */ +void search_add(mdns_search_once_t *search) +{ + search->next = s_search_once; + s_search_once = search; +} + +/** + * @brief Send search packet to all available interfaces + */ +static void search_send(mdns_search_once_t *search) +{ + mdns_search_once_t *queue = s_search_once; + bool found = false; + // looking for this search in active searches + while (queue) { + if (queue == search) { + found = true; + break; + } + queue = queue->next; + } + + if (!found) { + // no longer active -> skip sending this search + return; + } + + uint8_t i, j; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + mdns_priv_query_send(search, (mdns_if_t) i, (mdns_ip_protocol_t) j); + } + } +} + +void mdns_priv_query_action(mdns_action_t *action, mdns_action_subtype_t type) +{ + if (type == ACTION_RUN) { + switch (action->type) { + case ACTION_SEARCH_ADD: + search_add(action->data.search_add.search); + break; + case ACTION_SEARCH_SEND: + search_send(action->data.search_add.search); + break; + case ACTION_SEARCH_END: + search_finish(action->data.search_add.search); + break; + default: + abort(); + } + return; + } + if (type == ACTION_CLEANUP) { + /* ADD actions hold searches not yet in the list — always safe to free. + * SEND/END actions reference searches that may have been removed and + * freed by mdns_query_async_delete(). Only free if still in the list. */ + if (action->type == ACTION_SEARCH_ADD || + search_is_in_list(action->data.search_add.search)) { + search_free(action->data.search_add.search); + } + } +} + +/** + * @brief Called from timer task to run active searches + */ +void mdns_priv_query_start_stop(void) +{ + mdns_priv_service_lock(); + mdns_search_once_t *s = s_search_once; + uint32_t now = xTaskGetTickCount() * portTICK_PERIOD_MS; + if (!s) { + mdns_priv_service_unlock(); + return; + } + while (s) { + if (s->state != SEARCH_OFF) { + if (now > (s->started_at + s->timeout)) { + s->state = SEARCH_OFF; + if (send_search_action(ACTION_SEARCH_END, s) != ESP_OK) { + s->state = SEARCH_RUNNING; + } + } else if (s->state == SEARCH_INIT || (now - s->sent_at) > 1000) { + s->state = SEARCH_RUNNING; + s->sent_at = now; + if (send_search_action(ACTION_SEARCH_SEND, s) != ESP_OK) { + s->sent_at -= 1000; + } + } + } + s = s->next; + } + mdns_priv_service_unlock(); +} + +void mdns_priv_search_once_free(mdns_search_once_t *search) +{ + if (!search) { + return; + } + queueDetach(mdns_search_once_t, s_search_once, search); + mdns_mem_free(search->instance); + mdns_mem_free(search->service); + mdns_mem_free(search->proto); + vSemaphoreDelete(search->done_semaphore); + if (search->result) { + mdns_priv_query_results_free(search->result); + } + mdns_mem_free(search); +} + +void mdns_priv_query_free(void) +{ + while (s_search_once) { + mdns_search_once_t *h = s_search_once; + s_search_once = h->next; + mdns_mem_free(h->instance); + mdns_mem_free(h->service); + mdns_mem_free(h->proto); + vSemaphoreDelete(h->done_semaphore); + if (h->result) { + mdns_priv_query_results_free(h->result); + } + mdns_mem_free(h); + } +} + +/** + * @brief Called from parser to finish any searches that have reached maximum results + */ +void mdns_priv_query_done(void) +{ + mdns_search_once_t *search = s_search_once; + mdns_search_once_t *s = NULL; + while (search) { + s = search; + search = search->next; + if (s->max_results && s->num_results >= s->max_results) { + search_finish(s); + } + } +} + +/** + * @brief Called from packet parser to find matching running search + */ +mdns_search_once_t *mdns_priv_query_find_from(mdns_search_once_t *s, mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_result_t *r = NULL; + while (s) { + if (s->state == SEARCH_OFF) { + s = s->next; + continue; + } + + if (type == MDNS_TYPE_A || type == MDNS_TYPE_AAAA) { + if ((s->type == MDNS_TYPE_ANY && s->service != NULL) + || (s->type != MDNS_TYPE_ANY && s->type != type && s->type != MDNS_TYPE_PTR && s->type != MDNS_TYPE_SRV)) { + s = s->next; + continue; + } + if (s->type != MDNS_TYPE_PTR && s->type != MDNS_TYPE_SRV) { + if (!strcasecmp(name->host, s->instance)) { + return s; + } + s = s->next; + continue; + } + r = s->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !mdns_utils_str_null_or_empty(r->hostname) && !strcasecmp(name->host, r->hostname)) { + return s; + } + r = r->next; + } + s = s->next; + continue; + } + + if (type == MDNS_TYPE_SRV || type == MDNS_TYPE_TXT) { + if ((s->type == MDNS_TYPE_ANY && s->service == NULL) + || (s->type != MDNS_TYPE_ANY && s->type != type && s->type != MDNS_TYPE_PTR)) { + s = s->next; + continue; + } + if (strcasecmp(name->service, s->service) + || strcasecmp(name->proto, s->proto)) { + s = s->next; + continue; + } + if (s->type != MDNS_TYPE_PTR) { + if (s->instance && strcasecmp(name->host, s->instance) == 0) { + return s; + } + s = s->next; + continue; + } + return s; + } + + if (type == MDNS_TYPE_PTR && type == s->type) { + // Multi-label service names (e.g. "_services._dns-sd") are parsed into + // host + service fields; reconstruct the compound name for comparison. + if (name->host[0] && s->service && strchr(s->service, '.')) { + char compound[MDNS_NAME_BUF_LEN * 2]; + snprintf(compound, sizeof(compound), "%s.%s", name->host, name->service); + if (!strcasecmp(compound, s->service) && !strcasecmp(name->proto, s->proto)) { + return s; + } + } else if (s->service && s->proto && !strcasecmp(name->service, s->service) && !strcasecmp(name->proto, s->proto)) { + return s; + } + } + + s = s->next; + } + + return NULL; +} + +mdns_search_once_t *mdns_priv_query_find(mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return mdns_priv_query_find_from(s_search_once, name, type, tcpip_if, ip_protocol); +} + +/** + * @brief Create search packet for particular interface + */ +static mdns_tx_packet_t *create_search_packet(mdns_search_once_t *search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_result_t *r = NULL; + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(tcpip_if, ip_protocol); + if (!packet) { + return NULL; + } + + mdns_out_question_t *q = (mdns_out_question_t *)mdns_mem_malloc(sizeof(mdns_out_question_t)); + if (!q) { + HOOK_MALLOC_FAILED; + mdns_priv_free_tx_packet(packet); + return NULL; + } + q->next = NULL; + q->unicast = search->unicast; + q->type = search->type; + q->host = search->instance; + q->service = search->service; + q->proto = search->proto; + q->domain = MDNS_UTILS_DEFAULT_DOMAIN; + q->subtype = search->subtype; + q->own_dynamic_memory = false; + + // Multi-label service names (e.g. "_services._dns-sd") need splitting into + // separate DNS labels: host="_services", service="_dns-sd" + if (search->service) { + char *dot = strchr(search->service, '.'); + if (dot && dot > search->service) { + size_t host_len = dot - search->service; + size_t service_len = strlen(dot + 1); + if (host_len < MDNS_NAME_BUF_LEN && service_len < MDNS_NAME_BUF_LEN && service_len > 0) { + size_t proto_len = search->proto ? strlen(search->proto) : 0; + size_t domain_len = strlen(MDNS_UTILS_DEFAULT_DOMAIN); + char *host_part = mdns_mem_malloc(host_len + 1); + char *service_part = mdns_mem_malloc(service_len + 1); + char *proto_part = proto_len > 0 ? mdns_mem_malloc(proto_len + 1) : NULL; + char *domain_part = mdns_mem_malloc(domain_len + 1); + + if (!host_part || !service_part || !domain_part || (proto_len && !proto_part)) { + ESP_LOGW(TAG, "Failed to allocate memory for multi-label service query"); + mdns_mem_free(host_part); + mdns_mem_free(service_part); + mdns_mem_free(proto_part); + mdns_mem_free(domain_part); + mdns_mem_free(q); + mdns_priv_free_tx_packet(packet); + return NULL; + } + + memcpy(host_part, search->service, host_len); + host_part[host_len] = '\0'; + memcpy(service_part, dot + 1, service_len); + service_part[service_len] = '\0'; + if (proto_part) { + memcpy(proto_part, search->proto, proto_len); + proto_part[proto_len] = '\0'; + } + memcpy(domain_part, MDNS_UTILS_DEFAULT_DOMAIN, domain_len); + domain_part[domain_len] = '\0'; + + q->host = host_part; + q->service = service_part; + q->proto = proto_part; + q->domain = domain_part; + q->own_dynamic_memory = true; + } + } + } + + queueToEnd(mdns_out_question_t, packet->questions, q); + + if (search->type == MDNS_TYPE_PTR) { + r = search->result; + while (r) { + //full record on the same interface is available + if (r->esp_netif != mdns_priv_get_esp_netif(tcpip_if) || r->ip_protocol != ip_protocol || r->instance_name == NULL || r->hostname == NULL || r->addr == NULL) { + r = r->next; + continue; + } + mdns_out_answer_t *a = (mdns_out_answer_t *)mdns_mem_malloc(sizeof(mdns_out_answer_t)); + if (!a) { + HOOK_MALLOC_FAILED; + mdns_priv_free_tx_packet(packet); + return NULL; + } + a->type = MDNS_TYPE_PTR; + a->service = NULL; + a->custom_instance = r->instance_name; + a->custom_service = search->service; + a->custom_proto = search->proto; + a->bye = false; + a->flush = false; + a->next = NULL; + queueToEnd(mdns_out_answer_t, packet->answers, a); + r = r->next; + } + } + + return packet; +} + + +/** + * @brief Send search packet to particular interface + */ +void mdns_priv_query_send(mdns_search_once_t *search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_tx_packet_t *packet = NULL; + if (mdsn_priv_pcb_is_inited(tcpip_if, ip_protocol)) { + packet = create_search_packet(search, tcpip_if, ip_protocol); + if (!packet) { + return; + } + mdns_priv_dispatch_tx_packet(packet); + mdns_priv_free_tx_packet(packet); + } +} + +/** + * @brief Free search structure (except the results) + */ +static void search_free(mdns_search_once_t *search) +{ + mdns_mem_free(search->instance); + mdns_mem_free(search->service); + mdns_mem_free(search->proto); + vSemaphoreDelete(search->done_semaphore); + mdns_mem_free(search); +} + +/** + * @brief Allocate new search structure + */ +static mdns_search_once_t *search_init(const char *name, const char *service, const char *proto, uint16_t type, bool unicast, + uint32_t timeout, uint8_t max_results, mdns_query_notify_t notifier) +{ + mdns_search_once_t *search = (mdns_search_once_t *)mdns_mem_malloc(sizeof(mdns_search_once_t)); + if (!search) { + HOOK_MALLOC_FAILED; + return NULL; + } + memset(search, 0, sizeof(mdns_search_once_t)); + + search->done_semaphore = xSemaphoreCreateBinary(); + if (!search->done_semaphore) { + mdns_mem_free(search); + return NULL; + } + + if (!mdns_utils_str_null_or_empty(name)) { + search->instance = mdns_mem_strndup(name, MDNS_NAME_BUF_LEN - 1); + if (!search->instance) { + search_free(search); + return NULL; + } + } + + if (!mdns_utils_str_null_or_empty(service)) { + search->service = mdns_mem_strndup(service, MDNS_NAME_BUF_LEN - 1); + if (!search->service) { + search_free(search); + return NULL; + } + } + + if (!mdns_utils_str_null_or_empty(proto)) { + search->proto = mdns_mem_strndup(proto, MDNS_NAME_BUF_LEN - 1); + if (!search->proto) { + search_free(search); + return NULL; + } + } + + search->type = type; + search->unicast = unicast; + search->timeout = timeout; + search->num_results = 0; + search->max_results = max_results; + search->result = NULL; + search->state = SEARCH_INIT; + search->sent_at = 0; + search->started_at = xTaskGetTickCount() * portTICK_PERIOD_MS; + search->notifier = notifier; + search->next = NULL; + + return search; +} + +/** + * @brief Queue search action + */ +static esp_err_t send_search_action(mdns_action_type_t type, mdns_search_once_t *search) +{ + mdns_action_t *action = NULL; + + action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + + action->type = type; + action->data.search_add.search = search; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +/** + * @brief Called from parser to add TXT data to search result + */ +void mdns_priv_query_result_add_txt(mdns_search_once_t *search, mdns_txt_item_t *txt, uint8_t *txt_value_len, + size_t txt_count, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, + uint32_t ttl) +{ + mdns_result_t *r = search->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol) { + if (r->txt) { + goto free_txt; + } + r->txt = txt; + r->txt_value_len = txt_value_len; + r->txt_count = txt_count; + mdns_priv_query_update_result_ttl(r, ttl); + return; + } + r = r->next; + } + if (!search->max_results || search->num_results < search->max_results) { + r = (mdns_result_t *)mdns_mem_malloc(sizeof(mdns_result_t)); + if (!r) { + HOOK_MALLOC_FAILED; + goto free_txt; + } + + memset(r, 0, sizeof(mdns_result_t)); + r->txt = txt; + r->txt_value_len = txt_value_len; + r->txt_count = txt_count; + r->esp_netif = mdns_priv_get_esp_netif(tcpip_if); + r->ip_protocol = ip_protocol; + r->ttl = ttl; + r->next = search->result; + search->result = r; + search->num_results++; + return; + } + +free_txt: + for (size_t i = 0; i < txt_count; i++) { + mdns_mem_free((char *)(txt[i].key)); + mdns_mem_free((char *)(txt[i].value)); + } + mdns_mem_free(txt); + mdns_mem_free(txt_value_len); +} + +/** + * @brief Chain new IP to search result + */ +static void result_add_ip(mdns_result_t *r, esp_ip_addr_t *ip) +{ + mdns_ip_addr_t *a = r->addr; + while (a) { + if (a->addr.type == ip->type) { +#ifdef CONFIG_LWIP_IPV4 + if (a->addr.type == ESP_IPADDR_TYPE_V4 && a->addr.u_addr.ip4.addr == ip->u_addr.ip4.addr) { + return; + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (a->addr.type == ESP_IPADDR_TYPE_V6 && !memcmp(a->addr.u_addr.ip6.addr, ip->u_addr.ip6.addr, 16)) { + return; + } +#endif + } + a = a->next; + } + a = mdns_priv_result_addr_create_ip(ip); + if (!a) { + return; + } + a->next = r->addr; + r->addr = a; +} + +/** + * @brief Called from parser to add A/AAAA data to search result + */ +void mdns_priv_query_result_add_ip(mdns_search_once_t *search, const char *hostname, esp_ip_addr_t *ip, + mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint32_t ttl) +{ + mdns_result_t *r = NULL; + mdns_ip_addr_t *a = NULL; + + if ((search->type == MDNS_TYPE_A && ip->type == ESP_IPADDR_TYPE_V4) + || (search->type == MDNS_TYPE_AAAA && ip->type == ESP_IPADDR_TYPE_V6) + || search->type == MDNS_TYPE_ANY) { + r = search->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol) { + result_add_ip(r, ip); + mdns_priv_query_update_result_ttl(r, ttl); + return; + } + r = r->next; + } + if (!search->max_results || search->num_results < search->max_results) { + r = (mdns_result_t *)mdns_mem_malloc(sizeof(mdns_result_t)); + if (!r) { + HOOK_MALLOC_FAILED; + return; + } + + memset(r, 0, sizeof(mdns_result_t)); + + a = mdns_priv_result_addr_create_ip(ip); + if (!a) { + mdns_mem_free(r); + return; + } + a->next = r->addr; + r->hostname = mdns_mem_strdup(hostname); + r->addr = a; + r->esp_netif = mdns_priv_get_esp_netif(tcpip_if); + r->ip_protocol = ip_protocol; + r->next = search->result; + r->ttl = ttl; + search->result = r; + search->num_results++; + } + } else if (search->type == MDNS_TYPE_PTR || search->type == MDNS_TYPE_SRV) { + r = search->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !mdns_utils_str_null_or_empty(r->hostname) && !strcasecmp(hostname, r->hostname)) { + result_add_ip(r, ip); + mdns_priv_query_update_result_ttl(r, ttl); + break; + } + r = r->next; + } + } +} + +/** + * @brief Called from parser to add SRV data to search result + */ +void mdns_priv_query_result_add_srv(mdns_search_once_t *search, const char *hostname, uint16_t port, + mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint32_t ttl) +{ + mdns_result_t *r = search->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !mdns_utils_str_null_or_empty(r->hostname) && !strcasecmp(hostname, r->hostname)) { + mdns_priv_query_update_result_ttl(r, ttl); + return; + } + r = r->next; + } + if (!search->max_results || search->num_results < search->max_results) { + r = (mdns_result_t *)mdns_mem_malloc(sizeof(mdns_result_t)); + if (!r) { + HOOK_MALLOC_FAILED; + return; + } + + memset(r, 0, sizeof(mdns_result_t)); + r->hostname = mdns_mem_strdup(hostname); + if (!r->hostname) { + mdns_mem_free(r); + return; + } + if (search->instance) { + r->instance_name = mdns_mem_strdup(search->instance); + } + r->service_type = mdns_mem_strdup(search->service); + r->proto = mdns_mem_strdup(search->proto); + r->port = port; + r->esp_netif = mdns_priv_get_esp_netif(tcpip_if); + r->ip_protocol = ip_protocol; + r->ttl = ttl; + r->next = search->result; + search->result = r; + search->num_results++; + } +} + +/** + * @brief Called from parser to add PTR data to search result + */ +mdns_result_t *mdns_priv_query_result_add_ptr(mdns_search_once_t *search, const char *instance, + const char *service_type, const char *proto, mdns_if_t tcpip_if, + mdns_ip_protocol_t ip_protocol, uint32_t ttl) +{ + mdns_result_t *r = search->result; + while (r) { + if (r->esp_netif == mdns_priv_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !mdns_utils_str_null_or_empty(r->instance_name) && !strcasecmp(instance, r->instance_name)) { + mdns_priv_query_update_result_ttl(r, ttl); + return r; + } + r = r->next; + } + if (!search->max_results || search->num_results < search->max_results) { + r = (mdns_result_t *)mdns_mem_malloc(sizeof(mdns_result_t)); + if (!r) { + HOOK_MALLOC_FAILED; + return NULL; + } + + memset(r, 0, sizeof(mdns_result_t)); + r->instance_name = mdns_mem_strdup(instance); + r->service_type = mdns_mem_strdup(service_type); + r->proto = mdns_mem_strdup(proto); + if (!r->instance_name) { + mdns_mem_free(r); + return NULL; + } + + r->esp_netif = mdns_priv_get_esp_netif(tcpip_if); + r->ip_protocol = ip_protocol; + r->ttl = ttl; + r->next = search->result; + search->result = r; + search->num_results++; + return r; + } + return NULL; +} + +mdns_ip_addr_t *mdns_priv_result_addr_create_ip(esp_ip_addr_t *ip) +{ + mdns_ip_addr_t *a = (mdns_ip_addr_t *)mdns_mem_malloc(sizeof(mdns_ip_addr_t)); + if (!a) { + HOOK_MALLOC_FAILED; + return NULL; + } + memset(a, 0, sizeof(mdns_ip_addr_t)); + a->addr.type = ip->type; + if (ip->type == ESP_IPADDR_TYPE_V6) { + memcpy(a->addr.u_addr.ip6.addr, ip->u_addr.ip6.addr, 16); + } else { + a->addr.u_addr.ip4.addr = ip->u_addr.ip4.addr; + } + return a; +} + +/** + * @brief MDNS_PUBLIC_API + * */ +void mdns_query_results_free(mdns_result_t *results) +{ + mdns_priv_service_lock(); + mdns_priv_query_results_free(results); + mdns_priv_service_unlock(); +} + +esp_err_t mdns_query_async_delete(mdns_search_once_t *search) +{ + if (!search) { + return ESP_ERR_INVALID_ARG; + } + + mdns_priv_service_lock(); + if (search->state != SEARCH_OFF) { + mdns_priv_service_unlock(); + return ESP_ERR_INVALID_STATE; + } + /* Defensively detach from the search list before freeing. + * Normally search_finish() already called queueDetach, but in the race + * window (timer set SEARCH_OFF, ACTION_SEARCH_END not yet processed) + * the search may still be in the list. Without this, search_finish() + * or the CLEANUP handler would access freed memory. */ + queueDetach(mdns_search_once_t, s_search_once, search); + search->notifier = NULL; + search_free(search); + mdns_priv_service_unlock(); + + return ESP_OK; +} + +bool mdns_query_async_get_results(mdns_search_once_t *search, uint32_t timeout, mdns_result_t **results, uint8_t *num_results) +{ + if (xSemaphoreTake(search->done_semaphore, pdMS_TO_TICKS(timeout)) == pdTRUE) { + if (results) { + *results = search->result; + } + if (num_results) { + *num_results = search->num_results; + } + return true; + } + return false; +} + +mdns_search_once_t *mdns_query_async_new(const char *name, const char *service, const char *proto, uint16_t type, + uint32_t timeout, size_t max_results, mdns_query_notify_t notifier) +{ + mdns_search_once_t *search = NULL; + + if (!mdns_priv_is_server_init() || !timeout || mdns_utils_str_null_or_empty(service) != mdns_utils_str_null_or_empty(proto)) { + return NULL; + } + + search = search_init(name, service, proto, type, type != MDNS_TYPE_PTR, timeout, max_results, notifier); + if (!search) { + return NULL; + } + + if (send_search_action(ACTION_SEARCH_ADD, search)) { + search_free(search); + return NULL; + } + + return search; +} + +esp_err_t mdns_query_generic(const char *name, const char *service, const char *proto, uint16_t type, mdns_query_transmission_type_t transmission_type, uint32_t timeout, size_t max_results, mdns_result_t **results) +{ + mdns_search_once_t *search = NULL; + + *results = NULL; + + if (!mdns_priv_is_server_init()) { + return ESP_ERR_INVALID_STATE; + } + + if (!timeout || mdns_utils_str_null_or_empty(service) != mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + + search = search_init(name, service, proto, type, transmission_type == MDNS_QUERY_UNICAST, timeout, max_results, + NULL); + if (!search) { + return ESP_ERR_NO_MEM; + } + + if (send_search_action(ACTION_SEARCH_ADD, search)) { + search_free(search); + return ESP_ERR_NO_MEM; + } + xSemaphoreTake(search->done_semaphore, portMAX_DELAY); + + *results = search->result; + search_free(search); + + return ESP_OK; +} + +esp_err_t mdns_query(const char *name, const char *service_type, const char *proto, uint16_t type, uint32_t timeout, size_t max_results, mdns_result_t **results) +{ + // PTR queries should be multicast, all other types should be unicast + mdns_query_transmission_type_t transmission_type = (type == MDNS_TYPE_PTR) ? MDNS_QUERY_MULTICAST : MDNS_QUERY_UNICAST; + return mdns_query_generic(name, service_type, proto, type, transmission_type, timeout, max_results, results); +} + +esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout, size_t max_results, mdns_result_t **results) +{ + if (mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + + return mdns_query(NULL, service, proto, MDNS_TYPE_PTR, timeout, max_results, results); +} + +esp_err_t mdns_query_srv(const char *instance, const char *service, const char *proto, uint32_t timeout, mdns_result_t **result) +{ + if (mdns_utils_str_null_or_empty(instance) || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + + return mdns_query(instance, service, proto, MDNS_TYPE_SRV, timeout, 1, result); +} + +esp_err_t mdns_query_txt(const char *instance, const char *service, const char *proto, uint32_t timeout, mdns_result_t **result) +{ + if (mdns_utils_str_null_or_empty(instance) || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + + return mdns_query(instance, service, proto, MDNS_TYPE_TXT, timeout, 1, result); +} + +#ifdef CONFIG_LWIP_IPV4 +esp_err_t mdns_query_a(const char *name, uint32_t timeout, esp_ip4_addr_t *addr) +{ + mdns_result_t *result = NULL; + esp_err_t err; + + if (mdns_utils_str_null_or_empty(name)) { + return ESP_ERR_INVALID_ARG; + } + + if (strstr(name, ".local")) { + ESP_LOGW(TAG, "Please note that hostname must not contain domain name, as mDNS uses '.local' domain"); + } + + err = mdns_query(name, NULL, NULL, MDNS_TYPE_A, timeout, 1, &result); + + if (err) { + return err; + } + + if (!result) { + return ESP_ERR_NOT_FOUND; + } + + mdns_ip_addr_t *a = result->addr; + while (a) { + if (a->addr.type == ESP_IPADDR_TYPE_V4) { + addr->addr = a->addr.u_addr.ip4.addr; + mdns_query_results_free(result); + return ESP_OK; + } + a = a->next; + } + + mdns_query_results_free(result); + return ESP_ERR_NOT_FOUND; +} +#endif /* CONFIG_LWIP_IPV4 */ + +#ifdef CONFIG_LWIP_IPV6 +esp_err_t mdns_query_aaaa(const char *name, uint32_t timeout, esp_ip6_addr_t *addr) +{ + mdns_result_t *result = NULL; + esp_err_t err; + + if (mdns_utils_str_null_or_empty(name)) { + return ESP_ERR_INVALID_ARG; + } + + if (strstr(name, ".local")) { + ESP_LOGW(TAG, "Please note that hostname must not contain domain name, as mDNS uses '.local' domain"); + } + + err = mdns_query(name, NULL, NULL, MDNS_TYPE_AAAA, timeout, 1, &result); + + if (err) { + return err; + } + + if (!result) { + return ESP_ERR_NOT_FOUND; + } + + mdns_ip_addr_t *a = result->addr; + while (a) { + if (a->addr.type == ESP_IPADDR_TYPE_V6) { + memcpy(addr->addr, a->addr.u_addr.ip6.addr, 16); + mdns_query_results_free(result); + return ESP_OK; + } + a = a->next; + } + + mdns_query_results_free(result); + return ESP_ERR_NOT_FOUND; +} +#endif /* CONFIG_LWIP_IPV6 */ diff --git a/managed_components/espressif__mdns/mdns_receive.c b/managed_components/espressif__mdns/mdns_receive.c new file mode 100644 index 0000000..d92cb22 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_receive.c @@ -0,0 +1,1435 @@ + +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "sdkconfig.h" +#include "esp_log.h" +#include "mdns_private.h" +#include "mdns_networking.h" +#include "mdns.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_debug.h" +#include "mdns_netif.h" +#include "mdns_send.h" +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#include "mdns_browser.h" +#endif +#include "mdns_querier.h" +#include "mdns_pcb.h" +#include "mdns_responder.h" +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#include "mdns_cache.h" +#endif + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +typedef struct mdns_rx_staged_ip_s { + char hostname[MDNS_NAME_BUF_LEN]; + esp_ip_addr_t ip; + uint32_t ttl; + struct mdns_rx_staged_ip_s *next; +} mdns_rx_staged_ip_t; +#endif + +static const char *TAG = "mdns_receive"; + +/** + * @brief Check if parsed name is discovery + */ +static bool is_discovery(mdns_name_t *name, uint16_t type) +{ + return ( + (name->host[0] && !strcasecmp(name->host, "_services")) + && (name->service[0] && !strcasecmp(name->service, "_dns-sd")) + && (name->proto[0] && !strcasecmp(name->proto, "_udp")) + && (name->domain[0] && !strcasecmp(name->domain, MDNS_UTILS_DEFAULT_DOMAIN)) + && type == MDNS_TYPE_PTR + ); +} + +static mdns_srv_item_t *get_service_item_subtype(const char *subtype, const char *service, const char *proto) +{ + mdns_srv_item_t *s = mdns_priv_get_services(); + while (s) { + if (mdns_utils_service_match(s->service, service, proto, NULL)) { + mdns_subtype_t *subtype_item = s->service->subtype; + while (subtype_item) { + if (!strcasecmp(subtype_item->subtype, subtype)) { + return s; + } + subtype_item = subtype_item->next; + } + } + s = s->next; + } + return NULL; +} + +/** + * @brief Check if the parsed name is ours (matches service or host name) + */ +static bool is_ours(mdns_name_t *name) +{ + //domain have to be "local" + if (mdns_utils_str_null_or_empty(name->domain) || (strcasecmp(name->domain, MDNS_UTILS_DEFAULT_DOMAIN) +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + && strcasecmp(name->domain, "arpa") +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + )) { + return false; + } + + //if service and proto are empty, host must match out hostname + if (mdns_utils_str_null_or_empty(name->service) && mdns_utils_str_null_or_empty(name->proto)) { + if (!mdns_utils_str_null_or_empty(name->host) + && !mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname()) + && mdns_utils_hostname_is_ours(name->host)) { + return true; + } + return false; + } + + //if service or proto is empty, name is invalid + if (mdns_utils_str_null_or_empty(name->service) || mdns_utils_str_null_or_empty(name->proto)) { + return false; + } + + + //find the service + mdns_srv_item_t *service; + if (name->sub) { + service = get_service_item_subtype(name->host, name->service, name->proto); + } else if (mdns_utils_str_null_or_empty(name->host)) { + service = mdns_utils_get_service_item(name->service, name->proto, NULL); + } else { + service = mdns_utils_get_service_item_instance(name->host, name->service, name->proto, NULL); + } + if (!service) { + return false; + } + + //if query is PTR query and we have service, we have success + if (name->sub || mdns_utils_str_null_or_empty(name->host)) { + return true; + } + + //OK we have host in the name. find what is the instance of the service + const char *instance = mdns_utils_get_service_instance_name(service->service); + if (instance == NULL) { + return false; + } + + //compare the instance against the name + if (strcasecmp(name->host, instance) == 0) { + return true; + } + + return false; +} + +/** + * @brief Duplicate string or return error + */ +static esp_err_t strdup_check(char **out, char *in) +{ + if (in && in[0]) { + *out = mdns_mem_strdup(in); + if (!*out) { + return ESP_FAIL; + } + return ESP_OK; + } + *out = NULL; + return ESP_OK; +} + +/* + * @brief Appends/increments a number to name/instance in case of collision + * */ +static char *mangle_name(char *in) +{ + char *p = strrchr(in, '-'); + int suffix = 0; + if (p == NULL) { + //No - in ``in`` + suffix = 2; + } else { + char *endp = NULL; + suffix = strtol(p + 1, &endp, 10); + if (*endp != 0) { + //suffix is not numerical + suffix = 2; + p = NULL; //so we append -suffix to the entire string + } + } + char *ret; + if (p == NULL) { + //need to add -2 to string + ret = mdns_mem_malloc(strlen(in) + 3); + if (ret == NULL) { + HOOK_MALLOC_FAILED; + return NULL; + } + sprintf(ret, "%s-2", in); + } else { + size_t in_len = strlen(in); + ret = mdns_mem_malloc(in_len + 2); //one extra byte in case 9-10 or 99-100 etc + if (ret == NULL) { + HOOK_MALLOC_FAILED; + return NULL; + } + memcpy(ret, in, in_len); + int baseLen = p - in; //length of 'bla' in 'bla-123' + //overwrite suffix with new suffix + sprintf(ret + baseLen, "-%d", suffix + 1); + } + return ret; +} + +/** + * @brief Get number of items in TXT parsed data + */ +static int get_txt_items_count(const uint8_t *data, size_t len) +{ + if (len == 1) { + return 0; + } + + int num_items = 0; + size_t i = 0; + + while (i < len) { + uint8_t item_len = data[i++]; + if (!item_len) { + // Single byte '\0' is an empty string, ignored + continue; + } + if (item_len > len - i) { + return -1;//error + } + i += item_len; + num_items++; + } + return num_items; +} + +/** + * @brief Get the length of TXT item's key name + */ +static int get_txt_item_len(const uint8_t *data, size_t len) +{ + if (*data == '=') { + return -1; + } + for (size_t i = 0; i < len; i++) { + if (data[i] == '=') { + return i; + } + } + return len; +} + +static esp_err_t parse_txt_item_data(const uint8_t *data, size_t item_len, const char **key_out, char **value_out, + uint8_t *value_len_out) +{ + int key_len = get_txt_item_len(data, item_len); + if (key_len < 0) { + // Invalid item with no key + return ESP_ERR_INVALID_ARG; + } + + *key_out = mdns_mem_strndup((const char *)data, key_len); + if (!*key_out) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + + // Skips '=' only if presents + int value_index = key_len + ((key_len < item_len) ? 1 : 0); + uint8_t value_len = item_len > value_index ? item_len - value_index : 0; + *value_len_out = value_len; + + if (key_len < item_len) { + *value_out = (char *)mdns_mem_calloc(value_len + 1, sizeof(char)); + if (!*value_out) { + HOOK_MALLOC_FAILED; + mdns_mem_free((char *)*key_out); + *key_out = NULL; + return ESP_ERR_NO_MEM; + } + memcpy(*value_out, data + value_index, value_len); + } else { + *value_out = NULL; + } + + return ESP_OK; +} + +/** + * @brief Create TXT result array from parsed TXT data + */ +static void result_txt_create(const uint8_t *data, size_t len, mdns_txt_item_t **out_txt, uint8_t **out_value_len, + size_t *out_count) +{ + *out_txt = NULL; + *out_value_len = NULL; + *out_count = 0; + + int num_items = get_txt_items_count(data, len); + if (num_items < 0 || num_items > SIZE_MAX / sizeof(mdns_txt_item_t)) { + // Error: num_items is incorrect (or too large to allocate) + return; + } + + if (!num_items) { + return; + } + + mdns_txt_item_t *txt = (mdns_txt_item_t *)mdns_mem_calloc(num_items, sizeof(mdns_txt_item_t)); + if (!txt) { + HOOK_MALLOC_FAILED; + return; + } + uint8_t *txt_value_len = (uint8_t *)mdns_mem_calloc(num_items, sizeof(uint8_t)); + if (!txt_value_len) { + mdns_mem_free(txt); + HOOK_MALLOC_FAILED; + return; + } + + uint16_t data_index = 0; + size_t txt_num = 0; + + while (data_index < len && txt_num < num_items) { + uint8_t item_len = data[data_index++]; + if (item_len == 0) { + continue; + } + + if ((data_index + item_len) > len) { + goto handle_error;//error + } + + esp_err_t err = parse_txt_item_data(data + data_index, item_len, &txt[txt_num].key, (char **)&txt[txt_num].value, + &txt_value_len[txt_num]); + data_index += item_len; + + switch (err) { + case ESP_OK: + txt_num++; + break; + case ESP_ERR_INVALID_ARG: + // Invalid item with no key + continue; + default: + goto handle_error; + } + } + + if (txt_num == 0) { + mdns_mem_free(txt); + mdns_mem_free(txt_value_len); + return; + } + + *out_txt = txt; + *out_count = txt_num; + *out_value_len = txt_value_len; + return; + +handle_error : + for (int y = 0; y < txt_num; y++) { + mdns_txt_item_t *t = &txt[y]; + mdns_mem_free((char *)t->key); + mdns_mem_free((char *)t->value); + } + mdns_mem_free(txt_value_len); + mdns_mem_free(txt); +} + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +static bool result_txt_linked_list_create(const uint8_t *data, size_t len, mdns_txt_linked_item_t **out_txt) +{ + *out_txt = NULL; + mdns_txt_linked_item_t *txt_linked_list = NULL; + mdns_txt_linked_item_t **txt_ptr = &txt_linked_list; + uint16_t data_index = 0; + int txt_num = 0; + int num_items = get_txt_items_count(data, len); + if (num_items < 0 || num_items > SIZE_MAX / sizeof(mdns_txt_item_t)) { + // Error: num_items is incorrect (or too large to allocate) + return false; + } + if (num_items == 0) { + // Empty TXT, no need to allocate + return true; + } + + while (data_index < len && txt_num < num_items) { + uint8_t item_len = data[data_index++]; + if (item_len == 0) { + continue; + } + if ((data_index + item_len) > len) { + goto error; + } + + *txt_ptr = (mdns_txt_linked_item_t *)mdns_mem_calloc(1, sizeof(mdns_txt_linked_item_t)); + if (!*txt_ptr) { + HOOK_MALLOC_FAILED; + goto error; + } + + esp_err_t err = parse_txt_item_data(data + data_index, item_len, &(*txt_ptr)->key, &(*txt_ptr)->value, + &(*txt_ptr)->value_len); + + data_index += item_len; + switch (err) { + case ESP_OK: + txt_num++; + txt_ptr = &(*txt_ptr)->next; + break; + case ESP_ERR_INVALID_ARG: + // Invalid item with no key + mdns_mem_free(*txt_ptr); + *txt_ptr = NULL; + continue; + default: + goto error; + } + } + + *out_txt = txt_linked_list; + return true; + +error: + mdns_utils_free_txt_linked_list(txt_linked_list); + return false; +} +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +#ifdef CONFIG_LWIP_IPV4 +/** + * @brief Detect IPv4 address collision + */ +static int check_a_collision(esp_ip4_addr_t *ip, mdns_if_t tcpip_if) +{ + esp_netif_ip_info_t if_ip_info; + esp_netif_ip_info_t other_ip_info; + if (!ip->addr) { + return 1;//denial! they win + } + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(tcpip_if), &if_ip_info)) { + return 1;//they win + } + int ret = memcmp((uint8_t *)&if_ip_info.ip.addr, (uint8_t *)&ip->addr, sizeof(esp_ip4_addr_t)); + if (ret > 0) { + return -1;//we win + } else if (ret < 0) { + //is it the other interface? + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + if (other_if == MDNS_MAX_INTERFACES) { + return 1;//AP interface! They win + } + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(other_if), &other_ip_info)) { + return 1;//IPv4 not active! They win + } + if (ip->addr != other_ip_info.ip.addr) { + return 1;//IPv4 not ours! They win + } + mdns_priv_pcb_set_duplicate(tcpip_if); + return 2;//they win + } + return 0;//same +} +#endif /* CONFIG_LWIP_IPV4 */ + +#ifdef CONFIG_LWIP_IPV6 +/** + * @brief Detect IPv6 address collision + */ +static int check_aaaa_collision(esp_ip6_addr_t *ip, mdns_if_t tcpip_if) +{ + struct esp_ip6_addr if_ip6; + struct esp_ip6_addr other_ip6; + if (mdns_utils_ipv6_address_is_zero(*ip)) { + return 1;//denial! they win + } + if (esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(tcpip_if), &if_ip6)) { + return 1;//they win + } + int ret = memcmp((uint8_t *)&if_ip6.addr, (uint8_t *)ip->addr, MDNS_UTILS_SIZEOF_IP6_ADDR); + if (ret > 0) { + return -1;//we win + } else if (ret < 0) { + //is it the other interface? + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + if (other_if == MDNS_MAX_INTERFACES) { + return 1;//AP interface! They win + } + if (esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(other_if), &other_ip6)) { + return 1;//IPv6 not active! They win + } + if (memcmp((uint8_t *)&other_ip6.addr, (uint8_t *)ip->addr, MDNS_UTILS_SIZEOF_IP6_ADDR)) { + return 1;//IPv6 not ours! They win + } + mdns_priv_pcb_set_duplicate(tcpip_if); + return 2;//they win + } + return 0;//same +} +#endif /* CONFIG_LWIP_IPV6 */ + +/** + * @brief Detect TXT collision + */ +static int check_txt_collision(mdns_service_t *service, const uint8_t *data, size_t len) +{ + size_t data_len = 0; + if (len <= 1 && service->txt) { // len==0 means incorrect packet (and handled by the packet parser) + // but handled here again to fix clang-tidy warning on VLA "uint8_t our[0];" + return -1;//we win + } else if (len > 1 && !service->txt) { + return 1;//they win + } else if (len <= 1 && !service->txt) { + return 0;//same + } + + mdns_txt_linked_item_t *txt = service->txt; + while (txt) { + data_len += 1 /* record-len */ + strlen(txt->key) + txt->value_len + (txt->value ? 1 : 0 /* "=" */); + txt = txt->next; + } + + if (len > data_len) { + return 1;//they win + } else if (len < data_len) { + return -1;//we win + } + + uint16_t index = 0; + /* Packet-sized TXT must not be a VLA on the mDNS task stack. */ + uint8_t *ours = mdns_mem_malloc(len); + if (!ours) { + return 0; + } + + txt = service->txt; + while (txt) { + mdns_priv_append_one_txt_record_entry(ours, &index, txt); + txt = txt->next; + } + + int ret = memcmp(ours, data, len); + mdns_mem_free(ours); + if (ret > 0) { + return -1;//we win + } else if (ret < 0) { + return 1;//they win + } + return 0;//same +} + +/** + * @brief Detect SRV collision + */ +static int check_srv_collision(mdns_service_t *service, uint16_t priority, uint16_t weight, uint16_t port, const char *host, const char *domain) +{ + if (mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + return 0; + } + + size_t our_host_len = strlen(mdns_priv_get_global_hostname()); + size_t our_len = 14 + our_host_len; + + size_t their_host_len = strlen(host); + size_t their_domain_len = strlen(domain); + size_t their_len = 9 + their_host_len + their_domain_len; + + if (their_len > our_len) { + return 1;//they win + } else if (their_len < our_len) { + return -1;//we win + } + + /* + * Names are bounded by MDNS_NAME_MAX_LEN. Keep the compare buffers fixed so + * GCC does not allocate them with a runtime SP adjustment. + */ + enum { + MDNS_SRV_OUR_DATA_MAX = 14 + MDNS_NAME_MAX_LEN, + MDNS_SRV_THEIR_DATA_MAX = 9 + (2 * MDNS_NAME_MAX_LEN), + }; + if (our_host_len > MDNS_NAME_MAX_LEN || their_host_len > MDNS_NAME_MAX_LEN || + their_domain_len > MDNS_NAME_MAX_LEN || our_len > MDNS_SRV_OUR_DATA_MAX || + their_len > MDNS_SRV_THEIR_DATA_MAX) { + return 1;//they win + } + + uint16_t our_index = 0; + uint8_t our_data[MDNS_SRV_OUR_DATA_MAX]; + mdns_utils_append_u16(our_data, &our_index, service->priority); + mdns_utils_append_u16(our_data, &our_index, service->weight); + mdns_utils_append_u16(our_data, &our_index, service->port); + our_data[our_index++] = our_host_len; + memcpy(our_data + our_index, mdns_priv_get_global_hostname(), our_host_len); + our_index += our_host_len; + our_data[our_index++] = 5; + memcpy(our_data + our_index, MDNS_UTILS_DEFAULT_DOMAIN, 5); + our_index += 5; + our_data[our_index++] = 0; + + uint16_t their_index = 0; + uint8_t their_data[MDNS_SRV_THEIR_DATA_MAX]; + mdns_utils_append_u16(their_data, &their_index, priority); + mdns_utils_append_u16(their_data, &their_index, weight); + mdns_utils_append_u16(their_data, &their_index, port); + their_data[their_index++] = their_host_len; + memcpy(their_data + their_index, host, their_host_len); + their_index += their_host_len; + their_data[their_index++] = their_domain_len; + memcpy(their_data + their_index, domain, their_domain_len); + their_index += their_domain_len; + their_data[their_index++] = 0; + + int ret = memcmp(our_data, their_data, our_len); + if (ret > 0) { + return -1;//we win + } else if (ret < 0) { + return 1;//they win + } + return 0;//same +} + +/** + * @brief Check if the parsed name is self-hosted, i.e. we should resolve conflicts + */ +static bool is_name_selfhosted(mdns_name_t *name) +{ + if (mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { // self-hostname needs to be defined + return false; + } + + // hostname only -- check if selfhosted name + if (mdns_utils_str_null_or_empty(name->service) && mdns_utils_str_null_or_empty(name->proto) && + strcasecmp(name->host, mdns_priv_get_global_hostname()) == 0) { + return true; + } + + // service -- check if selfhosted service + mdns_srv_item_t *srv = mdns_utils_get_service_item(name->service, name->proto, NULL); + if (srv && strcasecmp(mdns_priv_get_global_hostname(), srv->service->hostname) == 0) { + return true; + } + return false; +} + +/** + * @brief Called from parser to check if question matches particular service + */ +static bool question_matches(mdns_parsed_question_t *question, uint16_t type, mdns_srv_item_t *service) +{ + if (question->type != type) { + return false; + } + if (type == MDNS_TYPE_A || type == MDNS_TYPE_AAAA) { + return true; + } else if (type == MDNS_TYPE_PTR || type == MDNS_TYPE_SDPTR) { + if (question->service && question->proto && question->domain + && !strcasecmp(service->service->service, question->service) + && !strcasecmp(service->service->proto, question->proto) + && !strcasecmp(MDNS_UTILS_DEFAULT_DOMAIN, question->domain)) { + if (!service->service->instance) { + return true; + } else if (service->service->instance && question->host && !strcasecmp(service->service->instance, question->host)) { + return true; + } + } + } else if (service && (type == MDNS_TYPE_SRV || type == MDNS_TYPE_TXT)) { + const char *name = mdns_utils_get_service_instance_name(service->service); + if (name && question->host && question->service && question->proto && question->domain + && !strcasecmp(name, question->host) + && !strcasecmp(service->service->service, question->service) + && !strcasecmp(service->service->proto, question->proto) + && !strcasecmp(MDNS_UTILS_DEFAULT_DOMAIN, question->domain)) { + return true; + } + } + + return false; +} + +/** + * @brief Removes saved question from parsed data + */ +static void remove_parsed_question(mdns_parsed_packet_t *parsed_packet, uint16_t type, mdns_srv_item_t *service) +{ + mdns_parsed_question_t *q = parsed_packet->questions; + + if (!q) { + return; + } + + if (question_matches(q, type, service)) { + parsed_packet->questions = q->next; + mdns_mem_free(q->host); + mdns_mem_free(q->service); + mdns_mem_free(q->proto); + mdns_mem_free(q->domain); + mdns_mem_free(q); + return; + } + + while (q->next) { + mdns_parsed_question_t *p = q->next; + if (question_matches(p, type, service)) { + q->next = p->next; + mdns_mem_free(p->host); + mdns_mem_free(p->service); + mdns_mem_free(p->proto); + mdns_mem_free(p->domain); + mdns_mem_free(p); + return; + } + q = q->next; + } +} + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +static void rx_staged_ip_free(mdns_rx_staged_ip_t *staged_ip) +{ + while (staged_ip) { + mdns_rx_staged_ip_t *next = staged_ip->next; + mdns_mem_free(staged_ip); + staged_ip = next; + } +} + +static void rx_staged_ip_add(mdns_rx_staged_ip_t **staged_ip, const char *hostname, const esp_ip_addr_t *ip, uint32_t ttl) +{ + if (!staged_ip || mdns_utils_str_null_or_empty(hostname) || !ip) { + return; + } + + mdns_rx_staged_ip_t *new_staged_ip = (mdns_rx_staged_ip_t *)mdns_mem_calloc(1, sizeof(mdns_rx_staged_ip_t)); + if (!new_staged_ip) { + HOOK_MALLOC_FAILED; + return; + } + + strncpy(new_staged_ip->hostname, hostname, MDNS_NAME_BUF_LEN - 1); + new_staged_ip->hostname[MDNS_NAME_BUF_LEN - 1] = '\0'; + new_staged_ip->ip = *ip; + new_staged_ip->ttl = ttl; + new_staged_ip->next = *staged_ip; + *staged_ip = new_staged_ip; +} + +static void rx_staged_ips_apply(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const mdns_rx_staged_ip_t *staged_ips) +{ + if (!esp_netif || !staged_ips) { + return; + } + + for (const mdns_rx_staged_ip_t *it = staged_ips; it; it = it->next) { + (void)mdns_priv_cache_update_existing_addr(esp_netif, ip_protocol, it->hostname, &it->ip, it->ttl); + } +} +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +/** + * @brief main packet parser + * + * @param packet the packet + */ +static void mdns_parse_packet(mdns_rx_packet_t *packet) +{ + static mdns_name_t n; + mdns_header_t header; + const uint8_t *data = mdns_priv_get_packet_data(packet); + size_t len = mdns_priv_get_packet_len(packet); + const uint8_t *content = data + MDNS_HEAD_LEN; + bool do_not_reply = false; + mdns_search_once_t *search_result = NULL; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + bool packet_has_cache_consumer = false; + mdns_browse_t *browse_result = NULL; + mdns_rx_staged_ip_t *staged_ips = NULL; +#endif + + DBG_RX_PACKET(packet, data, len); + +#ifndef CONFIG_MDNS_SKIP_SUPPRESSING_OWN_QUERIES + // Check if the packet wasn't sent by us +#ifdef CONFIG_LWIP_IPV4 + if (packet->ip_protocol == MDNS_IP_PROTOCOL_V4) { + esp_netif_ip_info_t if_ip_info; + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(packet->tcpip_if), &if_ip_info) == ESP_OK && + memcmp(&if_ip_info.ip.addr, &packet->src.u_addr.ip4.addr, sizeof(esp_ip4_addr_t)) == 0) { + return; + } + } +#endif /* CONFIG_LWIP_IPV4 */ +#ifdef CONFIG_LWIP_IPV6 + if (packet->ip_protocol == MDNS_IP_PROTOCOL_V6) { + struct esp_ip6_addr if_ip6; + if (esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(packet->tcpip_if), &if_ip6) == ESP_OK && + memcmp(&if_ip6, &packet->src.u_addr.ip6, sizeof(esp_ip6_addr_t)) == 0) { + return; + } + } +#endif /* CONFIG_LWIP_IPV6 */ +#endif // CONFIG_MDNS_SKIP_SUPPRESSING_OWN_QUERIES + + // Check for the minimum size of mdns packet + if (len < MDNS_HEAD_LEN) { + return; + } + + mdns_parsed_packet_t *parsed_packet = (mdns_parsed_packet_t *)mdns_mem_malloc(sizeof(mdns_parsed_packet_t)); + if (!parsed_packet) { + HOOK_MALLOC_FAILED; + return; + } + memset(parsed_packet, 0, sizeof(mdns_parsed_packet_t)); + + mdns_name_t *name = &n; + memset(name, 0, sizeof(mdns_name_t)); + + header.id = mdns_utils_read_u16(data, MDNS_HEAD_ID_OFFSET); + header.flags = mdns_utils_read_u16(data, MDNS_HEAD_FLAGS_OFFSET); + header.questions = mdns_utils_read_u16(data, MDNS_HEAD_QUESTIONS_OFFSET); + header.answers = mdns_utils_read_u16(data, MDNS_HEAD_ANSWERS_OFFSET); + header.servers = mdns_utils_read_u16(data, MDNS_HEAD_SERVERS_OFFSET); + header.additional = mdns_utils_read_u16(data, MDNS_HEAD_ADDITIONAL_OFFSET); + + if (header.flags == MDNS_FLAGS_QR_AUTHORITATIVE && packet->src_port != MDNS_SERVICE_PORT) { + mdns_mem_free(parsed_packet); + return; + } + + //if we have not set the hostname, we can not answer questions + if (header.questions && !header.answers && mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + mdns_mem_free(parsed_packet); + return; + } + + parsed_packet->tcpip_if = packet->tcpip_if; + parsed_packet->ip_protocol = packet->ip_protocol; + parsed_packet->multicast = packet->multicast; + parsed_packet->authoritative = (header.flags == MDNS_FLAGS_QR_AUTHORITATIVE); + parsed_packet->distributed = header.flags == MDNS_FLAGS_DISTRIBUTED; + parsed_packet->id = header.id; + esp_netif_ip_addr_copy(&parsed_packet->src, &packet->src); + parsed_packet->src_port = packet->src_port; + parsed_packet->records = NULL; + + if (header.questions) { + uint8_t qs = header.questions; + + while (qs--) { + content = mdns_utils_parse_fqdn(data, content, name, len); + if (!content) { + header.answers = 0; + header.additional = 0; + header.servers = 0; + goto clear_rx_packet; // error + } + + if (content + MDNS_CLASS_OFFSET + 1 >= data + len) { + goto clear_rx_packet; // malformed packet, won't read behind it + } + uint16_t type = mdns_utils_read_u16(content, MDNS_TYPE_OFFSET); + uint16_t mdns_class = mdns_utils_read_u16(content, MDNS_CLASS_OFFSET); + bool unicast = !!(mdns_class & 0x8000); + mdns_class &= 0x7FFF; + content = content + 4; + + if (mdns_class != 0x0001 || name->invalid) { // bad class or invalid name for this question entry + continue; + } + + if (is_discovery(name, type)) { + // Already expanded this packet's DNS-SD enumeration questions. + if (parsed_packet->discovery) { + continue; + } + parsed_packet->discovery = true; + mdns_srv_item_t *a = mdns_priv_get_services(); + while (a) { + mdns_parsed_question_t *question = (mdns_parsed_question_t *)mdns_mem_calloc(1, sizeof(mdns_parsed_question_t)); + if (!question) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + question->next = parsed_packet->questions; + parsed_packet->questions = question; + + question->unicast = unicast; + question->type = MDNS_TYPE_SDPTR; + question->host = NULL; + question->service = mdns_mem_strdup(a->service->service); + question->proto = mdns_mem_strdup(a->service->proto); + question->domain = mdns_mem_strdup(MDNS_UTILS_DEFAULT_DOMAIN); + if (!question->service || !question->proto || !question->domain) { + goto clear_rx_packet; + } + a = a->next; + } + continue; + } + if (!is_ours(name)) { + continue; + } + + if (type == MDNS_TYPE_ANY && !name->sub && !mdns_utils_str_null_or_empty(name->host)) { + parsed_packet->probe = true; + } + + mdns_parsed_question_t *question = (mdns_parsed_question_t *)mdns_mem_calloc(1, sizeof(mdns_parsed_question_t)); + if (!question) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + question->next = parsed_packet->questions; + parsed_packet->questions = question; + + question->unicast = unicast; + question->type = type; + question->sub = name->sub; + if (strdup_check(&(question->host), name->host) + || strdup_check(&(question->service), name->service) + || strdup_check(&(question->proto), name->proto) + || strdup_check(&(question->domain), name->domain)) { + goto clear_rx_packet; + } + } + } + + if (header.questions && !parsed_packet->questions && !parsed_packet->discovery && !header.answers) { + goto clear_rx_packet; + } else if (header.answers || header.servers || header.additional) { + uint16_t recordIndex = 0; + + while (content < (data + len)) { + search_result = NULL; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + browse_result = NULL; +#endif + + content = mdns_utils_parse_fqdn(data, content, name, len); + if (!content) { + goto clear_rx_packet; + } + + if (content + MDNS_LEN_OFFSET + 1 >= data + len) { + goto clear_rx_packet; // malformed packet, won't read behind it + } + uint16_t type = mdns_utils_read_u16(content, MDNS_TYPE_OFFSET); + uint16_t mdns_class = mdns_utils_read_u16(content, MDNS_CLASS_OFFSET); + uint32_t ttl = mdns_utils_read_u32(content, MDNS_TTL_OFFSET); + uint16_t data_len = mdns_utils_read_u16(content, MDNS_LEN_OFFSET); + const uint8_t *data_ptr = content + MDNS_DATA_OFFSET; + mdns_class &= 0x7FFF; + + content = data_ptr + data_len; + if (content > (data + len) || data_len == 0) { + goto clear_rx_packet; + } + + bool discovery = false; + bool ours = false; + mdns_srv_item_t *service = NULL; + mdns_parsed_record_type_t record_type = MDNS_ANSWER; + + if (recordIndex >= (header.answers + header.servers)) { + record_type = MDNS_EXTRA; + } else if (recordIndex >= (header.answers)) { + record_type = MDNS_NS; + } + recordIndex++; + + if (type == MDNS_TYPE_NSEC || type == MDNS_TYPE_OPT) { + //skip NSEC and OPT + continue; + } + + if (parsed_packet->discovery && is_discovery(name, type)) { + discovery = true; + } else if (!name->sub && is_ours(name)) { + ours = true; + if (name->service[0] && name->proto[0]) { + service = mdns_utils_get_service_item(name->service, name->proto, NULL); + } + } else { + if ((header.flags & MDNS_FLAGS_QUERY_REPSONSE) == 0 || record_type == MDNS_NS) { + //skip this record + continue; + } + search_result = mdns_priv_query_find(name, type, packet->tcpip_if, packet->ip_protocol); + } + +#ifdef CONFIG_MDNS_ENABLE_BROWSE + if (type == MDNS_TYPE_PTR || (!ours && !discovery)) { + browse_result = mdns_priv_browse_find_consumer(name, type, packet->tcpip_if, packet->ip_protocol); + if (browse_result) { + packet_has_cache_consumer = true; + } + } +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + + if (type == MDNS_TYPE_PTR) { + size_t rdata_bound = (size_t)(data_ptr + data_len - data); + if (!mdns_utils_parse_fqdn(data, data_ptr, name, rdata_bound)) { + continue;//error + } +#ifdef CONFIG_MDNS_ENABLE_BROWSE + if (browse_result && !mdns_utils_str_null_or_empty(name->host) + && !mdns_utils_str_null_or_empty(browse_result->service) + && !mdns_utils_str_null_or_empty(browse_result->proto)) { + (void)mdns_priv_cache_update_ptr(mdns_priv_get_esp_netif(packet->tcpip_if), packet->ip_protocol, + name->host, browse_result->service, browse_result->proto, + browse_result->subtype, ttl); + } +#endif + if (search_result) { + mdns_priv_query_result_add_ptr(search_result, name->host, name->service, name->proto, + packet->tcpip_if, packet->ip_protocol, ttl); + } else if ((discovery || ours) && !name->sub && is_ours(name)) { + if (name->host[0]) { + service = mdns_utils_get_service_item_instance(name->host, name->service, name->proto, NULL); + } else { + service = mdns_utils_get_service_item(name->service, name->proto, NULL); + } + if (discovery && service) { + remove_parsed_question(parsed_packet, MDNS_TYPE_SDPTR, service); + } else if (service && parsed_packet->questions && !parsed_packet->probe) { + remove_parsed_question(parsed_packet, type, service); + } else if (service) { + //check if TTL is more than half of the full TTL value (4500) + if (ttl > (MDNS_ANSWER_PTR_TTL / 2)) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); + } + } + if (service) { + mdns_parsed_record_t *record = mdns_mem_malloc(sizeof(mdns_parsed_record_t)); + if (!record) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + record->next = parsed_packet->records; + parsed_packet->records = record; + record->type = MDNS_TYPE_PTR; + record->record_type = MDNS_ANSWER; + record->ttl = ttl; + record->host = NULL; + record->service = NULL; + record->proto = NULL; + if (name->host[0]) { + record->host = mdns_mem_malloc(MDNS_NAME_BUF_LEN); + if (!record->host) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + memcpy(record->host, name->host, MDNS_NAME_BUF_LEN); + } + if (name->service[0]) { + record->service = mdns_mem_malloc(MDNS_NAME_BUF_LEN); + if (!record->service) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + memcpy(record->service, name->service, MDNS_NAME_BUF_LEN); + } + if (name->proto[0]) { + record->proto = mdns_mem_malloc(MDNS_NAME_BUF_LEN); + if (!record->proto) { + HOOK_MALLOC_FAILED; + goto clear_rx_packet; + } + memcpy(record->proto, name->proto, MDNS_NAME_BUF_LEN); + } + } + } + } else if (type == MDNS_TYPE_SRV) { +#ifdef CONFIG_MDNS_ENABLE_BROWSE + char browse_instance_name[MDNS_NAME_BUF_LEN] = {0}; + memcpy(browse_instance_name, name->host, MDNS_NAME_BUF_LEN); +#endif + mdns_result_t *result = NULL; + if (search_result && search_result->type == MDNS_TYPE_PTR) { + result = search_result->result; + while (result) { + if (mdns_priv_get_esp_netif(packet->tcpip_if) == result->esp_netif + && packet->ip_protocol == result->ip_protocol + && result->instance_name && !strcmp(name->host, result->instance_name)) { + break; + } + result = result->next; + } + if (!result) { + result = mdns_priv_query_result_add_ptr(search_result, name->host, name->service, name->proto, + packet->tcpip_if, packet->ip_protocol, ttl); + if (!result) { + continue; + } + } + } + bool is_selfhosted = is_name_selfhosted(name); + size_t rdata_bound = (size_t)(data_ptr + data_len - data); + if (!mdns_utils_parse_fqdn(data, data_ptr + MDNS_SRV_FQDN_OFFSET, name, rdata_bound)) { + continue; + } + if (data_ptr + MDNS_SRV_PORT_OFFSET + 1 >= data + len) { + goto clear_rx_packet; // malformed packet, won't read behind it + } + uint16_t priority = mdns_utils_read_u16(data_ptr, MDNS_SRV_PRIORITY_OFFSET); + uint16_t weight = mdns_utils_read_u16(data_ptr, MDNS_SRV_WEIGHT_OFFSET); + uint16_t port = mdns_utils_read_u16(data_ptr, MDNS_SRV_PORT_OFFSET); + +#ifdef CONFIG_MDNS_ENABLE_BROWSE + if (browse_result && !mdns_utils_str_null_or_empty(browse_instance_name) + && !mdns_utils_str_null_or_empty(browse_result->service) + && !mdns_utils_str_null_or_empty(browse_result->proto)) { + (void)mdns_priv_cache_update_srv(mdns_priv_get_esp_netif(packet->tcpip_if), packet->ip_protocol, + name->host, browse_instance_name, browse_result->service, + browse_result->proto, priority, weight, port, ttl); + } +#endif + if (search_result) { + if (search_result->type == MDNS_TYPE_PTR) { + if (!result->hostname) { // assign host/port for this entry only if not previously set + result->port = port; + result->hostname = mdns_mem_strdup(name->host); + } + } else { + mdns_priv_query_result_add_srv(search_result, name->host, port, packet->tcpip_if, + packet->ip_protocol, ttl); + } + } else if (ours) { + if (parsed_packet->questions && !parsed_packet->probe) { + remove_parsed_question(parsed_packet, type, service); + continue; + } else if (parsed_packet->distributed) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); + continue; + } + if (!is_selfhosted) { + continue; + } + //detect collision (-1=won, 0=none, 1=lost) + int col = 0; + if (mdns_class > 1) { + col = 1; + } else if (!mdns_class) { + col = -1; + } else if (service) { // only detect srv collision if service existed + col = check_srv_collision(service->service, priority, weight, port, name->host, name->domain); + } + if (service && col && (parsed_packet->probe || parsed_packet->authoritative)) { + if (col > 0 || !port) { + do_not_reply = true; + if (mdns_priv_pcb_is_probing(packet)) { + mdns_priv_pcb_set_probe_failed(packet); + if (!mdns_utils_str_null_or_empty(service->service->instance)) { + char *new_instance = mangle_name((char *) service->service->instance); + if (new_instance) { + mdns_mem_free((char *)service->service->instance); + service->service->instance = new_instance; + } + mdns_priv_probe_all_pcbs(&service, 1, false, false); + } else if (!mdns_utils_str_null_or_empty(mdns_priv_get_instance())) { + char *new_instance = mangle_name((char *) mdns_priv_get_instance()); + if (new_instance) { + mdns_priv_set_instance(new_instance); + } + mdns_priv_restart_all_pcbs_no_instance(); + } else { + char *new_host = mangle_name((char *) mdns_priv_get_global_hostname()); + if (new_host) { + mdns_priv_remap_self_service_hostname(mdns_priv_get_global_hostname(), new_host); + mdns_priv_set_global_hostname(new_host); + } + mdns_priv_restart_all_pcbs(); + } + } else if (service) { + mdns_priv_send_bye(packet->tcpip_if, packet->ip_protocol, &service, 1, false); + mdns_priv_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, &service, 1, false); + } + } + } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); + } + } + } else if (type == MDNS_TYPE_TXT) { + mdns_txt_item_t *txt = NULL; + uint8_t *txt_value_len = NULL; + size_t txt_count = 0; + + mdns_result_t *result = NULL; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + mdns_txt_linked_item_t *txt_linked_list = NULL; + if (browse_result && !mdns_utils_str_null_or_empty(name->host) + && !mdns_utils_str_null_or_empty(browse_result->service) + && !mdns_utils_str_null_or_empty(browse_result->proto)) { + if (result_txt_linked_list_create(data_ptr, data_len, &txt_linked_list)) { + (void)mdns_priv_cache_update_txt(mdns_priv_get_esp_netif(packet->tcpip_if), packet->ip_protocol, + name->host, browse_result->service, browse_result->proto, txt_linked_list, ttl); + txt_linked_list = NULL; + } + } +#endif + if (search_result) { + if (search_result->type == MDNS_TYPE_PTR) { + result = search_result->result; + while (result) { + if (mdns_priv_get_esp_netif(packet->tcpip_if) == result->esp_netif + && packet->ip_protocol == result->ip_protocol + && result->instance_name && !strcmp(name->host, result->instance_name)) { + break; + } + result = result->next; + } + if (!result) { + result = mdns_priv_query_result_add_ptr(search_result, name->host, name->service, + name->proto, + packet->tcpip_if, packet->ip_protocol, ttl); + if (!result) { + continue; + } + } + if (!result->txt) { + result_txt_create(data_ptr, data_len, &txt, &txt_value_len, &txt_count); + if (txt_count) { + result->txt = txt; + result->txt_count = txt_count; + result->txt_value_len = txt_value_len; + } + } + } else { + result_txt_create(data_ptr, data_len, &txt, &txt_value_len, &txt_count); + if (txt_count) { + mdns_priv_query_result_add_txt(search_result, txt, txt_value_len, txt_count, + packet->tcpip_if, packet->ip_protocol, ttl); + } + } + } else if (ours) { + if (parsed_packet->questions && !parsed_packet->probe && service) { + remove_parsed_question(parsed_packet, type, service); + continue; + } + if (!is_name_selfhosted(name)) { + continue; + } + //detect collision (-1=won, 0=none, 1=lost) + int col = 0; + if (mdns_class > 1) { + col = 1; + } else if (!mdns_class) { + col = -1; + } else if (service) { // only detect txt collision if service existed + col = check_txt_collision(service->service, data_ptr, data_len); + } + if (col && !mdns_priv_pcb_is_probing(packet) && service) { + do_not_reply = true; + mdns_priv_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, &service, 1, true); + } else if (ttl > (MDNS_ANSWER_TXT_TTL / 2) && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !mdns_priv_pcb_is_probing( + packet)) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); + } + } + + } +#ifdef CONFIG_LWIP_IPV6 + else if (type == MDNS_TYPE_AAAA) { // ipv6 + if (data_len < MDNS_ANSWER_AAAA_SIZE) { + continue; // malformed AAAA record, RDATA smaller than an IPv6 address + } + esp_ip_addr_t ip6; + ip6.type = ESP_IPADDR_TYPE_V6; + memcpy(ip6.u_addr.ip6.addr, data_ptr, MDNS_ANSWER_AAAA_SIZE); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + if (packet_has_cache_consumer) { + rx_staged_ip_add(&staged_ips, name->host, &ip6, ttl); + } +#endif + if (search_result) { + //check for more applicable searches (PTR & A/AAAA at the same time) + while (search_result) { + mdns_priv_query_result_add_ip(search_result, name->host, &ip6, packet->tcpip_if, + packet->ip_protocol, ttl); + search_result = mdns_priv_query_find_from(search_result->next, name, type, packet->tcpip_if, + packet->ip_protocol); + } + } else if (ours) { + if (parsed_packet->questions && !parsed_packet->probe) { + remove_parsed_question(parsed_packet, type, NULL); + continue; + } + if (!is_name_selfhosted(name)) { + continue; + } + //detect collision (-1=won, 0=none, 1=lost) + int col = 0; + if (mdns_class > 1) { + col = 1; + } else if (!mdns_class) { + col = -1; + } else { + col = check_aaaa_collision(&(ip6.u_addr.ip6), packet->tcpip_if); + } + if (col == 2) { + goto clear_rx_packet; + } else if (col == 1) { + do_not_reply = true; + if (mdns_priv_pcb_is_probing(packet)) { + if (col && (parsed_packet->probe || parsed_packet->authoritative)) { + mdns_priv_pcb_set_probe_failed(packet); + char *new_host = mangle_name((char *) mdns_priv_get_global_hostname()); + if (new_host) { + mdns_priv_remap_self_service_hostname(mdns_priv_get_global_hostname(), new_host); + mdns_priv_set_global_hostname(new_host); + } + mdns_priv_restart_all_pcbs(); + } + } else { + mdns_priv_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, NULL, 0, true); + } + } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !mdns_priv_pcb_is_probing( + packet)) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, NULL); + } + } + + } +#endif /* CONFIG_LWIP_IPV6 */ +#ifdef CONFIG_LWIP_IPV4 + else if (type == MDNS_TYPE_A) { + if (data_len < 4) { + continue; // malformed A record, RDATA smaller than an IPv4 address + } + esp_ip_addr_t ip; + ip.type = ESP_IPADDR_TYPE_V4; + memcpy(&(ip.u_addr.ip4.addr), data_ptr, 4); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + if (packet_has_cache_consumer) { + rx_staged_ip_add(&staged_ips, name->host, &ip, ttl); + } +#endif + if (search_result) { + //check for more applicable searches (PTR & A/AAAA at the same time) + while (search_result) { + mdns_priv_query_result_add_ip(search_result, name->host, &ip, packet->tcpip_if, + packet->ip_protocol, ttl); + search_result = mdns_priv_query_find_from(search_result->next, name, type, packet->tcpip_if, + packet->ip_protocol); + } + } else if (ours) { + if (parsed_packet->questions && !parsed_packet->probe) { + remove_parsed_question(parsed_packet, type, NULL); + continue; + } + if (!is_name_selfhosted(name)) { + continue; + } + //detect collision (-1=won, 0=none, 1=lost) + int col = 0; + if (mdns_class > 1) { + col = 1; + } else if (!mdns_class) { + col = -1; + } else { + col = check_a_collision(&(ip.u_addr.ip4), packet->tcpip_if); + } + if (col == 2) { + goto clear_rx_packet; + } else if (col == 1) { + do_not_reply = true; + if (mdns_priv_pcb_is_probing(packet)) { + if (col && (parsed_packet->probe || parsed_packet->authoritative)) { + mdns_priv_pcb_set_probe_failed(packet); + char *new_host = mangle_name((char *) mdns_priv_get_global_hostname()); + if (new_host) { + mdns_priv_remap_self_service_hostname(mdns_priv_get_global_hostname(), new_host); + mdns_priv_set_global_hostname(new_host); + } + mdns_priv_restart_all_pcbs(); + } + } else { + mdns_priv_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, NULL, 0, true); + } + } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !mdns_priv_pcb_is_probing( + packet)) { + mdns_priv_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, NULL); + } + } + + } +#endif /* CONFIG_LWIP_IPV4 */ + } + //end while + if (parsed_packet->authoritative) { + mdns_priv_query_done(); + } + } + + if (!do_not_reply && mdns_priv_pcb_is_after_probing(packet) && (parsed_packet->questions || parsed_packet->discovery)) { + mdns_priv_create_answer_from_parsed_packet(parsed_packet); + } + +clear_rx_packet: +#ifdef CONFIG_MDNS_ENABLE_BROWSE + rx_staged_ips_apply(mdns_priv_get_esp_netif(packet->tcpip_if), packet->ip_protocol, staged_ips); + rx_staged_ip_free(staged_ips); +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + while (parsed_packet->questions) { + mdns_parsed_question_t *question = parsed_packet->questions; + parsed_packet->questions = parsed_packet->questions->next; + if (question->host) { + mdns_mem_free(question->host); + } + if (question->service) { + mdns_mem_free(question->service); + } + if (question->proto) { + mdns_mem_free(question->proto); + } + if (question->domain) { + mdns_mem_free(question->domain); + } + mdns_mem_free(question); + } + while (parsed_packet->records) { + mdns_parsed_record_t *record = parsed_packet->records; + parsed_packet->records = parsed_packet->records->next; + if (record->host) { + mdns_mem_free(record->host); + } + if (record->service) { + mdns_mem_free(record->service); + } + if (record->proto) { + mdns_mem_free(record->proto); + } + record->next = NULL; + mdns_mem_free(record); + } + mdns_mem_free(parsed_packet); +} + +void mdns_priv_receive_action(mdns_action_t *action, mdns_action_subtype_t type) +{ + if (action->type != ACTION_RX_HANDLE) { + abort(); + } + if (type == ACTION_RUN) { + mdns_parse_packet(action->data.rx_handle.packet); + mdns_priv_packet_free(action->data.rx_handle.packet); + } else if (type == ACTION_CLEANUP) { + mdns_priv_packet_free(action->data.rx_handle.packet); + } +} diff --git a/managed_components/espressif__mdns/mdns_responder.c b/managed_components/espressif__mdns/mdns_responder.c new file mode 100644 index 0000000..87471bb --- /dev/null +++ b/managed_components/espressif__mdns/mdns_responder.c @@ -0,0 +1,1730 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "esp_log.h" +#include "esp_check.h" +#include "mdns.h" +#include "mdns_private.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#include "mdns_send.h" +#include "mdns_querier.h" +#include "mdns_pcb.h" +#include "mdns_service.h" + +typedef struct mdns_hostname_changed_callback_s { + mdns_hostname_changed_cb_t cb; + void *arg; + struct mdns_hostname_changed_callback_s *next; +} mdns_hostname_changed_callback_t; + +typedef struct mdns_server_s { + const char *hostname; + mdns_hostname_changed_callback_t *hostname_changed_cbs; + const char *instance; + mdns_srv_item_t *services; + mdns_host_item_t *host_list; + mdns_host_item_t self_host; + SemaphoreHandle_t action_sema; +} mdns_server_t; + +static const char *TAG = "mdns_responder"; +static mdns_server_t *s_server = NULL; + +esp_err_t mdns_priv_responder_init(void) +{ + s_server = (mdns_server_t *)mdns_mem_malloc(sizeof(mdns_server_t)); + if (!s_server) { + HOOK_MALLOC_FAILED; + return ESP_ERR_NO_MEM; + } + memset((uint8_t *)s_server, 0, sizeof(mdns_server_t)); + + s_server->action_sema = xSemaphoreCreateBinary(); + if (!s_server->action_sema) { + mdns_mem_free(s_server); + return ESP_ERR_NO_MEM; + } + + return ESP_OK; +} + +static void free_delegated_hostnames(void) +{ + mdns_host_item_t *host = s_server->host_list; + while (host != NULL) { + mdns_utils_free_address_list(host->address_list); + mdns_mem_free((char *)host->hostname); + mdns_host_item_t *item = host; + host = host->next; + mdns_mem_free(item); + } + s_server->host_list = NULL; +} + +static void free_hostname_changed_callbacks(void) +{ + mdns_hostname_changed_callback_t *callback = s_server->hostname_changed_cbs; + while (callback != NULL) { + mdns_hostname_changed_callback_t *next = callback->next; + mdns_mem_free(callback); + callback = next; + } + s_server->hostname_changed_cbs = NULL; +} + +void mdns_priv_responder_free(void) +{ + if (s_server->action_sema != NULL) { + vSemaphoreDelete(s_server->action_sema); + s_server->action_sema = NULL; + } + if (s_server == NULL) { + return; + } + mdns_mem_free((char *)s_server->hostname); + mdns_mem_free((char *)s_server->instance); + free_delegated_hostnames(); + free_hostname_changed_callbacks(); + mdns_mem_free(s_server); + s_server = NULL; +} + +const char *mdns_priv_get_global_hostname(void) +{ + return s_server ? s_server->hostname : NULL; +} + +mdns_srv_item_t *mdns_priv_get_services(void) +{ + return s_server ? s_server->services : NULL; +} + +mdns_host_item_t *mdns_priv_get_hosts(void) +{ + return s_server ? s_server->host_list : NULL; +} + +mdns_host_item_t *mdns_priv_get_self_host(void) +{ + return s_server ? &s_server->self_host : NULL; +} + +void mdns_priv_set_global_hostname(const char *hostname) +{ + if (s_server) { + bool hostname_changed = s_server->hostname != hostname && + (!s_server->hostname || !hostname || strcmp(s_server->hostname, hostname) != 0); + if (s_server->hostname) { + mdns_mem_free((void *)s_server->hostname); + } + s_server->hostname = hostname; + s_server->self_host.hostname = hostname; + if (hostname_changed) { + for (mdns_hostname_changed_callback_t *callback = s_server->hostname_changed_cbs; + callback != NULL; callback = callback->next) { + callback->cb(hostname, callback->arg); + } + } + } +} + +const char *mdns_priv_get_instance(void) +{ + return s_server ? s_server->instance : NULL; +} + +void mdns_priv_set_instance(const char *instance) +{ + if (s_server) { + if (s_server->instance) { + mdns_mem_free((void *)s_server->instance); + } + s_server->instance = instance; + } +} + +bool mdns_priv_is_server_init(void) +{ + return s_server != NULL; +} + +static bool can_add_more_services(void) +{ +#if MDNS_MAX_SERVICES == 0 + return false; +#else + mdns_srv_item_t *s = s_server->services; + uint16_t service_num = 0; + while (s) { + service_num ++; + s = s->next; + if (service_num >= MDNS_MAX_SERVICES) { + return false; + } + } + return true; +#endif +} + +/** + * @brief Send announcement on all active PCBs + */ +static void announce_all_pcbs(mdns_srv_item_t **services, size_t len, bool include_ip) +{ + uint8_t i, j; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + mdns_priv_pcb_announce((mdns_if_t) i, (mdns_ip_protocol_t) j, services, len, include_ip); + } + } +} + +/** + * @brief Send bye to all services + */ +static void send_final_bye(bool include_ip) +{ + //collect all services to send bye packet + size_t srv_count = 0; + mdns_srv_item_t *a = s_server->services; + while (a) { + srv_count++; + a = a->next; + } + if (!srv_count) { + return; + } + mdns_srv_item_t *services[srv_count]; + size_t i = 0; + a = s_server->services; + while (a) { + services[i++] = a; + a = a->next; + } + mdns_priv_pcb_send_bye_service(services, srv_count, include_ip); +} + +/** + * @brief Stop the responder on all services without instance + */ +static void send_bye_all_pcbs_no_instance(bool include_ip) +{ + size_t srv_count = 0; + mdns_srv_item_t *a = s_server->services; + while (a) { + if (!a->service->instance) { + srv_count++; + } + a = a->next; + } + if (!srv_count) { + return; + } + mdns_srv_item_t *services[srv_count]; + size_t i = 0; + a = s_server->services; + while (a) { + if (!a->service->instance) { + services[i++] = a; + } + a = a->next; + } + mdns_priv_pcb_send_bye_service(services, srv_count, include_ip); +} + +void mdns_priv_restart_all_pcbs_no_instance(void) +{ + size_t srv_count = 0; + mdns_srv_item_t *a = s_server->services; + while (a) { + if (!a->service->instance) { + srv_count++; + } + a = a->next; + } + if (!srv_count) { + return; + } + mdns_srv_item_t *services[srv_count]; + size_t i = 0; + a = s_server->services; + while (a) { + if (!a->service->instance) { + services[i++] = a; + } + a = a->next; + } + mdns_priv_probe_all_pcbs(services, srv_count, false, true); +} + +void mdns_priv_restart_all_pcbs(void) +{ + mdns_priv_clear_tx_queue(); + size_t srv_count = 0; + mdns_srv_item_t *a = s_server->services; + while (a) { + srv_count++; + a = a->next; + } + if (srv_count == 0) { + mdns_priv_probe_all_pcbs(NULL, 0, true, true); + return; + } + mdns_srv_item_t *services[srv_count]; + size_t l = 0; + a = s_server->services; + while (a) { + services[l++] = a; + a = a->next; + } + + mdns_priv_probe_all_pcbs(services, srv_count, true, true); +} + +/** + * @brief Base function that creates/allocates new text item list + * @param num_items service number of txt items or 0 + * @param txt service txt items array or NULL + * @param type enum presenting provided txt item type + * + * @return pointer to the linked txt item list or NULL + */ +static mdns_txt_linked_item_t *allocate_txt_base(size_t num_items, const void* txt, mdns_txt_item_type_t type) +{ + const mdns_txt_item_t *txt_normal = NULL; + const mdns_txt_item_with_value_len_t *txt_with_len = NULL; + if (type == MDNS_TXT_ITEM) { + txt_normal = txt; + } else { + txt_with_len = txt; + } + + mdns_txt_linked_item_t *new_txt = NULL; + size_t i = 0; + if (num_items) { + for (i = 0; i < num_items; i++) { + const char *key = NULL; + const char *value = NULL; + uint8_t value_len = 0; + + if (type == MDNS_TXT_ITEM) { + key = txt_normal[i].key; + value = txt_normal[i].value; + value_len = value ? strlen(value) : 0; + } else { + key = txt_with_len[i].key; + value = (char *)txt_with_len[i].value; + value_len = value ? txt_with_len[i].value_len : 0; + } + + mdns_txt_linked_item_t *new_item = (mdns_txt_linked_item_t *)mdns_mem_malloc(sizeof(mdns_txt_linked_item_t)); + if (!new_item) { + HOOK_MALLOC_FAILED; + break; + } + new_item->key = mdns_mem_strdup(key); + if (!new_item->key) { + mdns_mem_free(new_item); + break; + } + if (value) { + new_item->value = (char *)mdns_mem_malloc(value_len + 1); + if (!new_item->value) { + mdns_mem_free((char *)new_item->key); + mdns_mem_free(new_item); + break; + } + memcpy(new_item->value, value, value_len); + new_item->value[value_len] = '\0'; + new_item->value_len = value_len; + } else { + new_item->value = NULL; + new_item->value_len = 0; + } + new_item->next = new_txt; + new_txt = new_item; + } + } + return new_txt; +} + +/** + * @brief Deallocate the txt linked list + * @param txt pointer to the txt pointer to free, noop if txt==NULL + */ +static void free_linked_txt(mdns_txt_linked_item_t *txt) +{ + mdns_txt_linked_item_t *t; + while (txt) { + t = txt; + txt = txt->next; + mdns_mem_free((char *)t->value); + mdns_mem_free((char *)t->key); + mdns_mem_free(t); + } +} + +/** + * @brief Base function that creates/allocates new service + * @param service service type + * @param proto service proto + * @param hostname service hostname + * @param port service port + * @param instance service instance + * @param num_items service number of txt items or 0 + * @param txt service txt items array or NULL + * @param txt_item_type enum presenting provided txt item type + * @return pointer to the service or NULL on error + */ +static mdns_service_t *create_service_base(const char *service, const char *proto, const char *hostname, + uint16_t port, const char *instance, size_t num_items, + const void* txt, mdns_txt_item_type_t txt_item_type) +{ + mdns_service_t *s = (mdns_service_t *)mdns_mem_calloc(1, sizeof(mdns_service_t)); + if (!s) { + HOOK_MALLOC_FAILED; + return NULL; + } + + mdns_txt_linked_item_t *new_txt = allocate_txt_base(num_items, txt, txt_item_type); + if (num_items && new_txt == NULL) { + goto fail; + } + + s->priority = 0; + s->weight = 0; + s->instance = instance ? mdns_mem_strndup(instance, MDNS_NAME_BUF_LEN - 1) : NULL; + s->txt = new_txt; + s->port = port; + s->subtype = NULL; + + if (hostname) { + s->hostname = mdns_mem_strndup(hostname, MDNS_NAME_BUF_LEN - 1); + if (!s->hostname) { + goto fail; + } + } else { + s->hostname = NULL; + } + + s->service = mdns_mem_strndup(service, MDNS_NAME_BUF_LEN - 1); + if (!s->service) { + goto fail; + } + + s->proto = mdns_mem_strndup(proto, MDNS_NAME_BUF_LEN - 1); + if (!s->proto) { + goto fail; + } + return s; + +fail: + free_linked_txt(s->txt); + mdns_mem_free((char *)s->instance); + mdns_mem_free((char *)s->service); + mdns_mem_free((char *)s->proto); + mdns_mem_free((char *)s->hostname); + mdns_mem_free(s); + + return NULL; +} + +static void free_subtype(mdns_subtype_t *subtype) +{ + while (subtype) { + mdns_subtype_t *next = subtype->next; + mdns_mem_free((char *)subtype->subtype); + mdns_mem_free(subtype); + subtype = next; + } +} + +static void free_service_subtype(mdns_service_t *service) +{ + free_subtype(service->subtype); + service->subtype = NULL; +} + +/** + * @brief free service memory + * + * @param service the service + */ +static void free_service(mdns_service_t *service) +{ + if (!service) { + return; + } + mdns_mem_free((char *)service->instance); + mdns_mem_free((char *)service->service); + mdns_mem_free((char *)service->proto); + mdns_mem_free((char *)service->hostname); + while (service->txt) { + mdns_txt_linked_item_t *s = service->txt; + service->txt = service->txt->next; + mdns_mem_free((char *)s->key); + mdns_mem_free((char *)s->value); + mdns_mem_free(s); + } + free_service_subtype(service); + mdns_mem_free(service); +} + +bool mdns_priv_delegate_hostname_add(const char *hostname, mdns_ip_addr_t *address_list) +{ + if (mdns_utils_hostname_is_ours(hostname)) { + return false; + } + + mdns_host_item_t *host = (mdns_host_item_t *)mdns_mem_malloc(sizeof(mdns_host_item_t)); + + if (host == NULL) { + return false; + } + host->address_list = address_list; + host->hostname = hostname; + host->next = s_server->host_list; + s_server->host_list = host; + return true; +} + +static bool delegate_hostname_set_address(const char *hostname, mdns_ip_addr_t *address_list) +{ + if (!mdns_utils_str_null_or_empty(s_server->hostname) && + strcasecmp(hostname, s_server->hostname) == 0) { + return false; + } + mdns_host_item_t *host = s_server->host_list; + while (host != NULL) { + if (strcasecmp(hostname, host->hostname) == 0) { + // free previous address list + mdns_utils_free_address_list(host->address_list); + // set current address list to the host + host->address_list = address_list; + return true; + } + host = host->next; + } + return false; +} + +static bool delegate_hostname_remove(const char *hostname) +{ + mdns_srv_item_t *srv = s_server->services; + mdns_srv_item_t *prev_srv = NULL; + while (srv) { + if (strcasecmp(srv->service->hostname, hostname) == 0) { + mdns_srv_item_t *to_free = srv; + mdns_priv_pcb_send_bye_service(&srv, 1, false); + mdns_priv_remove_scheduled_service_packets(srv->service); + if (prev_srv == NULL) { + s_server->services = srv->next; + srv = srv->next; + } else { + prev_srv->next = srv->next; + srv = srv->next; + } + free_service(to_free->service); + mdns_mem_free(to_free); + } else { + prev_srv = srv; + srv = srv->next; + } + } + mdns_host_item_t *host = s_server->host_list; + mdns_host_item_t *prev_host = NULL; + while (host != NULL) { + if (strcasecmp(hostname, host->hostname) == 0) { + if (prev_host == NULL) { + s_server->host_list = host->next; + } else { + prev_host->next = host->next; + } + mdns_utils_free_address_list(host->address_list); + mdns_mem_free((char *)host->hostname); + mdns_mem_free(host); + break; + } else { + prev_host = host; + host = host->next; + } + } + return true; +} + +void mdns_priv_remap_self_service_hostname(const char *old_hostname, const char *new_hostname) +{ + mdns_srv_item_t *service = s_server->services; + + while (service) { + if (service->service->hostname && + strcmp(service->service->hostname, old_hostname) == 0) { + mdns_mem_free((char *)service->service->hostname); + service->service->hostname = mdns_mem_strdup(new_hostname); + } + service = service->next; + } +} + +void mdns_priv_responder_action(mdns_action_t *action, mdns_action_subtype_t type) +{ + if (type == ACTION_RUN) { + switch (action->type) { + case ACTION_HOSTNAME_SET: + send_bye_all_pcbs_no_instance(true); + mdns_priv_remap_self_service_hostname(s_server->hostname, action->data.hostname_set.hostname); + mdns_priv_set_global_hostname(action->data.hostname_set.hostname); + mdns_priv_restart_all_pcbs(); + xSemaphoreGive(s_server->action_sema); + break; + case ACTION_INSTANCE_SET: + send_bye_all_pcbs_no_instance(false); + mdns_mem_free((char *)s_server->instance); + s_server->instance = action->data.instance; + mdns_priv_restart_all_pcbs_no_instance(); + break; + case ACTION_DELEGATE_HOSTNAME_ADD: + if (!mdns_priv_delegate_hostname_add(action->data.delegate_hostname.hostname, + action->data.delegate_hostname.address_list)) { + mdns_mem_free((char *)action->data.delegate_hostname.hostname); + mdns_utils_free_address_list(action->data.delegate_hostname.address_list); + } + xSemaphoreGive(s_server->action_sema); + break; + case ACTION_DELEGATE_HOSTNAME_SET_ADDR: + if (!delegate_hostname_set_address(action->data.delegate_hostname.hostname, + action->data.delegate_hostname.address_list)) { + mdns_utils_free_address_list(action->data.delegate_hostname.address_list); + } + mdns_mem_free((char *)action->data.delegate_hostname.hostname); + break; + case ACTION_DELEGATE_HOSTNAME_REMOVE: + delegate_hostname_remove(action->data.delegate_hostname.hostname); + mdns_mem_free((char *)action->data.delegate_hostname.hostname); + break; + default: + abort(); + } + return; + } + if (type == ACTION_CLEANUP) { + switch (action->type) { + case ACTION_HOSTNAME_SET: + mdns_mem_free(action->data.hostname_set.hostname); + break; + case ACTION_INSTANCE_SET: + mdns_mem_free(action->data.instance); + break; + case ACTION_DELEGATE_HOSTNAME_SET_ADDR: + case ACTION_DELEGATE_HOSTNAME_ADD: + mdns_mem_free((char *)action->data.delegate_hostname.hostname); + mdns_utils_free_address_list(action->data.delegate_hostname.address_list); + break; + case ACTION_DELEGATE_HOSTNAME_REMOVE: + mdns_mem_free((char *)action->data.delegate_hostname.hostname); + break; + default: + abort(); + } + return; + } +} + +/** + * @ingroup PUBLIC_API + */ +esp_err_t mdns_hostname_set(const char *hostname) +{ + if (!s_server) { + return ESP_ERR_INVALID_ARG; + } + if (mdns_utils_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { + return ESP_ERR_INVALID_ARG; + } + char *new_hostname = mdns_mem_strndup(hostname, MDNS_NAME_BUF_LEN - 1); + if (!new_hostname) { + return ESP_ERR_NO_MEM; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + mdns_mem_free(new_hostname); + return ESP_ERR_NO_MEM; + } + action->type = ACTION_HOSTNAME_SET; + action->data.hostname_set.hostname = new_hostname; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(new_hostname); + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + xSemaphoreTake(s_server->action_sema, portMAX_DELAY); + return ESP_OK; +} + +esp_err_t mdns_register_hostname_changed_callback(mdns_hostname_changed_cb_t cb, void *arg) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (!cb) { + return ESP_ERR_INVALID_ARG; + } + + mdns_priv_service_lock(); + for (mdns_hostname_changed_callback_t *callback = s_server->hostname_changed_cbs; + callback != NULL; callback = callback->next) { + if (callback->cb == cb && callback->arg == arg) { + mdns_priv_service_unlock(); + return ESP_OK; + } + } + + mdns_hostname_changed_callback_t *callback = mdns_mem_malloc(sizeof(*callback)); + if (!callback) { + HOOK_MALLOC_FAILED; + mdns_priv_service_unlock(); + return ESP_ERR_NO_MEM; + } + callback->cb = cb; + callback->arg = arg; + callback->next = s_server->hostname_changed_cbs; + s_server->hostname_changed_cbs = callback; + mdns_priv_service_unlock(); + return ESP_OK; +} + +esp_err_t mdns_hostname_get(char *hostname) +{ + if (!hostname) { + return ESP_ERR_INVALID_ARG; + } + + if (!s_server || !s_server->hostname) { + return ESP_ERR_INVALID_STATE; + } + + mdns_priv_service_lock(); + size_t len = strnlen(s_server->hostname, MDNS_NAME_BUF_LEN - 1); + strncpy(hostname, s_server->hostname, len); + hostname[len] = 0; + mdns_priv_service_unlock(); + return ESP_OK; +} + +esp_err_t mdns_delegate_hostname_add(const char *hostname, const mdns_ip_addr_t *address_list) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (mdns_utils_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { + return ESP_ERR_INVALID_ARG; + } + char *new_hostname = mdns_mem_strndup(hostname, MDNS_NAME_BUF_LEN - 1); + if (!new_hostname) { + return ESP_ERR_NO_MEM; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + mdns_mem_free(new_hostname); + return ESP_ERR_NO_MEM; + } + action->type = ACTION_DELEGATE_HOSTNAME_ADD; + action->data.delegate_hostname.hostname = new_hostname; + action->data.delegate_hostname.address_list = mdns_utils_copy_address_list(address_list); + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(new_hostname); + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + xSemaphoreTake(s_server->action_sema, portMAX_DELAY); + return ESP_OK; +} + +esp_err_t mdns_delegate_hostname_remove(const char *hostname) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (mdns_utils_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { + return ESP_ERR_INVALID_ARG; + } + char *new_hostname = mdns_mem_strndup(hostname, MDNS_NAME_BUF_LEN - 1); + if (!new_hostname) { + return ESP_ERR_NO_MEM; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + mdns_mem_free(new_hostname); + return ESP_ERR_NO_MEM; + } + action->type = ACTION_DELEGATE_HOSTNAME_REMOVE; + action->data.delegate_hostname.hostname = new_hostname; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(new_hostname); + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +esp_err_t mdns_delegate_hostname_set_address(const char *hostname, const mdns_ip_addr_t *address_list) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (mdns_utils_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { + return ESP_ERR_INVALID_ARG; + } + char *new_hostname = mdns_mem_strndup(hostname, MDNS_NAME_BUF_LEN - 1); + if (!new_hostname) { + return ESP_ERR_NO_MEM; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + mdns_mem_free(new_hostname); + return ESP_ERR_NO_MEM; + } + action->type = ACTION_DELEGATE_HOSTNAME_SET_ADDR; + action->data.delegate_hostname.hostname = new_hostname; + action->data.delegate_hostname.address_list = mdns_utils_copy_address_list(address_list); + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(new_hostname); + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +bool mdns_hostname_exists(const char *hostname) +{ + bool ret = false; + mdns_priv_service_lock(); + ret = mdns_utils_hostname_is_ours(hostname); + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_instance_name_set(const char *instance) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (mdns_utils_str_null_or_empty(instance) || s_server->hostname == NULL || strlen(instance) > (MDNS_NAME_BUF_LEN - 1)) { + return ESP_ERR_INVALID_ARG; + } + char *new_instance = mdns_mem_strndup(instance, MDNS_NAME_BUF_LEN - 1); + if (!new_instance) { + return ESP_ERR_NO_MEM; + } + + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + HOOK_MALLOC_FAILED; + mdns_mem_free(new_instance); + return ESP_ERR_NO_MEM; + } + action->type = ACTION_INSTANCE_SET; + action->data.instance = new_instance; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(new_instance); + mdns_mem_free(action); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +static esp_err_t mdns_service_add_for_host_base(const char *instance, const char *service, const char *proto, const char *host, + uint16_t port, void* txt, size_t num_items, mdns_txt_item_type_t txt_item_type) +{ + if (!s_server || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto) || !s_server->hostname) { + return ESP_ERR_INVALID_ARG; + } + + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + mdns_service_t *s = NULL; + + ESP_GOTO_ON_FALSE(can_add_more_services(), ESP_ERR_NO_MEM, err, TAG, + "Cannot add more services, please increase CONFIG_MDNS_MAX_SERVICES (%d)", CONFIG_MDNS_MAX_SERVICES); + + mdns_srv_item_t *item = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(!item, ESP_ERR_INVALID_ARG, err, TAG, "Service already exists"); + + s = create_service_base(service, proto, hostname, port, instance, num_items, txt, txt_item_type); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NO_MEM, err, TAG, "Cannot create service: Out of memory"); + + item = (mdns_srv_item_t *)mdns_mem_malloc(sizeof(mdns_srv_item_t)); + ESP_GOTO_ON_FALSE(item, ESP_ERR_NO_MEM, err, TAG, "Cannot create service: Out of memory"); + + item->service = s; + item->next = NULL; + + item->next = s_server->services; + s_server->services = item; + mdns_priv_probe_all_pcbs(&item, 1, false, false); + mdns_priv_service_unlock(); + return ESP_OK; + +err: + mdns_priv_service_unlock(); + free_service(s); + if (ret == ESP_ERR_NO_MEM) { + HOOK_MALLOC_FAILED; + } + return ret; +} + +esp_err_t mdns_service_add_for_host(const char *instance, const char *service, const char *proto, const char *host, + uint16_t port, mdns_txt_item_t txt[], size_t num_items) +{ + return mdns_service_add_for_host_base(instance, service, proto, host, port, txt, num_items, MDNS_TXT_ITEM); +} + +esp_err_t mdns_service_add(const char *instance, const char *service, const char *proto, uint16_t port, + mdns_txt_item_t txt[], size_t num_items) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_add_for_host(instance, service, proto, NULL, port, txt, num_items); +} + +esp_err_t mdns_service_add_for_host_with_explicit_txt_item_value_len(const char *instance, const char *service, const char *proto, const char *host, + uint16_t port, mdns_txt_item_with_value_len_t txt[], size_t num_items) +{ + return mdns_service_add_for_host_base(instance, service, proto, host, port, txt, num_items, MDNS_TXT_ITEM_WITH_VALUE_LEN); +} + +esp_err_t mdns_service_add_with_explicit_txt_item_value_len(const char *instance, const char *service, const char *proto, uint16_t port, + mdns_txt_item_with_value_len_t txt[], size_t num_items) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_add_for_host_with_explicit_txt_item_value_len(instance, service, proto, NULL, port, txt, num_items); +} + +bool mdns_service_exists(const char *service_type, const char *proto, const char *hostname) +{ + bool ret = false; + mdns_priv_service_lock(); + ret = mdns_utils_get_service_item(service_type, proto, hostname) != NULL; + mdns_priv_service_unlock(); + return ret; +} + +bool mdns_service_exists_with_instance(const char *instance, const char *service_type, const char *proto, + const char *hostname) +{ + bool ret = false; + mdns_priv_service_lock(); + ret = mdns_utils_get_service_item_instance(instance, service_type, proto, hostname) != NULL; + mdns_priv_service_unlock(); + return ret; +} + +static mdns_txt_item_t *copy_txt_items(mdns_txt_linked_item_t *items, uint8_t **txt_value_len, size_t *txt_count) +{ + mdns_txt_item_t *ret = NULL; + size_t ret_index = 0; + for (mdns_txt_linked_item_t *tmp = items; tmp != NULL; tmp = tmp->next) { + ret_index++; + } + *txt_count = ret_index; + if (ret_index == 0) { // handle empty TXT + *txt_value_len = NULL; + return NULL; + } + ret = (mdns_txt_item_t *)mdns_mem_calloc(ret_index, sizeof(mdns_txt_item_t)); + *txt_value_len = (uint8_t *)mdns_mem_calloc(ret_index, sizeof(uint8_t)); + if (!ret || !(*txt_value_len)) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + ret_index = 0; + for (mdns_txt_linked_item_t *tmp = items; tmp != NULL; tmp = tmp->next) { + size_t key_len = strlen(tmp->key); + char *key = (char *)mdns_mem_malloc(key_len + 1); + if (!key) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + memcpy(key, tmp->key, key_len); + key[key_len] = 0; + ret[ret_index].key = key; + char *value = NULL; + if (tmp->value) { + value = (char *)mdns_mem_malloc(tmp->value_len + 1); + if (!value) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + memcpy(value, tmp->value, tmp->value_len); + value[tmp->value_len] = 0; + } + ret[ret_index].value = value; + (*txt_value_len)[ret_index] = tmp->value_len; + ret_index++; + } + return ret; + +handle_error: + for (size_t y = 0; y < ret_index + 1 && ret != NULL; y++) { + mdns_txt_item_t *t = &ret[y]; + mdns_mem_free((char *)t->key); + mdns_mem_free((char *)t->value); + } + mdns_mem_free(*txt_value_len); + mdns_mem_free(ret); + return NULL; +} + +static mdns_ip_addr_t *copy_delegated_host_address_list(char *hostname) +{ + mdns_host_item_t *host = s_server->host_list; + while (host) { + if (strcasecmp(host->hostname, hostname) == 0) { + return mdns_utils_copy_address_list(host->address_list); + } + host = host->next; + } + return NULL; +} + +static bool service_has_subtype(const mdns_service_t *service, const char *subtype) +{ + if (!subtype) { + return true; + } + for (const mdns_subtype_t *item = service->subtype; item; item = item->next) { + if (!strcasecmp(item->subtype, subtype)) { + return true; + } + } + return false; +} + +static mdns_result_t *lookup_service(const char *instance, const char *service, const char *proto, const char *subtype, + size_t max_results, bool selfhost) +{ + if (mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return NULL; + } + mdns_result_t *results = NULL; + size_t num_results = 0; + mdns_srv_item_t *s = s_server->services; + while (s) { + mdns_service_t *srv = s->service; + if (!srv || !srv->hostname) { + s = s->next; + continue; + } + bool is_service_selfhosted = !mdns_utils_str_null_or_empty(s_server->hostname) && !strcasecmp(s_server->hostname, srv->hostname); + bool is_service_delegated = mdns_utils_str_null_or_empty(s_server->hostname) || strcasecmp(s_server->hostname, srv->hostname); + if ((selfhost && is_service_selfhosted) || (!selfhost && is_service_delegated)) { + if (!strcasecmp(srv->service, service) && !strcasecmp(srv->proto, proto) && service_has_subtype(srv, subtype) && + (mdns_utils_str_null_or_empty(instance) || mdns_utils_instance_name_match(srv->instance, instance))) { + mdns_result_t *item = (mdns_result_t *)mdns_mem_calloc(1, sizeof(mdns_result_t)); + if (!item) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + item->next = results; + results = item; + item->esp_netif = NULL; + item->ttl = mdns_utils_str_null_or_empty(instance) ? MDNS_ANSWER_PTR_TTL : MDNS_ANSWER_SRV_TTL; + item->ip_protocol = MDNS_IP_PROTOCOL_MAX; + if (srv->instance) { + item->instance_name = mdns_mem_strndup(srv->instance, MDNS_NAME_BUF_LEN - 1); + if (!item->instance_name) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + } else { + item->instance_name = NULL; + } + item->service_type = mdns_mem_strndup(srv->service, MDNS_NAME_BUF_LEN - 1); + if (!item->service_type) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + item->proto = mdns_mem_strndup(srv->proto, MDNS_NAME_BUF_LEN - 1); + if (!item->proto) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + item->hostname = mdns_mem_strndup(srv->hostname, MDNS_NAME_BUF_LEN - 1); + if (!item->hostname) { + HOOK_MALLOC_FAILED; + goto handle_error; + } + item->port = srv->port; + item->txt = copy_txt_items(srv->txt, &(item->txt_value_len), &(item->txt_count)); + // We should not append addresses for selfhost lookup result as we don't know which interface's address to append. + if (selfhost) { + item->addr = NULL; + } else { + item->addr = copy_delegated_host_address_list(item->hostname); + if (!item->addr) { + goto handle_error; + } + } + if (num_results < max_results) { + num_results++; + } + if (num_results >= max_results) { + break; + } + } + } + s = s->next; + } + return results; +handle_error: + mdns_priv_query_results_free(results); + return NULL; +} + +esp_err_t mdns_service_port_set_for_host(const char *instance, const char *service, const char *proto, const char *host, uint16_t port) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && port, + ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + s->service->port = port; + announce_all_pcbs(&s, 1, true); + +err: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_port_set(const char *service, const char *proto, uint16_t port) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_port_set_for_host(NULL, service, proto, NULL, port); +} + +static esp_err_t mdns_service_txt_set_for_host_base(const char *instance, const char *service, const char *proto, const char *host, + void* txt_items, uint8_t num_items, mdns_txt_item_type_t txt_item_type) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && !(num_items && txt_items == NULL), + ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + mdns_txt_linked_item_t *new_txt = NULL; + if (num_items) { + new_txt = allocate_txt_base(num_items, txt_items, txt_item_type); + ESP_GOTO_ON_FALSE(new_txt, ESP_ERR_NO_MEM, err, TAG, "Fails to allocate linked txt items list"); + } + mdns_service_t *srv = s->service; + mdns_txt_linked_item_t *txt = srv->txt; + srv->txt = NULL; + free_linked_txt(txt); + srv->txt = new_txt; + announce_all_pcbs(&s, 1, false); + +err: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_txt_set_for_host(const char *instance, const char *service, const char *proto, const char *host, + mdns_txt_item_t txt_items[], uint8_t num_items) +{ + return mdns_service_txt_set_for_host_base(instance, service, proto, host, txt_items, num_items, MDNS_TXT_ITEM); +} + +esp_err_t mdns_service_txt_set(const char *service, const char *proto, mdns_txt_item_t txt[], uint8_t num_items) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_txt_set_for_host(NULL, service, proto, NULL, txt, num_items); +} + +esp_err_t mdns_service_txt_set_for_host_with_explicit_txt_item_value_len(const char *instance, const char *service, const char *proto, const char *host, + mdns_txt_item_with_value_len_t txt_items[], uint8_t num_items) +{ + return mdns_service_txt_set_for_host_base(instance, service, proto, host, txt_items, num_items, MDNS_TXT_ITEM_WITH_VALUE_LEN); +} + +esp_err_t mdns_service_txt_set_with_explicit_txt_item_value_len(const char *service, const char *proto, mdns_txt_item_with_value_len_t txt[], uint8_t num_items) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_txt_set_for_host_with_explicit_txt_item_value_len(NULL, service, proto, NULL, txt, num_items); +} + +esp_err_t mdns_service_txt_item_set_for_host_with_explicit_value_len(const char *instance, const char *service, const char *proto, + const char *host, const char *key, const char *value_arg, uint8_t value_len) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + char *value = NULL; + mdns_txt_linked_item_t *new_txt = NULL; + const char *hostname = host ? host : s_server->hostname; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && !mdns_utils_str_null_or_empty(key) && + !((!value_arg && value_len)), ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + mdns_service_t *srv = s->service; + if (value_arg) { + value = (char *) mdns_mem_malloc(value_len + 1); + ESP_GOTO_ON_FALSE(value, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + memcpy(value, value_arg, value_len); + value[value_len] = '\0'; + } else { + value_len = 0; + } + mdns_txt_linked_item_t *txt = srv->txt; + while (txt) { + if (strcmp(txt->key, key) == 0) { + mdns_mem_free((char *)txt->value); + txt->value = value; + txt->value_len = value_len; + break; + } + txt = txt->next; + } + if (!txt) { + new_txt = (mdns_txt_linked_item_t *)mdns_mem_malloc(sizeof(mdns_txt_linked_item_t)); + ESP_GOTO_ON_FALSE(new_txt, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + new_txt->key = mdns_mem_strdup(key); + ESP_GOTO_ON_FALSE(new_txt->key, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + new_txt->value = value; + new_txt->value_len = value_len; + new_txt->next = srv->txt; + srv->txt = new_txt; + } + + announce_all_pcbs(&s, 1, false); + +err: + mdns_priv_service_unlock(); + return ret; +out_of_mem: + mdns_priv_service_unlock(); + HOOK_MALLOC_FAILED; + mdns_mem_free(value); + mdns_mem_free(new_txt); + return ret; +} + +esp_err_t mdns_service_txt_item_set_for_host(const char *instance, const char *service, const char *proto, const char *hostname, + const char *key, const char *value) +{ + return mdns_service_txt_item_set_for_host_with_explicit_value_len(instance, service, proto, hostname, key, value, + strlen(value)); +} + + +esp_err_t mdns_service_txt_item_set(const char *service, const char *proto, const char *key, const char *value) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_txt_item_set_for_host_with_explicit_value_len(NULL, service, proto, NULL, key, + value, strlen(value)); +} + +esp_err_t mdns_service_txt_item_set_with_explicit_value_len(const char *service, const char *proto, const char *key, + const char *value, uint8_t value_len) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_txt_item_set_for_host_with_explicit_value_len(NULL, service, proto, NULL, key, value, value_len); +} + +esp_err_t mdns_service_txt_item_remove_for_host(const char *instance, const char *service, const char *proto, const char *host, + const char *key) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && !mdns_utils_str_null_or_empty(key), + ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + mdns_service_t *srv = s->service; + mdns_txt_linked_item_t *txt = srv->txt; + if (!txt) { + goto err; + } + if (strcmp(txt->key, key) == 0) { + srv->txt = txt->next; + mdns_mem_free((char *)txt->key); + mdns_mem_free((char *)txt->value); + mdns_mem_free(txt); + } else { + while (txt->next) { + if (strcmp(txt->next->key, key) == 0) { + mdns_txt_linked_item_t *t = txt->next; + txt->next = t->next; + mdns_mem_free((char *)t->key); + mdns_mem_free((char *)t->value); + mdns_mem_free(t); + break; + } else { + txt = txt->next; + } + } + } + + announce_all_pcbs(&s, 1, false); + +err: + mdns_priv_service_unlock(); + if (ret == ESP_ERR_NO_MEM) { + HOOK_MALLOC_FAILED; + } + return ret; +} + +esp_err_t mdns_service_txt_item_remove(const char *service, const char *proto, const char *key) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_txt_item_remove_for_host(NULL, service, proto, NULL, key); +} + +static esp_err_t service_subtype_remove_for_host(mdns_srv_item_t *service, const char *subtype) +{ + esp_err_t ret = ESP_ERR_NOT_FOUND; + mdns_subtype_t *srv_subtype = service->service->subtype; + mdns_subtype_t *pre = service->service->subtype; + while (srv_subtype) { + if (strcmp(srv_subtype->subtype, subtype) == 0) { + // Target subtype is found. + if (srv_subtype == service->service->subtype) { + // The first node needs to be removed + service->service->subtype = service->service->subtype->next; + } else { + pre->next = srv_subtype->next; + } + mdns_mem_free((char *)srv_subtype->subtype); + mdns_mem_free(srv_subtype); + ret = ESP_OK; + break; + } + pre = srv_subtype; + srv_subtype = srv_subtype->next; + } + if (ret == ESP_ERR_NOT_FOUND) { + ESP_LOGE(TAG, "Subtype : %s doesn't exist", subtype); + } + + return ret; +} + +esp_err_t mdns_service_subtype_remove_for_host(const char *instance_name, const char *service, const char *proto, + const char *hostname, const char *subtype) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && + !mdns_utils_str_null_or_empty(subtype), ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance_name, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + ret = service_subtype_remove_for_host(s, subtype); + ESP_GOTO_ON_ERROR(ret, err, TAG, "Failed to remove the subtype: %s", subtype); + + // Transmit a sendbye message for the removed subtype. + mdns_subtype_t *remove_subtypes = (mdns_subtype_t *)mdns_mem_malloc(sizeof(mdns_subtype_t)); + ESP_GOTO_ON_FALSE(remove_subtypes, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + remove_subtypes->subtype = mdns_mem_strdup(subtype); + ESP_GOTO_ON_FALSE(remove_subtypes->subtype, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + remove_subtypes->next = NULL; + + mdns_priv_send_bye_subtype(s, instance_name, remove_subtypes); + free_subtype(remove_subtypes); +err: + mdns_priv_service_unlock(); + return ret; +out_of_mem: + HOOK_MALLOC_FAILED; + mdns_mem_free(remove_subtypes); + mdns_priv_service_unlock(); + return ret; +} + +static esp_err_t service_subtype_add_for_host(mdns_srv_item_t *service, const char *subtype) +{ + esp_err_t ret = ESP_OK; + mdns_subtype_t *srv_subtype = service->service->subtype; + while (srv_subtype) { + ESP_GOTO_ON_FALSE(strcmp(srv_subtype->subtype, subtype) != 0, ESP_ERR_INVALID_ARG, err, TAG, "Subtype: %s has already been added", subtype); + srv_subtype = srv_subtype->next; + } + + mdns_subtype_t *subtype_item = (mdns_subtype_t *)mdns_mem_malloc(sizeof(mdns_subtype_t)); + ESP_GOTO_ON_FALSE(subtype_item, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + subtype_item->subtype = mdns_mem_strdup(subtype); + ESP_GOTO_ON_FALSE(subtype_item->subtype, ESP_ERR_NO_MEM, out_of_mem, TAG, "Out of memory"); + subtype_item->next = service->service->subtype; + service->service->subtype = subtype_item; + +err: + return ret; +out_of_mem: + HOOK_MALLOC_FAILED; + mdns_mem_free(subtype_item); + return ret; +} + +esp_err_t mdns_service_subtype_add_multiple_items_for_host(const char *instance_name, const char *service, const char *proto, + const char *hostname, mdns_subtype_item_t subtype[], uint8_t num_items) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + int cur_index = 0; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && + (num_items > 0), ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance_name, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + for (; cur_index < num_items; cur_index++) { + ret = service_subtype_add_for_host(s, subtype[cur_index].subtype); + if (ret == ESP_OK) { + continue; + } else if (ret == ESP_ERR_NO_MEM) { + ESP_LOGE(TAG, "Out of memory"); + goto err; + } else { + ESP_LOGE(TAG, "Failed to add subtype: %s", subtype[cur_index].subtype); + goto exit; + } + } + + announce_all_pcbs(&s, 1, false); +err: + if (ret == ESP_ERR_NO_MEM) { + for (int idx = 0; idx < cur_index; idx++) { + service_subtype_remove_for_host(s, subtype[idx].subtype); + } + } +exit: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_subtype_add_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, const char *subtype) +{ + mdns_subtype_item_t _subtype[1]; + _subtype[0].subtype = subtype; + return mdns_service_subtype_add_multiple_items_for_host(instance_name, service_type, proto, hostname, _subtype, 1); +} + +static mdns_subtype_t *service_find_subtype_needed_sendbye(mdns_service_t *service, mdns_subtype_item_t subtype[], + uint8_t num_items) +{ + if (!service) { + return NULL; + } + + mdns_subtype_t *current = service->subtype; + mdns_subtype_t *prev = NULL; + mdns_subtype_t *prev_goodbye = NULL; + mdns_subtype_t *out_goodbye_subtype = NULL; + + while (current) { + bool subtype_in_update = false; + + for (int i = 0; i < num_items; i++) { + if (strcmp(subtype[i].subtype, current->subtype) == 0) { + subtype_in_update = true; + break; + } + } + + if (!subtype_in_update) { + // Remove from original list + if (prev) { + prev->next = current->next; + } else { + service->subtype = current->next; + } + + mdns_subtype_t *to_move = current; + current = current->next; + + // Add to goodbye list + to_move->next = NULL; + if (prev_goodbye) { + prev_goodbye->next = to_move; + } else { + out_goodbye_subtype = to_move; + } + prev_goodbye = to_move; + } else { + prev = current; + current = current->next; + } + } + + return out_goodbye_subtype; +} + +esp_err_t mdns_service_subtype_update_multiple_items_for_host(const char *instance_name, const char *service_type, const char *proto, + const char *hostname, mdns_subtype_item_t subtype[], uint8_t num_items) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + int cur_index = 0; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service_type) && !mdns_utils_str_null_or_empty(proto), + ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance_name, service_type, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + mdns_subtype_t *goodbye_subtype = service_find_subtype_needed_sendbye(s->service, subtype, num_items); + + if (goodbye_subtype) { + mdns_priv_send_bye_subtype(s, instance_name, goodbye_subtype); + } + + free_subtype(goodbye_subtype); + free_service_subtype(s->service); + + for (; cur_index < num_items; cur_index++) { + ret = service_subtype_add_for_host(s, subtype[cur_index].subtype); + if (ret == ESP_OK) { + continue; + } else if (ret == ESP_ERR_NO_MEM) { + ESP_LOGE(TAG, "Out of memory"); + goto err; + } else { + ESP_LOGE(TAG, "Failed to add subtype: %s", subtype[cur_index].subtype); + goto exit; + } + } + if (num_items) { + announce_all_pcbs(&s, 1, false); + } +err: + if (ret == ESP_ERR_NO_MEM) { + for (int idx = 0; idx < cur_index; idx++) { + service_subtype_remove_for_host(s, subtype[idx].subtype); + } + } +exit: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_instance_name_set_for_host(const char *instance_old, const char *service, const char *proto, const char *host, + const char *instance) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto) && + !mdns_utils_str_null_or_empty(instance) && strlen(instance) <= (MDNS_NAME_BUF_LEN - 1), ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance_old, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + if (s->service->instance) { + mdns_priv_pcb_send_bye_service(&s, 1, false); + mdns_mem_free((char *)s->service->instance); + } + s->service->instance = mdns_mem_strndup(instance, MDNS_NAME_BUF_LEN - 1); + ESP_GOTO_ON_FALSE(s->service->instance, ESP_ERR_NO_MEM, err, TAG, "Out of memory"); + mdns_priv_probe_all_pcbs(&s, 1, false, false); + +err: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_instance_name_set(const char *service, const char *proto, const char *instance) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_instance_name_set_for_host(NULL, service, proto, NULL, instance); +} + +esp_err_t mdns_service_remove_for_host(const char *instance, const char *service, const char *proto, const char *host) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + const char *hostname = host ? host : s_server->hostname; + ESP_GOTO_ON_FALSE(s_server && s_server->services && !mdns_utils_str_null_or_empty(service) && !mdns_utils_str_null_or_empty(proto), + ESP_ERR_INVALID_ARG, err, TAG, "Invalid state or arguments"); + mdns_srv_item_t *s = mdns_utils_get_service_item_instance(instance, service, proto, hostname); + ESP_GOTO_ON_FALSE(s, ESP_ERR_NOT_FOUND, err, TAG, "Service doesn't exist"); + + mdns_srv_item_t *a = s_server->services; + mdns_srv_item_t *b = a; + if (instance) { + while (a) { + if (mdns_utils_service_match_instance(a->service, instance, service, proto, hostname)) { + if (s_server->services != a) { + b->next = a->next; + } else { + s_server->services = a->next; + } + mdns_priv_pcb_send_bye_service(&a, 1, false); + mdns_priv_remove_scheduled_service_packets(a->service); + free_service(a->service); + mdns_mem_free(a); + break; + } + b = a; + a = a->next; + } + } else { + while (a) { + if (mdns_utils_service_match(a->service, service, proto, hostname)) { + if (s_server->services != a) { + b->next = a->next; + } else { + s_server->services = a->next; + } + mdns_priv_pcb_send_bye_service(&a, 1, false); + mdns_priv_remove_scheduled_service_packets(a->service); + free_service(a->service); + mdns_mem_free(a); + break; + } + b = a; + a = a->next; + } + } + +err: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_service_remove(const char *service_type, const char *proto) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + return mdns_service_remove_for_host(NULL, service_type, proto, NULL); +} + +esp_err_t mdns_service_remove_all(void) +{ + mdns_priv_service_lock(); + esp_err_t ret = ESP_OK; + ESP_GOTO_ON_FALSE(s_server, ESP_ERR_INVALID_ARG, done, TAG, "Invalid state"); + if (!s_server->services) { + goto done; + } + + send_final_bye(false); + mdns_srv_item_t *services = s_server->services; + s_server->services = NULL; + while (services) { + mdns_srv_item_t *s = services; + services = services->next; + mdns_priv_remove_scheduled_service_packets(s->service); + free_service(s->service); + mdns_mem_free(s); + } + +done: + mdns_priv_service_unlock(); + return ret; +} + +esp_err_t mdns_lookup_delegated_service(const char *instance, const char *service, const char *proto, size_t max_results, + mdns_result_t **result) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (!result || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + mdns_priv_service_lock(); + *result = lookup_service(instance, service, proto, NULL, max_results, false); + mdns_priv_service_unlock(); + return ESP_OK; +} + +esp_err_t mdns_lookup_delegated_service_with_subtype(const char *instance, const char *service, const char *proto, + const char *subtype, size_t max_results, mdns_result_t **result) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (!result || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto) || + mdns_utils_str_null_or_empty(subtype)) { + return ESP_ERR_INVALID_ARG; + } + mdns_priv_service_lock(); + *result = lookup_service(instance, service, proto, subtype, max_results, false); + mdns_priv_service_unlock(); + return ESP_OK; +} + +esp_err_t mdns_lookup_selfhosted_service(const char *instance, const char *service, const char *proto, size_t max_results, + mdns_result_t **result) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (!result || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto)) { + return ESP_ERR_INVALID_ARG; + } + mdns_priv_service_lock(); + *result = lookup_service(instance, service, proto, NULL, max_results, true); + mdns_priv_service_unlock(); + return ESP_OK; +} + +esp_err_t mdns_lookup_selfhosted_service_with_subtype(const char *instance, const char *service, const char *proto, + const char *subtype, size_t max_results, mdns_result_t **result) +{ + if (!s_server) { + return ESP_ERR_INVALID_STATE; + } + if (!result || mdns_utils_str_null_or_empty(service) || mdns_utils_str_null_or_empty(proto) || + mdns_utils_str_null_or_empty(subtype)) { + return ESP_ERR_INVALID_ARG; + } + mdns_priv_service_lock(); + *result = lookup_service(instance, service, proto, subtype, max_results, true); + mdns_priv_service_unlock(); + return ESP_OK; +} diff --git a/managed_components/espressif__mdns/mdns_send.c b/managed_components/espressif__mdns/mdns_send.c new file mode 100644 index 0000000..6eeb943 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_send.c @@ -0,0 +1,1902 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "mdns_send.h" +#include "mdns_utils.h" +#include "mdns_networking.h" +#include "mdns_debug.h" +#include "mdns_mem_caps.h" +#include "esp_log.h" +#include "mdns_debug.h" +#include "mdns_netif.h" +#include "mdns_pcb.h" +#include "mdns_responder.h" +#include "mdns_service.h" + +static const char *TAG = "mdns_send"; +static const char *MDNS_SUB_STR = "_sub"; + +static mdns_tx_packet_t *s_tx_queue_head; + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0])) +#endif + +/** + * @brief appends uint32_t in a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param value the value to set + * + * @return length of added data: 0 on error or 4 on success + */ +static inline uint8_t append_u32(uint8_t *packet, uint16_t *index, uint32_t value) +{ + if ((*index + sizeof(uint32_t)) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + mdns_utils_append_u8(packet, index, (value >> 24) & 0xFF); + mdns_utils_append_u8(packet, index, (value >> 16) & 0xFF); + mdns_utils_append_u8(packet, index, (value >> 8) & 0xFF); + mdns_utils_append_u8(packet, index, value & 0xFF); + return sizeof(uint32_t); +} + +/** + * @brief appends answer type, class, ttl and data length to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param type answer type + * @param ttl answer ttl + * + * @return length of added data: 0 on error or 10 on success + */ +static inline uint8_t append_type(uint8_t *packet, uint16_t *index, uint8_t type, bool flush, uint32_t ttl) +{ + const size_t len = sizeof(uint16_t) * 2 + sizeof(uint32_t) + sizeof(uint16_t); + if ((*index + len) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + uint16_t mdns_class = MDNS_CLASS_IN; + if (flush) { + mdns_class = MDNS_CLASS_IN_FLUSH_CACHE; + } + if (type == MDNS_ANSWER_PTR) { + mdns_utils_append_u16(packet, index, MDNS_TYPE_PTR); + mdns_utils_append_u16(packet, index, mdns_class); + } else if (type == MDNS_ANSWER_TXT) { + mdns_utils_append_u16(packet, index, MDNS_TYPE_TXT); + mdns_utils_append_u16(packet, index, mdns_class); + } else if (type == MDNS_ANSWER_SRV) { + mdns_utils_append_u16(packet, index, MDNS_TYPE_SRV); + mdns_utils_append_u16(packet, index, mdns_class); + } else if (type == MDNS_ANSWER_A) { + mdns_utils_append_u16(packet, index, MDNS_TYPE_A); + mdns_utils_append_u16(packet, index, mdns_class); + } else if (type == MDNS_ANSWER_AAAA) { + mdns_utils_append_u16(packet, index, MDNS_TYPE_AAAA); + mdns_utils_append_u16(packet, index, mdns_class); + } else { + return 0; + } + append_u32(packet, index, ttl); + mdns_utils_append_u16(packet, index, 0); + return len; +} + +/** + * @brief appends single string to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param string the string to append + * + * @return length of added data: 0 on error or length of the string + 1 on success + */ +static inline uint8_t append_string(uint8_t *packet, uint16_t *index, const char *string) +{ + uint8_t len = strlen(string); + if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + mdns_utils_append_u8(packet, index, len); + memcpy(packet + *index, string, len); + *index += len; + return len + 1; +} + +int mdns_priv_append_one_txt_record_entry(uint8_t *packet, uint16_t *index, mdns_txt_linked_item_t *txt) +{ + if (txt == NULL || txt->key == NULL) { + return -1; + } + size_t key_len = strlen(txt->key); + size_t len = key_len + txt->value_len + (txt->value ? 1 : 0); + if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + mdns_utils_append_u8(packet, index, len); + memcpy(packet + *index, txt->key, key_len); + if (txt->value) { + packet[*index + key_len] = '='; + memcpy(packet + *index + key_len + 1, txt->value, txt->value_len); + } + *index += len; + return len + 1; +} + +static uint16_t append_fqdn(uint8_t *packet, uint16_t *index, const char *strings[], uint8_t count, size_t packet_len); + +/** + * @brief sets uint16_t value in a packet + * + * @param packet MDNS packet + * @param index offset of uint16_t value + * @param value the value to set + */ +static inline void set_u16(uint8_t *packet, uint16_t index, uint16_t value) +{ + if ((index + 1) >= MDNS_MAX_PACKET_SIZE) { + return; + } + packet[index] = (value >> 8) & 0xFF; + packet[index + 1] = value & 0xFF; +} + +/** + * @brief Allocate new packet for sending + */ +mdns_tx_packet_t *mdns_priv_alloc_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_tx_packet_t *packet = (mdns_tx_packet_t *)mdns_mem_malloc(sizeof(mdns_tx_packet_t)); + if (!packet) { + HOOK_MALLOC_FAILED; + return NULL; + } + memset((uint8_t *)packet, 0, sizeof(mdns_tx_packet_t)); + packet->tcpip_if = tcpip_if; + packet->ip_protocol = ip_protocol; + packet->port = MDNS_SERVICE_PORT; +#ifdef CONFIG_LWIP_IPV4 + if (ip_protocol == MDNS_IP_PROTOCOL_V4) { + esp_ip_addr_t addr = ESP_IP4ADDR_INIT(224, 0, 0, 251); + memcpy(&packet->dst, &addr, sizeof(esp_ip_addr_t)); + } +#endif +#ifdef CONFIG_LWIP_IPV6 + if (ip_protocol == MDNS_IP_PROTOCOL_V6) { + esp_ip_addr_t addr = ESP_IP6ADDR_INIT(0x000002ff, 0, 0, 0xfb000000); + memcpy(&packet->dst, &addr, sizeof(esp_ip_addr_t)); + } +#endif + return packet; +} + +/** + * @brief frees a packet + * + * @param packet the packet + */ +void mdns_priv_free_tx_packet(mdns_tx_packet_t *packet) +{ + if (!packet) { + return; + } + mdns_out_question_t *q = packet->questions; + while (q) { + mdns_out_question_t *next = q->next; + if (q->own_dynamic_memory) { + mdns_mem_free((char *)q->host); + mdns_mem_free((char *)q->service); + mdns_mem_free((char *)q->proto); + mdns_mem_free((char *)q->domain); + } + mdns_mem_free(q); + q = next; + } + queueFree(mdns_out_answer_t, packet->answers); + queueFree(mdns_out_answer_t, packet->servers); + queueFree(mdns_out_answer_t, packet->additional); + mdns_mem_free(packet); +} + +/** + * @brief Allocate new answer and add it to answer list (destination) + */ +bool mdns_priv_create_answer(mdns_out_answer_t **destination, uint16_t type, mdns_service_t *service, + mdns_host_item_t *host, bool flush, bool bye) +{ + mdns_out_answer_t *d = *destination; + while (d) { + if (d->type == type && d->service == service && d->host == host) { + return true; + } + d = d->next; + } + + mdns_out_answer_t *a = (mdns_out_answer_t *)mdns_mem_malloc(sizeof(mdns_out_answer_t)); + if (!a) { + HOOK_MALLOC_FAILED; + return false; + } + a->type = type; + a->service = service; + a->host = host; + a->custom_service = NULL; + a->bye = bye; + a->flush = flush; + a->next = NULL; + queueToEnd(mdns_out_answer_t, *destination, a); + return true; +} + +static mdns_host_item_t *get_host_item(const char *hostname) +{ + if (hostname == NULL || strcasecmp(hostname, mdns_priv_get_global_hostname()) == 0) { + return mdns_priv_get_self_host(); + } + mdns_host_item_t *host = mdns_priv_get_hosts(); + while (host != NULL) { + if (strcasecmp(host->hostname, hostname) == 0) { + return host; + } + host = host->next; + } + return NULL; +} + +static bool create_answer_from_service(mdns_tx_packet_t *packet, mdns_service_t *service, + mdns_parsed_question_t *question, bool shared, bool send_flush) +{ + mdns_host_item_t *host = get_host_item(service->hostname); + bool is_delegated = (host != mdns_priv_get_self_host()); + bool is_instance_question = !question->sub && !mdns_utils_str_null_or_empty(question->host); + if ((question->type == MDNS_TYPE_ANY) && is_instance_question) { + // Instance-scoped ANY queries expect the resolved data (SRV/TXT) to be + // part of the answer section so that queriers can stop searching as soon + // as they receive this packet (RFC6762 section 6, RFC6763 section 12.1). + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SRV, service, NULL, send_flush, false) || + !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_TXT, service, NULL, send_flush, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_A, service, host, send_flush, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_AAAA, service, host, send_flush, false)) { + return false; + } + } else if (question->type == MDNS_TYPE_PTR || (question->type == MDNS_TYPE_ANY && !is_instance_question)) { + // For service discovery (PTR or wildcard ANY) RFC6763 section 12.1 + // requires SRV/TXT/address records to stay in the additional section. + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, service, NULL, false, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_SRV, service, NULL, send_flush, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_TXT, service, NULL, send_flush, false) || + !mdns_priv_create_answer((shared || is_delegated) ? &packet->additional : &packet->answers, MDNS_TYPE_A, + service, host, send_flush, + false) || + !mdns_priv_create_answer((shared || is_delegated) ? &packet->additional : &packet->answers, + MDNS_TYPE_AAAA, service, host, + send_flush, false)) { + return false; + } + } else if (question->type == MDNS_TYPE_SRV) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SRV, service, NULL, send_flush, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_A, service, host, send_flush, false) || + !mdns_priv_create_answer(&packet->additional, MDNS_TYPE_AAAA, service, host, send_flush, false)) { + return false; + } + } else if (question->type == MDNS_TYPE_TXT) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_TXT, service, NULL, send_flush, false)) { + return false; + } + } else if (question->type == MDNS_TYPE_SDPTR) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SDPTR, service, NULL, false, false)) { + return false; + } + } + return true; +} + +static bool create_answer_from_hostname(mdns_tx_packet_t *packet, const char *hostname, bool send_flush) +{ + mdns_host_item_t *host = get_host_item(hostname); + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_A, NULL, host, send_flush, false) || + !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, host, send_flush, false)) { + return false; + } + return true; +} + +static bool service_match_ptr_question(const mdns_service_t *service, const mdns_parsed_question_t *question) +{ + if (!mdns_utils_service_match(service, question->service, question->proto, NULL)) { + return false; + } + // The question parser stores anything before _type._proto in question->host + // So the question->host can be subtype or instance name based on its content + if (question->sub) { + mdns_subtype_t *subtype = service->subtype; + while (subtype) { + if (!strcasecmp(subtype->subtype, question->host)) { + return true; + } + subtype = subtype->next; + } + return false; + } + if (question->host) { + if (strcasecmp(mdns_utils_get_service_instance_name(service), question->host) != 0) { + return false; + } + } + return true; +} +static bool append_host(mdns_out_answer_t **destination, mdns_host_item_t *host, bool flush, bool bye) +{ + if (!mdns_priv_create_answer(destination, MDNS_TYPE_A, NULL, host, flush, bye)) { + return false; + } + if (!mdns_priv_create_answer(destination, MDNS_TYPE_AAAA, NULL, host, flush, bye)) { + return false; + } + return true; +} + +bool mdns_priv_append_host_list_in_services(mdns_out_answer_t **destination, mdns_srv_item_t *services[], + size_t services_len, bool flush, bool bye) +{ + if (services == NULL) { + mdns_host_item_t *host = get_host_item(mdns_priv_get_global_hostname()); + if (host != NULL) { + return append_host(destination, host, flush, bye); + } + return true; + } + for (size_t i = 0; i < services_len; i++) { + mdns_host_item_t *host = get_host_item(services[i]->service->hostname); + if (!append_host(destination, host, flush, bye)) { + return false; + } + } + return true; +} + +static bool append_host_list(mdns_out_answer_t **destination, bool flush, bool bye) +{ + if (!mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname())) { + mdns_host_item_t *self_host = get_host_item(mdns_priv_get_global_hostname()); + if (!append_host(destination, self_host, flush, bye)) { + return false; + } + } + mdns_host_item_t *host = mdns_priv_get_hosts(); + while (host != NULL) { + host = host->next; + if (!append_host(destination, host, flush, bye)) { + return false; + } + } + return true; +} + +/** + * @brief Check if question is already in the list + */ +static bool question_exists(mdns_out_question_t *needle, mdns_out_question_t *haystack) +{ + while (haystack) { + if (haystack->type == needle->type + && haystack->host == needle->host + && haystack->service == needle->service + && haystack->proto == needle->proto) { + return true; + } + haystack = haystack->next; + } + return false; +} + +static bool append_host_question(mdns_out_question_t **questions, const char *hostname, bool unicast) +{ + mdns_out_question_t *q = (mdns_out_question_t *)mdns_mem_malloc(sizeof(mdns_out_question_t)); + if (!q) { + HOOK_MALLOC_FAILED; + return false; + } + q->next = NULL; + q->unicast = unicast; + q->type = MDNS_TYPE_ANY; + q->host = hostname; + q->service = NULL; + q->proto = NULL; + q->domain = MDNS_UTILS_DEFAULT_DOMAIN; + q->subtype = NULL; + q->own_dynamic_memory = false; + if (question_exists(q, *questions)) { + mdns_mem_free(q); + } else { + queueToEnd(mdns_out_question_t, *questions, q); + } + return true; +} + +static bool append_host_questions_for_services(mdns_out_question_t **questions, mdns_srv_item_t *services[], + size_t len, bool unicast) +{ + if (!mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname()) && + !append_host_question(questions, mdns_priv_get_global_hostname(), unicast)) { + return false; + } + for (size_t i = 0; i < len; i++) { + if (!append_host_question(questions, services[i]->service->hostname, unicast)) { + return false; + } + } + return true; +} + +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES +static inline int append_single_str(uint8_t *packet, uint16_t *index, const char *str, int len) +{ + if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + if (!mdns_utils_append_u8(packet, index, len)) { + return 0; + } + memcpy(packet + *index, str, len); + *index += len; + return *index; +} + +/** + * @brief appends FQDN to a packet from hostname separated by dots. This API works the same way as + * append_fqdn(), but refrains from DNS compression (as it's mainly used for IP addresses (many short items), + * where we gain very little (or compression even gets counter-productive mainly for IPv6 addresses) + * + * @param packet MDNS packet + * @param index offset in the packet + * @param name name representing FQDN in '.' separated parts + * @param last true if appending the last part (domain, typically "arpa") + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_fqdn_dots(uint8_t *packet, uint16_t *index, const char *name, bool last) +{ + int len = strlen(name); + char *host = (char *)name; + char *end = host; + char *start = host; + do { + end = memchr(start, '.', host + len - start); + end = end ? end : host + len; + int part_len = end - start; + if (!append_single_str(packet, index, start, part_len)) { + return 0; + } + start = ++end; + } while (end < name + len); + + if (!append_single_str(packet, index, "arpa", sizeof("arpa") - 1)) { + return 0; + } + + //empty string so terminate + if (!mdns_utils_append_u8(packet, index, 0)) { + return 0; + } + return *index; +} + +/** + * @brief Appends reverse lookup PTR record + */ +static uint8_t append_reverse_ptr_record(uint8_t *packet, uint16_t *index, const char *name) +{ + if (strstr(name, "in-addr") == NULL && strstr(name, "ip6") == NULL) { + return 0; + } + + if (!append_fqdn_dots(packet, index, name, false)) { + return 0; + } + + if (!append_type(packet, index, MDNS_ANSWER_PTR, false, 10 /* TTL set to 10s*/)) { + return 0; + } + + uint16_t data_len_location = *index - 2; /* store the position of size (2=16bis) of this record */ + const char *str[2] = {mdns_priv_get_self_host()->hostname, MDNS_UTILS_DEFAULT_DOMAIN }; + + int part_length = append_fqdn(packet, index, str, 2, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + + set_u16(packet, data_len_location, part_length); + return 1; /* appending only 1 record */ +} +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + +void mdns_priv_create_answer_from_parsed_packet(mdns_parsed_packet_t *parsed_packet) +{ + if (!parsed_packet->questions) { + return; + } + bool send_flush = parsed_packet->src_port == MDNS_SERVICE_PORT; + bool unicast = false; + bool shared = false; + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(parsed_packet->tcpip_if, parsed_packet->ip_protocol); + if (!packet) { + return; + } + packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; + packet->distributed = parsed_packet->distributed; + packet->id = parsed_packet->id; + + mdns_parsed_question_t *q = parsed_packet->questions; + uint32_t out_record_nums = 0; + while (q) { + shared = q->type == MDNS_TYPE_PTR || q->type == MDNS_TYPE_SDPTR || !parsed_packet->probe; + // DNS-SD subtypes only define PTR records at the subtype owner name. + // Do not interpret the subtype label as an instance name for SRV/TXT. + if (q->sub && (q->type == MDNS_TYPE_SRV || q->type == MDNS_TYPE_TXT)) { + q = q->next; + continue; + } + if (q->type == MDNS_TYPE_SRV || q->type == MDNS_TYPE_TXT) { + mdns_srv_item_t *service = mdns_utils_get_service_item_instance(q->host, q->service, q->proto, NULL); + if (service == NULL) { // Service not found, but we continue to the next question + q = q->next; + continue; + } + if (!create_answer_from_service(packet, service->service, q, shared, send_flush)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } + } else if (q->service && q->proto) { + mdns_srv_item_t *service = mdns_priv_get_services(); + while (service) { + if (service_match_ptr_question(service->service, q)) { + mdns_parsed_record_t *r = parsed_packet->records; + bool is_record_exist = false; + while (r) { + if (service->service->instance && r->host) { + if (mdns_utils_service_match_instance(service->service, r->host, r->service, r->proto, NULL) && r->ttl > (MDNS_ANSWER_PTR_TTL / 2)) { + is_record_exist = true; + break; + } + } else if (!service->service->instance && !r->host) { + if (mdns_utils_service_match(service->service, r->service, r->proto, NULL) && r->ttl > (MDNS_ANSWER_PTR_TTL / 2)) { + is_record_exist = true; + break; + } + } + r = r->next; + } + if (!is_record_exist) { + if (!create_answer_from_service(packet, service->service, q, shared, send_flush)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } + } + } + service = service->next; + } + } else if (q->type == MDNS_TYPE_A || q->type == MDNS_TYPE_AAAA) { + if (!create_answer_from_hostname(packet, q->host, send_flush)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } + } else if (q->type == MDNS_TYPE_ANY) { + if (!append_host_list(&packet->answers, send_flush, false)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + } else if (q->type == MDNS_TYPE_PTR) { + mdns_host_item_t *host = get_host_item(q->host); + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, NULL, host, send_flush, false)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + } else if (!mdns_priv_create_answer(&packet->answers, q->type, NULL, NULL, send_flush, false)) { + mdns_priv_free_tx_packet(packet); + return; + } else { + out_record_nums++; + } + + if (parsed_packet->src_port != MDNS_SERVICE_PORT && // Repeat the queries only for "One-Shot mDNS queries" + (q->type == MDNS_TYPE_ANY || q->type == MDNS_TYPE_A || q->type == MDNS_TYPE_AAAA +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + || q->type == MDNS_TYPE_PTR +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + )) { + mdns_out_question_t *out_question = mdns_mem_malloc(sizeof(mdns_out_question_t)); + if (out_question == NULL) { + HOOK_MALLOC_FAILED; + mdns_priv_free_tx_packet(packet); + return; + } + out_question->type = q->type; + out_question->unicast = q->unicast; + out_question->host = q->host; + q->host = NULL; + out_question->service = q->service; + q->service = NULL; + out_question->proto = q->proto; + q->proto = NULL; + out_question->domain = q->domain; + q->domain = NULL; + out_question->subtype = q->sub ? out_question->host : NULL; + out_question->next = NULL; + out_question->own_dynamic_memory = true; + queueToEnd(mdns_out_question_t, packet->questions, out_question); + } + if (q->unicast) { + unicast = true; + } + q = q->next; + } + if (out_record_nums == 0) { + mdns_priv_free_tx_packet(packet); + return; + } + if (unicast || !send_flush) { + memcpy(&packet->dst, &parsed_packet->src, sizeof(esp_ip_addr_t)); + packet->port = parsed_packet->src_port; + } + + static uint8_t share_step = 0; + if (shared) { + mdns_priv_send_after(packet, 25 + (share_step * 25)); + share_step = (share_step + 1) & 0x03; + } else { + mdns_priv_dispatch_tx_packet(packet); + mdns_priv_free_tx_packet(packet); + } +} + +/** + * @brief appends FQDN to a packet, incrementing the index and + * compressing the output if previous occurrence of the string (or part of it) has been found + * + * @param packet MDNS packet + * @param index offset in the packet + * @param strings string array containing the parts of the FQDN + * @param count number of strings in the array + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_fqdn(uint8_t *packet, uint16_t *index, const char *strings[], uint8_t count, size_t packet_len) +{ + if (!count) { + // empty string so terminate + return mdns_utils_append_u8(packet, index, 0); + } + static char buf[MDNS_NAME_BUF_LEN]; + uint8_t len = strlen(strings[0]); + // try to find first the string length in the packet (if it exists) + uint8_t *len_location = (uint8_t *)memchr(packet, (char)len, *index); + while (len_location) { + mdns_name_t name; + // check if the string after len_location is the string that we are looking for + if (memcmp(len_location + 1, strings[0], len)) { //not continuing with our string +search_next: + // try and find the length byte further in the packet + len_location = (uint8_t *)memchr(len_location + 1, (char)len, *index - (len_location + 1 - packet)); + continue; + } + // seems that we might have found the string that we are looking for + // read the destination into name and compare + name.parts = 0; + name.sub = 0; + name.invalid = false; + name.host[0] = 0; + name.service[0] = 0; + name.proto[0] = 0; + name.domain[0] = 0; + const uint8_t *content = mdns_utils_read_fqdn(packet, len_location, &name, buf, packet_len); + if (!content) { + // not a readable fqdn? + goto search_next; // could be our unfinished fqdn, continue searching + } + if (name.parts == count) { + uint8_t i; + for (i = 0; i < count; i++) { + if (strcasecmp(strings[i], (const char *)&name + (i * (MDNS_NAME_BUF_LEN)))) { + // not our string! let's search more + goto search_next; + } + } + // we actually have found the string + break; + } else { + goto search_next; + } + } + // string is not yet in the packet, so let's add it + if (!len_location) { + uint8_t written = append_string(packet, index, strings[0]); + if (!written) { + return 0; + } + // run the same for the other strings in the name + return written + append_fqdn(packet, index, &strings[1], count - 1, packet_len); + } + + // we have found the string so let's insert a pointer to it instead + uint16_t offset = len_location - packet; + offset |= MDNS_NAME_REF; + return mdns_utils_append_u16(packet, index, offset); +} + + +/** + * @brief Append question to packet + */ +static uint16_t append_question(uint8_t *packet, uint16_t *index, mdns_out_question_t *q) +{ + uint8_t part_length; +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + if (!q->subtype && q->host && (strstr(q->host, "in-addr") || strstr(q->host, "ip6"))) { + part_length = append_fqdn_dots(packet, index, q->host, false); + if (!part_length) { + return 0; + } + } else +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + { + const char *str[5]; + uint8_t str_index = 0; + if (q->subtype) { + str[str_index++] = q->subtype; + str[str_index++] = MDNS_SUB_STR; + } else if (q->host) { + str[str_index++] = q->host; + } + if (q->service) { + str[str_index++] = q->service; + } + if (q->proto) { + str[str_index++] = q->proto; + } + if (q->domain) { + str[str_index++] = q->domain; + } + part_length = append_fqdn(packet, index, str, str_index, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + } + + part_length += mdns_utils_append_u16(packet, index, q->type); + part_length += mdns_utils_append_u16(packet, index, q->unicast ? 0x8001 : 0x0001); + return part_length; +} + +/** + * @brief appends PTR record for service to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param server the server that is hosting the service + * @param service the service to add record for + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_ptr_record(uint8_t *packet, uint16_t *index, const char *instance, const char *service, const char *proto, bool flush, bool bye) +{ + const char *str[4]; + uint16_t record_length = 0; + uint8_t part_length; + + if (service == NULL) { + return 0; + } + + str[0] = instance; + str[1] = service; + str[2] = proto; + str[3] = MDNS_UTILS_DEFAULT_DOMAIN; + + part_length = append_fqdn(packet, index, str + 1, 3, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_PTR, false, bye ? 0 : MDNS_ANSWER_PTR_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + part_length = append_fqdn(packet, index, str, 4, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + set_u16(packet, data_len_location, part_length); + record_length += part_length; + return record_length; +} + +/** + * @brief appends PTR record for a subtype to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param instance the service instance name + * @param subtype the service subtype + * @param proto the service protocol + * @param flush whether to set the flush flag + * @param bye whether to set the bye flag + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_subtype_ptr_record(uint8_t *packet, uint16_t *index, const char *instance, + const char *subtype, const char *service, const char *proto, bool flush, + bool bye) +{ + const char *subtype_str[5] = {subtype, MDNS_SUB_STR, service, proto, MDNS_UTILS_DEFAULT_DOMAIN}; + const char *instance_str[4] = {instance, service, proto, MDNS_UTILS_DEFAULT_DOMAIN}; + uint16_t record_length = 0; + uint8_t part_length; + + if (service == NULL) { + return 0; + } + + part_length = append_fqdn(packet, index, subtype_str, ARRAY_SIZE(subtype_str), MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_PTR, false, bye ? 0 : MDNS_ANSWER_PTR_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + part_length = append_fqdn(packet, index, instance_str, ARRAY_SIZE(instance_str), MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + set_u16(packet, data_len_location, part_length); + record_length += part_length; + return record_length; +} +/** + * @brief Append PTR answers to packet + * + * @return number of answers added to the packet + */ +static uint8_t append_service_ptr_answers(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, + bool bye) +{ + uint8_t appended_answers = 0; + + if (append_ptr_record(packet, index, mdns_utils_get_service_instance_name(service), service->service, + service->proto, flush, bye) <= 0) { + return appended_answers; + } + appended_answers++; + + mdns_subtype_t *subtype = service->subtype; + while (subtype) { + appended_answers += + (append_subtype_ptr_record(packet, index, mdns_utils_get_service_instance_name(service), subtype->subtype, + service->service, service->proto, flush, bye) > 0); + subtype = subtype->next; + } + + return appended_answers; +} + +/** + * @brief appends SRV record for service to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param server the server that is hosting the service + * @param service the service to add record for + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_srv_record(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, bool bye) +{ + const char *str[4]; + uint16_t record_length = 0; + uint8_t part_length; + + if (service == NULL) { + return 0; + } + + str[0] = mdns_utils_get_service_instance_name(service); + str[1] = service->service; + str[2] = service->proto; + str[3] = MDNS_UTILS_DEFAULT_DOMAIN; + + if (!str[0]) { + return 0; + } + + part_length = append_fqdn(packet, index, str, 4, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_SRV, flush, bye ? 0 : MDNS_ANSWER_SRV_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + + part_length = 0; + part_length += mdns_utils_append_u16(packet, index, service->priority); + part_length += mdns_utils_append_u16(packet, index, service->weight); + part_length += mdns_utils_append_u16(packet, index, service->port); + if (part_length != 6) { + return 0; + } + + if (service->hostname) { + str[0] = service->hostname; + } else { + str[0] = mdns_priv_get_global_hostname(); + } + str[1] = MDNS_UTILS_DEFAULT_DOMAIN; + + if (mdns_utils_str_null_or_empty(str[0])) { + return 0; + } + + part_length = append_fqdn(packet, index, str, 2, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + set_u16(packet, data_len_location, part_length + 6); + + record_length += part_length + 6; + return record_length; +} + +/** + * @brief appends TXT record for service to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param server the server that is hosting the service + * @param service the service to add record for + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_txt_record(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, bool bye) +{ + const char *str[4]; + uint16_t record_length = 0; + uint8_t part_length; + + if (service == NULL) { + return 0; + } + + str[0] = mdns_utils_get_service_instance_name(service); + str[1] = service->service; + str[2] = service->proto; + str[3] = MDNS_UTILS_DEFAULT_DOMAIN; + + if (!str[0]) { + return 0; + } + + part_length = append_fqdn(packet, index, str, 4, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_TXT, flush, bye ? 0 : MDNS_ANSWER_TXT_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + uint16_t data_len = 0; + + mdns_txt_linked_item_t *txt = service->txt; + while (txt) { + int l = mdns_priv_append_one_txt_record_entry(packet, index, txt); + if (l > 0) { + data_len += l; + } else if (l == 0) { // TXT entry won't fit into the mdns packet + return 0; + } + txt = txt->next; + } + if (!data_len) { + data_len = 1; + packet[*index] = 0; + *index = *index + 1; + } + set_u16(packet, data_len_location, data_len); + record_length += data_len; + return record_length; +} + +/** + * @brief appends DNS-SD PTR record for service to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param server the server that is hosting the service + * @param service the service to add record for + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_sdptr_record(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, bool bye) +{ + const char *str[3]; + const char *sd_str[4]; + uint16_t record_length = 0; + uint8_t part_length; + + if (service == NULL) { + return 0; + } + + sd_str[0] = (char *)"_services"; + sd_str[1] = (char *)"_dns-sd"; + sd_str[2] = (char *)"_udp"; + sd_str[3] = MDNS_UTILS_DEFAULT_DOMAIN; + + str[0] = service->service; + str[1] = service->proto; + str[2] = MDNS_UTILS_DEFAULT_DOMAIN; + + part_length = append_fqdn(packet, index, sd_str, 4, MDNS_MAX_PACKET_SIZE); + + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_PTR, flush, MDNS_ANSWER_PTR_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + part_length = append_fqdn(packet, index, str, 3, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + set_u16(packet, data_len_location, part_length); + record_length += part_length; + return record_length; +} + +#ifdef CONFIG_LWIP_IPV4 +/** + * @brief appends A record to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param hostname the hostname address to add + * @param ip the IP address to add + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_a_record(uint8_t *packet, uint16_t *index, const char *hostname, uint32_t ip, bool flush, bool bye) +{ + const char *str[2]; + uint16_t record_length = 0; + uint8_t part_length; + + str[0] = hostname; + str[1] = MDNS_UTILS_DEFAULT_DOMAIN; + + if (mdns_utils_str_null_or_empty(str[0])) { + return 0; + } + + part_length = append_fqdn(packet, index, str, 2, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_A, flush, bye ? 0 : MDNS_ANSWER_A_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + + if ((*index + 3) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + mdns_utils_append_u8(packet, index, ip & 0xFF); + mdns_utils_append_u8(packet, index, (ip >> 8) & 0xFF); + mdns_utils_append_u8(packet, index, (ip >> 16) & 0xFF); + mdns_utils_append_u8(packet, index, (ip >> 24) & 0xFF); + set_u16(packet, data_len_location, 4); + + record_length += 4; + return record_length; +} +#endif /* CONFIG_LWIP_IPV4 */ + +#ifdef CONFIG_LWIP_IPV6 +/** + * @brief appends AAAA record to a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param hostname the hostname address to add + * @param ipv6 the IPv6 address to add + * + * @return length of added data: 0 on error or length on success + */ +static uint16_t append_aaaa_record(uint8_t *packet, uint16_t *index, const char *hostname, uint8_t *ipv6, bool flush, bool bye) +{ + const char *str[2]; + uint16_t record_length = 0; + uint8_t part_length; + + str[0] = hostname; + str[1] = MDNS_UTILS_DEFAULT_DOMAIN; + + if (mdns_utils_str_null_or_empty(str[0])) { + return 0; + } + + + part_length = append_fqdn(packet, index, str, 2, MDNS_MAX_PACKET_SIZE); + if (!part_length) { + return 0; + } + record_length += part_length; + + part_length = append_type(packet, index, MDNS_ANSWER_AAAA, flush, bye ? 0 : MDNS_ANSWER_AAAA_TTL); + if (!part_length) { + return 0; + } + record_length += part_length; + + uint16_t data_len_location = *index - 2; + + if ((*index + MDNS_ANSWER_AAAA_SIZE) > MDNS_MAX_PACKET_SIZE) { + return 0; + } + + part_length = MDNS_ANSWER_AAAA_SIZE; + memcpy(packet + *index, ipv6, part_length); + *index += part_length; + set_u16(packet, data_len_location, part_length); + record_length += part_length; + return record_length; +} +#endif + +static uint8_t append_host_answer(uint8_t *packet, uint16_t *index, mdns_host_item_t *host, + uint8_t address_type, bool flush, bool bye) +{ + mdns_ip_addr_t *addr = host->address_list; + uint8_t num_records = 0; + + while (addr != NULL) { + if (addr->addr.type == address_type) { +#ifdef CONFIG_LWIP_IPV4 + if (address_type == ESP_IPADDR_TYPE_V4 && + append_a_record(packet, index, host->hostname, addr->addr.u_addr.ip4.addr, flush, bye) <= 0) { + break; + } +#endif /* CONFIG_LWIP_IPV4 */ +#ifdef CONFIG_LWIP_IPV6 + if (address_type == ESP_IPADDR_TYPE_V6 && + append_aaaa_record(packet, index, host->hostname, (uint8_t *)addr->addr.u_addr.ip6.addr, flush, + bye) <= 0) { + break; + } +#endif /* CONFIG_LWIP_IPV6 */ + num_records++; + } + addr = addr->next; + } + return num_records; +} + +/** + * @brief Append answer to packet + * + * @return number of answers added to the packet + */ +static uint8_t append_answer(uint8_t *packet, uint16_t *index, mdns_out_answer_t *answer, mdns_if_t tcpip_if) +{ + if (answer->host) { + bool is_host_valid = (mdns_priv_get_self_host() == answer->host); + mdns_host_item_t *target_host = mdns_priv_get_hosts(); + while (target_host && !is_host_valid) { + if (target_host == answer->host) { + is_host_valid = true; + } + target_host = target_host->next; + } + if (!is_host_valid) { + return 0; + } + } + + if (answer->type == MDNS_TYPE_PTR) { + if (answer->service) { + return append_service_ptr_answers(packet, index, answer->service, answer->flush, answer->bye); +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + } else if (answer->host && answer->host->hostname && + (strstr(answer->host->hostname, "in-addr") || strstr(answer->host->hostname, "ip6"))) { + return append_reverse_ptr_record(packet, index, answer->host->hostname) > 0; +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ + } else { + return append_ptr_record(packet, index, + answer->custom_instance, answer->custom_service, answer->custom_proto, + answer->flush, answer->bye) > 0; + } + } else if (answer->type == MDNS_TYPE_SRV) { + return append_srv_record(packet, index, answer->service, answer->flush, answer->bye) > 0; + } else if (answer->type == MDNS_TYPE_TXT) { + return append_txt_record(packet, index, answer->service, answer->flush, answer->bye) > 0; + } else if (answer->type == MDNS_TYPE_SDPTR) { + return append_sdptr_record(packet, index, answer->service, answer->flush, answer->bye) > 0; + } +#ifdef CONFIG_LWIP_IPV4 + else if (answer->type == MDNS_TYPE_A) { + if (answer->host == mdns_priv_get_self_host()) { + esp_netif_ip_info_t if_ip_info; + if (!mdns_priv_if_ready(tcpip_if, MDNS_IP_PROTOCOL_V4) && !mdns_priv_pcb_is_duplicate(tcpip_if, + MDNS_IP_PROTOCOL_V4)) { + return 0; + } + // No IPv4 address (e.g. IPv6-only netif with DHCP client stopped): don't advertise A 0.0.0.0 + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(tcpip_if), &if_ip_info) || if_ip_info.ip.addr == 0) { + return 0; + } + if (append_a_record(packet, index, mdns_priv_get_global_hostname(), if_ip_info.ip.addr, answer->flush, answer->bye) <= 0) { + return 0; + } + if (!mdns_priv_pcb_check_for_duplicates(tcpip_if)) { + return 1; + } + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(other_if), &if_ip_info) || if_ip_info.ip.addr == 0) { + return 1; + } + if (append_a_record(packet, index, mdns_priv_get_global_hostname(), if_ip_info.ip.addr, answer->flush, answer->bye) > 0) { + return 2; + } + return 1; + } else if (answer->host != NULL) { + return append_host_answer(packet, index, answer->host, ESP_IPADDR_TYPE_V4, answer->flush, answer->bye); + } + } +#endif /* CONFIG_LWIP_IPV4 */ +#ifdef CONFIG_LWIP_IPV6 + else if (answer->type == MDNS_TYPE_AAAA) { + if (answer->host == mdns_priv_get_self_host()) { + struct esp_ip6_addr if_ip6s[NETIF_IPV6_MAX_NUMS]; + uint8_t count = 0; + if (!mdns_priv_if_ready(tcpip_if, MDNS_IP_PROTOCOL_V6) && !mdns_priv_pcb_is_duplicate(tcpip_if, + MDNS_IP_PROTOCOL_V6)) { + return 0; + } + count = esp_netif_get_all_ip6(mdns_priv_get_esp_netif(tcpip_if), if_ip6s); + assert(count <= NETIF_IPV6_MAX_NUMS); + for (int i = 0; i < count; i++) { + if (mdns_utils_ipv6_address_is_zero(if_ip6s[i])) { + return 0; + } + if (append_aaaa_record(packet, index, mdns_priv_get_global_hostname(), (uint8_t *)if_ip6s[i].addr, + answer->flush, answer->bye) <= 0) { + return 0; + } + } + if (!mdns_priv_pcb_check_for_duplicates(tcpip_if)) { + return count; + } + + mdns_if_t other_if = mdns_priv_netif_get_other_interface(tcpip_if); + struct esp_ip6_addr other_ip6; + if (esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(other_if), &other_ip6)) { + return count; + } + if (append_aaaa_record(packet, index, mdns_priv_get_global_hostname(), (uint8_t *)other_ip6.addr, + answer->flush, answer->bye) > 0) { + return 1 + count; + } + return count; + } else if (answer->host != NULL) { + return append_host_answer(packet, index, answer->host, ESP_IPADDR_TYPE_V6, answer->flush, + answer->bye); + } + } +#endif /* CONFIG_LWIP_IPV6 */ + return 0; +} + +/** + * @brief sends a packet + * + * @param p the packet + */ +void mdns_priv_dispatch_tx_packet(mdns_tx_packet_t *p) +{ + static uint8_t packet[MDNS_MAX_PACKET_SIZE]; + uint16_t index = MDNS_HEAD_LEN; + memset(packet, 0, MDNS_HEAD_LEN); + mdns_out_question_t *q; + mdns_out_answer_t *a; + uint8_t count; + + set_u16(packet, MDNS_HEAD_FLAGS_OFFSET, p->flags); + set_u16(packet, MDNS_HEAD_ID_OFFSET, p->id); + + count = 0; + q = p->questions; + while (q) { + if (append_question(packet, &index, q)) { + count++; + } + q = q->next; + } + set_u16(packet, MDNS_HEAD_QUESTIONS_OFFSET, count); + + count = 0; + a = p->answers; + while (a) { + count += append_answer(packet, &index, a, p->tcpip_if); + a = a->next; + } + set_u16(packet, MDNS_HEAD_ANSWERS_OFFSET, count); + + count = 0; + a = p->servers; + while (a) { + count += append_answer(packet, &index, a, p->tcpip_if); + a = a->next; + } + set_u16(packet, MDNS_HEAD_SERVERS_OFFSET, count); + + count = 0; + a = p->additional; + while (a) { + count += append_answer(packet, &index, a, p->tcpip_if); + a = a->next; + } + set_u16(packet, MDNS_HEAD_ADDITIONAL_OFFSET, count); + + DBG_TX_PACKET(p, packet, index); + + mdns_priv_if_write(p->tcpip_if, p->ip_protocol, &p->dst, p->port, packet, index); +} + +/** + * @brief Create probe packet for particular services on particular PCB + */ +mdns_tx_packet_t *mdns_priv_create_probe_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t *services[], size_t len, bool first, bool include_ip) +{ + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(tcpip_if, ip_protocol); + if (!packet) { + return NULL; + } + + size_t i; + for (i = 0; i < len; i++) { + mdns_out_question_t *q = (mdns_out_question_t *)mdns_mem_malloc(sizeof(mdns_out_question_t)); + if (!q) { + HOOK_MALLOC_FAILED; + mdns_priv_free_tx_packet(packet); + return NULL; + } + q->next = NULL; + q->unicast = first; + q->type = MDNS_TYPE_ANY; + q->host = mdns_utils_get_service_instance_name(services[i]->service); + q->service = services[i]->service->service; + q->proto = services[i]->service->proto; + q->domain = MDNS_UTILS_DEFAULT_DOMAIN; + q->subtype = NULL; + q->own_dynamic_memory = false; + if (!q->host || question_exists(q, packet->questions)) { + mdns_mem_free(q); + continue; + } else { + queueToEnd(mdns_out_question_t, packet->questions, q); + } + + if (!q->host || !mdns_priv_create_answer(&packet->servers, MDNS_TYPE_SRV, services[i]->service, NULL, false, + false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + } + + if (include_ip) { + if (!append_host_questions_for_services(&packet->questions, services, len, first)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + + if (!mdns_priv_append_host_list_in_services(&packet->servers, services, len, false, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + } + + return packet; +} + +/** + * @brief Create announce packet for particular services on particular PCB + */ +mdns_tx_packet_t *mdns_priv_create_announce_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t *services[], size_t len, bool include_ip) +{ + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(tcpip_if, ip_protocol); + if (!packet) { + return NULL; + } + packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; + + uint8_t i; + for (i = 0; i < len; i++) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SDPTR, services[i]->service, NULL, false, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, services[i]->service, NULL, false, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SRV, services[i]->service, NULL, true, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_TXT, services[i]->service, NULL, true, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + } + if (include_ip) { + if (!mdns_priv_append_host_list_in_services(&packet->servers, services, len, true, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + } + return packet; +} + +/** + * @brief Convert probe packet to announce + */ +mdns_tx_packet_t *mdns_priv_create_announce_from_probe(mdns_tx_packet_t *probe) +{ + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(probe->tcpip_if, probe->ip_protocol); + if (!packet) { + return NULL; + } + packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; + + mdns_out_answer_t *s = probe->servers; + while (s) { + if (s->type == MDNS_TYPE_SRV) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SDPTR, s->service, NULL, false, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, s->service, NULL, false, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_SRV, s->service, NULL, true, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_TXT, s->service, NULL, true, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + mdns_host_item_t *host = get_host_item(s->service->hostname); + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_A, NULL, host, true, false) + || !mdns_priv_create_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, host, true, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + + } else if (s->type == MDNS_TYPE_A || s->type == MDNS_TYPE_AAAA) { + if (!mdns_priv_create_answer(&packet->answers, s->type, NULL, s->host, true, false)) { + mdns_priv_free_tx_packet(packet); + return NULL; + } + } + + s = s->next; + } + return packet; +} + +void mdns_priv_send_bye(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool include_ip) +{ + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(tcpip_if, ip_protocol); + if (!packet) { + return; + } + packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; + size_t i; + for (i = 0; i < len; i++) { + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, services[i]->service, NULL, true, true)) { + mdns_priv_free_tx_packet(packet); + return; + } + } + if (include_ip) { + mdns_priv_append_host_list_in_services(&packet->answers, services, len, true, true); + } + mdns_priv_dispatch_tx_packet(packet); + mdns_priv_free_tx_packet(packet); +} + +/** + * @brief Send bye for particular subtypes + */ +void mdns_priv_send_bye_subtype(mdns_srv_item_t *service, const char *instance_name, mdns_subtype_t *remove_subtypes) +{ + uint8_t i, j; + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (j = 0; j < MDNS_IP_PROTOCOL_MAX; j++) { + if (mdns_priv_if_ready(i, j)) { + mdns_tx_packet_t *packet = mdns_priv_alloc_packet((mdns_if_t) i, (mdns_ip_protocol_t) j); + if (packet == NULL) { + return; + } + packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; + if (!mdns_priv_create_answer(&packet->answers, MDNS_TYPE_PTR, service->service, NULL, true, true)) { + mdns_priv_free_tx_packet(packet); + return; + } + + static uint8_t pkt[MDNS_MAX_PACKET_SIZE]; + uint16_t index = MDNS_HEAD_LEN; + memset(pkt, 0, MDNS_HEAD_LEN); + mdns_out_answer_t *a; + uint8_t count; + + set_u16(pkt, MDNS_HEAD_FLAGS_OFFSET, packet->flags); + set_u16(pkt, MDNS_HEAD_ID_OFFSET, packet->id); + + count = 0; + a = packet->answers; + while (a) { + if (a->type == MDNS_TYPE_PTR && a->service) { + const mdns_subtype_t *current_subtype = remove_subtypes; + while (current_subtype) { + count += (append_subtype_ptr_record(pkt, &index, instance_name, current_subtype->subtype, a->service->service, a->service->proto, a->flush, a->bye) > 0); + current_subtype = current_subtype->next; + } + } + a = a->next; + } + set_u16(pkt, MDNS_HEAD_ANSWERS_OFFSET, count); + + mdns_priv_if_write(packet->tcpip_if, packet->ip_protocol, &packet->dst, packet->port, pkt, index); + + mdns_priv_free_tx_packet(packet); + } + } + } +} + +/** + * @brief Find, remove and free answer from the scheduled packets + */ +void mdns_priv_remove_scheduled_answer(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint16_t type, mdns_srv_item_t *service) +{ + mdns_srv_item_t s = {NULL, NULL}; + if (!service) { + service = &s; + } + mdns_tx_packet_t *q = s_tx_queue_head; + while (q) { + if (q->tcpip_if == tcpip_if && q->ip_protocol == ip_protocol && q->distributed) { + mdns_out_answer_t *a = q->answers; + if (a) { + if (a->type == type && a->service == service->service) { + q->answers = q->answers->next; + mdns_mem_free(a); + } else { + while (a->next) { + if (a->next->type == type && a->next->service == service->service) { + mdns_out_answer_t *b = a->next; + a->next = b->next; + mdns_mem_free(b); + break; + } + a = a->next; + } + } + } + } + q = q->next; + } +} + + +/** + * @brief schedules a packet to be sent after given milliseconds + * + * @param packet the packet + * @param ms_after number of milliseconds after which the packet should be dispatched + */ +void mdns_priv_send_after(mdns_tx_packet_t *packet, uint32_t ms_after) +{ + if (!packet) { + return; + } + packet->send_at = (xTaskGetTickCount() * portTICK_PERIOD_MS) + ms_after; + packet->next = NULL; + if (!s_tx_queue_head || s_tx_queue_head->send_at > packet->send_at) { + packet->next = s_tx_queue_head; + s_tx_queue_head = packet; + return; + } + mdns_tx_packet_t *q = s_tx_queue_head; + while (q->next && q->next->send_at <= packet->send_at) { + q = q->next; + } + packet->next = q->next; + q->next = packet; +} + +/** + * @brief free all packets scheduled for sending + */ +void mdns_priv_clear_tx_queue(void) +{ + mdns_tx_packet_t *q; + while (s_tx_queue_head) { + q = s_tx_queue_head; + s_tx_queue_head = s_tx_queue_head->next; + mdns_priv_free_tx_packet(q); + } +} + +/** + * @brief clear packets scheduled for sending on a specific interface + * + * @param tcpip_if the interface + * @param ip_protocol pcb type V4/V6 + */ +void mdns_priv_clear_tx_queue_if(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_tx_packet_t *q, * p; + while (s_tx_queue_head && s_tx_queue_head->tcpip_if == tcpip_if && s_tx_queue_head->ip_protocol == ip_protocol) { + q = s_tx_queue_head; + s_tx_queue_head = s_tx_queue_head->next; + mdns_priv_free_tx_packet(q); + } + if (s_tx_queue_head) { + q = s_tx_queue_head; + while (q->next) { + if (q->next->tcpip_if == tcpip_if && q->next->ip_protocol == ip_protocol) { + p = q->next; + q->next = p->next; + mdns_priv_free_tx_packet(p); + } else { + q = q->next; + } + } + } +} + +/** + * @brief get the next packet scheduled for sending on a specific interface + * + * @param tcpip_if the interface + * @param ip_protocol pcb type V4/V6 + */ +mdns_tx_packet_t *mdns_priv_get_next_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + mdns_tx_packet_t *q = s_tx_queue_head; + while (q) { + if (q->tcpip_if == tcpip_if && q->ip_protocol == ip_protocol) { + return q; + } + q = q->next; + } + return NULL; +} + +/** + * @brief Called from timer task to run mDNS responder + * + * periodically checks first unqueued packet (from tx head). + * if it is scheduled to be transmitted, then pushes the packet to action queue to be handled. + * + */ +void mdns_priv_send_packets(void) +{ + mdns_priv_service_lock(); + mdns_tx_packet_t *p = s_tx_queue_head; + mdns_action_t *action = NULL; + + // find first unqueued packet + while (p && p->queued) { + p = p->next; + } + if (!p) { + mdns_priv_service_unlock(); + return; + } + while (p && (int32_t)(p->send_at - (xTaskGetTickCount() * portTICK_PERIOD_MS)) < 0) { + action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (action) { + action->type = ACTION_TX_HANDLE; + action->data.tx_handle.packet = p; + p->queued = true; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + p->queued = false; + } + } else { + HOOK_MALLOC_FAILED; + break; + } + //Find the next unqued packet + p = p->next; + } + mdns_priv_service_unlock(); +} + + + +/** + * @brief Remove and free service answer from answer list (destination) + */ +static void dealloc_scheduled_service_answers(mdns_out_answer_t **destination, mdns_service_t *service) +{ + mdns_out_answer_t *d = *destination; + if (!d) { + return; + } + while (d && d->service == service) { + *destination = d->next; + mdns_mem_free(d); + d = *destination; + } + while (d && d->next) { + mdns_out_answer_t *a = d->next; + if (a->service == service) { + d->next = a->next; + mdns_mem_free(a); + } else { + d = d->next; + } + } +} + +/** + * @brief Find, remove and free answers and scheduled packets for service + */ +void mdns_priv_remove_scheduled_service_packets(mdns_service_t *service) +{ + if (!service) { + return; + } + mdns_tx_packet_t *p = NULL; + mdns_tx_packet_t *q = s_tx_queue_head; + while (q) { + bool had_answers = (q->answers != NULL); + + dealloc_scheduled_service_answers(&(q->answers), service); + dealloc_scheduled_service_answers(&(q->additional), service); + dealloc_scheduled_service_answers(&(q->servers), service); + + if (mdns_priv_if_ready(q->tcpip_if, q->ip_protocol)) { + bool should_remove_questions = false; + mdns_priv_pcb_check_probing_services(q->tcpip_if, q->ip_protocol, service, + had_answers && q->answers == NULL, &should_remove_questions); + if (should_remove_questions && q->questions) { + mdns_out_question_t *qsn = NULL; + mdns_out_question_t *qs = q->questions; + if (qs->type == MDNS_TYPE_ANY + && qs->service && strcmp(qs->service, service->service) == 0 + && qs->proto && strcmp(qs->proto, service->proto) == 0) { + q->questions = q->questions->next; + mdns_mem_free(qs); + } else while (qs->next) { + qsn = qs->next; + if (qsn->type == MDNS_TYPE_ANY + && qsn->service && strcmp(qsn->service, service->service) == 0 + && qsn->proto && strcmp(qsn->proto, service->proto) == 0) { + qs->next = qsn->next; + mdns_mem_free(qsn); + break; + } + qs = qs->next; + } + } + } + + p = q; + q = q->next; + if (!p->questions && !p->answers && !p->additional && !p->servers) { + queueDetach(mdns_tx_packet_t, s_tx_queue_head, p); + mdns_priv_free_tx_packet(p); + } + } +} + +static void handle_packet(mdns_tx_packet_t *p) +{ + if (mdns_priv_pcb_is_off(p->tcpip_if, p->ip_protocol)) { + mdns_priv_free_tx_packet(p); + return; + } + mdns_priv_dispatch_tx_packet(p); + mdns_priv_pcb_schedule_tx_packet(p); +} + +static void send_packet(mdns_tx_packet_t *packet) +{ + mdns_tx_packet_t *p = s_tx_queue_head; + // packet to be handled should be at tx head, but must be consistent with the one pushed to action queue + if (p && p == packet && p->queued) { + p->queued = false; // clearing, as the packet might be reused (pushed and transmitted again) + s_tx_queue_head = p->next; + handle_packet(p); + } else { + ESP_LOGD(TAG, "Skipping transmit of an unexpected packet!"); + } +} + +/** + * @brief Remove and free answer from answer list (destination) + */ +void mdns_priv_dealloc_answer(mdns_out_answer_t **destination, uint16_t type, mdns_srv_item_t *service) +{ + mdns_out_answer_t *d = *destination; + if (!d) { + return; + } + mdns_srv_item_t s = {NULL, NULL}; + if (!service) { + service = &s; + } + if (d->type == type && d->service == service->service) { + *destination = d->next; + mdns_mem_free(d); + return; + } + while (d->next) { + mdns_out_answer_t *a = d->next; + if (a->type == type && a->service == service->service) { + d->next = a->next; + mdns_mem_free(a); + return; + } + d = d->next; + } +} + +void mdns_priv_send_action(mdns_action_t *action, mdns_action_subtype_t type) +{ + if (action->type != ACTION_TX_HANDLE) { + abort(); + } + if (type == ACTION_RUN) { + send_packet(action->data.tx_handle.packet); + } + // ACTION_CLEANUP: do not free the packet. Until send_packet() unlinks it, the packet is still + // in the TX queue, which owns it and frees it (e.g. in mdns_priv_clear_tx_queue()) +} diff --git a/managed_components/espressif__mdns/mdns_service.c b/managed_components/espressif__mdns/mdns_service.c new file mode 100644 index 0000000..ec49443 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_service.c @@ -0,0 +1,476 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" +#include "esp_check.h" +#include "mdns.h" +#include "mdns_mem_caps.h" +#include "mdns_utils.h" +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#include "mdns_browser.h" +#endif +#include "mdns_netif.h" +#include "mdns_send.h" +#include "mdns_receive.h" +#include "mdns_querier.h" +#include "mdns_pcb.h" +#include "mdns_responder.h" +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#include "mdns_cache.h" +#endif + +#define MDNS_SERVICE_STACK_DEPTH CONFIG_MDNS_TASK_STACK_SIZE +#define MDNS_TASK_PRIORITY CONFIG_MDNS_TASK_PRIORITY +#if (MDNS_TASK_PRIORITY > ESP_TASK_PRIO_MAX) +#error "mDNS task priority is higher than ESP_TASK_PRIO_MAX" +#elif (MDNS_TASK_PRIORITY > ESP_TASKD_EVENT_PRIO) +#warning "mDNS task priority is higher than ESP_TASKD_EVENT_PRIO, mDNS library might not work correctly" +#endif +#define MDNS_TASK_AFFINITY CONFIG_MDNS_TASK_AFFINITY + +/* Classic dynamic create only when the stack must stay internal and FreeRTOS won't place it in SPIRAM. */ +#if !CONFIG_MDNS_TASK_CREATE_FROM_SPIRAM && !CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM +#define MDNS_TASK_USE_SIMPLE_CREATE 1 +#else +#define MDNS_TASK_USE_SIMPLE_CREATE 0 +#endif + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#define MDNS_CACHE_SYNC_TIMEOUT_MS 1000 +#endif + +#define MDNS_SERVICE_LOCK() xSemaphoreTake(s_service_semaphore, portMAX_DELAY) +#define MDNS_SERVICE_UNLOCK() xSemaphoreGive(s_service_semaphore) + +static volatile TaskHandle_t s_service_task_handle = NULL; +static SemaphoreHandle_t s_service_semaphore = NULL; +#if !MDNS_TASK_USE_SIMPLE_CREATE +static StackType_t *s_stack_buffer; +#endif +static QueueHandle_t s_action_queue; +static esp_timer_handle_t s_timer_handle; + +static const char *TAG = "mdns_service"; + +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES +static inline char nibble_to_hex(int var) +{ + return var > 9 ? var - 10 + 'a' : var + '0'; +} +#endif + +/** + * @brief Performs interface changes based on system events or custom commands + */ +static void perform_event_action(mdns_if_t mdns_if, mdns_event_actions_t action) +{ + if (!mdns_priv_is_server_init() || mdns_if >= MDNS_MAX_INTERFACES) { + return; + } + if (action & MDNS_EVENT_ENABLE_IP4) { + mdns_priv_pcb_enable(mdns_if, MDNS_IP_PROTOCOL_V4); + } + if (action & MDNS_EVENT_ENABLE_IP6) { + mdns_priv_pcb_enable(mdns_if, MDNS_IP_PROTOCOL_V6); + } + if (action & MDNS_EVENT_DISABLE_IP4) { + mdns_priv_pcb_disable(mdns_if, MDNS_IP_PROTOCOL_V4); + } + if (action & MDNS_EVENT_DISABLE_IP6) { + mdns_priv_pcb_disable(mdns_if, MDNS_IP_PROTOCOL_V6); + } + if (action & MDNS_EVENT_ANNOUNCE_IP4) { + mdns_priv_pcb_announce(mdns_if, MDNS_IP_PROTOCOL_V4, NULL, 0, true); + } + if (action & MDNS_EVENT_ANNOUNCE_IP6) { + mdns_priv_pcb_announce(mdns_if, MDNS_IP_PROTOCOL_V6, NULL, 0, true); + } + +#ifdef CONFIG_MDNS_RESPOND_REVERSE_QUERIES +#ifdef CONFIG_LWIP_IPV4 + if (action & MDNS_EVENT_IP4_REVERSE_LOOKUP) { + esp_netif_ip_info_t if_ip_info; + if (esp_netif_get_ip_info(mdns_priv_get_esp_netif(mdns_if), &if_ip_info) == ESP_OK) { + esp_ip4_addr_t *ip = &if_ip_info.ip; + char *reverse_query_name = NULL; + if (asprintf(&reverse_query_name, "%d.%d.%d.%d.in-addr", + esp_ip4_addr4_16(ip), esp_ip4_addr3_16(ip), + esp_ip4_addr2_16(ip), esp_ip4_addr1_16(ip)) > 0 && reverse_query_name) { + ESP_LOGD(TAG, "Registered reverse query: %s.arpa", reverse_query_name); + mdns_priv_delegate_hostname_add(reverse_query_name, NULL); + } + } + } +#endif /* CONFIG_LWIP_IPV4 */ +#ifdef CONFIG_LWIP_IPV6 + if (action & MDNS_EVENT_IP6_REVERSE_LOOKUP) { + esp_ip6_addr_t addr6; + if (!esp_netif_get_ip6_linklocal(mdns_priv_get_esp_netif(mdns_if), &addr6) && !mdns_utils_ipv6_address_is_zero(addr6)) { + uint8_t *paddr = (uint8_t *)&addr6.addr; + const char sub[] = "ip6"; + const size_t query_name_size = 4 * sizeof(addr6.addr) /* (2 nibbles + 2 dots)/per byte of IP address */ + sizeof(sub); + char *reverse_query_name = mdns_mem_malloc(query_name_size); + if (reverse_query_name) { + char *ptr = &reverse_query_name[query_name_size]; // point to the end + memcpy(ptr - sizeof(sub), sub, sizeof(sub)); // copy the IP sub-domain + ptr -= sizeof(sub) + 1; // move before the sub-domain + while (reverse_query_name < ptr) { // continue populating reverse query from the end + *ptr-- = '.'; // nibble by nibble, until we reach the beginning + *ptr-- = nibble_to_hex(((*paddr) >> 4) & 0x0F); + *ptr-- = '.'; + *ptr-- = nibble_to_hex((*paddr) & 0x0F); + paddr++; + } + ESP_LOGD(TAG, "Registered reverse query: %s.arpa", reverse_query_name); + mdns_priv_delegate_hostname_add(reverse_query_name, NULL); + } + } + } +#endif /* CONFIG_LWIP_IPV6 */ +#endif /* CONFIG_MDNS_RESPOND_REVERSE_QUERIES */ +} + +/** + * @brief Free action data + */ +static void free_action(mdns_action_t *action) +{ + switch (action->type) { + case ACTION_SEARCH_ADD: + case ACTION_SEARCH_SEND: + case ACTION_SEARCH_END: + mdns_priv_query_action(action, ACTION_CLEANUP); + break; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + case ACTION_BROWSE_START: + case ACTION_BROWSE_END: + mdns_priv_browse_action(action, ACTION_CLEANUP); + break; +#endif + case ACTION_TX_HANDLE: + mdns_priv_send_action(action, ACTION_CLEANUP); + break; + case ACTION_RX_HANDLE: + mdns_priv_receive_action(action, ACTION_CLEANUP); + break; + case ACTION_HOSTNAME_SET: + case ACTION_INSTANCE_SET: + case ACTION_DELEGATE_HOSTNAME_SET_ADDR: + case ACTION_DELEGATE_HOSTNAME_REMOVE: + case ACTION_DELEGATE_HOSTNAME_ADD: + mdns_priv_responder_action(action, ACTION_CLEANUP); + break; + default: + break; + } + mdns_mem_free(action); +} + +/** + * @brief Called from service thread to execute given action + */ +static void execute_action(mdns_action_t *action) +{ + switch (action->type) { + case ACTION_SYSTEM_EVENT: + perform_event_action(action->data.sys_event.interface, action->data.sys_event.event_action); + break; + case ACTION_SEARCH_ADD: + case ACTION_SEARCH_SEND: + case ACTION_SEARCH_END: + mdns_priv_query_action(action, ACTION_RUN); + break; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + case ACTION_BROWSE_START: + case ACTION_BROWSE_END: + mdns_priv_browse_action(action, ACTION_RUN); + break; +#endif + + case ACTION_TX_HANDLE: + mdns_priv_send_action(action, ACTION_RUN); + break; + case ACTION_RX_HANDLE: + mdns_priv_receive_action(action, ACTION_RUN); + break; + case ACTION_HOSTNAME_SET: + case ACTION_INSTANCE_SET: + case ACTION_DELEGATE_HOSTNAME_ADD: + case ACTION_DELEGATE_HOSTNAME_SET_ADDR: + case ACTION_DELEGATE_HOSTNAME_REMOVE: + mdns_priv_responder_action(action, ACTION_RUN); + break; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + case ACTION_BROWSE_SEND_BY_IP_PROTOCOL: + mdns_priv_browse_send_by_ip_protocol(action->data.browse_send.interface, action->data.browse_send.ip_protocol); + break; +#endif + default: + break; + } + mdns_mem_free(action); +} + +/** + * @brief the main MDNS service task. Packets are received and parsed here + */ +static void service_task(void *pvParameters) +{ + mdns_action_t *a = NULL; + TickType_t wait_ticks = portMAX_DELAY; +#ifdef CONFIG_MDNS_ENABLE_BROWSE + wait_ticks = pdMS_TO_TICKS(MDNS_CACHE_SYNC_TIMEOUT_MS); +#endif + + for (;;) { + if (mdns_priv_is_server_init() && s_action_queue) { + BaseType_t received = xQueueReceive(s_action_queue, &a, wait_ticks); + if (received == pdTRUE) { + assert(a); + if (a->type == ACTION_TASK_STOP) { + break; + } + } + + MDNS_SERVICE_LOCK(); + if (received == pdTRUE) { + execute_action(a); + } +#ifdef CONFIG_MDNS_ENABLE_BROWSE + // Clean up stale records, or process updates from rx events. + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + MDNS_SERVICE_UNLOCK(); + } else { + vTaskDelay(500 * portTICK_PERIOD_MS); + } + } + s_service_task_handle = NULL; + vTaskDelay(portMAX_DELAY); +} + +static void timer_cb(void *arg) +{ + mdns_priv_send_packets(); + mdns_priv_query_start_stop(); +} + +static esp_err_t start_timer(void) +{ + esp_timer_create_args_t timer_conf = { + .callback = timer_cb, + .arg = NULL, + .dispatch_method = ESP_TIMER_TASK, + .name = "mdns_timer" + }; + esp_err_t err = esp_timer_create(&timer_conf, &(s_timer_handle)); + if (err) { + return err; + } + return esp_timer_start_periodic(s_timer_handle, MDNS_TIMER_PERIOD_US); +} + +static esp_err_t stop_timer(void) +{ + esp_err_t err = ESP_OK; + if (s_timer_handle) { + err = esp_timer_stop(s_timer_handle); + if (err) { + return err; + } + err = esp_timer_delete(s_timer_handle); + } + return err; +} + +static esp_err_t create_task_with_caps(void) +{ + esp_err_t ret = ESP_OK; + +#if MDNS_TASK_USE_SIMPLE_CREATE + BaseType_t res = xTaskCreatePinnedToCore(service_task, "mdns", MDNS_SERVICE_STACK_DEPTH, NULL, MDNS_TASK_PRIORITY, + (TaskHandle_t *)&s_service_task_handle, MDNS_TASK_AFFINITY); + ESP_RETURN_ON_FALSE(res == pdPASS && s_service_task_handle != NULL, ESP_FAIL, TAG, "failed to create task for the mDNS"); + return ret; +#else + static StaticTask_t mdns_task_buffer; + + s_stack_buffer = mdns_mem_task_malloc(MDNS_SERVICE_STACK_DEPTH); + ESP_GOTO_ON_FALSE(s_stack_buffer != NULL, ESP_FAIL, alloc_failed, TAG, "failed to allocate memory for the mDNS task's stack"); + + s_service_task_handle = xTaskCreateStaticPinnedToCore(service_task, "mdns", MDNS_SERVICE_STACK_DEPTH, NULL, MDNS_TASK_PRIORITY, + s_stack_buffer, &mdns_task_buffer, MDNS_TASK_AFFINITY); + ESP_GOTO_ON_FALSE(s_service_task_handle != NULL, ESP_FAIL, err, TAG, "failed to create task for the mDNS"); + + return ret; + +alloc_failed: + HOOK_MALLOC_FAILED; +err: + mdns_mem_task_free(s_stack_buffer); + return ret; +#endif +} + +/** + * @brief Start the service thread if not running + * + * @return + * - ESP_OK on success + * - ESP_FAIL on error + */ +static esp_err_t service_task_start(void) +{ + esp_err_t ret = ESP_OK; + if (!s_service_semaphore) { + s_service_semaphore = xSemaphoreCreateMutex(); + ESP_RETURN_ON_FALSE(s_service_semaphore != NULL, ESP_FAIL, TAG, "Failed to create the mDNS service lock"); + } + MDNS_SERVICE_LOCK(); + ESP_GOTO_ON_ERROR(start_timer(), err, TAG, "Failed to start the mDNS service timer"); + + if (!s_service_task_handle) { + ESP_GOTO_ON_ERROR(create_task_with_caps(), err_stop_timer, TAG, "Failed to start the mDNS service task"); +#if !MDNS_TASK_USE_SIMPLE_CREATE && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0) && !CONFIG_IDF_TARGET_LINUX + StackType_t *mdns_debug_stack_buffer; + StaticTask_t *mdns_debug_task_buffer; + xTaskGetStaticBuffers(s_service_task_handle, &mdns_debug_stack_buffer, &mdns_debug_task_buffer); + ESP_LOGD(TAG, "mdns_debug_stack_buffer:%p mdns_debug_task_buffer:%p\n", mdns_debug_stack_buffer, mdns_debug_task_buffer); +#endif + } + MDNS_SERVICE_UNLOCK(); + return ret; + +err_stop_timer: + stop_timer(); +err: + MDNS_SERVICE_UNLOCK(); + vSemaphoreDelete(s_service_semaphore); + s_service_semaphore = NULL; + return ret; +} + +/** + * @brief Stop the service thread + * + * @return + * - ESP_OK + */ +static esp_err_t service_task_stop(void) +{ + stop_timer(); + if (s_service_task_handle) { + TaskHandle_t task_handle = s_service_task_handle; + mdns_action_t action; + mdns_action_t *a = &action; + action.type = ACTION_TASK_STOP; + if (xQueueSend(s_action_queue, &a, (TickType_t)0) != pdPASS) { + s_service_task_handle = NULL; + } + while (s_service_task_handle) { + vTaskDelay(10 / portTICK_PERIOD_MS); + } + vTaskDelete(task_handle); + } + vSemaphoreDelete(s_service_semaphore); + s_service_semaphore = NULL; + return ESP_OK; +} + +void mdns_priv_service_lock(void) +{ + MDNS_SERVICE_LOCK(); +} + +void mdns_priv_service_unlock(void) +{ + MDNS_SERVICE_UNLOCK(); +} + +esp_err_t mdns_init(void) +{ + esp_err_t err = ESP_OK; + + if (mdns_priv_is_server_init()) { + return err; + } + + if (mdns_priv_responder_init() != ESP_OK) { + return ESP_ERR_NO_MEM; + } + + s_action_queue = xQueueCreate(MDNS_ACTION_QUEUE_LEN, sizeof(mdns_action_t *)); + if (!s_action_queue) { + err = ESP_ERR_NO_MEM; + goto free_responder; + } + + if (mdns_priv_netif_init() != ESP_OK) { + err = ESP_FAIL; + goto free_queue; + } + + if (service_task_start()) { + //service start failed! + err = ESP_FAIL; + goto free_all_and_disable_pcbs; + } + + return ESP_OK; + +free_all_and_disable_pcbs: + mdns_priv_netif_deinit(); +free_queue: + vQueueDelete(s_action_queue); +free_responder: + mdns_priv_responder_free(); + return err; +} + +void mdns_free(void) +{ + if (!mdns_priv_is_server_init()) { + return; + } + + // Unregister handlers before destroying the mdns internals to avoid receiving async events while deinit + mdns_priv_netif_unregister_predefined_handlers(); + + mdns_service_remove_all(); + service_task_stop(); +#if !MDNS_TASK_USE_SIMPLE_CREATE + mdns_mem_task_free(s_stack_buffer); +#endif + mdns_priv_pcb_deinit(); + if (s_action_queue) { + mdns_action_t *c; + while (xQueueReceive(s_action_queue, &c, 0) == pdTRUE) { + free_action(c); + } + vQueueDelete(s_action_queue); + } + mdns_priv_clear_tx_queue(); + mdns_priv_query_free(); +#ifdef CONFIG_MDNS_ENABLE_BROWSE + mdns_priv_browse_free(); + mdns_priv_cache_clear(); +#endif + mdns_priv_responder_free(); +} + +bool mdns_priv_queue_action(mdns_action_t *action) +{ + if (xQueueSend(s_action_queue, &action, (TickType_t)0) != pdPASS) { + return false; + } + return true; +} diff --git a/managed_components/espressif__mdns/mdns_utils.c b/managed_components/espressif__mdns/mdns_utils.c new file mode 100644 index 0000000..11c8c85 --- /dev/null +++ b/managed_components/espressif__mdns/mdns_utils.c @@ -0,0 +1,318 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include "sdkconfig.h" +#include "mdns_private.h" +#include "mdns_mem_caps.h" +#include "esp_log.h" +#include "mdns_utils.h" +#include "mdns_responder.h" + +static const char *TAG = "mdns_utils"; +static const char *MDNS_DEFAULT_DOMAIN = "local"; +static const char *MDNS_SUB_STR = "_sub"; + +#define MDNS_FQDN_MAX_COMPRESSION_DEPTH 16 + +static const uint8_t *mdns_utils_read_fqdn_impl(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, + char *buf, size_t packet_len, unsigned compression_depth) +{ + size_t index = 0; + const uint8_t *packet_end = packet + packet_len; + while (start + index < packet_end && start[index]) { + if (name->parts == 4) { + name->invalid = true; + } + uint8_t len = start[index++]; + if (len < 0xC0) { + if (len > 63) { + //length can not be more than 63 + return NULL; + } + uint8_t i; + for (i = 0; i < len; i++) { + if (start + index >= packet_end) { + return NULL; + } + buf[i] = start[index++]; + } + buf[len] = '\0'; + if (name->parts == 1 && buf[0] != '_' + && (strcasecmp(buf, MDNS_DEFAULT_DOMAIN) != 0) + && (strcasecmp(buf, "arpa") != 0) +#ifndef CONFIG_MDNS_RESPOND_REVERSE_QUERIES + && (strcasecmp(buf, "ip6") != 0) + && (strcasecmp(buf, "in-addr") != 0) +#endif + ) { + strlcat(name->host, ".", sizeof(name->host)); + strlcat(name->host, buf, sizeof(name->host)); + } else if (strcasecmp(buf, MDNS_SUB_STR) == 0) { + // A DNS-SD subtype name has the form ._sub.... + // Keep the subtype label in host, but reject _sub in any other position. + if (name->parts != 1 || name->sub) { + name->invalid = true; + } else { + name->sub = 1; + } + } else if (!name->invalid) { + char *mdns_name_ptrs[] = {name->host, name->service, name->proto, name->domain}; + memcpy(mdns_name_ptrs[name->parts++], buf, len + 1); + } + } else { + if (start + index >= packet_end) { + // truncated compression pointer (second byte would be out of bounds) + return NULL; + } + size_t address = (((uint16_t)len & 0x3F) << 8) | start[index++]; + if ((packet + address) >= start) { + //reference address can not be after where we are + return NULL; + } + if (compression_depth >= MDNS_FQDN_MAX_COMPRESSION_DEPTH) { + return NULL; + } + if (mdns_utils_read_fqdn_impl(packet, packet + address, name, buf, packet_len, + compression_depth + 1)) { + return start + index; + } + return NULL; + } + } + return start + index + 1; +} + +const uint8_t *mdns_utils_read_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, char *buf, + size_t packet_len) +{ + return mdns_utils_read_fqdn_impl(packet, start, name, buf, packet_len, 0); +} + +const uint8_t *mdns_utils_parse_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, size_t packet_len) +{ + name->parts = 0; + name->sub = 0; + name->host[0] = 0; + name->service[0] = 0; + name->proto[0] = 0; + name->domain[0] = 0; + name->invalid = false; + + static char buf[MDNS_NAME_BUF_LEN]; + + const uint8_t *next_data = (uint8_t *) mdns_utils_read_fqdn(packet, start, name, buf, packet_len); + if (!next_data) { + return 0; + } + if (name->sub && name->parts != 4) { + name->invalid = true; + } + if (!name->parts || name->invalid) { + return next_data; + } + if (name->parts == 3) { + memmove((uint8_t *)name + (MDNS_NAME_BUF_LEN), (uint8_t *)name, 3 * (MDNS_NAME_BUF_LEN)); + name->host[0] = 0; + } else if (name->parts == 2) { + memmove((uint8_t *)(name->domain), (uint8_t *)(name->service), (MDNS_NAME_BUF_LEN)); + name->service[0] = 0; + name->proto[0] = 0; + } + if (strcasecmp(name->domain, MDNS_DEFAULT_DOMAIN) == 0 || strcasecmp(name->domain, "arpa") == 0) { + return next_data; + } + name->invalid = true; // mark the current name invalid, but continue with other question + return next_data; +} + +bool mdns_utils_hostname_is_ours(const char *hostname) +{ + if (!mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname()) && + strcasecmp(hostname, mdns_priv_get_global_hostname()) == 0) { + return true; + } + mdns_host_item_t *host = mdns_priv_get_hosts(); + while (host != NULL) { + if (strcasecmp(hostname, host->hostname) == 0) { + return true; + } + host = host->next; + } + return false; +} + +bool mdns_utils_service_match(const mdns_service_t *srv, const char *service, const char *proto, + const char *hostname) +{ + if (!service || !proto || !srv || !srv->hostname) { + return false; + } + return !strcasecmp(srv->service, service) && !strcasecmp(srv->proto, proto) && + (mdns_utils_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); +} + +mdns_srv_item_t *mdns_utils_get_service_item(const char *service, const char *proto, const char *hostname) +{ + mdns_srv_item_t *s = mdns_priv_get_services(); + while (s) { + if (mdns_utils_service_match(s->service, service, proto, hostname)) { + return s; + } + s = s->next; + } + return NULL; +} + +mdns_srv_item_t *mdns_utils_get_service_item_instance(const char *instance, const char *service, const char *proto, + const char *hostname) +{ + mdns_srv_item_t *s = mdns_priv_get_services(); + while (s) { + if (instance) { + if (mdns_utils_service_match_instance(s->service, instance, service, proto, hostname)) { + return s; + } + } else { + if (mdns_utils_service_match(s->service, service, proto, hostname)) { + return s; + } + } + s = s->next; + } + return NULL; +} + +bool mdns_utils_service_match_instance(const mdns_service_t *srv, const char *instance, const char *service, + const char *proto, const char *hostname) +{ + // service and proto must be supplied, if not this instance won't match + if (!service || !proto) { + return false; + } + // instance==NULL -> mdns_utils_instance_name_match() will check the default instance + // hostname==NULL -> matches if instance, service and proto matches + return !strcasecmp(srv->service, service) && mdns_utils_instance_name_match(srv->instance, instance) && + !strcasecmp(srv->proto, proto) && (mdns_utils_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); +} + +static const char *get_default_instance_name(void) +{ + const char* instance = mdns_priv_get_instance(); + if (!mdns_utils_str_null_or_empty(instance)) { + return instance; + } + + const char* host = mdns_priv_get_global_hostname(); + if (!mdns_utils_str_null_or_empty(host)) { + return host; + } + return NULL; +} + +/** + * @brief Get the service name of a service + */ +const char *mdns_utils_get_service_instance_name(const mdns_service_t *service) +{ + if (service && !mdns_utils_str_null_or_empty(service->instance)) { + return service->instance; + } + + return get_default_instance_name(); +} + + +bool mdns_utils_instance_name_match(const char *lhs, const char *rhs) +{ + if (lhs == NULL) { + lhs = get_default_instance_name(); + } + if (rhs == NULL) { + rhs = get_default_instance_name(); + } + return !strcasecmp(lhs, rhs); +} + + +mdns_ip_addr_t *mdns_utils_copy_address_list(const mdns_ip_addr_t *address_list) +{ + mdns_ip_addr_t *head = NULL; + mdns_ip_addr_t *tail = NULL; + while (address_list != NULL) { + mdns_ip_addr_t *addr = (mdns_ip_addr_t *)mdns_mem_malloc(sizeof(mdns_ip_addr_t)); + if (addr == NULL) { + HOOK_MALLOC_FAILED; + mdns_utils_free_address_list(head); + return NULL; + } + addr->addr = address_list->addr; + addr->next = NULL; + if (head == NULL) { + head = addr; + tail = addr; + } else { + tail->next = addr; + tail = tail->next; + } + address_list = address_list->next; + } + return head; +} + +void mdns_utils_free_address_list(mdns_ip_addr_t *address_list) +{ + while (address_list != NULL) { + mdns_ip_addr_t *next = address_list->next; + mdns_mem_free(address_list); + address_list = next; + } +} + +#ifdef CONFIG_LWIP_IPV6 +bool mdns_utils_ipv6_address_is_zero(esp_ip6_addr_t ip6) +{ + uint8_t i; + uint8_t *data = (uint8_t *)ip6.addr; + for (i = 0; i < MDNS_UTILS_SIZEOF_IP6_ADDR; i++) { + if (data[i]) { + return false; + } + } + return true; +} +#endif /* CONFIG_LWIP_IPV6 */ + +uint8_t mdns_utils_append_u16(uint8_t *packet, uint16_t *index, uint16_t value) +{ + if ((*index + 1) >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + mdns_utils_append_u8(packet, index, (value >> 8) & 0xFF); + mdns_utils_append_u8(packet, index, value & 0xFF); + return 2; +} + +void mdns_utils_free_txt_linked_list(mdns_txt_linked_item_t *txt) +{ + while (txt) { + mdns_txt_linked_item_t *next = txt->next; + mdns_mem_free((char *)txt->key); + mdns_mem_free(txt->value); + mdns_mem_free(txt); + txt = next; + } +} + +bool mdns_utils_str_case_equal(const char *a, const char *b) +{ + return !mdns_utils_str_null_or_empty(a) && !mdns_utils_str_null_or_empty(b) && strcasecmp(a, b) == 0; +} + +bool mdns_utils_str_case_equal_nullable(const char *a, const char *b) +{ + return (mdns_utils_str_null_or_empty(a) && mdns_utils_str_null_or_empty(b)) || mdns_utils_str_case_equal(a, b); +} diff --git a/managed_components/espressif__mdns/mem_prefix_script.py b/managed_components/espressif__mdns/mem_prefix_script.py new file mode 100644 index 0000000..b9af09d --- /dev/null +++ b/managed_components/espressif__mdns/mem_prefix_script.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 +import re +import sys + +# Configurable prefix for memory functions +MDNS_MEM_PREFIX = 'mdns_mem_' # Change this to modify the prefix + + +def add_prefix_to_mem_funcs(content): + # List of memory functions to prefix + mem_funcs = [ + 'malloc', + 'calloc', + 'free', + 'strdup', + 'strndup' + ] + + # Create regex pattern matching the memory functions but not already prefixed ones + pattern = fr'(?') + sys.exit(1) + + process_file(sys.argv[1]) diff --git a/managed_components/espressif__mdns/private_include/mdns_browser.h b/managed_components/espressif__mdns/private_include/mdns_browser.h new file mode 100644 index 0000000..f35553d --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_browser.h @@ -0,0 +1,101 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Free browse item queue + * + * @note Called from mdns_free() + */ +void mdns_priv_browse_free(void); + +/** + * @brief Check if a running browse `_service._proto` exists. + * + * @param service Service name. + * @param proto Protocol name. + * @return true if a running browse `_service._proto` exists, false otherwise. + */ +bool mdns_priv_browse_has_service(const char *service, const char *proto); + +/** + * @brief Check if a running browse `_service._proto` with the given subtype exists. + * + * @param service Service name. + * @param proto Protocol name. + * @param subtype Subtype name, or NULL to match browses without subtype. + * @return true if a running browse with identical service, proto and subtype exists, false otherwise. + */ +bool mdns_priv_browse_has_subtype(const char *service, const char *proto, const char *subtype); + +/** + * @brief Looks for a running browse item as consumer of the provided record data + * + * @note Called from the packet parser (mdns_receive.c) + * + * @return matching browse item, or NULL if not found + */ +mdns_browse_t *mdns_priv_browse_find_consumer(mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Send out browse queries by IP protocol + * + * @note Called from the network events (mdns_netif.c) + * @note Calls (indirectly) search-send from mdns_querier.c, which sends out the query + */ +void mdns_priv_browse_send_by_ip_protocol(mdns_if_t mdns_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Perform action from mdns service queue + * + * @note Called by `free_action()` and `execute_action()` in mdns_service.c + */ +void mdns_priv_browse_action(mdns_action_t *action, mdns_action_subtype_t type); + +/** + * @brief Build temporary result and queue for sync from service cache + * + * @param entry Owner cache entry. + * @param service Updated service cache. + * @param records Bitmask of cache record types to sync. + * + * @note Called from mdns_priv_cache_process_sync() in mdns_cache.c + * + * @return true if all matching browses have been notified about the updated service, false otherwise + */ +bool mdns_priv_browse_update_from_service_cache(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_cache_record_mask_t records); + +/** + * @brief Notify one browse about one visible cache service. + * + * @return true if browse is successfully notified, false otherwise + */ +bool mdns_priv_browse_notify_from_service_cache(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_browse_t *browse); + +/** + * @brief Notify the affected normal/subtype browse about a PTR goodbye. + * + * @param subtype The PTR subtype, or NULL for the base PTR. + * + * @note Used for both goodbye and natural expiration. + * + * @note Must be called before the PTR/subtype is removed from the cache to avoid UAF. + */ +bool mdns_priv_browse_notify_ptr_goodbye_from_service_cache(const mdns_cache_entry_t *entry, + const mdns_service_cache_t *service, + const char *subtype); +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_cache.h b/managed_components/espressif__mdns/private_include/mdns_cache.h new file mode 100644 index 0000000..8cd020a --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_cache.h @@ -0,0 +1,204 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Check if a host has a service by hostname, esp_netif, ip_protocol, service, and proto. + * + * @param hostname The hostname to check. + * @param esp_netif Pointer to the esp_netif to check. + * @param ip_protocol IP protocol to check. + * @param service The service name to check. + * @param proto The protocol to check. + * + * @return true if the host has the service, false otherwise. + */ +bool mdns_priv_cache_host_has_service(const char *hostname, const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *service, const char *proto); + +/** + * @brief Find the subtype node in a service cache by subtype name. + * + * @param service Pointer to the service cache. + * @param subtype The subtype name to find. + * + * @return Pointer to the subtype node if found, NULL otherwise. + */ +const mdns_cache_subtype_t *mdns_priv_cache_service_find_subtype(const mdns_service_cache_t *service, const char *subtype); + +/** + * @brief Update a PTR record for service cache `_service._proto` with possible subtype. + * + * @param esp_netif Pointer to the esp_netif. + * @param ip_protocol IP protocol. + * @param instance The instance name. + * @param service The service name. + * @param proto The protocol. + * @param subtype The subtype, or null/empty for base PTR record. + * @param ttl The PTR TTL. + * + * @return The result of the update, see @ref mdns_cache_update_result_t. + * + * @note The PTR record will be marked to-sync when: + * - A new service is added to the cache. + * - A new subtype is appended to the service cache. + * - The PTR TTL is updated. + * + * @note A TTL=0 goodbye notifies only the matching base/subtype browsers and + * removes only that PTR record. Other cached records are preserved. + */ +mdns_cache_update_result_t mdns_priv_cache_update_ptr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *instance, const char *service, const char *proto, + const char *subtype, uint32_t ttl); + +/** + * @brief Update a SRV record for service cache `instance._service._proto`. + * + * @param esp_netif Pointer to the esp_netif. + * @param ip_protocol IP protocol. + * @param hostname The hostname to update. + * @param instance The instance name. + * @param service The service name. + * @param proto The protocol. + * @param priority The priority to update. + * @param weight The weight to update. + * @param port The port to update. + * @param ttl The SRV TTL. + * + * @return The result of the update, see @ref mdns_cache_update_result_t. + * + * @note The SRV record will be marked to-sync when: + * - A new SRV record is added to the service cache. + * - The service cache is moved to the host designated by @ref hostname. + * - The SRV record is updated. + * - Receives a TTL=0 goodbye: the SRV record will be marked as absent. + */ +mdns_cache_update_result_t mdns_priv_cache_update_srv(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const char *instance, const char *service, + const char *proto, uint16_t priority, uint16_t weight, + uint16_t port, uint32_t ttl); + +/** + * @brief Update a TXT record for service cache `instance._service._proto`. + * + * @param esp_netif Pointer to the esp_netif. + * @param ip_protocol IP protocol. + * @param instance The instance name. + * @param service The service name. + * @param proto The protocol. + * @param txt The TXT record to update. + * @param ttl The TXT TTL. + * + * @return The result of the update, see @ref mdns_cache_update_result_t. + * + * @note The TXT record will be marked to-sync when: + * - A new TXT record is added to the service cache. + * - The TXT record is updated. + * - Receives a TTL=0 goodbye: the TXT record will be marked as absent. + */ +mdns_cache_update_result_t mdns_priv_cache_update_txt(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *instance, const char *service, const char *proto, + mdns_txt_linked_item_t *txt, uint32_t ttl); + +/** + * @brief Update an A/AAAA record for a cache entry `hostname`. + * + * @param esp_netif Pointer to the esp_netif. + * @param ip_protocol IP protocol. + * @param hostname The hostname to update. + * @param addr The address to update. + * @param ttl The TTL. + * + * @return The result of the update, see @ref mdns_cache_update_result_t. + * + * @note When an A/AAAA record is updated (added, removed, or updated), + * all services under this cache entry will be marked to-sync for browses. + */ +mdns_cache_update_result_t mdns_priv_cache_update_addr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const esp_ip_addr_t *addr, uint32_t ttl); + +/** + * @brief Update an A/AAAA record for an existing cache entry `hostname`. + * + * @param esp_netif Pointer to the esp_netif. + * @param ip_protocol IP protocol. + * @param hostname The hostname to update. + * @param addr The address to update. + * @param ttl The TTL. + * + * @return The result of the update, see @ref mdns_cache_update_result_t. + * If the cache entry does not exist, or no consumers subscribe to the hostname or service under the hostname, + * return MDNS_CACHE_NO_CHANGE. + * + * @note When an A/AAAA record is updated (added, removed, or updated), + * all services under this cache entry will be marked to-sync for browses. + * + * @note Used by browses in case ADDR records come before SRV record. + */ +mdns_cache_update_result_t mdns_priv_cache_update_existing_addr(const esp_netif_t *esp_netif, mdns_ip_protocol_t ip_protocol, + const char *hostname, const esp_ip_addr_t *addr, uint32_t ttl); + +/** + * @brief Remove expired records from the entire cache. + * + * @param now_us The current time in microseconds from esp_timer_get_time(). + * + * @note This function is called in mDNS service task while holding service lock. + * PTR expiration notifies browses immediately, other records are marked to-sync for browses. + */ +void mdns_priv_cache_remove_expired_records(int64_t now_us); + +/** + * @brief Trim down the expiration time of unsubscribed records. + * + * @param now_us The current time in microseconds from esp_timer_get_time(). + * + * @note This function scans through s_expiry and sets the expiration time of unsubscribed records to + * `min(expires_at_us, now_us + MDNS_CACHE_UNSUBSCRIBED_GRACE_SEC * MDNS_US_PER_SEC)`. + * Finally cleaned up in service task by `mdns_priv_cache_remove_expired_records()`. + */ +void mdns_priv_cache_trim_unsubscribed_records(int64_t now_us); + +/** + * @brief Clear all cache entries. + */ +void mdns_priv_cache_clear(void); + +/** + * @brief Convert a service cache to a mdns_result_t. + * + * @param entry Pointer to the cache entry. + * @param service Pointer to the service cache. + * @param out_result Pointer to the output mdns_result_t. + * @return ESP_OK on success, ESP_ERR_NO_MEM on allocation failure. + */ +esp_err_t mdns_priv_service_cache_to_result(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_result_t **out_result); + +/** + * @brief Process all pending synchronization cache entries. + * + * @note This function is called by the MDNS task to process all pending synchronization cache entries. + * It will generate temporary results, notify corresponding consumers, and clear the sync out flags. + */ +void mdns_priv_cache_process_sync(void); + +/** + * @brief Replay all currently visible cache services to a newly registered browse. + * + * @return true if successfully notified, false otherwise + */ +bool mdns_priv_cache_notify_browse(mdns_browse_t *browse); +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_debug.h b/managed_components/espressif__mdns/private_include/mdns_debug.h new file mode 100644 index 0000000..ce713ec --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_debug.h @@ -0,0 +1,72 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "sdkconfig.h" +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef CONFIG_MDNS_ENABLE_DEBUG_PRINTS +#include "esp_log.h" + +/* Define the debug macros for the mDNS module + */ +#ifdef CONFIG_MDNS_ENABLE_BROWSE +#define DBG_BROWSE_RESULTS(result, browse) mdns_debug_printf_browse_result(result, browse) + +#define DBG_BROWSE_RESULTS_WITH_MSG(result, ...) do { \ + ESP_LOGD("mdns", __VA_ARGS__); \ + mdns_debug_printf_browse_result_all(result); \ + } while(0) +#else +#define DBG_BROWSE_RESULTS(result, browse) +#define DBG_BROWSE_RESULTS_WITH_MSG(result, ...) +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +#define DBG_TX_PACKET(packet, data, len) mdns_debug_tx_packet(packet, data, len) + +#define DBG_RX_PACKET(packet, data, len) mdns_debug_rx_packet(packet, data, len) + +#ifdef CONFIG_MDNS_ENABLE_BROWSE +/** + * @brief Print the browse results + */ +void mdns_debug_printf_browse_result(mdns_result_t *r_t, mdns_browse_t *b_t); + +/** + * @brief Print all the browse results + */ +void mdns_debug_printf_browse_result_all(mdns_result_t *r_t); +#endif /* CONFIG_MDNS_ENABLE_BROWSE */ + +/** + * @brief Print the tx packet + */ +void mdns_debug_tx_packet(mdns_tx_packet_t *p, uint8_t packet[MDNS_MAX_PACKET_SIZE], uint16_t index); + +/** + * @brief Print the rx packet + */ +void mdns_debug_rx_packet(mdns_rx_packet_t *packet, const uint8_t* data, uint16_t len); + +#else + +/* Define the dummy debug macros if debugging is OFF + */ +#define DBG_BROWSE_RESULTS(result, browse) +#define DBG_BROWSE_RESULTS_WITH_MSG(result, ...) +#define DBG_TX_PACKET(packet, data, len) +#define DBG_RX_PACKET(packet, data, len) + +#endif // CONFIG_MDNS_ENABLE_DEBUG_PRINTS + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_mem_caps.h b/managed_components/espressif__mdns/private_include/mdns_mem_caps.h new file mode 100644 index 0000000..2d63390 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_mem_caps.h @@ -0,0 +1,65 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Allocate memory. + * @param size Number of bytes to allocate. + * @return Pointer to allocated memory, or NULL on failure. + */ +void *mdns_mem_malloc(size_t size); + +/** + * @brief Allocate and zero memory. + * @param num Number of elements. + * @param size Size of each element. + * @return Pointer to allocated memory, or NULL on failure. + */ +void *mdns_mem_calloc(size_t num, size_t size); + +/** + * @brief Free allocated memory. + * @param ptr Pointer to memory to free. + */ +void mdns_mem_free(void *ptr); + +/** + * @brief Duplicate a string. + * @param s String to duplicate. + * @return Pointer to duplicated string, or NULL on failure. + */ +char *mdns_mem_strdup(const char *s); + +/** + * @brief Duplicate a string with length limit. + * @param s String to duplicate. + * @param n Maximum number of characters to copy. + * @return Pointer to duplicated string, or NULL on failure. + */ +char *mdns_mem_strndup(const char *s, size_t n); + +/** + * @brief Allocate memory for mDNS task. + * @param size Number of bytes to allocate. + * @return Pointer to allocated memory, or NULL on failure. + */ +void *mdns_mem_task_malloc(size_t size); + +/** + * @brief Free allocated memory for mDNS task. + * @param ptr Pointer to memory to free. + */ +void mdns_mem_task_free(void *ptr); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_netif.h b/managed_components/espressif__mdns/private_include/mdns_netif.h new file mode 100644 index 0000000..42aa5f1 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_netif.h @@ -0,0 +1,67 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize the mDNS network interfaces + * + * @note Called from mdns_init() in mdns.c + */ +esp_err_t mdns_priv_netif_init(void); + +/** + * @brief Deinitialize the mDNS network interfaces + * + * @note Called from mdns_init() in mdns.c + */ +esp_err_t mdns_priv_netif_deinit(void); + +/** + * @brief Unregister predefined (default) network interfaces + * + * @note Called from mdns_free() in mdns.c + * + */ +void mdns_priv_netif_unregister_predefined_handlers(void); + +/** + * @brief Clean the internal netif for the particular interface + * + * @note Called from mdns_responder on disabling pcbs + */ +void mdns_priv_netif_disable(mdns_if_t tcpip_if); + +/** + * @brief Returns potentially duplicated interface + * + * @note Called from multiple places where Rx and Tx packets are processed + */ +mdns_if_t mdns_priv_netif_get_other_interface(mdns_if_t tcpip_if); + +/** + * @brief Gets the actual esp_netif pointer from the internal network interface list + * + * The supplied ordinal number could + * - point to a predef netif -> "STA", "AP", "ETH" + * - if no entry in the list (NULL) -> check if the system added this netif + * - point to a custom netif -> just return the entry in the list + * - users is responsible for the lifetime of this netif (to be valid between mdns-init -> deinit) + * + * @param tcpip_if Ordinal number of the interface + * @return Pointer ot the esp_netif object if the interface is available, NULL otherwise + */ +esp_netif_t *mdns_priv_get_esp_netif(mdns_if_t tcpip_if); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_networking.h b/managed_components/espressif__mdns/private_include/mdns_networking.h new file mode 100644 index 0000000..9b5e396 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_networking.h @@ -0,0 +1,62 @@ +/* + * SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +/* + * MDNS Server Networking -- private include + * + */ +#include "mdns.h" +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Check if the netif on the selected interfacce and protocol is ready + */ +bool mdns_priv_if_ready(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Start PCB + */ +esp_err_t mdns_priv_if_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Stop PCB + */ +esp_err_t mdns_priv_if_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief send packet over UDP + * + * @param server The server + * @param data byte array containing the packet data + * @param len length of the packet data + * + * @return length of sent packet or 0 on error + */ +size_t mdns_priv_if_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, const esp_ip_addr_t *ip, uint16_t port, uint8_t *data, size_t len); + +/** + * @brief Gets data pointer to the mDNS packet + */ +void *mdns_priv_get_packet_data(mdns_rx_packet_t *packet); + +/** + * @brief Gets data length of c + */ +size_t mdns_priv_get_packet_len(mdns_rx_packet_t *packet); + +/** + * @brief Free the mDNS packet + */ +void mdns_priv_packet_free(mdns_rx_packet_t *packet); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_pcb.h b/managed_components/espressif__mdns/private_include/mdns_pcb.h new file mode 100644 index 0000000..723bdca --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_pcb.h @@ -0,0 +1,121 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Disable the PCB for the selected interface and protocol + * @note Called from the main module (deinit and event handler) + */ +void mdns_priv_pcb_disable(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Enable the PCB for the selected interface and protocol + * @note Called from the main module (deinit and event handler) + */ +void mdns_priv_pcb_enable(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Set the interface as duplicate + * @note Called from the packet parser when checking for collisions + */ +void mdns_priv_pcb_set_duplicate(mdns_if_t tcpip_if); + +/** + * @brief Send announcement on particular PCB + * @note Called mainly from mdns.c to send announcements on all interfaces + */ +void mdns_priv_pcb_announce(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool include_ip); + +/** + * @brief Checks if the PCB is OFF + * @note Called from mdns_send.c + */ +bool mdns_priv_pcb_is_off(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Schedules TX packets for various PCB states of probing and announcing + * @note Called from mdns_send.c + */ +void mdns_priv_pcb_schedule_tx_packet(mdns_tx_packet_t *p); + +/** + * @brief Update probing services on certain service removal + * @note Called from mdns_send.c upon removing scheduled packets for a service + */ +void mdns_priv_pcb_check_probing_services(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_service_t *service, bool removed_answers, bool *should_remove_questions); + +/** + * @brief Deinit pcbs + * @note Called from mdns_free() + */ +void mdns_priv_pcb_deinit(void); + +/** + * @brief Checks if the netif and PCB is initialized + * @note Called from mdns_send.c + */ +bool mdsn_priv_pcb_is_inited(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Checks if PCB is duplicated + * @note Called from mdns_send.c + */ +bool mdns_priv_pcb_is_duplicate(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Checks if PCB is probing + * @note Called from mdns_receive.c + */ +bool mdns_priv_pcb_is_probing(mdns_rx_packet_t *packet); + +/** + * @brief Set probe failed to PCB + * @note Called from mdns_receive.c + */ +void mdns_priv_pcb_set_probe_failed(mdns_rx_packet_t *packet); + +/** + * @brief Checks if PCB completed probing + * @note Called from mdns_receive.c + */ +bool mdns_priv_pcb_is_after_probing(mdns_rx_packet_t *packet); + +/** + * @brief Checks if the selected interface has a duplicate + * @note Called from mdns_send.c + */ +bool mdns_priv_pcb_check_for_duplicates(mdns_if_t tcpip_if); + +/** + * @brief Sends bye for particular services on particular PCB + * @note Called from mdns.c + */ +void mdns_priv_pcb_send_bye_service(mdns_srv_item_t **services, size_t len, bool include_ip); + +/** + * @brief Send probe on all active PCBs + */ +void mdns_priv_probe_all_pcbs(mdns_srv_item_t **services, size_t len, bool probe_ip, bool clear_old_probe); + +/** + * @brief Send probe for particular services on particular PCB + * + * Tests possible duplication on probing service structure and probes only for new entries. + * - If pcb probing then add only non-probing services and restarts probing + * - If pcb not probing, run probing for all specified services + */ +void mdns_priv_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool probe_ip); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_private.h b/managed_components/espressif__mdns/private_include/mdns_private.h new file mode 100644 index 0000000..50f7df3 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_private.h @@ -0,0 +1,505 @@ +/* + * SPDX-FileCopyrightText: 2015-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "sdkconfig.h" +#include "mdns.h" +#include "esp_task.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" +#include "esp_timer.h" +#include "esp_system.h" + +/** Number of predefined interfaces */ +#ifndef CONFIG_MDNS_PREDEF_NETIF_STA +#define CONFIG_MDNS_PREDEF_NETIF_STA 0 +#endif +#ifndef CONFIG_MDNS_PREDEF_NETIF_AP +#define CONFIG_MDNS_PREDEF_NETIF_AP 0 +#endif +#ifndef CONFIG_MDNS_PREDEF_NETIF_ETH +#define CONFIG_MDNS_PREDEF_NETIF_ETH 0 +#endif +#define MDNS_MAX_PREDEF_INTERFACES (CONFIG_MDNS_PREDEF_NETIF_STA + CONFIG_MDNS_PREDEF_NETIF_AP + CONFIG_MDNS_PREDEF_NETIF_ETH) + +#ifdef CONFIG_LWIP_IPV6_NUM_ADDRESSES +#define NETIF_IPV6_MAX_NUMS CONFIG_LWIP_IPV6_NUM_ADDRESSES +#else +#define NETIF_IPV6_MAX_NUMS 3 +#endif + +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 1, 0) +/* CONFIG_LWIP_IPV4 was introduced in IDF v5.1 */ +/* For IDF v5.0, set CONFIG_LWIP_IPV4 to 1 by default */ +#ifndef CONFIG_LWIP_IPV4 +#define CONFIG_LWIP_IPV4 1 +#endif // CONFIG_LWIP_IPV4 +#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 1, 0) + +/** Number of configured interfaces */ +#if MDNS_MAX_PREDEF_INTERFACES > CONFIG_MDNS_MAX_INTERFACES +#warning Number of configured interfaces is less then number of predefined interfaces. Please update CONFIG_MDNS_MAX_INTERFACES. +#define MDNS_MAX_INTERFACES (MDNS_MAX_PREDEF_INTERFACES) +#else +#define MDNS_MAX_INTERFACES (CONFIG_MDNS_MAX_INTERFACES) +#endif + +/** The maximum number of services */ +#define MDNS_MAX_SERVICES CONFIG_MDNS_MAX_SERVICES + +#define MDNS_ANSWER_PTR_TTL 4500 +#define MDNS_ANSWER_TXT_TTL 4500 +#define MDNS_ANSWER_SRV_TTL 120 +#define MDNS_ANSWER_A_TTL 120 +#define MDNS_ANSWER_AAAA_TTL 120 + +#define MDNS_FLAGS_QUERY_REPSONSE 0x8000 +#define MDNS_FLAGS_AUTHORITATIVE 0x0400 +#define MDNS_FLAGS_QR_AUTHORITATIVE (MDNS_FLAGS_QUERY_REPSONSE | MDNS_FLAGS_AUTHORITATIVE) +#define MDNS_FLAGS_DISTRIBUTED 0x0200 + +#define MDNS_NAME_REF 0xC000 + +//custom type! only used by this implementation +//to help manage service discovery handling +#define MDNS_TYPE_SDPTR 0x0032 + +#define MDNS_CLASS_IN 0x0001 +#define MDNS_CLASS_ANY 0x00FF +#define MDNS_CLASS_IN_FLUSH_CACHE 0x8001 + +#define MDNS_ANSWER_ALL 0x3F +#define MDNS_ANSWER_PTR 0x08 +#define MDNS_ANSWER_TXT 0x04 +#define MDNS_ANSWER_SRV 0x02 +#define MDNS_ANSWER_A 0x01 +#define MDNS_ANSWER_AAAA 0x10 +#define MDNS_ANSWER_NSEC 0x20 +#define MDNS_ANSWER_SDPTR 0x80 +#define MDNS_ANSWER_AAAA_SIZE 16 + +#define MDNS_SERVICE_PORT 5353 // UDP port that the server runs on +#define MDNS_SERVICE_ADD_TIMEOUT_MS CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS + +#define MDNS_PACKET_QUEUE_LEN 16 // Maximum packets that can be queued for parsing +#define MDNS_ACTION_QUEUE_LEN CONFIG_MDNS_ACTION_QUEUE_LEN // Maximum actions pending to the server +#define MDNS_TXT_MAX_LEN 1024 // Maximum string length of text data in TXT record +#define MDNS_MAX_PACKET_SIZE 1460 // Maximum size of mDNS outgoing packet + +#define MDNS_HEAD_LEN 12 +#define MDNS_HEAD_ID_OFFSET 0 +#define MDNS_HEAD_FLAGS_OFFSET 2 +#define MDNS_HEAD_QUESTIONS_OFFSET 4 +#define MDNS_HEAD_ANSWERS_OFFSET 6 +#define MDNS_HEAD_SERVERS_OFFSET 8 +#define MDNS_HEAD_ADDITIONAL_OFFSET 10 + +#define MDNS_TYPE_OFFSET 0 +#define MDNS_CLASS_OFFSET 2 +#define MDNS_TTL_OFFSET 4 +#define MDNS_LEN_OFFSET 8 +#define MDNS_DATA_OFFSET 10 + +#define MDNS_SRV_PRIORITY_OFFSET 0 +#define MDNS_SRV_WEIGHT_OFFSET 2 +#define MDNS_SRV_PORT_OFFSET 4 +#define MDNS_SRV_FQDN_OFFSET 6 + +#define MDNS_TIMER_PERIOD_US (CONFIG_MDNS_TIMER_PERIOD_MS*1000) + +#define MDNS_US_PER_SEC 1000000LL + +#define queueToEnd(type, queue, item) \ + if (!queue) { \ + queue = item; \ + } else { \ + type * _q = queue; \ + while (_q->next) { _q = _q->next; } \ + _q->next = item; \ + } + +#define queueDetach(type, queue, item) \ + if (queue) { \ + if (queue == item) { \ + queue = queue->next; \ + } else { \ + type * _q = queue; \ + while (_q->next && _q->next != item) { \ + _q = _q->next; \ + } \ + if (_q->next == item) { \ + _q->next = item->next; \ + item->next = NULL; \ + } \ + } \ + } + +#define queueFree(type, queue) while (queue) { type * _q = queue; queue = queue->next; mdns_mem_free(_q); } + +#ifndef HOOK_MALLOC_FAILED +#define HOOK_MALLOC_FAILED do { ESP_LOGE(TAG, "Cannot allocate memory (%s(%d), free heap: %" PRIu32 " bytes)", __func__, __LINE__, esp_get_free_heap_size()); } while(0) +#endif + +typedef size_t mdns_if_t; + +typedef enum { + MDNS_ANSWER, MDNS_NS, MDNS_EXTRA +} mdns_parsed_record_type_t; + +typedef enum { + ACTION_SYSTEM_EVENT, + ACTION_HOSTNAME_SET, + ACTION_INSTANCE_SET, + ACTION_SEARCH_ADD, + ACTION_SEARCH_SEND, + ACTION_SEARCH_END, + ACTION_BROWSE_START, + ACTION_BROWSE_END, + ACTION_TX_HANDLE, + ACTION_RX_HANDLE, + ACTION_TASK_STOP, + ACTION_DELEGATE_HOSTNAME_ADD, + ACTION_DELEGATE_HOSTNAME_REMOVE, + ACTION_DELEGATE_HOSTNAME_SET_ADDR, + ACTION_BROWSE_SEND_BY_IP_PROTOCOL, + ACTION_MAX +} mdns_action_type_t; + +typedef enum { + ACTION_RUN, + ACTION_CLEANUP, +} mdns_action_subtype_t; + +typedef struct { + uint16_t id; + uint16_t flags; + uint16_t questions; //QDCOUNT + uint16_t answers; //ANCOUNT + uint16_t servers; //NSCOUNT + uint16_t additional;//ARCOUNT +} mdns_header_t; + +typedef struct { + char host[MDNS_NAME_BUF_LEN]; // hostname for A/AAAA records, instance name for SRV records + char service[MDNS_NAME_BUF_LEN]; + char proto[MDNS_NAME_BUF_LEN]; + char domain[MDNS_NAME_BUF_LEN]; + uint8_t parts; + uint8_t sub; // 0: no subtype, 1: subtype + bool invalid; +} mdns_name_t; + +typedef struct mdns_parsed_question_s { + struct mdns_parsed_question_s *next; + uint16_t type; + bool sub; + bool unicast; + char *host; + char *service; + char *proto; + char *domain; +} mdns_parsed_question_t; + +typedef struct mdns_parsed_record_s { + struct mdns_parsed_record_s *next; + mdns_parsed_record_type_t record_type; + uint16_t type; + uint16_t clas; + uint8_t flush; + uint32_t ttl; + char *host; + char *service; + char *proto; + char *domain; + uint16_t data_len; + uint8_t *data; +} mdns_parsed_record_t; + +typedef struct { + mdns_if_t tcpip_if; + mdns_ip_protocol_t ip_protocol; + esp_ip_addr_t src; + uint16_t src_port; + uint8_t multicast; + uint8_t authoritative; + uint8_t probe; + uint8_t discovery; + uint8_t distributed; + mdns_parsed_question_t *questions; + mdns_parsed_record_t *records; + uint16_t id; +} mdns_parsed_packet_t; + +typedef struct { + mdns_if_t tcpip_if; + mdns_ip_protocol_t ip_protocol; + struct pbuf *pb; + esp_ip_addr_t src; + esp_ip_addr_t dest; + uint16_t src_port; + uint8_t multicast; +} mdns_rx_packet_t; + +typedef struct mdns_txt_linked_item_s { + const char *key; /*!< item key name */ + char *value; /*!< item value string */ + uint8_t value_len; /*!< item value length */ + struct mdns_txt_linked_item_s *next; /*!< next result, or NULL for the last result in the list */ +} mdns_txt_linked_item_t; + +typedef struct mdns_subtype_s { + const char *subtype; /*!< subtype */ + struct mdns_subtype_s *next; /*!< next result, or NULL for the last result in the list */ +} mdns_subtype_t; + +typedef struct { + const char *instance; + const char *service; + const char *proto; + const char *hostname; + uint16_t priority; + uint16_t weight; + uint16_t port; + mdns_txt_linked_item_t *txt; + mdns_subtype_t *subtype; +} mdns_service_t; + +typedef struct mdns_srv_item_s { + struct mdns_srv_item_s *next; + mdns_service_t *service; +} mdns_srv_item_t; + +typedef struct mdns_out_question_s { + struct mdns_out_question_s *next; + uint16_t type; + bool unicast; + const char *host; + const char *service; + const char *proto; + const char *domain; + const char *subtype; + bool own_dynamic_memory; +} mdns_out_question_t; + +typedef struct mdns_host_item_t { + const char *hostname; + mdns_ip_addr_t *address_list; + struct mdns_host_item_t *next; +} mdns_host_item_t; + +typedef struct mdns_out_answer_s { + struct mdns_out_answer_s *next; + uint16_t type; + uint8_t bye; + uint8_t flush; + mdns_service_t *service; + mdns_host_item_t *host; + const char *custom_instance; + const char *custom_service; + const char *custom_proto; +} mdns_out_answer_t; + +typedef struct mdns_tx_packet_s { + struct mdns_tx_packet_s *next; + uint32_t send_at; + mdns_if_t tcpip_if; + mdns_ip_protocol_t ip_protocol; + esp_ip_addr_t dst; + uint16_t port; + uint16_t flags; + uint8_t distributed; + mdns_out_question_t *questions; + mdns_out_answer_t *answers; + mdns_out_answer_t *servers; + mdns_out_answer_t *additional; + bool queued; + uint16_t id; +} mdns_tx_packet_t; + +typedef enum { + SEARCH_OFF, + SEARCH_INIT, + SEARCH_RUNNING, + SEARCH_MAX +} mdns_search_once_state_t; + +typedef enum { + BROWSE_OFF, + BROWSE_INIT, + BROWSE_RUNNING, + BROWSE_MAX +} mdns_browse_state_t; + +typedef struct mdns_search_once_s { + struct mdns_search_once_s *next; + + mdns_search_once_state_t state; + uint32_t started_at; + uint32_t sent_at; + uint32_t timeout; + mdns_query_notify_t notifier; + SemaphoreHandle_t done_semaphore; + uint16_t type; + bool unicast; + uint8_t max_results; + uint8_t num_results; + char *instance; + char *service; + char *proto; + char *subtype; + mdns_result_t *result; +} mdns_search_once_t; + +typedef struct mdns_browse_s { + struct mdns_browse_s *next; + + mdns_browse_state_t state; + mdns_browse_notify_t notifier; + + char *service; + char *proto; + char *subtype; +} mdns_browse_t; + +typedef struct { + mdns_action_type_t type; + union { + struct { + char *hostname; + } hostname_set; + char *instance; + struct { + mdns_if_t interface; + mdns_event_actions_t event_action; + } sys_event; + struct { + mdns_search_once_t *search; + } search_add; + struct { + mdns_tx_packet_t *packet; + } tx_handle; + struct { + mdns_rx_packet_t *packet; + } rx_handle; + struct { + const char *hostname; + mdns_ip_addr_t *address_list; + } delegate_hostname; + struct { + mdns_browse_t *browse; + } browse_add; + struct { + mdns_if_t interface; + mdns_ip_protocol_t ip_protocol; + } browse_send; + } data; +} mdns_action_t; + +typedef enum { + MDNS_CACHE_CONSUMER_BROWSE = (1U << 0), +} mdns_cache_consumer_type_t; + +typedef uint8_t mdns_cache_consumer_mask_t; + +typedef enum { + // Browse update flags + MDNS_CACHE_RECORD_PTR = (1U << 0), /*!< Normal PTR record updated, only notify no-subtype browses. */ + MDNS_CACHE_RECORD_SUBTYPE = (1U << 1), /*!< PTR record with subtype updated, only notify browse with identical subtype. */ + // Resolver update flags + MDNS_CACHE_RECORD_SRV = (1U << 2), + MDNS_CACHE_RECORD_TXT = (1U << 3), + MDNS_CACHE_RECORD_ADDR = (1U << 4), +} mdns_cache_record_type_t; + +typedef uint8_t mdns_cache_record_mask_t; + +/** + * @brief mDNS cache expiry structure + */ +typedef struct mdns_cache_expiry_s { + bool queued; + mdns_cache_record_mask_t record_mask; + struct mdns_cache_expiry_s *next; + + struct mdns_cache_entry_s *entry; + struct mdns_service_cache_s *service; + struct mdns_cache_addr_s *addr; + struct mdns_cache_subtype_s *subtype; + int64_t expires_at_us; /*!< record absolute expiration time in microseconds */ +} mdns_cache_expiry_t; + +/** + * @brief mDNS cache PTR subtype structure + */ +typedef struct mdns_cache_subtype_s { + char *subtype; + uint32_t ttl; + bool pending_sync; /*!< true if the subtype needs sync notification */ + struct mdns_cache_subtype_s *next; +} mdns_cache_subtype_t; + +/** + * @brief mDNS cache ADDR list structure + */ +typedef struct mdns_cache_addr_s { + esp_ip_addr_t addr; + uint32_t ttl; + struct mdns_cache_addr_s *next; +} mdns_cache_addr_t; + +/** + * @brief mDNS cache service structure, contains PTR (with subtype list), SRV and TXT records + */ +typedef struct mdns_service_cache_s { + char *instance_name; + char *service; + char *proto; + // PTR + bool ptr_present; /*!< true if PTR record is present */ + uint32_t ptr_ttl; + // Subtype list + mdns_cache_subtype_t *subtype_list; + // SRV + bool srv_present; /*!< true if SRV record is present */ + uint16_t priority; + uint16_t weight; + uint16_t port; + uint32_t srv_ttl; + // TXT + bool txt_present; /*!< true if TXT record is present */ + mdns_txt_linked_item_t *txt_list; + uint32_t txt_ttl; + // To-sync flags + mdns_cache_record_mask_t sync_records; /*!< bitmask of records to sync, see @ref mdns_cache_record_type_t */ + mdns_cache_consumer_mask_t sync_consumers; /*!< bitmask of consumers to sync, see @ref mdns_cache_consumer_type_t */ + struct mdns_service_cache_s *next; +} mdns_service_cache_t; + +/** + * @brief mDNS cache entry structure, contains hostname, IP address list and service cache list + */ +typedef struct mdns_cache_entry_s { + char *hostname; + esp_netif_t *esp_netif; + mdns_ip_protocol_t ip_protocol; + + mdns_cache_addr_t *addr_list; + mdns_service_cache_t *service_cache_list; + struct mdns_cache_entry_s *next; +} mdns_cache_entry_t; + +/** + * @brief mDNS cache update result structure + */ +typedef enum { + MDNS_CACHE_NO_CHANGE, /*!< no change to the cache */ + MDNS_CACHE_ADDED, /*!< new cache entry or service cache appended */ + MDNS_CACHE_UPDATED, /*!< existing service cache entry updated */ + MDNS_CACHE_REMOVED, /*!< existing service cache entry removed */ + MDNS_CACHE_ERROR, /*!< error occurred while updating the cache */ +} mdns_cache_update_result_t; diff --git a/managed_components/espressif__mdns/private_include/mdns_querier.h b/managed_components/espressif__mdns/private_include/mdns_querier.h new file mode 100644 index 0000000..0c71552 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_querier.h @@ -0,0 +1,116 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Start or stop requested queries + * @note Called periodically from timer task in mdns.c + */ +void mdns_priv_query_start_stop(void); + +/** + * @brief Free search item queue + * @note Called from mdns_free() + */ +void mdns_priv_query_free(void); + +/** + * @brief Free one search object (detached or still on the active list) + */ +void mdns_priv_search_once_free(mdns_search_once_t *search); + +/** + * @brief Free search results + * @note Called from multiple modules (browser, querier, core) + */ +void mdns_priv_query_results_free(mdns_result_t *results); + +/** + * @brief Complete the query if max results reached + * @note Called from the packet parser + */ +void mdns_priv_query_done(void); + +/** +* @brief Looks for the name/type in active search items +* +* @note Called from the packet parser (mdns_receive.c) +* +* @return search results +*/ +mdns_search_once_t *mdns_priv_query_find(mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Looks for the name/type in the search items + * + * @note Called from the packet parser (mdns_receive.c) + */ +mdns_search_once_t *mdns_priv_query_find_from(mdns_search_once_t *s, mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Add TXT item to the search results + * @note Called from the packet parser (mdns_receive.c) + */ +void mdns_priv_query_result_add_txt(mdns_search_once_t *search, mdns_txt_item_t *txt, uint8_t *txt_value_len, + size_t txt_count, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, + uint32_t ttl); +/** + * @brief Add IP (A/AAAA records) to the search results + * @note Called from the packet parser (mdns_receive.c) + */ +void mdns_priv_query_result_add_ip(mdns_search_once_t *search, const char *hostname, esp_ip_addr_t *ip, + mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint32_t ttl); + +/** + * @brief Add SRV record to the search results + * @note Called from the packet parser (mdns_receive.c) + */ +void mdns_priv_query_result_add_srv(mdns_search_once_t *search, const char *hostname, uint16_t port, + mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint32_t ttl); + +/** + * @brief Add PTR record to the search results + * @note Called from the packet parser (mdns_receive.c) + */ +mdns_result_t *mdns_priv_query_result_add_ptr(mdns_search_once_t *search, const char *instance, + const char *service_type, const char *proto, mdns_if_t tcpip_if, + mdns_ip_protocol_t ip_protocol, uint32_t ttl); + +/** + * @brief Perform action from mdns service queue + * + * @note Called from the _mdns_service_task() in mdns.c + */ +void mdns_priv_query_action(mdns_action_t *action, mdns_action_subtype_t type); + +/** + * @brief Create linked IP (copy) from parsed one + */ +mdns_ip_addr_t *mdns_priv_result_addr_create_ip(esp_ip_addr_t *ip); + +/** + * @brief Update TTL results to whichever is smaller + */ +static inline void mdns_priv_query_update_result_ttl(mdns_result_t *r, uint32_t ttl) +{ + r->ttl = r->ttl < ttl ? r->ttl : ttl; +} + +/** + * @brief Send a search query packet on the specified interface and protocol + */ +void mdns_priv_query_send(mdns_search_once_t *search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_receive.h b/managed_components/espressif__mdns/private_include/mdns_receive.h new file mode 100644 index 0000000..03cad70 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_receive.h @@ -0,0 +1,24 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief Perform action from mdns service queue +* +* @note Called from the _mdns_service_task() in mdns.c +*/ +void mdns_priv_receive_action(mdns_action_t *action, mdns_action_subtype_t type); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_responder.h b/managed_components/espressif__mdns/private_include/mdns_responder.h new file mode 100644 index 0000000..fc0fbed --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_responder.h @@ -0,0 +1,98 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief Perform action from mdns responder +* +* @note Called from the _mdns_service_task() in mdns.c +*/ +void mdns_priv_responder_action(mdns_action_t *action, mdns_action_subtype_t type); + +/** + * @brief Initializes responder storage + */ +esp_err_t mdns_priv_responder_init(void); + +/** + * @brief Frees responder storage + */ +void mdns_priv_responder_free(void); + +/** + * @brief get global (mdns_server->hostname) hostname + */ +const char *mdns_priv_get_global_hostname(void); + +/** + * @brief get service list + */ +mdns_srv_item_t *mdns_priv_get_services(void); + +/** + * @brief get host list + */ +mdns_host_item_t *mdns_priv_get_hosts(void); + +/** + * @brief get self host + */ +mdns_host_item_t *mdns_priv_get_self_host(void); + +/** + * @brief set global hostname + */ +void mdns_priv_set_global_hostname(const char *hostname); + +/** + * @brief get mdns_server->instance + */ +const char *mdns_priv_get_instance(void); + +/** + * @brief set mdns_server->instance + */ +void mdns_priv_set_instance(const char *instance); + +/** + * @brief Returns true if the mdns server is initialized + */ +bool mdns_priv_is_server_init(void); + +/** + * @brief Restart the responder on all services without instance + */ +void mdns_priv_restart_all_pcbs_no_instance(void); + +/** + * @brief Restart the responder on all active PCBs + */ +void mdns_priv_restart_all_pcbs(void); + +/** + * @brief Adds a delegated hostname to the linked list + * @param hostname Host name pointer + * @param address_list Address list + * @return true on success + * false if the host wasn't attached (this is our hostname, or alloc failure) so we have to free the structs + */ +bool mdns_priv_delegate_hostname_add(const char *hostname, mdns_ip_addr_t *address_list); + +/** + * @brief Remaps hostname of self service + */ +void mdns_priv_remap_self_service_hostname(const char *old_hostname, const char *new_hostname); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_send.h b/managed_components/espressif__mdns/private_include/mdns_send.h new file mode 100644 index 0000000..43fa916 --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_send.h @@ -0,0 +1,131 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Free a transmit packet and its associated resources + */ +void mdns_priv_free_tx_packet(mdns_tx_packet_t *packet); + +/** + * @brief Create a probe packet for service discovery + */ +mdns_tx_packet_t *mdns_priv_create_probe_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t *services[], size_t len, bool first, bool include_ip); + +/** + * @brief Allocate and initialize an answer record for mDNS response + */ +bool mdns_priv_create_answer(mdns_out_answer_t **destination, uint16_t type, mdns_service_t *service, + mdns_host_item_t *host, bool flush, bool bye); + +/** + * @brief Create an announcement packet for service advertisement + */ +mdns_tx_packet_t *mdns_priv_create_announce_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t *services[], size_t len, bool include_ip); + +/** + * @brief Create an announcement packet from an existing probe packet + */ +mdns_tx_packet_t *mdns_priv_create_announce_from_probe(mdns_tx_packet_t *probe); + +/** + * @brief Dispatch a transmit packet for sending + */ +void mdns_priv_dispatch_tx_packet(mdns_tx_packet_t *p); + +/** + * @brief Send a goodbye message for a service subtype + */ +void mdns_priv_send_bye_subtype(mdns_srv_item_t *service, const char *instance_name, mdns_subtype_t *remove_subtypes); + +/** + * @brief Append host list information to service records + */ +bool mdns_priv_append_host_list_in_services(mdns_out_answer_t **destination, mdns_srv_item_t *services[], size_t services_len, bool flush, bool bye); + +/** + * @brief Clear the transmit queue head for a specific interface and protocol + */ +void mdns_priv_clear_tx_queue_if(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Clear the global transmit queue head + */ +void mdns_priv_clear_tx_queue(void); + +/** + * @brief Remove scheduled service packets for a given service + */ +void mdns_priv_remove_scheduled_service_packets(mdns_service_t *service); + +/** + * @brief Get the next packet from the PCB queue for a specific interface and protocol + */ +mdns_tx_packet_t *mdns_priv_get_next_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Deallocate an answer record + */ +void mdns_priv_dealloc_answer(mdns_out_answer_t **destination, uint16_t type, mdns_srv_item_t *service); + +/** + * @brief Remove a scheduled answer for a specific interface, protocol, and service + */ +void mdns_priv_remove_scheduled_answer(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint16_t type, mdns_srv_item_t *service); + +/** + * @brief Allocate a new packet with default settings + */ +mdns_tx_packet_t *mdns_priv_alloc_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); + +/** + * @brief Send all pending mDNS packets + */ +void mdns_priv_send_packets(void); + +/** + * @brief Execute an mDNS action with specified type + */ +void mdns_priv_send_action(mdns_action_t *action, mdns_action_subtype_t type); + +/** + * @brief Schedule a transmit packet for sending after a specified delay + */ +void mdns_priv_send_after(mdns_tx_packet_t *packet, uint32_t ms_after); + +/** + * @brief Send by for particular services on particular PCB + */ +void mdns_priv_send_bye(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t **services, size_t len, bool include_ip); + +/** + * @brief Create answer packet to questions from parsed packet + */ +void mdns_priv_create_answer_from_parsed_packet(mdns_parsed_packet_t *parsed_packet); + +/** + * @brief appends one TXT record ("key=value" or "key") + * + * @param packet MDNS packet + * @param index offset in the packet + * @param txt one txt record + * + * @return length of added data: length of the added txt value + 1 on success + * 0 if data won't fit the packet + * -1 if invalid TXT entry + */ +int mdns_priv_append_one_txt_record_entry(uint8_t *packet, uint16_t *index, mdns_txt_linked_item_t *txt); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_service.h b/managed_components/espressif__mdns/private_include/mdns_service.h new file mode 100644 index 0000000..597da0f --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_service.h @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "mdns_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Lock mdns service + */ +void mdns_priv_service_lock(void); + +/** + * @brief Unlock mdns service + */ +void mdns_priv_service_unlock(void); + +/** + * @brief Send the given action to the service queue + */ +bool mdns_priv_queue_action(mdns_action_t *action); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/private_include/mdns_utils.h b/managed_components/espressif__mdns/private_include/mdns_utils.h new file mode 100644 index 0000000..806aace --- /dev/null +++ b/managed_components/espressif__mdns/private_include/mdns_utils.h @@ -0,0 +1,172 @@ +/* + * SPDX-FileCopyrightText: 2015-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "mdns_private.h" + +#define MDNS_UTILS_DEFAULT_DOMAIN "local" +#define MDNS_UTILS_SIZEOF_IP6_ADDR (MDNS_ANSWER_AAAA_SIZE) + +/** + * @brief read uint16_t from a packet + * @param packet the packet + * @param index index in the packet where the value starts + * + * @return the value + */ +static inline uint16_t mdns_utils_read_u16(const uint8_t *packet, uint16_t index) +{ + return (uint16_t)(packet[index]) << 8 | packet[index + 1]; +} + +/** + * @brief read uint32_t from a packet + * @param packet the packet + * @param index index in the packet where the value starts + * + * @return the value + */ +static inline uint32_t mdns_utils_read_u32(const uint8_t *packet, uint16_t index) +{ + return (uint32_t)(packet[index]) << 24 | (uint32_t)(packet[index + 1]) << 16 | (uint32_t)(packet[index + 2]) << 8 | packet[index + 3]; +} + +/** + * @brief Check for null or empty string + */ +static inline bool mdns_utils_str_null_or_empty(const char *str) +{ + return (str == NULL || *str == 0); +} + +/** + * @brief reads and formats MDNS FQDN into mdns_name_t structure + * + * @param packet MDNS packet + * @param start Starting point of FQDN + * @param name mdns_name_t structure to populate + * + * @return the address after the parsed FQDN in the packet or NULL on error + */ +const uint8_t *mdns_utils_parse_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, size_t packet_len); + +/** + * @brief reads MDNS FQDN into mdns_name_t structure + * FQDN is in format: [hostname.|[instance.]_service._proto.]local. + * + * @param packet MDNS packet + * @param start Starting point of FQDN + * @param name mdns_name_t structure to populate + * @param buf temporary char buffer + * + * @return the address after the parsed FQDN in the packet or NULL on error + */ +const uint8_t *mdns_utils_read_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, char *buf, size_t packet_len); + +/** + * @brief Check if IPv6 address is NULL + */ +bool mdns_utils_ipv6_address_is_zero(esp_ip6_addr_t ip6); + + +/** + * @brief Checks if the hostname is ours + */ +bool mdns_utils_hostname_is_ours(const char *hostname); + +/** + * @brief Checks if given service matches with arguments + */ +bool mdns_utils_service_match(const mdns_service_t *srv, const char *service, const char *proto, + const char *hostname); + +/** + * @brief finds service from given service type + * @param server the server + * @param service service type to match + * @param proto proto to match + * @param hostname hostname of the service (if non-null) + * + * @return the service item if found or NULL on error + */ +mdns_srv_item_t *mdns_utils_get_service_item(const char *service, const char *proto, const char *hostname); + +/** + * @brief finds service from given instance, etc + */ +mdns_srv_item_t *mdns_utils_get_service_item_instance(const char *instance, const char *service, const char *proto, + const char *hostname); + +/** + * @brief returns true if the service matches with args + */ +bool mdns_utils_service_match_instance(const mdns_service_t *srv, const char *instance, const char *service, + const char *proto, const char *hostname); + +/** + * @brief returns true if the two instances match + */ +bool mdns_utils_instance_name_match(const char *lhs, const char *rhs); + +/** + * @brief Get service instance name + */ +const char *mdns_utils_get_service_instance_name(const mdns_service_t *service); + +/** + * @brief Copy address list + */ +mdns_ip_addr_t *mdns_utils_copy_address_list(const mdns_ip_addr_t *address_list); + +/** + * @brief Free address list + */ +void mdns_utils_free_address_list(mdns_ip_addr_t *address_list); + +/** + * @brief appends uint16_t in a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param value the value to set + * + * @return length of added data: 0 on error or 2 on success + */ +uint8_t mdns_utils_append_u16(uint8_t *packet, uint16_t *index, uint16_t value); + +/** + * @brief appends byte in a packet, incrementing the index + * + * @param packet MDNS packet + * @param index offset in the packet + * @param value the value to set + * + * @return length of added data: 0 on error or 1 on success + */ +static inline uint8_t mdns_utils_append_u8(uint8_t *packet, uint16_t *index, uint8_t value) +{ + if (*index >= MDNS_MAX_PACKET_SIZE) { + return 0; + } + packet[*index] = value; + *index += 1; + return 1; +} + +/** + * @brief Free a TXT linked list. + * + * @param txt Pointer to the TXT linked list. + */ +void mdns_utils_free_txt_linked_list(mdns_txt_linked_item_t *txt); + +/** + * @brief Check if two strings are valid and case-insensitivly equal + */ +bool mdns_utils_str_case_equal(const char *a, const char *b); + +/** + * @brief Check if two strings are either both null/empty or valid and case-insensitivly equal + */ +bool mdns_utils_str_case_equal_nullable(const char *a, const char *b); diff --git a/managed_components/espressif__mdns/refactor_2025.md b/managed_components/espressif__mdns/refactor_2025.md new file mode 100644 index 0000000..53b6fd7 --- /dev/null +++ b/managed_components/espressif__mdns/refactor_2025.md @@ -0,0 +1,56 @@ +# MDNS Component Refactor + +## Introduction + +The MDNS component has been refactored from a single monolithic file `mdns.c` into a set of focused modules with clear responsibilities. This restructuring maintains the same functionality while improving code organization, maintainability, and testability. + +The refactor has been performed in thee major stages, to ensure smooth transition to production while avoiding major changes in untested paths. These stages are: +[x] Restructuring into several modules while keeping the actual code changes to minimum +[ ] Cover functionality of each module by specifically focused unit tests. +[ ] Optimizations on module levels (string and queue operations, esp_timer dependency, socket task improvements, error checking) + +## Module Structure + +### mdns_service.c +The central service module that orchestrates the MDNS component operation. It manages the service task, timer, action queue, and system event handling. This module provides the entry points for the public API and coordinates actions between different modules. It's responsible for the general lifecycle of the MDNS service. + +### mdns_responder.c +Implements the responder functionality that answers incoming MDNS queries. It manages hostname and service registration, and generates appropriate response packets based on the queried information. The responder tracks all registered services and their associated metadata, handling hostname conflicts and service announcement. + +### mdns_browser.c +Handles browse/query functionality, managing browse requests for MDNS services on the network. It provides the infrastructure for adding, tracking, and removing browse requests, and processes incoming service discovery responses. The module manages browsing state and notifies applications when services appear or disappear. + +### mdns_querier.c +Handles outgoing query functionality, maintaining state for ongoing queries and processing query responses. It supports one-shot and continuous queries, manages query timeouts, and organizes results. The module provides the infrastructure for applications to discover services and resolve hostnames. + +### mdns_send.c +Manages packet generation and transmission. It constructs properly formatted MDNS packets, with correct headers and resource records, and handles the transmission scheduling and queueing of outgoing messages. This module encapsulates knowledge about the MDNS protocol packet structure. + +### mdns_receive.c +Processes incoming MDNS packets, parsing and validating their structure. It extracts queries and responses from received packets and dispatches them to the appropriate handling modules. This module focuses on packet parsing and initial classification. + +### mdns_pcb.c +Manages protocol control blocks (PCBs) that handle the state machine for MDNS interface operation. It coordinates the probing, announcing, and running states for each network interface and protocol combination. This module is responsible for service conflict detection, duplicate interface handling, and ensuring proper service announcements. + +### mdns_networking_lwip.c and mdns_networking_socket.c +These modules provide networking abstraction for different underlying network stacks. They handle multicast group management, packet reception, and transmission over the network interfaces. This abstraction allows the MDNS implementation to work with different networking stacks. + +### mdns_netif.c +Manages network interface registration and monitoring. It tracks network interface state changes and notifies the MDNS service when interfaces become available or unavailable, enabling dynamic adaptation to network configuration changes. + +### mdns_utils.c +Contains common utility functions used across multiple modules, such as string handling, data structure operations, and debug helpers. This module centralizes shared functionality to avoid code duplication. + +### mdns_mem_caps.c +Provides memory allocation functions with capability-based allocation support. It encapsulates memory management operations, making it easier to track and debug memory usage across the MDNS component. + +### mdns_debug.c +Contains debugging and logging utilities specific to the MDNS component. It provides structured logging and debug information for troubleshooting complex MDNS operations. + +## Testability Improvements + +The refactored module structure significantly enhances testability by clearly separating different functional areas. Each module can now be tested in isolation with proper mocking of its dependencies. The separation of networking, packet handling, and business logic makes it possible to create focused unit tests without the complexity of managing the entire MDNS stack. Module-specific state is now contained within individual modules rather than distributed throughout a monolithic codebase, making test case setup and verification more straightforward. The refactoring also improves the ability to simulate various network conditions and edge cases by intercepting inter-module communication at well-defined boundaries. + +## Conclusion + +The MDNS component refactoring provides a more maintainable and testable architecture while preserving the existing public API. By breaking down the monolithic implementation into focused modules with clear responsibilities, the codebase becomes easier to understand, extend, and maintain. The refactored structure makes it simpler to identify and fix bugs, implement new features, and adapt to future requirements. This architectural improvement supports long-term evolution of the component while maintaining backward compatibility for existing applications. diff --git a/managed_components/espressif__mdns/refactoring_details.md b/managed_components/espressif__mdns/refactoring_details.md new file mode 100644 index 0000000..8ee403d --- /dev/null +++ b/managed_components/espressif__mdns/refactoring_details.md @@ -0,0 +1,244 @@ +| Original Function | Refactored Function | Concerns | +|------------------|--------------------|---------| +| [mdns_if_from_preset_if](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L136) | [mdns_if_from_preset](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L87) | The function name was changed from `mdns_if_from_preset_if` to `mdns_if_from_preset`, but the logic remains identical. While this appears to be a systematic naming convention change (supported by the evidence that all call sites in the refactored codebase now use the new name), there's a risk that some call sites in the original codebase might not have been updated, or that external code depending on the original function name could break. The functionality itself is preserved, but the interface change could cause linkage or compilation issues if not all dependencies are updated. | +| [esp_netif_from_preset_if](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L151) | [netif_from_preset](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L102) | | +| [_mdns_get_esp_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L179) | [mdns_priv_get_esp_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L118) | The function `esp_netif_from_preset_if()` has been replaced with `netif_from_preset()` in the refactored code. While both functions appear to serve the same purpose of looking up predefined network interfaces, this change could introduce subtle bugs if:
1. The new function has different error handling behavior
2. The new function returns different values for edge cases (e.g., when interfaces are not available)
3. The new function has different performance characteristics that could affect timing-sensitive MDNS operations

The original `esp_netif_from_preset_if()` was an inline function with a switch statement mapping predefined interface types to actual esp_netif instances. If `netif_from_preset()` has a different implementation or doesn't handle all the same `mdns_predef_if_t` enum values, this could break MDNS functionality for predefined interfaces like STA, AP, or ETH when they become available after initialization. | +| [_mdns_clean_netif_ptr](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L196) | [mdns_priv_netif_disable](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L134) | | +| [_mdns_get_if_from_esp_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L207) | [get_if_from_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L144) | The function `esp_netif_from_preset_if` was renamed to `netif_from_preset` in the refactored code. While both functions appear to serve the same purpose (converting a predefined interface enum to an esp_netif pointer), this change could introduce subtle bugs if the implementation of `netif_from_preset` differs from the original `esp_netif_from_preset_if` function, particularly in error handling, return values for unsupported interface types, or behavioral differences in edge cases. | +| [_str_null_or_empty](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L224) | [mdns_utils_str_null_or_empty](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.h#L38) | The refactoring introduced a potential compilation issue. The original function `_str_null_or_empty` was defined as `static inline` within `mdns.c`, making it only visible within that translation unit. The refactored version `mdns_utils_str_null_or_empty` is also `static inline` but in `mdns_utils.h`, which means it needs to be properly included in all files that use it. From the search results, I can see that `mdns_browser.c`, `mdns_debug.c`, and `mdns_responder.c` are using the new function, but I cannot verify if the original `mdns.c` file has been updated to include `mdns_utils.h` and replace all calls to `_str_null_or_empty` with `mdns_utils_str_null_or_empty`. If the original `mdns.c` still contains calls to the old function name without including the new header, this will cause compilation failures. | +| [_mdns_mangle_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L232) | [mangle_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L138) | | +| [_mdns_service_match](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L272) | [mdns_utils_service_match](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L121) | The refactored function adds a null check for the 'srv' parameter (!srv), which changes the behavior from the original function. In the original implementation, callers could potentially pass NULL for 'srv', which would cause a segmentation fault when accessing srv->hostname. The refactored version now explicitly checks for NULL and returns false, which may mask underlying bugs in calling code that should be fixed rather than silently handled. Additionally, the function visibility changed from static to public, which could break encapsulation if this was intended to be an internal helper function. | +| [_mdns_get_service_item](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L291) | [mdns_utils_get_service_item](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L131) | The refactored function changed from static to non-static visibility and now uses mdns_priv_get_services() instead of directly accessing _mdns_server->services. This could introduce subtle bugs related to:
1. Thread safety - the original function was likely called within MDNS_SERVICE_LOCK/UNLOCK contexts, but the refactored version's access pattern through mdns_priv_get_services() may not provide the same guarantees
2. Encapsulation - making the function non-static exposes internal service lookup logic that was previously hidden
3. Dependency on mdns_utils_service_match having identical behavior to _mdns_service_match, which needs verification
4. Potential null pointer issues if mdns_priv_get_services() returns NULL when _mdns_server->services would not be NULL | +| [_mdns_get_service_item_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L303) | [get_service_item_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L39) | | +| [mdns_get_host_item](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L321) | [get_host_item](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L240) | The refactored get_host_item function introduces a potential NULL return when the hostname matches the server's hostname or is NULL. In the original implementation, &_mdns_self_host was always returned (a guaranteed non-NULL address), but the refactored version calls mdns_priv_get_self_host() which can return NULL if s_server is NULL. This could break callers that assume non-NULL returns for self-host cases, potentially causing segmentation faults or incorrect behavior in service discovery and host resolution. | +| [_mdns_can_add_more_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L336) | [can_add_more_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L129) | | +| [_mdns_send_rx_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L354) | [send_rx_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_networking_lwip.c#L48) | The refactored function 'send_rx_action' replaces the direct xQueueSend call with mdns_priv_queue_action, but the implementation of mdns_priv_queue_action is not visible in the provided context. This introduces a potential subtle bug if mdns_priv_queue_action does not properly handle the queue operation with the same blocking/non-blocking behavior (original used (TickType_t)0 timeout) or if it returns incorrect boolean values that don't match the expected ESP_OK/ESP_ERR_NO_MEM semantics. Additionally, the function was changed from global to static scope, which could break external callers if not properly addressed in the refactoring. | +| [_mdns_get_default_instance_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L373) | [get_default_instance_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L175) | The refactored function introduces potential subtle bugs due to the separation of concerns. Specifically:
1. The helper functions mdns_priv_get_instance() and mdns_priv_get_global_hostname() may have different NULL-checking behavior than the original direct _mdns_server access
2. There could be thread safety issues if s_server (the refactored equivalent of _mdns_server) is accessed without proper synchronization
3. The behavior when s_server is NULL may not exactly match the original behavior, particularly in edge cases
4. The replacement of _str_null_or_empty with mdns_utils_str_null_or_empty could have different implementations that handle edge cases differently | +| [_mdns_get_service_instance_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L389) | [mdns_utils_get_service_instance_name](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L192) | The refactored function get_default_instance_name() can return NULL when both mdns_priv_get_instance() and mdns_priv_get_global_hostname() return NULL or empty strings, whereas the original _mdns_get_default_instance_name() appears to always return a non-NULL string. This behavioral change could lead to null pointer dereferences in callers that expect a valid string, as evidenced by the original usage patterns where the return value is used directly in string operations without null checks. | +| [_mdns_instance_name_match](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L398) | [mdns_utils_instance_name_match](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L202) | The refactored function `mdns_utils_instance_name_match` calls `get_default_instance_name()` which uses `mdns_priv_get_instance()` internally, while the original function `_mdns_instance_name_match` used `_mdns_get_default_instance_name()` that directly accessed `_mdns_server->instance`. The behavioral equivalence depends on whether `mdns_priv_get_instance()` returns the same value as the original direct server access, particularly in edge cases where the server state might be inconsistent or during initialization/teardown phases. | +| [_mdns_service_match_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L409) | [mdns_utils_service_match_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L162) | The refactored function changed from static to public scope (removed static keyword), which could break encapsulation and allow unintended external access to internal service matching logic. Additionally, the helper function `mdns_utils_str_null_or_empty` might have different behavior than the original `_str_null_or_empty` if it was reimplemented during the utility extraction. | +| [_mdns_get_service_item_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L422) | [mdns_utils_get_service_item_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L143) | | +| [_mdns_read_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L452) | [mdns_utils_read_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L18) | The refactored function mdns_utils_parse_fqdn uses a static buffer (static char buf[MDNS_NAME_BUF_LEN]) which could cause thread safety issues in a multi-threaded environment or reentrancy problems if the function is called recursively. Additionally, the memory movement operations using memmove in mdns_utils_parse_fqdn appear to be incorrectly calculating the offsets - the destination and source calculations seem to assume the mdns_name_t structure fields are exactly MDNS_NAME_BUF_LEN bytes apart, which may not be correct if the structure has padding or different field sizes. | +| [_mdns_set_u16](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L512) | ??? | | +| [_mdns_append_u8](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L530) | [mdns_utils_append_u8](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.h#L147) | | +| [_mdns_append_u16](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L549) | [mdns_utils_append_u16](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L262) | | +| [_mdns_append_u32](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L568) | [append_u32](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L39) | The bounds check in the refactored function uses `(*index + sizeof(uint32_t)) >= MDNS_MAX_PACKET_SIZE` while the original used `(*index + 3) >= MDNS_MAX_PACKET_SIZE`. Although `sizeof(uint32_t)` should typically be 4, this creates a potential portability issue if compiled on a system where `uint32_t` has a different size. Additionally, the refactored function now depends on `mdns_utils_append_u8` which has different error handling - it returns 0 on bounds violation but doesn't prevent the index from being incremented in subsequent calls, potentially causing inconsistent state. | +| [_mdns_append_type](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L590) | [append_type](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L61) | The refactored function uses inconsistent function naming: `mdns_utils_append_u16` and `append_u32` (without the `mdns_utils_` prefix). This suggests either a missing utility function implementation or inconsistent refactoring that could lead to compilation errors if `append_u32` is not properly defined in the same context. Additionally, the buffer size calculation changed from hardcoded 10 to using sizeof operations, which while functionally equivalent, introduces potential maintenance complexity. | +| [_mdns_append_string_with_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L622) | [append_string](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L103) | The refactored function `append_string` introduces a subtle bug by replacing the explicit length parameter with `strlen(string)`. This breaks compatibility with:
1. Non-null-terminated strings that were previously supported
2. Binary data that might contain embedded null bytes
3. Callers who want to control the exact length written (important for DNS label encoding)
4. Embedded systems use cases where string length might be known without scanning

Additionally, the return value behavior has changed from returning the number of bytes written (len + 1) to potentially returning 0 on failure, which may break error handling logic in callers expecting the original return value pattern. | +| [_mdns_append_string](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L642) | [append_string](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L103) | The refactored function `append_single_str` has a critical semantic change in its return value. While the original `_mdns_append_string` returns the length of added data (string length + 1) on success, `append_single_str` returns the updated packet index. This could break calling code that relies on the original return value semantics for length calculations or error checking. Additionally, `append_single_str` introduces an extra error check for `mdns_utils_append_u8` that wasn't present in the original, which changes the error handling behavior. | +| [append_one_txt_record_entry](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L665) | [mdns_priv_append_one_txt_record_entry](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L3399) | The boundary check condition `(*index + len + 1) >= MDNS_MAX_PACKET_SIZE` in both original and refactored code may be incorrect. It should likely use `>` instead of `>=` to prevent buffer overflow when `*index + len + 1` exactly equals `MDNS_MAX_PACKET_SIZE`. This would write one byte beyond the allocated buffer size. The refactoring preserved this potential off-by-one error rather than fixing it. | +| [append_single_str](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L686) | [append_single_str](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L430) | The refactored append_single_str function now calls mdns_utils_append_u8 instead of _mdns_append_u8, but the return value check is incorrect. The original _mdns_append_u8 likely returned 0 on failure, but the new mdns_utils_append_u8 returns 1 on success and 0 on failure. However, the refactored code checks "if (!mdns_utils_append_u8(...))" which is correct for the new return semantics, but there's a potential issue: the original function returned the final packet index on success, while the new helper returns a boolean. This could cause issues if any calling code depends on the specific return value semantics beyond just success/failure checking. | +| [append_fqdn_dots](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L711) | [append_fqdn_dots](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L455) | The refactored append_fqdn_dots function in Result 1 has a subtle bug: it always appends "arpa" suffix regardless of the input domain, whereas the original function's logic suggests this should only be used for reverse DNS queries. The function also ignores the 'last' parameter completely, which may indicate missing functionality for handling non-reverse DNS queries. Additionally, the hardcoded "arpa" suffix could cause incorrect FQDN formatting for regular forward DNS queries. | +| [_mdns_append_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L750) | [append_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L667) | The refactored function calls `append_string` instead of `_mdns_append_string`, but the search results show no implementation of `append_string` in the refactored codebase. This suggests the function may be missing, which would cause linking errors or runtime failures. Additionally, the recursive call to `append_fqdn` relies on this potentially missing function, creating a dependency chain that may be broken. | +| [_mdns_append_ptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L823) | [append_ptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L781) | | +| [_mdns_append_subtype_ptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L873) | ??? | | +| [_mdns_append_sdptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L918) | [append_sdptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1038) | | +| [_mdns_append_txt_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L968) | [append_txt_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L974) | The refactored function uses renamed helper functions (mdns_utils_get_service_instance_name, append_fqdn, append_type, mdns_priv_append_one_txt_record_entry, set_u16) and constants (MDNS_UTILS_DEFAULT_DOMAIN) without verification that these have identical behavior and error handling as their original counterparts. Specifically, if any of these helper functions now have different buffer bounds checking, error return values, or memory management behavior, it could introduce subtle bugs in packet construction, buffer overflow protection, or error propagation. | +| [_mdns_append_srv_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1032) | [append_srv_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L902) | The refactored function replaces direct struct member access `_mdns_server->hostname` with a function call `mdns_priv_get_global_hostname()`. This could introduce subtle bugs if:
1. The function returns NULL when the original struct member was guaranteed to be non-NULL
2. The function has different error handling semantics
3. The function introduces side effects or performance overhead not present in the original
4. The function's behavior differs in edge cases (e.g., during initialization/shutdown)

Additionally, the function name changes from `_mdns_append_u16` to `mdns_utils_append_u16` and similar utility function renames could introduce behavioral differences if the implementations are not functionally equivalent. | +| [_mdns_append_a_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1105) | [append_a_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1089) | The boundary check condition `(*index + 3) >= MDNS_MAX_PACKET_SIZE` is preserved from the original but appears to be incorrect. When *index equals MDNS_MAX_PACKET_SIZE - 3, the condition evaluates to true (preventing the write), but the code needs to write 4 bytes starting from *index. This means the valid range should be *index <= MDNS_MAX_PACKET_SIZE - 4. The condition should likely be `(*index + 4) > MDNS_MAX_PACKET_SIZE` or `(*index > MDNS_MAX_PACKET_SIZE - 4)` to properly prevent buffer overflow. | +| [_mdns_append_aaaa_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1157) | [append_aaaa_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1141) | The refactored function uses renamed utility functions (append_fqdn, append_type, set_u16, mdns_utils_str_null_or_empty) and constants (MDNS_UTILS_DEFAULT_DOMAIN) without verification that they maintain identical behavior to the original implementations. Specifically, if any of these helper functions now have different error handling, boundary checking, or return value semantics, it could cause subtle bugs in AAAA record construction. The domain name change from MDNS_DEFAULT_DOMAIN to MDNS_UTILS_DEFAULT_DOMAIN could also affect DNS resolution if the values differ. | +| [_mdns_append_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1201) | [append_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L734) | The refactored function uses `append_fqdn` and `mdns_utils_append_u16` which may have different error handling behavior than the original `_mdns_append_fqdn` and `_mdns_append_u16` functions. Specifically, the bounds checking in `mdns_utils_append_u16` returns 0 on error, but the original function's behavior is unknown. Additionally, the cumulative length calculation in the refactored function could be incorrect if the utility functions return 0 on error, as it would add 0 to `part_length` instead of properly handling the error case. | +| [_mdns_get_other_if](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1242) | [mdns_priv_netif_get_other_interface](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L73) | | +| [_mdns_if_is_dup](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1253) | [mdns_priv_pcb_check_for_duplicates](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L89) | The refactored function uses a different data structure (s_pcbs) and interface lookup mechanism (s_esp_netifs[tcpip_if].duplicate) compared to the original (_mdns_server->interfaces[...].pcbs and _mdns_get_other_if). Without verification that these data structures are properly initialized and contain equivalent state information, there's a risk of accessing uninitialized memory or incorrect duplicate detection. Additionally, the refactored code assumes MDNS_IP_PROTOCOL_MAX equals 2 (covering both IPv4 and IPv6), which may not match the original implementation's explicit protocol checks. | +| [_ipv6_address_is_zero](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1273) | [mdns_utils_ipv6_address_is_zero](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L249) | | +| [_mdns_append_host_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1286) | [append_host_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1182) | The refactored append_answer function introduces new host validation logic that checks if the host is valid (either self-host or in the hosts list) before processing. This validation was not present in the original _mdns_append_host_answer function and could potentially block legitimate host answers if the validation logic is incorrect or if there are timing issues with the host list management. Additionally, the return value semantics have changed - the original function returned the count of successfully appended records, while append_answer returns different values (0, 1, 2, count) depending on the context, which could break the calling code's expectations. | +| [_mdns_append_reverse_ptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1318) | [append_reverse_ptr_record](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L485) | The refactored function uses `mdns_priv_get_self_host()->hostname` without checking if `mdns_priv_get_self_host()` returns NULL. In the original code, `_mdns_self_host.hostname` was accessed directly, suggesting `_mdns_self_host` was a global struct. The new access pattern through a function call introduces a potential null pointer dereference if the function returns NULL when the self host is not properly initialized. | +| [_mdns_append_service_ptr_answers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1350) | [append_service_ptr_answers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L870) | | +| [_mdns_append_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1378) | [append_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1215) | The refactoring introduces potential behavioral changes in the IPv4 and IPv6 address handling logic. Specifically:

1. The original code checked `_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].state != PCB_DUP` and `_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].state != PCB_DUP`, but the refactored code uses `!mdns_priv_pcb_is_duplicate(tcpip_if, MDNS_IP_PROTOCOL_V4)` and `!mdns_priv_pcb_is_duplicate(tcpip_if, MDNS_IP_PROTOCOL_V6)`. The logic appears inverted - the original checks if state is NOT PCB_DUP, while the new function name suggests it checks if IS duplicate.

2. The original used `_mdns_if_is_dup(tcpip_if)` while the refactored uses `mdns_priv_pcb_check_for_duplicates(tcpip_if)`. These appear to be different checks with potentially different semantics.

3. The IPv6 zero address check changed from `_ipv6_address_is_zero(if_ip6s[i])` to `mdns_utils_ipv6_address_is_zero(if_ip6s[i])`. Without seeing the implementation of both functions, we cannot guarantee identical behavior.

These changes could affect when additional interface addresses are appended and when IPv6 addresses are considered valid, potentially breaking the duplicate interface handling logic and IPv6 address validation. | +| [_mdns_dispatch_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1490) | [mdns_priv_dispatch_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1329) | The refactoring changed the function from static to global visibility (mdns_priv_dispatch_tx_packet), which breaks encapsulation and could allow unintended external calls to this internal packet dispatch function. Additionally, the static buffer 'packet[MDNS_MAX_PACKET_SIZE]' remains, creating potential thread safety issues if multiple threads call this function concurrently, as they would share the same buffer. The debug functionality extraction to DBG_TX_PACKET macro and mdns_debug_tx_packet function appears correct, but without seeing the macro definition, we cannot verify if debug code is properly conditionally compiled. | +| [_mdns_free_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1559) | [mdns_priv_free_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L187) | | +| [_mdns_schedule_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1588) | [mdns_priv_send_after](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1617) | The refactored function mdns_priv_send_after has changed from static to non-static visibility, which could lead to unintended external access to the internal packet scheduling mechanism. Additionally, the global queue variable has been renamed from _mdns_server->tx_queue_head to s_tx_queue_head, but without seeing the broader context of how s_tx_queue_head is declared and managed, there may be synchronization issues if multiple threads can access this queue concurrently. The original function was tightly coupled with the _mdns_server structure, and this refactoring appears to separate the queue management from the server context without clear evidence of proper synchronization mechanisms being added. | +| [_mdns_clear_tx_queue_head](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1611) | [mdns_priv_clear_tx_queue](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2107) | The refactored function uses a global variable `s_tx_queue_head` instead of accessing it through `_mdns_server->tx_queue_head`. This changes the data structure from a server-specific queue to a global queue, which could introduce race conditions in multi-server scenarios or break the encapsulation of server state. Additionally, the function name change suggests it's now part of a different module (mdns_send.c), which may indicate architectural changes that need verification across the entire codebase. | +| [_mdns_clear_pcb_tx_queue_head](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1627) | [mdns_priv_clear_tx_queue_if](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1656) | | +| [_mdns_get_next_pcb_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1655) | [mdns_priv_get_next_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2294) | The refactored function changed from accessing `_mdns_server->tx_queue_head` to `s_tx_queue_head`, which represents a change in global state management. This could introduce subtle bugs if:
1. `s_tx_queue_head` is not properly initialized or synchronized with the rest of the system
2. Other parts of the codebase still reference `_mdns_server->tx_queue_head` inconsistently
3. The queue management operations (add/remove packets) use different queue head variables in different modules

Additionally, the function visibility changed from static to non-static, which could break encapsulation and allow unintended external access to internal queue operations. | +| [_mdns_remove_scheduled_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1670) | [mdns_priv_remove_scheduled_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2558) | The refactored function changed from static to non-static scope while maintaining the pattern of creating a local mdns_srv_item_t variable when service is NULL. This could lead to undefined behavior if the function is called from multiple threads or contexts, as the local variable's address is used for comparison in the linked list traversal. Additionally, the global variable access changed from _mdns_server->tx_queue_head to s_tx_queue_head, which may have different synchronization guarantees. | +| [_mdns_dealloc_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1704) | [mdns_priv_dealloc_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2408) | The refactored function `mdns_priv_dealloc_answer` has a potential bug when `service` parameter is NULL. In the original function, when `service` is NULL, it creates a local `mdns_srv_item_t s` with NULL pointers and uses `service = &s`, then compares `d->service == service->service`. However, `service->service` will be NULL in this case, so it's comparing `d->service == NULL`. This logic is preserved in the refactored version, but the comparison `d->service == service->service` when `service` points to a stack-allocated structure with NULL members could be confusing and error-prone. The function appears to be trying to match answers where the service pointer is NULL, but this pattern is fragile and depends on the caller's understanding of when to pass NULL vs an actual service. | +| [_mdns_alloc_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1733) | [mdns_priv_create_answer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L1053) | The refactored function `mdns_priv_create_answer` has lost the `static` qualifier that was present in the original `_mdns_alloc_answer` function. This changes the function's visibility from file-scope to global scope, which could lead to unintended external access and potential linkage issues. Additionally, the function name change from `_mdns_alloc_answer` to `mdns_priv_create_answer` suggests it should remain private, but removing the `static` qualifier contradicts this intention. | +| [_mdns_alloc_packet_default](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1763) | [mdns_priv_alloc_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2698) | The function visibility has changed from static to non-static (exported), which could break encapsulation and allow unintended external access to this internal packet allocation function. This may lead to architectural issues where external code could bypass proper MDNS APIs and directly manipulate packet allocation, potentially causing memory management issues or protocol violations. | +| [_mdns_create_answer_from_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1789) | [create_answer_from_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L255) | The refactored function uses `mdns_priv_get_self_host()` instead of comparing directly with `&_mdns_self_host`, which could introduce subtle behavioral differences if the function doesn't return the expected reference. Additionally, the MDNS_TYPE_SDPTR case consistently uses `false` for the `send_flush` parameter in both versions, but this might be an existing issue that wasn't addressed during refactoring. | +| [_mdns_create_answer_from_hostname](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1824) | [create_answer_from_hostname](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L292) | | +| [_mdns_service_match_ptr_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1834) | [service_match_ptr_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L302) | The refactored function uses renamed helper functions (mdns_utils_service_match and mdns_utils_get_service_instance_name) without verification that they maintain identical behavior to the original _mdns_service_match and _mdns_get_service_instance_name functions. If these helper functions have different error handling, null checking, or return value semantics, it could introduce subtle bugs in service discovery logic. | +| [_mdns_create_answer_from_parsed_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L1862) | [mdns_priv_create_answer_from_parsed_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L3276) | The refactored function has changed from static to non-static visibility, which could break encapsulation and allow unintended external access. Additionally, the function `mdns_priv_get_services()` replaces direct access to `mdns_server->services`, but without seeing its implementation, we cannot verify it returns the same service list with proper synchronization. The `get_host_item()` function also replaces `mdns_get_host_item()` - if these have different implementations, it could affect host matching logic and service discovery behavior. | +| [_mdns_question_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2009) | [question_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L377) | | +| [_mdns_append_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2023) | [append_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L326) | The refactored `append_host_list` function contains a potential linked list traversal bug. The original code in `_mdns_append_host_list` correctly traversed the host list by advancing the pointer after processing each host. However, the refactored version advances `host = host->next` before calling `append_host`, which means:
1. The first host in the list is skipped entirely
2. The last iteration will attempt to access `host->next` which could be NULL, leading to potential NULL pointer dereference in `append_host`
3. This could result in missing host entries in MDNS responses

The correct pattern should be:
```c
while (host != NULL) {
if (!append_host(destination, host, flush, bye)) {
return false;
}
host = host->next;
}
``` | +| [_mdns_append_host_list_in_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2034) | [mdns_priv_append_host_list_in_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L1834) | The refactored function changes the hostname lookup mechanism from `_mdns_server->hostname` to `mdns_priv_get_global_hostname()`. This could introduce subtle bugs if:
1. The global hostname differs from the server hostname in certain contexts
2. The `mdns_priv_get_global_hostname()` function has different initialization timing or state dependencies
3. There are race conditions where the global hostname changes during packet construction

Additionally, the function dependencies have changed from `mdns_get_host_item` and `_mdns_append_host` to `get_host_item` and `append_host`. Without verifying these functions have identical behavior, there's risk of:
- Different error handling semantics
- Changed memory management patterns
- Modified host lookup logic | +| [_mdns_append_host_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2053) | [append_host_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L356) | The refactored append_host_list function has a critical bug in the while loop logic. The original code correctly processes the current host before advancing to the next one (host = host->next at the end of the loop). The refactored version advances the pointer before processing (host = host->next at the beginning of the loop), which causes it to skip the first host in the list and potentially access invalid memory when the list is empty or has only one element. | +| [_mdns_append_host_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2071) | [append_host_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L391) | The refactored function uses MDNS_UTILS_DEFAULT_DOMAIN instead of MDNS_DEFAULT_DOMAIN, which could be a different constant value. Additionally, it calls question_exists instead of _mdns_question_exists, which might have different implementation behavior. The related function append_host_questions_for_services now uses mdns_priv_get_global_hostname() instead of directly accessing _mdns_server->hostname, which could introduce different behavior if the global hostname retrieval differs from the direct struct access. | +| [_mdns_append_host_questions_for_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2094) | [append_host_questions_for_services](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L414) | The refactored function introduces a subtle bug in the append_host_question helper function. The original implementation did not check for duplicate questions before adding them to the queue, but the refactored version now includes a question_exists check that frees the allocated memory if a duplicate is found, yet still returns true. This means:
1. Memory is allocated but potentially leaked if duplicates exist (malloc followed by free without being added to queue)
2. The function returns true even when the question wasn't actually added to the questions list
3. This could lead to inconsistent state where callers think questions were added but they weren't
Additionally, the change from direct _mdns_server->hostname access to mdns_priv_get_global_hostname() and from _str_null_or_empty to mdns_utils_str_null_or_empty could introduce behavioral differences if these functions don't have identical implementations. | +| [_mdns_create_probe_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2112) | [mdns_priv_create_probe_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L887) | The function `question_exists` (without the `mdns_priv_` prefix) appears to be a different implementation than the original `_mdns_question_exists`. This could introduce subtle bugs if the new function has different behavior for duplicate question detection, potentially causing incorrect packet construction or memory leaks. Additionally, the constant `MDNS_UTILS_DEFAULT_DOMAIN` may have a different value than the original `MDNS_DEFAULT_DOMAIN`, which could affect DNS query formatting and service discovery. | +| [_mdns_create_announce_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2166) | [mdns_priv_create_announce_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L1256) | The refactored function uses different underlying helper functions (mdns_priv_alloc_packet, mdns_priv_create_answer, mdns_priv_free_tx_packet, mdns_priv_append_host_list_in_services) compared to the original (_mdns_alloc_packet_default, _mdns_alloc_answer, _mdns_free_tx_packet, _mdns_append_host_list_in_services). While the function signatures appear identical, the inability to find these renamed functions in the search results suggests they may have different implementations or behaviors that could introduce subtle bugs, particularly around memory management, error handling, or protocol compliance. The refactoring assumes functional equivalence of these underlying components without verification. | +| [_mdns_create_announce_from_probe](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2196) | [mdns_priv_create_announce_from_probe](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L1417) | The function `mdns_get_host_item` from the original code has been replaced with `get_host_item` without the `mdns_` prefix. This could indicate either an incomplete refactoring where the prefix was accidentally omitted, or a different function with potentially different behavior. If `get_host_item` is not the correct replacement or has different memory management semantics, it could lead to null pointer dereferences or incorrect host item lookups. | +| [_mdns_pcb_send_bye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2236) | [mdns_priv_send_bye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1505) | The refactored function mdns_priv_pcb_send_bye_service introduces a new global hostname check using mdns_utils_str_null_or_empty(mdns_priv_get_global_hostname()) that wasn't present in the original code. This could prevent goodbye packets from being sent when the global hostname is empty, potentially leaving stale service records in the network. The original implementation would send goodbye packets regardless of hostname state, which may be the intended behavior for proper service cleanup. | +| [_mdns_init_pcb_probe_new_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2260) | [init_probe_new_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L339) | The refactoring introduces a potential stack overflow vulnerability in mdns_priv_init_pcb_probe where a Variable Length Array (VLA) `new_probe_services[len]` is allocated on the stack without bounds checking. If `len` is large, this could cause stack exhaustion. Additionally, the global hostname check in mdns_priv_init_pcb_probe may prematurely set PCB state to RUNNING without probing services, potentially skipping necessary service discovery steps. | +| [_mdns_init_pcb_probe_new_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2260) | [mdns_priv_init_pcb_probe](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_pcb.c#L2478) | The refactoring introduces a potential stack overflow vulnerability in mdns_priv_init_pcb_probe where a Variable Length Array (VLA) `new_probe_services[len]` is allocated on the stack without bounds checking. If `len` is large, this could cause stack exhaustion. Additionally, the global hostname check in mdns_priv_init_pcb_probe may prematurely set PCB state to RUNNING without probing services, potentially skipping necessary service discovery steps. | +| [_mdns_init_pcb_probe](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2316) | [mdns_priv_init_pcb_probe](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_pcb.c#L2478) | The refactored code introduces a potential stack overflow vulnerability by using a Variable Length Array (VLA) `new_probe_services[len]` without bounds checking. In the original code, the VLA usage was the same, but the refactoring context doesn't show if `len` is properly validated elsewhere. Large `len` values could exhaust the stack, especially in embedded environments. Additionally, the refactored `init_probe_new_service` function has complex memory management logic that could leak memory if `mdns_priv_create_probe_packet` returns NULL, though this appears consistent with the original design. | +| [_mdns_restart_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2356) | [restart_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L127) | The refactored function uses `mdns_priv_get_services()` instead of direct access to `_mdns_server->services`, which changes the data access pattern. While this might be intentional encapsulation, it could introduce subtle bugs if:
1. `mdns_priv_get_services()` returns a different service list than the original global variable
2. The function is called multiple times (line 132 and 140) and the service list changes between calls
3. The service counting logic becomes inconsistent if services are added/removed during execution

Additionally, the function name changed from `_mdns_restart_pcb` to `restart_pcb`, which may affect visibility and linkage if this was previously a static function. | +| [_mdns_send_bye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2382) | [mdns_priv_pcb_send_bye_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L429) | The refactored function uses a different PCB state access pattern: original code accessed `_mdns_server->interfaces[i].pcbs[j].state` while refactored code uses `s_pcbs[i][j].state`. This structural change could introduce subtle bugs if the PCB state management or initialization logic differs between the two implementations, potentially leading to incorrect state checks or accessing uninitialized memory. | +| [_mdns_send_bye_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2401) | [mdns_priv_send_bye_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L1681) | The refactored function changed from static to non-static visibility, which could break encapsulation and allow unintended external access. Additionally, the static buffer 'pkt' remains in the refactored code, creating potential race conditions in multi-threaded environments since multiple instances could overwrite the same buffer. | +| [_mdns_announce_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2451) | [mdns_priv_pcb_announce](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_pcb.c#L861) | The refactored function accesses PCB state through a different global structure (s_pcbs[][] instead of _mdns_server->interfaces[].pcbs[]), which could lead to state inconsistencies if the initialization or synchronization of these structures differs. Additionally, the hostname check now uses mdns_priv_get_global_hostname() instead of direct access to _mdns_server->hostname, which may return different values if the global hostname management was modified during refactoring. | +| [_mdns_probe_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2494) | [mdns_priv_probe_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_pcb.c#L2342) | The refactored function accesses PCB data through `s_pcbs[i][j]` instead of `_mdns_server->interfaces[i].pcbs[j]`, which represents a significant architectural change in data structure organization. This could introduce subtle bugs if:

1. The `s_pcbs` array is not properly initialized or synchronized with the original server state
2. The memory layout or indexing differs between the two data structures
3. There are race conditions in accessing the global `s_pcbs` vs the server-managed PCB structures

Additionally, the helper function `mdns_priv_init_pcb_probe` (shown in Result 3) has been substantially refactored with new logic for duplicate service detection and different probing state handling, which may change the probing behavior in edge cases where services are already being probed. | +| [_mdns_announce_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2516) | [announce_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L150) | The refactored function `announce_all_pcbs` calls `mdns_priv_pcb_announce` which introduces state-dependent behavior that wasn't present in the original implementation. In the PCB_RUNNING state, there's a global hostname check that can cause the function to return early without any announcement if the hostname is null or empty. This could lead to silent failures where services aren't announced when expected, particularly during system initialization or hostname changes. The original implementation would always attempt to announce regardless of PCB state or hostname status. | +| [_mdns_send_final_bye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2529) | [send_final_bye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L163) | The refactored function send_final_bye calls mdns_priv_pcb_send_bye_service which adds a hostname validation check that wasn't present in the original function. This could prevent bye packets from being sent when the global hostname is empty/null, potentially leaving stale service records in the network. Additionally, the new implementation iterates through multiple interfaces/protocols and checks PCB state, which may change the multicast behavior compared to the original single-call approach. | +| [_mdns_send_bye_all_pcbs_no_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2554) | [send_bye_all_pcbs_no_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L188) | The refactored function `send_bye_all_pcbs_no_instance` now calls `mdns_priv_pcb_send_bye_service` which includes an additional global hostname check that wasn't present in the original implementation. This could potentially prevent bye packets from being sent when the global hostname is empty, even though services without instances should still be able to send bye packets independently of the hostname state. This represents a behavioral change that might affect service shutdown behavior. | +| [_mdns_restart_all_pcbs_no_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2582) | [mdns_priv_restart_all_pcbs_no_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L213) | | +| [_mdns_restart_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2610) | [mdns_priv_restart_all_pcbs](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L238) | The refactored function changed from static to non-static visibility, which could lead to unintended external access and linkage issues. Additionally, the global variable changed from _mdns_server to s_server, and function calls changed from _mdns_clear_tx_queue_head() to mdns_priv_clear_tx_queue() and _mdns_probe_all_pcbs() to mdns_priv_probe_all_pcbs(). Without verification that these are functionally equivalent, there's risk of behavioral changes or memory management issues. | +| [_mdns_allocate_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2643) | [allocate_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L269) | The refactored function `allocate_txt` has a subtle memory leak bug. In the original function, when `mdns_mem_strdup(txt[i].value)` fails, it properly cleans up by freeing both `new_item->key` and `new_item` before breaking. However, in the refactored version, when `mdns_mem_strdup(txt[i].value)` fails, it only frees `(char *)new_item->key` and `new_item`, but any previously allocated items in the linked list (`new_txt`) remain allocated and are not cleaned up. This creates a memory leak where partial allocations are not properly rolled back when allocation failures occur mid-loop. | +| [_mdns_free_linked_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2682) | [free_linked_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L308) | The refactored function free_linked_txt casts t->key and t->value to (char *) before freeing, which assumes these fields were allocated as char arrays. While this matches the original behavior, this pattern relies on implementation details of the memory allocator and could be problematic if the allocation types change. The casting suggests potential type safety issues in the memory management design. | +| [_mdns_create_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2706) | [create_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L332) | The refactored code introduces a potential resource leak in the error handling path of mdns_service_add_for_host. When create_service succeeds but the subsequent mdns_mem_malloc for the mdns_srv_item_t fails, the function calls free_service(s) but does not remove the service from the global s_server->services list. Additionally, the locking mechanism (mdns_priv_service_lock/unlock) wraps the entire function but the original _mdns_create_service was likely called within an already locked context, potentially creating deadlock risks or inconsistent locking behavior. | +| [_mdns_dealloc_scheduled_service_answers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2762) | [dealloc_scheduled_service_answers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1742) | The refactored function 'dealloc_scheduled_service_answers' has identical logic to the original but there's a potential issue with the second while loop. In the original function, when d->next is NULL but d itself matches the service, it won't be removed in the second loop. The refactored version preserves this same behavior, which might be intentional but could lead to leftover answers if the first element after the initial removal matches the service but has no next pointer. This appears to be a pre-existing issue carried over from the original implementation. | +| [_mdns_remove_scheduled_service_packets](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2787) | [mdns_priv_remove_scheduled_service_packets](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mock_mdns_send.c#L2171) | The refactored function passes the condition `had_answers && q->answers == NULL` to `mdns_priv_pcb_check_probing_services` for the announcing state check, but this condition is evaluated before the deallocation calls. In the original code, this condition was checked after deallocation, which could lead to different behavior if the deallocation functions modify the answers list during execution. This timing difference might cause incorrect PCB state transitions during service removal. | +| [_mdns_free_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2868) | [free_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L385) | The refactored function `free_subtype` appears to be a direct replacement for `_mdns_free_subtype` with identical logic, but there's a potential memory safety issue: the function casts `subtype->subtype` to `(char *)` before freeing, which suggests the original data might have been declared as `const char *`. This cast could mask const-correctness violations in the codebase. If the subtype string was originally allocated as read-only memory or through string literals, this could lead to undefined behavior when attempting to free it. | +| [_mdns_free_service_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2878) | [free_service_subtype](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L395) | | +| [_mdns_free_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2889) | [free_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L406) | The refactored function `free_service` calls `free_service_subtype(service)` which sets `service->subtype = NULL`, but this happens after the service structure has already been freed with `mdns_mem_free(service)`. This creates a use-after-free bug where we're writing to memory that has already been deallocated. In the original code, `_mdns_free_service_subtype` was called before freeing the service structure, which was correct. | +| [_mdns_check_srv_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2917) | [check_srv_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L438) | The refactored function hardcodes domain length as 5 bytes when copying MDNS_UTILS_DEFAULT_DOMAIN, but there's no verification that MDNS_UTILS_DEFAULT_DOMAIN is actually exactly 5 bytes. If the domain constant differs in length, this could cause buffer overruns or incorrect collision detection. Additionally, the function uses Variable Length Arrays (VLAs) which could cause stack overflow with very long hostnames, and the uint16_t index variables may overflow if the total data length exceeds 65535 bytes. | +| [_mdns_check_txt_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L2974) | [check_txt_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L393) | The refactored function uses mdns_priv_append_one_txt_record_entry instead of append_one_txt_record_entry. While both functions appear to have identical signatures and similar logic, the refactored version is no longer inline and has been moved to a separate compilation unit (mdns_send.c). This could potentially impact performance in the collision detection hot path, and there's a risk that the implementation might differ slightly in edge cases (like handling of empty values or special characters) which could affect the byte-for-byte comparison critical for proper mDNS collision resolution. | +| [mdns_pcb_deinit_local](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3016) | [deinit_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L107) | The NULL check on `pcb` in the refactored function is problematic. In the original code, `_pcb` was obtained via `&_mdns_server->interfaces[tcpip_if].pcbs[ip_proto]`, which would always return a valid address (not NULL) if the array structure exists. In the refactored code, `pcb = &s_pcbs[tcpip_if][ip_proto]` should also always return a valid address. This NULL check could mask actual initialization issues with the `s_pcbs` array and might prevent proper error propagation from `mdns_priv_if_deinit`. The check should either be removed or replaced with a proper array bounds validation. | +| [_mdns_dup_interface](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3035) | [mdns_priv_pcb_set_duplicate](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L186) | The refactored function uses a different data structure (s_pcbs[tcpip_if][i] vs _mdns_server->interfaces[tcpip_if].pcbs[i]) and the state transition to PCB_DUP is performed unconditionally without verifying if the PCB was previously in a valid state. This could lead to inconsistent state management if the PCB was already in PCB_OFF or another terminal state. Additionally, the function is no longer static, which changes its visibility and could affect encapsulation. | +| [_mdns_check_a_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3059) | [check_a_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L322) | The refactored function uses different helper functions (mdns_priv_get_esp_netif, mdns_priv_netif_get_other_interface, mdns_priv_pcb_set_duplicate) compared to the original (_mdns_get_esp_netif, _mdns_get_other_if, _mdns_dup_interface). While the function logic appears identical, there's a risk that these renamed helper functions might have different implementations or error handling behaviors that could affect the collision detection logic. Specifically, if mdns_priv_netif_get_other_interface returns different values than _mdns_get_other_if for edge cases, or if mdns_priv_pcb_set_duplicate has different side effects than _mdns_dup_interface, this could introduce subtle behavioral changes in the collision resolution protocol. | +| [_mdns_check_aaaa_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3095) | [check_aaaa_collision](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L358) | The refactored function uses renamed helper functions and constants whose implementations cannot be verified from the provided context. Specifically:
1. `mdns_priv_netif_get_other_interface` replaces `_mdns_get_other_if` - if this function has different behavior in edge cases (like when interfaces are disabled), it could affect collision detection logic
2. `mdns_priv_pcb_set_duplicate` replaces `_mdns_dup_interface` - if this function performs additional operations or misses some operations from the original, it could impact interface state management
3. `MDNS_UTILS_SIZEOF_IP6_ADDR` must exactly match the original `_MDNS_SIZEOF_IP6_ADDR` (typically 16 bytes for IPv6 addresses), otherwise memcmp comparisons will be incorrect

The functional logic appears identical, but without verifying the implementations of these renamed components, there's risk of subtle behavioral changes. | +| [_hostname_is_ours](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3127) | [mdns_utils_hostname_is_ours](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L105) | The refactored function mdns_utils_hostname_is_ours accesses global data through mdns_priv_get_global_hostname() and mdns_priv_get_hosts() without any locking mechanism, while the original function was called within MDNS_SERVICE_LOCK/UNLOCK sections. This could lead to race conditions if the global hostname or host list is modified concurrently. The wrapper function mdns_hostname_exists does provide locking, but direct calls to mdns_utils_hostname_is_ours without locking could access inconsistent state. | +| [_mdns_delegate_hostname_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3150) | [mdns_priv_delegate_hostname_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L426) | The refactored function uses s_server->host_list instead of the global _mdns_host_list, but there's no null check for s_server. If s_server is NULL, this will cause a segmentation fault when accessing s_server->host_list. The original function directly used the global variable _mdns_host_list which would always be accessible (though potentially NULL for an empty list). This introduces a new failure mode that wasn't present in the original implementation. | +| [free_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3168) | [mdns_utils_free_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L239) | | +| [_mdns_delegate_hostname_set_address](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3178) | [delegate_hostname_set_address](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L444) | The refactored function delegate_hostname_set_address uses mdns_utils_free_address_list instead of the original free_address_list, but the memory ownership semantics may have changed. In the original code, when ACTION_DELEGATE_HOSTNAME_SET_ADDR action fails, the caller explicitly frees the address_list, suggesting the function takes ownership. The refactored version appears to directly assign the address_list to the host item without clear documentation of ownership transfer, which could lead to double-free or memory leaks if the memory management contract has changed. | +| [copy_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3198) | [mdns_utils_copy_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L214) | The refactored function introduces a HOOK_MALLOC_FAILED macro call before freeing the partially allocated list. If this hook has side effects (like logging, delays, or state changes), it could potentially affect error handling behavior or timing in memory-constrained scenarios. Additionally, the function now depends on mdns_utils_free_address_list being available and functionally equivalent to the original free_address_list. | +| [free_delegated_hostnames](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3222) | [free_delegated_hostnames](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L49) | The refactored function now accesses s_server->host_list instead of the global _mdns_host_list, but there is no NULL check for s_server. If free_delegated_hostnames is called when s_server is NULL (e.g., during shutdown or error conditions), this will cause a segmentation fault. Additionally, the function mdns_priv_responder_free calls free_delegated_hostnames after checking if s_server is NULL, suggesting that s_server could be NULL in some scenarios. | +| [_mdns_delegate_hostname_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3235) | [delegate_hostname_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L464) | The refactored function uses different global variables and function names without clear verification that they maintain identical behavior. Specifically: s_server vs _mdns_server, mdns_priv_pcb_send_bye_service vs _mdns_send_bye, mdns_priv_remove_scheduled_service_packets vs _mdns_remove_scheduled_service_packets, and free_service vs _mdns_free_service. The host list management also changed from _mdns_host_list to s_server->host_list. These changes could introduce subtle bugs if the underlying implementations differ, especially around memory management, protocol behavior, or state consistency. | +| [_mdns_name_is_discovery](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3282) | [is_discovery](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L28) | | +| [_mdns_name_is_selfhosted](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3296) | [is_name_selfhosted](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L495) | The refactored function `is_name_selfhosted` introduces a potential null pointer dereference. The original function accessed `_mdns_server->hostname` directly, while the refactored version calls `mdns_priv_get_global_hostname()` without checking if the returned pointer is valid before passing it to `mdns_utils_str_null_or_empty()`. If `mdns_priv_get_global_hostname()` can return NULL, this could lead to undefined behavior. | +| [_mdns_name_is_ours](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3319) | [is_ours](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L60) | The refactored function uses mdns_utils_hostname_is_ours which now checks against multiple hosts from mdns_priv_get_hosts() in addition to the global hostname. This expands the definition of "ours" to include additional hosts, which may break assumptions in the original code that only the global hostname was considered. Additionally, the change from _mdns_server->hostname to mdns_priv_get_global_hostname() could have different semantics if the underlying data structure or initialization timing has changed. | +| [_mdns_read_u16](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3385) | [mdns_utils_read_u16](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.h#L18) | | +| [_mdns_read_u32](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3397) | [mdns_utils_read_u32](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.h#L30) | | +| [_mdns_parse_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3411) | [mdns_utils_parse_fqdn](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_utils.c#L71) | The refactoring changed the function scope from static to external (non-static), which could lead to unintended access from other compilation units and potential namespace pollution. Additionally, the static buffer usage in both mdns_utils_parse_fqdn and mdns_utils_read_fqdn creates reentrancy issues in multi-threaded environments or during recursive calls. | +| [_mdns_question_matches](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3448) | [question_matches](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L518) | The refactored function uses MDNS_UTILS_DEFAULT_DOMAIN instead of MDNS_DEFAULT_DOMAIN, which could introduce subtle bugs if these constants have different values or if MDNS_UTILS_DEFAULT_DOMAIN is not properly defined in the refactored codebase. Additionally, the function _mdns_get_service_instance_name was renamed to mdns_utils_get_service_instance_name, and any behavioral differences between these functions could affect the matching logic for SRV and TXT record types. | +| [_mdns_remove_parsed_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3483) | [remove_parsed_question](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L553) | | +| [_mdns_txt_items_count_get](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3515) | [get_txt_items_count](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L181) | | +| [_mdns_txt_item_name_get_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3542) | [get_txt_item_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L208) | The refactored code in result_txt_create removed the bounds check "txt_num >= num_items" that was present in the original code. In the original implementation, the condition was "if (name_len < 0 || txt_num >= num_items)" which provided protection against buffer overruns when the actual number of parsed TXT items exceeds the pre-allocated array size. The refactored version only checks "if (name_len < 0)" which could lead to writing beyond the allocated txt array bounds if get_txt_items_count returns an incorrect value or if the TXT data contains more valid items than expected. | +| [_mdns_result_txt_create](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3558) | [result_txt_create](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L224) | The refactored function removed the `txt_num >= num_items` check from the invalid item condition, relying solely on the while loop condition `txt_num < num_items`. This creates a potential buffer overrun vulnerability if there are many invalid TXT items (where name_len < 0) followed by valid ones. The original code had double protection by checking both conditions, but the refactored version only checks the array bounds in the loop condition, which could be bypassed if invalid items cause the loop to continue without incrementing txt_num properly. | +| [_mdns_strdup_check](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3654) | [strdup_check](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L122) | | +| [mdns_parse_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L3672) | [mdns_parse_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_receive.c#L587) | The refactored function has been changed from public to static scope, which could break external callers. Additionally, there are potential subtle bugs in the collision detection logic where the refactored version uses simplified PCB state checking via `mdns_priv_pcb_is_probing(packet)` instead of the original direct structure access `_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running`. This abstraction might not handle all edge cases identically, particularly during concurrent probe operations or interface state transitions. | +| [_mdns_enable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4362) | [mdns_priv_pcb_enable](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L172) | | +| [_mdns_disable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4376) | [mdns_priv_pcb_disable](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L153) | The refactored function changes the data structure access pattern from `_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state` to `s_pcbs[tcpip_if][ip_protocol].state`, which represents a significant architectural change. This could introduce subtle bugs related to:
1. Memory layout differences affecting state synchronization
2. Race conditions if the new s_pcbs structure has different locking mechanisms
3. Potential null pointer dereferences if s_pcbs array initialization differs from the original _mdns_server structure
4. Consistency issues with the PCB state transitions across the codebase due to the structural change

Additionally, the function renaming (`mdns_pcb_deinit_local` → `deinit_pcb`, `_mdns_get_other_if` → `mdns_priv_netif_get_other_interface`) suggests broader architectural changes that could affect error handling paths or edge case behavior. | +| [nibble_to_hex](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4393) | [nibble_to_hex](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L46) | | +| [perform_event_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4402) | [perform_event_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L55) | The refactored function maintains the same logic but introduces potential memory leaks in the reverse DNS lookup code. In the IPv4 reverse lookup, asprintf allocates memory for reverse_query_name but there's no free() call if mdns_priv_delegate_hostname_add succeeds. Similarly, in IPv6 reverse lookup, mdns_mem_malloc allocates memory but there's no corresponding free. The original code had the same issue, but this refactoring missed the opportunity to fix it. | +| [post_mdns_disable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4473) | [post_disable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L183) | | +| [post_mdns_enable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4478) | [post_enable_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L189) | | +| [post_mdns_announce_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4483) | [post_announce_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L195) | | +| [mdns_preset_if_handle_system_event](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4489) | [handle_system_event_for_preset](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L202) | The refactored function replaces manual browse iteration with mdns_priv_browse_send_all(), but without seeing the implementation of this function, we cannot verify if it maintains the same iteration behavior as the original _mdns_browse_send() calls. Additionally, the function name changes (esp_netif_from_preset_if to netif_from_preset, etc.) suggest potential semantic differences that need verification. | +| [_mdns_search_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4582) | [search_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L343) | The refactored search_free function does not check if the search parameter is NULL before dereferencing its fields. While the original function also lacked this check, the refactoring moved the function to a different context (mdns_querier.c) where the calling patterns might have changed. In C programming, defensive programming practices suggest checking for NULL pointers before dereferencing, especially for cleanup functions that might be called from multiple contexts with potentially invalid parameters. | +| [_mdns_search_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4594) | [search_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L355) | | +| [_mdns_search_finish](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4652) | [search_finish](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L59) | The refactored function changes the global variable from `_mdns_server->search_once` to `s_search_once`, but there's no evidence that the ACTION_SEARCH_END case in the action handler was updated to call the new function. This could leave dangling searches that are never properly finished when triggered through the action system, potentially causing resource leaks or synchronization issues with the semaphore. | +| [_mdns_search_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4665) | [search_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L72) | | +| [_mdns_search_finish_done](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4674) | [mdns_priv_query_done](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L181) | The refactored function uses a global variable `s_search_once` instead of accessing it through `_mdns_server->search_once`, which changes the data structure access pattern. Additionally, the new `search_finish` function performs different cleanup operations (queue detachment and semaphore signaling) compared to the original `_mdns_search_finish` function, whose implementation is not shown for verification. This could lead to inconsistent search state management or resource cleanup issues. | +| [_mdns_result_addr_create_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4690) | [mdns_priv_result_addr_create_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L653) | The function visibility changed from static to non-static, which could lead to unintended usage across the codebase. Additionally, the refactored function is now called from new contexts (result_add_ip and mdns_priv_query_result_add_ip) that weren't in the original codebase, potentially introducing different error handling requirements. While the core implementation remains identical, the architectural changes in how IP addresses are managed could affect resource cleanup patterns in case of failures. | +| [_mdns_result_update_ttl](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4707) | [mdns_priv_query_update_result_ttl](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.h#L99) | | +| [_mdns_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4715) | [result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L485) | The refactoring introduces a subtle bug in the memory management logic. In the original code, when _mdns_result_addr_create_ip fails, the function simply returns without affecting the result structure. However, in mdns_priv_query_result_add_ip, when mdns_priv_result_addr_create_ip fails during new result creation, the partially allocated mdns_result_t structure is freed, but the search->result pointer is never updated, leaving the search result list in an inconsistent state. Additionally, the hostname string duplication occurs after IP address creation, which could lead to memory leaks if the IP creation fails but the hostname was already allocated. | +| [_mdns_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4715) | [mdns_priv_query_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L514) | The refactoring introduces a subtle bug in the memory management logic. In the original code, when _mdns_result_addr_create_ip fails, the function simply returns without affecting the result structure. However, in mdns_priv_query_result_add_ip, when mdns_priv_result_addr_create_ip fails during new result creation, the partially allocated mdns_result_t structure is freed, but the search->result pointer is never updated, leaving the search result list in an inconsistent state. Additionally, the hostname string duplication occurs after IP address creation, which could lead to memory leaks if the IP creation fails but the hostname was already allocated. | +| [_mdns_search_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4744) | [mdns_priv_query_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L514) | The function 'result_add_ip' is called without the 'mdns_priv_' prefix, which may indicate either a missing namespace prefix or an undefined function. This could lead to linking errors or incorrect behavior if the intended function is not available. All other helper functions were properly prefixed with 'mdns_priv_' or 'mdns_utils_', making this inconsistency potentially problematic. | +| [_mdns_search_result_add_ptr](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4802) | [mdns_priv_query_result_add_ptr](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L614) | The refactored function mdns_priv_query_result_add_ptr appears to have a critical bug: callers in the refactored code (mdns_receive.c lines 851-852, 922-923, 1038-1040) do not check the return value for NULL, unlike the original code which explicitly checked for NULL returns (lines 4020-4023, 4132-4135). This could lead to NULL pointer dereferences if the function fails to allocate memory or encounters other errors. The function signature still returns mdns_result_t*, suggesting it should be checked, but the calling code ignores the return value. | +| [_mdns_search_result_add_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4844) | [mdns_priv_query_result_add_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L572) | | +| [_mdns_search_result_add_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4886) | [mdns_priv_query_result_add_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L435) | The refactoring splits the original unified TXT handling function into two specialized functions (query vs browse) with different signatures. The original parser call site at line 4149 now needs to determine which function to call based on context, but the additional parameters required by mdns_priv_browse_result_add_txt (instance, service, proto) may not be available in all calling contexts where the original function was used. This could lead to either incorrect function selection or missing data when calling the browse version, potentially causing incomplete TXT record processing or memory access issues. | +| [_mdns_search_find_from](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L4936) | [mdns_priv_query_find_from](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L197) | The function has been changed from static to non-static linkage, which could expose internal implementation details and create unintended dependencies. Additionally, the utility function replacements (_mdns_get_esp_netif → mdns_priv_get_esp_netif and _str_null_or_empty → mdns_utils_str_null_or_empty) need verification that they maintain identical behavior in all edge cases, particularly for NULL inputs and network interface mapping. | +| [_mdns_create_search_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5003) | [create_search_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L269) | The refactored function uses `mdns_priv_alloc_packet` instead of `_mdns_alloc_packet_default`. If `mdns_priv_alloc_packet` doesn't provide the same default packet initialization (like setting default flags, TTL values, or other packet metadata), it could result in malformed mDNS search packets that don't conform to protocol specifications. Additionally, the domain constant change from `MDNS_DEFAULT_DOMAIN` to `MDNS_UTILS_DEFAULT_DOMAIN` could affect DNS query formation if the values differ, potentially causing search queries to use the wrong domain. | +| [_mdns_search_send_pcb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5060) | [mdns_priv_query_send](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L327) | The refactored function uses `mdsn_priv_pcb_is_inited(tcpip_if, ip_protocol)` instead of the original complex condition `mdns_is_netif_ready(tcpip_if, ip_protocol) && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state > PCB_INIT`. This could introduce subtle bugs if the new function doesn't properly replicate both the network interface readiness check AND the PCB state validation. Additionally, there appears to be a potential typo in the function name "mdsn_priv_pcb_is_inited" (missing 'n' in 'mdns'). | +| [_mdns_search_send](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5076) | [search_send](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L81) | The refactored function `mdns_priv_query_send` (which replaces `_mdns_search_send_pcb`) immediately frees the packet after dispatch with `mdns_priv_free_tx_packet(packet)`, while the original implementation's packet lifecycle management is unclear. This could cause issues if packet transmission is asynchronous and the packet needs to remain valid until transmission completes. Additionally, the refactored version introduces early return on packet creation failure, which changes the error handling behavior compared to the original loop structure. | +| [_mdns_tx_handle_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5102) | [handle_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1816) | The refactoring splits the original function's logic across multiple functions, but introduces a potential bug in the PCB_PROBE_3 case. In the original code, when creating an announce packet fails, it breaks from the switch statement after scheduling a retry. However, in the refactored version, the variable 'p' is reassigned to 'a' (the new announce packet) in the success case, but this reassignment only affects the local copy in mdns_priv_pcb_schedule_tx_packet. The calling function handle_packet still holds the original 'p' pointer, which could lead to double-free or use-after-free issues if the packet lifecycle isn't properly managed across the function boundaries. | +| [_mdns_tx_handle_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5102) | [mdns_priv_pcb_schedule_tx_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_pcb.c#L211) | The refactoring splits the original function's logic across multiple functions, but introduces a potential bug in the PCB_PROBE_3 case. In the original code, when creating an announce packet fails, it breaks from the switch statement after scheduling a retry. However, in the refactored version, the variable 'p' is reassigned to 'a' (the new announce packet) in the success case, but this reassignment only affects the local copy in mdns_priv_pcb_schedule_tx_packet. The calling function handle_packet still holds the original 'p' pointer, which could lead to double-free or use-after-free issues if the packet lifecycle isn't properly managed across the function boundaries. | +| [_mdns_remap_self_service_hostname](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5159) | [mdns_priv_remap_self_service_hostname](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L508) | The function scope change from static to non-static could potentially cause linking conflicts if this function is now accessible from other compilation units. Additionally, the global variable change from _mdns_server to s_server requires verification that s_server is properly initialized and equivalent to the original _mdns_server in all execution contexts. | +| [_mdns_sync_browse_result_link_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5173) | [sync_browse_result_link_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L236) | The function name changed from `_mdns_sync_browse_result_link_free` to `sync_browse_result_link_free` (removing the leading underscore and "mdns_" prefix). While the core logic remains identical, this naming change could introduce subtle bugs if:
1. Call sites in the refactored codebase haven't been updated to use the new function name
2. The function visibility/scope changed due to the naming convention alteration
3. Other parts of the codebase rely on the specific naming pattern for internal functions

The original function was called in ACTION_BROWSE_SYNC cases in mdns.c, and if those call sites weren't properly updated to reference the renamed function, it would result in compilation errors or runtime failures due to undefined function references. | +| [_mdns_free_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5188) | [free_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L126) | The refactored free_action function delegates cleanup to external functions (mdns_priv_*_action with ACTION_CLEANUP mode) without visible implementation. This introduces a risk that the specific memory cleanup operations performed in the original function (mdns_mem_free for hostnames, _mdns_search_free for searches, free_address_list for address lists) may not be properly handled, potentially leading to memory leaks. The architectural change from direct cleanup to delegation requires verification that all cleanup functions properly handle their respective resource types. | +| [_mdns_execute_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5235) | [execute_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_engine.c#L15) | The refactoring introduces several subtle bugs:

1. **Missing ACTION_SYSTEM_EVENT handling**: In Result 2 (mdns_engine.c), the ACTION_SYSTEM_EVENT case is completely empty, while the original function called perform_event_action(). This will break system event processing.

2. **Missing semaphore operations**: The original ACTION_HOSTNAME_SET case called xSemaphoreGive(_mdns_server->action_sema) after completion, but the refactored version delegates to mdns_priv_responder_action without preserving this critical synchronization.

3. **Missing memory cleanup in ACTION_BROWSE_SYNC**: The original function explicitly called _mdns_sync_browse_result_link_free() for ACTION_BROWSE_SYNC, but the refactored version delegates this to mdns_priv_browse_action without clear evidence this cleanup is preserved.

4. **Split responsibility confusion**: The introduction of both execute_action and free_action functions suggests the original single responsibility has been split, but it's unclear when each should be called. This could lead to double-free or memory leaks if not properly coordinated.

5. **Inconsistent implementations**: Having two different execute_action functions (Result 1 vs Result 2) with different behavior for ACTION_SYSTEM_EVENT suggests either incomplete refactoring or platform-specific variations that need verification. | +| [_mdns_execute_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5235) | [free_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L126) | The refactoring introduces several subtle bugs:

1. **Missing ACTION_SYSTEM_EVENT handling**: In Result 2 (mdns_engine.c), the ACTION_SYSTEM_EVENT case is completely empty, while the original function called perform_event_action(). This will break system event processing.

2. **Missing semaphore operations**: The original ACTION_HOSTNAME_SET case called xSemaphoreGive(_mdns_server->action_sema) after completion, but the refactored version delegates to mdns_priv_responder_action without preserving this critical synchronization.

3. **Missing memory cleanup in ACTION_BROWSE_SYNC**: The original function explicitly called _mdns_sync_browse_result_link_free() for ACTION_BROWSE_SYNC, but the refactored version delegates this to mdns_priv_browse_action without clear evidence this cleanup is preserved.

4. **Split responsibility confusion**: The introduction of both execute_action and free_action functions suggests the original single responsibility has been split, but it's unclear when each should be called. This could lead to double-free or memory leaks if not properly coordinated.

5. **Inconsistent implementations**: Having two different execute_action functions (Result 1 vs Result 2) with different behavior for ACTION_SYSTEM_EVENT suggests either incomplete refactoring or platform-specific variations that need verification. | +| [_mdns_send_search_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5322) | [send_search_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L413) | The refactored function replaces direct queue access `xQueueSend(_mdns_server->action_queue, &action, (TickType_t)0)` with a wrapper function `mdns_priv_queue_action(action)`. Without seeing the implementation of `mdns_priv_queue_action`, we cannot verify if it maintains the same non-blocking behavior (0 timeout) and return value semantics. If `mdns_priv_queue_action` uses blocking behavior or has different error handling, it could introduce timing issues or resource management problems in the MDNS search functionality. | +| [_mdns_scheduler_run](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5348) | [mdns_priv_send_packets](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_send.c#L1703) | The refactored function uses `mdns_priv_queue_action(action)` instead of directly calling `xQueueSend`. While this appears to be a wrapper function, there's a potential subtle bug: if `mdns_priv_queue_action` has different timeout behavior than the original `(TickType_t)0` (non-blocking), it could introduce blocking behavior that wasn't present in the original implementation. Additionally, the error handling logic assumes `mdns_priv_queue_action` returns false on failure (matching the original `xQueueSend != pdPASS`), but this needs verification to ensure the same cleanup behavior is maintained. | +| [_mdns_search_run](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5385) | [mdns_priv_query_start_stop](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L133) | The refactored function mdns_priv_query_start_stop introduces a subtle bug in error handling. In the original code, when _mdns_send_search_action(ACTION_SEARCH_END, s) fails, the search state is restored to SEARCH_RUNNING, allowing retry in the next iteration. However, in the refactored version, when send_search_action(ACTION_SEARCH_END, s) fails, the state is also restored to SEARCH_RUNNING, but the timeout condition (now > (s->started_at + s->timeout)) will remain true in subsequent iterations, causing the search to immediately try to end again in an infinite loop until the send succeeds. This could lead to excessive retries and potential resource exhaustion. | +| [_mdns_service_task](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5417) | [service_task](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L200) | The refactored function replaces the direct pointer check `_mdns_server && _mdns_server->action_queue` with a function call `mdns_priv_is_server_init()` and a global variable `s_action_queue`. This introduces potential issues:
1. The function call `mdns_priv_is_server_init()` may have different timing/side effects compared to the simple pointer check
2. The global `s_action_queue` is not protected by the same locking mechanism as the original server structure
3. There's a potential race condition if `s_action_queue` is modified while the service task is running
4. The separation of server initialization check from queue access could lead to inconsistent state detection | +| [_mdns_timer_cb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5439) | [timer_cb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L222) | The refactoring changes the core functionality of the timer callback from scheduler/search operations to packet sending/query operations. While the structural mapping is clear (timer_cb replaces _mdns_timer_cb and start_timer replaces _mdns_start_timer), the functional equivalence cannot be verified without understanding what mdns_priv_send_packets and mdns_priv_query_start_stop do compared to the original _mdns_scheduler_run and _mdns_search_run. This could introduce subtle bugs in MDNS protocol timing, packet scheduling, or service discovery behavior. | +| [_mdns_timer_cb](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5439) | [start_timer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L228) | The refactoring changes the core functionality of the timer callback from scheduler/search operations to packet sending/query operations. While the structural mapping is clear (timer_cb replaces _mdns_timer_cb and start_timer replaces _mdns_start_timer), the functional equivalence cannot be verified without understanding what mdns_priv_send_packets and mdns_priv_query_start_stop do compared to the original _mdns_scheduler_run and _mdns_search_run. This could introduce subtle bugs in MDNS protocol timing, packet scheduling, or service discovery behavior. | +| [_mdns_start_timer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5445) | [start_timer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L228) | The refactored start_timer function uses a global variable s_timer_handle instead of the original _mdns_server->timer_handle, but there's no evidence that s_timer_handle is properly initialized to NULL. This could lead to double-creation of timers if the function is called multiple times, as the original code would have stored the handle in a server structure that gets reinitialized. Additionally, the callback function was renamed from _mdns_timer_cb to timer_cb without verification that the implementation remains equivalent. | +| [_mdns_stop_timer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5460) | [stop_timer](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L243) | | +| [_mdns_task_create_with_caps](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5473) | [create_task_with_caps](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L256) | The refactored function introduces a new error handling path with 'alloc_failed' label that calls HOOK_MALLOC_FAILED before proceeding to the 'err' label. This changes the control flow and could potentially cause issues if HOOK_MALLOC_FAILED has side effects or if the order of cleanup operations matters. In the original function, memory allocation failure went directly to the cleanup code, but now there's an intermediate step that might interfere with proper resource management. | +| [_mdns_service_task_start](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5498) | [service_task_start](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L283) | | +| [_mdns_service_task_stop](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5537) | [service_task_stop](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L320) | The refactored function maintains the same potential resource management issue as the original: if xQueueSend fails, the semaphore gets deleted immediately while the task might still be running and accessing it. However, there's an additional subtle change - the refactored version uses different timer functions (esp_timer_stop/delete vs original _mdns_stop_timer) which could have different error handling behavior. The original _mdns_stop_timer might have handled timer state differently than the new stop_timer function. | +| [mdns_post_custom_action_tcpip_if](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5558) | [post_custom_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L159) | The refactored function inverts the queue operation logic: original uses `xQueueSend(...) != pdPASS` for failure case, while refactored uses `!mdns_priv_queue_action(action)` for failure case. This suggests `mdns_priv_queue_action` returns true on success, but without seeing its implementation, we cannot verify if the queue behavior is equivalent. Additionally, the server initialization check changed from direct `!_mdns_server` to `!mdns_priv_is_server_init()` which may have different semantics. | +| [set_default_duplicated_interfaces](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5579) | [set_default_duplicated_interfaces](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L285) | The function appears to be identical in both implementations (100% similarity), but there's a potential architectural concern. The refactored codebase contains mdns_priv_pcb_set_duplicate which handles PCB-level duplication with additional operations (clearing TX queues, deinitializing PCBs, setting PCB_DUP state), while the original netif-level duplication logic remains unchanged. This creates a potential inconsistency where netif-level duplication is established but PCB-level duplication handling may not be properly synchronized. The bidirectional relationship between interfaces is managed differently in these two approaches, which could lead to race conditions or inconsistent state between netif and PCB layers. | +| [unregister_predefined_handlers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5597) | [mdns_priv_netif_unregister_predefined_handlers](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L303) | The refactored function uses a different event handler function name: 'handle_system_event_for_preset' instead of 'mdns_preset_if_handle_system_event'. While the conditional compilation logic is identical, this change could introduce subtle bugs if:
1. The new handler function has different behavior or implementation
2. The new handler function has a different signature that's not compatible with the event system
3. The original handler function 'mdns_preset_if_handle_system_event' is still registered elsewhere and not properly cleaned up
4. The new handler function doesn't exist or has different error handling

The search shows 'mdns_preset_if_handle_system_event' exists in the original codebase with a specific implementation, but no matches were found for 'handle_system_event_for_preset' in the refactored codebase, suggesting it might be missing or renamed differently. | +| [mdns_netif_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5614) | [mdns_netif_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L384) | The refactored post_custom_action function returns ESP_OK even when mdns_priv_queue_action fails (returns false), which occurs when memory allocation for the action fails. This masks memory allocation failures and changes the error behavior from the original implementation. The original mdns_post_custom_action_tcpip_if likely returned ESP_ERR_NO_MEM in this scenario, but the refactored version returns success, potentially hiding critical resource constraints. | +| [mdns_register_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5619) | [mdns_register_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L389) | The refactored mdns_unregister_netif function in Result 2 has a critical bug where it calls mdns_priv_service_lock() twice at the end instead of unlocking. This will cause a deadlock situation where the service lock is never released, blocking all subsequent mDNS operations that require the lock. The correct pattern should be mdns_priv_service_unlock() before returning. | +| [mdns_unregister_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5645) | [mdns_unregister_netif](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_netif.c#L415) | The refactored mdns_unregister_netif function has a critical bug where it calls mdns_priv_service_lock() twice instead of calling mdns_priv_service_unlock() to release the lock. This will cause a deadlock situation as the service lock is never released, preventing other threads from accessing the shared resource and potentially hanging the system. | +| [mdns_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5665) | [mdns_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L351) | The refactored mdns_init function has a subtle bug in error handling: when mdns_priv_netif_init() fails, the code jumps to free_queue label which only deletes the action queue, but does not delete the semaphore created in mdns_priv_responder_init(). In the original code, both the queue and semaphore were properly cleaned up in the error path. This could lead to a resource leak of the semaphore. | +| [mdns_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5763) | [mdns_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_service.c#L391) | The refactored mdns_free function introduces a subtle bug in the cleanup sequence. In the original code, free_delegated_hostnames() was called before mdns_mem_free((char *)_mdns_server->hostname) and mdns_mem_free((char *)_mdns_server->instance). However, in the refactored version, free_delegated_hostnames() is called inside mdns_priv_responder_free() AFTER the hostname and instance have already been freed. This could lead to accessing freed memory if free_delegated_hostnames() references the server's hostname or instance fields. | +| [mdns_hostname_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5816) | [mdns_hostname_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L591) | The refactored function replaces direct xQueueSend with mdns_priv_queue_action, but there's a potential synchronization bug. The original code used xQueueSend with 0 timeout (non-blocking) and returned ESP_ERR_NO_MEM on queue full. The new mdns_priv_queue_action function's implementation is unknown - if it uses a different timeout or blocking behavior, it could cause deadlocks or different memory error handling. Additionally, the semaphore take operation (xSemaphoreTake) remains but the queue mechanism changed, which could lead to inconsistent state if the new queue function doesn't properly coordinate with the semaphore signaling. | +| [mdns_hostname_get](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5846) | [mdns_hostname_get](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L621) | | +| [mdns_delegate_hostname_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5864) | [mdns_delegate_hostname_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L639) | The refactored function uses mdns_priv_queue_action() instead of xQueueSend() with (TickType_t)0 timeout. If mdns_priv_queue_action() has different queue semantics (e.g., different timeout behavior or error handling), it could introduce subtle bugs in memory management or action queuing reliability. Additionally, the replacement of copy_address_list() with mdns_utils_copy_address_list() requires verification that the memory allocation and cleanup behavior remains identical, especially in error scenarios. | +| [mdns_delegate_hostname_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5895) | [mdns_delegate_hostname_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L670) | The refactored function shows inconsistent synchronization behavior compared to similar functions in the same codebase. While mdns_hostname_set and mdns_delegate_hostname_add both call xSemaphoreTake(s_server->action_sema, portMAX_DELAY) after queueing their actions, mdns_delegate_hostname_remove does not. This inconsistency could lead to race conditions where callers of mdns_delegate_hostname_remove assume the operation is complete when it may still be pending in the action queue. The original codebase also lacked this synchronization, but the refactoring introduced this pattern inconsistently across similar functions. | +| [mdns_delegate_hostname_set_address](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5924) | [mdns_delegate_hostname_set_address](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L699) | The refactored function removed the semaphore synchronization (xSemaphoreTake) that was present in similar functions (mdns_delegate_hostname_add and mdns_hostname_set), while the queue mechanism changed from direct xQueueSend to mdns_priv_queue_action. This creates inconsistent synchronization behavior across similar API functions and could lead to race conditions if the action handler expects synchronous completion. The original implementation used immediate queue sending (timeout 0) without waiting, but the refactored similar functions now wait for semaphore, suggesting this function may have missed a required synchronization update. | +| [mdns_hostname_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5954) | [mdns_hostname_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L729) | | +| [mdns_instance_name_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5963) | [mdns_instance_name_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L738) | The refactored function replaces direct xQueueSend with mdns_priv_queue_action, but the timeout behavior may have changed. The original used (TickType_t)0 timeout (non-blocking), while the helper function's timeout semantics are unclear. Additionally, the refactored version lacks the explicit semaphore synchronization present in mdns_hostname_set (xSemaphoreTake), potentially creating inconsistent behavior between similar operations. | +| [mdns_service_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L5996) | [mdns_service_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L767) | The refactored function has a critical bug in the linked list insertion logic. The original code correctly sets up the linked list by assigning the new item to the head of the services list. However, the refactored code has a logical error: it sets `item->next = NULL` and then immediately overwrites it with `item->next = s_server->services`, which is correct, but then assigns `s_server->services = item`. This appears correct at first glance, but there's a subtle issue - the original code properly maintains the linked list structure while the refactored version might have different behavior if the helper functions (like `mdns_utils_get_service_item_instance` and `create_service`) have different implementations than their original counterparts. Additionally, the memory cleanup function changed from `_mdns_free_service` to `free_service` - if these have different implementations, it could lead to memory leaks or corruption in error paths. | +| [mdns_service_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6038) | [mdns_service_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L809) | The refactored mdns_service_add function appears functionally equivalent to the original, but there are potential issues in its dependency chain. The function itself only changed the global variable name from _mdns_server to s_server, but the mdns_service_add_for_host function it calls has undergone significant refactoring with new locking mechanisms, service limit checks, and different error handling patterns. This could introduce subtle bugs like:
1. Deadlocks if the new mdns_priv_service_lock/unlock functions are not properly balanced
2. Different service validation behavior through mdns_utils_get_service_item_instance
3. Changed memory allocation patterns with create_service and HOOK_MALLOC_FAILED
4. Potential race conditions if the locking scope differs from the original implementation | +| [mdns_service_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6047) | [mdns_service_exists](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L818) | | +| [mdns_service_exists_with_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6056) | [mdns_service_exists_with_instance](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L827) | | +| [_copy_mdns_txt_items](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6066) | [copy_txt_items](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L837) | The error handling cleanup loop condition `y < ret_index + 1` in both original and refactored code appears to have a potential off-by-one error. When `ret_index` represents the number of successfully allocated items, accessing `ret[ret_index]` (which would be the `ret_index + 1`-th element) could read/write beyond the allocated memory bounds if an allocation failure occurs early in the second loop. The condition should likely be `y < ret_index` to only clean up the items that were actually allocated. | +| [_copy_delegated_host_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6119) | [copy_delegated_host_address_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L890) | | +| [_mdns_lookup_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6131) | [lookup_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_console.c#L1139) | | +| [mdns_service_port_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6211) | [mdns_service_port_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L982) | | +| [mdns_service_port_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6229) | [mdns_service_port_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1000) | | +| [mdns_service_txt_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6237) | [mdns_service_txt_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1008) | The refactored function has the same subtle bug as the original: when memory allocation fails (allocate_txt returns NULL), the function returns ESP_ERR_NO_MEM directly without releasing the service lock (mdns_priv_service_unlock). This creates a potential deadlock scenario where the service lock remains held indefinitely after a memory allocation failure. | +| [mdns_service_txt_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6267) | [mdns_service_txt_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1038) | The refactored function uses s_server instead of _mdns_server for the server state check. While both appear to serve the same purpose (global MDNS server state), the refactored code introduces a potential NULL pointer dereference in mdns_priv_responder_free() at line 64 where it accesses s_server->action_sema without first checking if s_server is NULL, unlike the original code which consistently checked _mdns_server before accessing its members. | +| [mdns_service_txt_item_set_for_host_with_explicit_value_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6275) | [mdns_service_txt_item_set_for_host_with_explicit_value_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1046) | The refactored function uses renamed helper functions (mdns_utils_str_null_or_empty, mdns_utils_get_service_item_instance, announce_all_pcbs, mdns_priv_service_lock/unlock) and a renamed global variable (s_server). While the core logic appears identical, there's a risk that these renamed functions may have different implementations or behaviors compared to their original counterparts. Specifically, the memory allocation error handling in the out_of_mem label still uses HOOK_MALLOC_FAILED and mdns_mem_free, but if the renamed locking functions don't properly handle error states or if the global s_server initialization differs from _mdns_server, it could lead to subtle bugs like memory leaks, race conditions, or incorrect service discovery behavior. | +| [mdns_service_txt_item_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6331) | [mdns_service_txt_item_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1102) | The refactored function appears identical to the original, but there are two related functions (mdns_service_txt_item_set and mdns_service_txt_item_set_with_explicit_value_len) that now include state checking for s_server, while the original mdns_service_txt_item_set_for_host does not. This creates an inconsistency where some TXT item setting functions check server state while others don't. Additionally, the global variable has been renamed from _mdns_server to s_server, which could indicate broader changes in the codebase that might affect error handling consistency. | +| [mdns_service_txt_item_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6339) | [mdns_service_txt_item_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1110) | | +| [mdns_service_txt_item_set_with_explicit_value_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6348) | [mdns_service_txt_item_set_with_explicit_value_len](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1119) | | +| [mdns_service_txt_item_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6357) | [mdns_service_txt_item_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1128) | The refactored function calls `announce_all_pcbs(&s, 1, false)` but there's no evidence that `announce_all_pcbs` exists in the refactored codebase. The search for "announce_all_pcbs" returned no matches, suggesting this function may be missing or renamed differently than expected. This could lead to a compilation error or runtime failure when trying to announce the TXT item removal. | +| [mdns_service_txt_item_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6404) | [mdns_service_txt_item_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1175) | The refactored mdns_service_txt_item_remove_for_host function has several potential issues:
1. The complex ESP_GOTO_ON_FALSE conditional combines multiple error checks (server state, service/proto/key validation) into a single error path, which may mask specific error conditions that were handled separately in the original implementation
2. The memory management uses mdns_mem_free() instead of the original free() calls, which could indicate inconsistent memory management strategy across the codebase
3. The announce_all_pcbs(&s, 1, false) call appears to be new functionality that wasn't present in the original TXT removal logic, potentially causing unnecessary network announcements
4. The error handling with HOOK_MALLOC_FAILED at the end seems misplaced since no memory allocation occurs in the main logic path of this function
5. The function returns ESP_OK even when no TXT item was found to remove (the function completes without setting an error when the key isn't found) | +| [_mdns_service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6412) | [service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1183) | The refactored mdns_service_subtype_remove_for_host function has a potential memory leak in the error path. When memory allocation fails at remove_subtypes->subtype = mdns_mem_strdup(subtype), the code jumps to out_of_mem label which frees remove_subtypes but does not free the already allocated remove_subtypes structure itself. This creates a scenario where remove_subtypes is allocated but its subtype field allocation fails, leaving the remove_subtypes structure leaked. The original function had no such memory allocation, so this is a new bug introduced during refactoring. | +| [_mdns_service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6412) | [mdns_service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1212) | The refactored mdns_service_subtype_remove_for_host function has a potential memory leak in the error path. When memory allocation fails at remove_subtypes->subtype = mdns_mem_strdup(subtype), the code jumps to out_of_mem label which frees remove_subtypes but does not free the already allocated remove_subtypes structure itself. This creates a scenario where remove_subtypes is allocated but its subtype field allocation fails, leaving the remove_subtypes structure leaked. The original function had no such memory allocation, so this is a new bug introduced during refactoring. | +| [mdns_service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6441) | [mdns_service_subtype_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1212) | The refactored function uses `free_subtype(remove_subtypes)` instead of `_mdns_free_subtype(remove_subtypes)`. If `free_subtype` doesn't properly handle the case where `remove_subtypes->subtype` is NULL (due to failed mdns_mem_strdup), this could lead to memory leaks or undefined behavior. Additionally, the refactored version calls `free_subtype` even when `mdns_priv_send_bye_subtype` might have taken ownership of the subtypes, potentially causing double-free issues if the ownership semantics changed. | +| [_mdns_service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6474) | [service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1245) | The refactored function 'mdns_service_subtype_add_multiple_items_for_host' has inconsistent error handling compared to the original. In the original code, when _mdns_service_subtype_add_for_host returns ESP_ERR_INVALID_ARG (subtype already exists), the calling code continues processing other subtypes. However, in the refactored version, any error other than ESP_OK or ESP_ERR_NO_MEM causes immediate termination with goto exit, preventing processing of remaining subtypes and potentially leaving the service in an inconsistent state. Additionally, the memory cleanup rollback only occurs for ESP_ERR_NO_MEM cases, not for other error types. | +| [mdns_service_subtype_add_multiple_items_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6498) | [mdns_service_subtype_add_multiple_items_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1269) | The refactored function in Result 1 appears to be the direct replacement, but there are several subtle concerns:

1. **Missing validation for num_items > 0**: In the original code, the ESP_GOTO_ON_FALSE check includes `(num_items > 0)`, but in Result 1, this validation appears to be missing from the condition, which could allow calling the function with num_items=0 and bypass proper error handling.

2. **Function signature inconsistency**: The refactored function uses parameter name 'service' while the original uses 'service_type' in the header declaration. This could cause compilation issues if the header wasn't updated consistently.

3. **Resource management in error path**: The cleanup loop in the error path uses `service_subtype_remove_for_host` which may have different memory management behavior than the original `_mdns_service_subtype_remove_for_host`. If the memory allocation strategy changed (as seen in Result 3), the removal function might not properly handle the new allocation pattern.

4. **Potential double-free in update function**: Result 2 shows `free_subtype(goodbye_subtype)` followed by `free_service_subtype(s->service)` - if these functions have overlapping cleanup responsibilities, this could lead to double-free issues. | +| [mdns_service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6535) | [mdns_service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1306) | The refactoring introduced a subtle bug in the error handling logic. In the original implementation, when _mdns_service_subtype_add_for_host returns ESP_ERR_NO_MEM, the calling function mdns_service_subtype_add_multiple_items_for_host would continue processing other subtypes but eventually roll back all successful additions. However, in the refactored version, service_subtype_add_for_host immediately returns ESP_ERR_NO_MEM without proper cleanup of the allocated subtype_item, causing a memory leak. Additionally, the refactored version uses different error labels (err vs out_of_mem) and the memory cleanup path in service_subtype_add_for_host returns the same error code regardless of which allocation failed, losing error specificity. | +| [mdns_service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6535) | [service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1245) | The refactoring introduced a subtle bug in the error handling logic. In the original implementation, when _mdns_service_subtype_add_for_host returns ESP_ERR_NO_MEM, the calling function mdns_service_subtype_add_multiple_items_for_host would continue processing other subtypes but eventually roll back all successful additions. However, in the refactored version, service_subtype_add_for_host immediately returns ESP_ERR_NO_MEM without proper cleanup of the allocated subtype_item, causing a memory leak. Additionally, the refactored version uses different error labels (err vs out_of_mem) and the memory cleanup path in service_subtype_add_for_host returns the same error code regardless of which allocation failed, losing error specificity. | +| [mdns_service_subtype_add_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6535) | [mdns_service_subtype_add_multiple_items_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1269) | The refactoring introduced a subtle bug in the error handling logic. In the original implementation, when _mdns_service_subtype_add_for_host returns ESP_ERR_NO_MEM, the calling function mdns_service_subtype_add_multiple_items_for_host would continue processing other subtypes but eventually roll back all successful additions. However, in the refactored version, service_subtype_add_for_host immediately returns ESP_ERR_NO_MEM without proper cleanup of the allocated subtype_item, causing a memory leak. Additionally, the refactored version uses different error labels (err vs out_of_mem) and the memory cleanup path in service_subtype_add_for_host returns the same error code regardless of which allocation failed, losing error specificity. | +| [_mdns_service_find_subtype_needed_sendbye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6543) | [service_find_subtype_needed_sendbye](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1314) | | +| [mdns_service_subtype_update_multiple_items_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6593) | [mdns_service_subtype_update_multiple_items_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1364) | The refactored function calls free_service_subtype(s->service) which completely clears all subtypes from the service before adding new ones in the loop. This differs from the original behavior where _mdns_free_service_subtype might have been more selective. This could cause temporary service unavailability and potential race conditions where subtypes are briefly unavailable between the free and add operations. Additionally, the refactored version uses different locking functions (mdns_priv_service_lock/unlock vs MDNS_SERVICE_LOCK/UNLOCK) which may have different thread safety guarantees. | +| [mdns_service_instance_name_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6640) | [mdns_service_instance_name_set_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1411) | | +| [mdns_service_instance_name_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6666) | [mdns_service_instance_name_set](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1437) | The refactored function in Result 1 appears to be functionally equivalent to the original, but there's a subtle variable name change from `_mdns_server` to `s_server`. While this is likely just a naming convention change, it could indicate broader architectural changes that might affect other parts of the codebase if the global server variable semantics have changed. The function maintains the same parameter signature and delegation pattern to `mdns_service_instance_name_set_for_host`.

However, the presence of `mdns_instance_name_set` (Result 2) is concerning as it suggests a parallel API with different semantics - it only takes an instance parameter and implements the functionality directly rather than delegating. This could lead to confusion about which function to use and potential inconsistencies in service instance management. | +| [mdns_service_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6674) | [mdns_service_remove_for_host](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1445) | The refactored function calls `free_service(a->service)` and `mdns_mem_free(a)` after removing the service from the linked list, but the original function used `_mdns_free_service(a->service)`. Without seeing the implementation of `free_service` vs `_mdns_free_service`, there's a risk that the refactored version may have different memory management behavior, potentially leading to memory leaks or double-free issues if the implementations differ. | +| [mdns_service_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6727) | [mdns_service_remove](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1498) | | +| [mdns_service_remove_all](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6735) | [mdns_service_remove_all](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1506) | | +| [mdns_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6763) | [mdns_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L673) | | +| [_mdns_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6770) | [mdns_priv_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L25) | The refactoring changes the locking mechanism from MDNS_SERVICE_LOCK/UNLOCK to mdns_priv_service_lock/unlock without clear evidence of functional equivalence. This could introduce subtle synchronization issues, deadlock risks, or race conditions if the new locking functions have different semantics, scope, or implementation than the original ones. The change from static to public function scope (mdns_priv_query_results_free) also increases the risk of improper direct usage bypassing necessary locking. | +| [_mdns_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6770) | [mdns_query_results_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L673) | The refactoring changes the locking mechanism from MDNS_SERVICE_LOCK/UNLOCK to mdns_priv_service_lock/unlock without clear evidence of functional equivalence. This could introduce subtle synchronization issues, deadlock risks, or race conditions if the new locking functions have different semantics, scope, or implementation than the original ones. The change from static to public function scope (mdns_priv_query_results_free) also increases the risk of improper direct usage bypassing necessary locking. | +| [mdns_query_async_delete](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6801) | [mdns_query_async_delete](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L680) | | +| [mdns_query_async_get_results](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6817) | [mdns_query_async_get_results](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L696) | The function implementation remains identical, but the relocation from mdns.c to mdns_querier.c introduces potential architectural risks. The main concerns are: 1) Header file dependencies - mdns.h must properly declare the function and include necessary types from the new module, 2) Structure definition consistency - mdns_search_once_t must have identical layout in both compilation units, particularly the done_semaphore and result fields, 3) Build system integration - mdns_querier.c must be properly compiled and linked, and 4) Cross-module access - other functions in mdns.c that previously accessed this function directly may now require proper inter-module function calls. | +| [mdns_query_async_new](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6831) | [mdns_query_async_new](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L710) | The refactored search_init function now uses uint8_t for max_results parameter instead of size_t, which could cause truncation issues if max_results values exceed 255. This is a potential data loss bug since the original function accepted size_t and could handle larger values. Additionally, the search_init function creates a semaphore that needs verification of proper cleanup in all error paths through search_free. | +| [mdns_query_generic](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6853) | [mdns_query_generic](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L732) | The refactored function uses renamed helper functions (mdns_priv_is_server_init, mdns_utils_str_null_or_empty, search_init, send_search_action, search_free) without clear verification that these maintain the exact same behavior and error handling semantics as their original counterparts. Specifically:

1. The condition `mdns_utils_str_null_or_empty(service) != mdns_utils_str_null_or_empty(proto)` relies on the renamed string function returning consistent boolean values
2. The search initialization and action functions may have different memory management or error propagation behaviors
3. The semaphore wait on `search->done_semaphore` assumes the internal search structure and synchronization mechanism remains unchanged
4. Without seeing the implementations of these renamed functions, we cannot verify that resource cleanup (search_free) properly handles the results pointer assignment that occurs before freeing

These renamed functions could introduce subtle behavioral changes in error cases, memory management, or protocol compliance. | +| [mdns_query](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6884) | [mdns_query](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L764) | The refactored mdns_query function appears identical to the original, but its dependency on mdns_query_generic has been significantly changed, introducing potential subtle bugs:

1. **Timeout handling regression**: The refactored mdns_query_generic uses `portMAX_DELAY` instead of the original timeout parameter, making queries potentially block indefinitely rather than respecting the user-specified timeout.

2. **Error code inconsistency**: The refactored version returns `ESP_ERR_NO_MEM` when `send_search_action` fails, but this function could fail for other reasons (network errors, internal state issues) that should return different error codes.

3. **Parameter validation change**: The validation logic for service/proto parameters has been altered from the original implementation, potentially allowing invalid parameter combinations that were previously rejected.

4. **Function dependency changes**: The refactored code uses `search_init`, `send_search_action`, and `search_free` instead of the original `_mdns_search_init` and internal mechanisms, raising concerns about functional equivalence and proper resource management.

While the mdns_query wrapper function itself is unchanged, these underlying changes in mdns_query_generic could lead to unexpected blocking behavior, incorrect error reporting, and different parameter validation semantics. | +| [mdns_query_ptr](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6889) | [mdns_query_ptr](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L769) | | +| [mdns_query_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6898) | [mdns_query_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L778) | | +| [mdns_query_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6907) | [mdns_query_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L787) | | +| [mdns_lookup_delegated_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6916) | [mdns_lookup_delegated_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1531) | The refactored lookup_service function in mdns_console.c (Result 2) creates a circular dependency: it calls mdns_lookup_delegated_service/mdns_lookup_selfhosted_service, which in turn call the lookup_service function in mdns_responder.c. This appears to be a naming collision where two different functions with the same name exist in different compilation units, which could lead to linker errors or incorrect function resolution depending on the build configuration. | +| [mdns_lookup_selfhosted_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6931) | [mdns_lookup_selfhosted_service](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_responder.c#L1546) | The refactored code introduces a potential circular dependency. The function `lookup_service` in mdns_console.c calls `mdns_lookup_selfhosted_service`, which in turn calls `lookup_service` (the internal implementation). This creates infinite recursion. The original code called `_mdns_lookup_service` directly without this circular call pattern. Additionally, the parameter order in the `lookup_service` wrapper function appears inconsistent - it takes a `delegated` parameter but the actual implementation functions don't have this parameter in their signatures. | +| [mdns_query_a](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6947) | [mdns_query_a](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L797) | The refactored function changes the validation function from `_str_null_or_empty` to `mdns_utils_str_null_or_empty`. While this appears to be a simple renaming for better organization, there's a risk that the new function might have different behavior (e.g., different empty string definition, different return values, or different error handling) that could affect the input validation logic. The original codebase search didn't find references to `mdns_utils_str_null_or_empty`, suggesting this might be a newly introduced utility function whose implementation should be verified for functional equivalence. | +| [mdns_query_aaaa](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L6986) | [mdns_query_aaaa](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_querier.c#L836) | | +| [mdns_debug_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7026) | [dbg_packet](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_debug.c#L106) | The refactored function changes the timestamp type from uint32_t to uint64_t but uses the same format string logic. In embedded systems with 32-bit architectures, this could cause issues with printf formatting and stack alignment. Additionally, the static mdns_name_t variable could cause thread-safety issues in multi-threaded environments, and the new mdns_dbg_flush() call at the end might introduce blocking behavior that wasn't present in the original function. | +| [_mdns_sync_browse_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7256) | [mdns_priv_browse_sync](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L595) | The refactored function `mdns_priv_browse_sync` hardcodes the action type to `ACTION_BROWSE_SYNC`, removing the `type` parameter from the original function. This could be problematic if the original function was ever called with action types other than `ACTION_BROWSE_SYNC`. While the search shows only `ACTION_BROWSE_SYNC` usage in the original codebase, this change reduces flexibility and could break future extensions that might use different browse sync action types. | +| [_mdns_send_browse_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7278) | [send_browse_action](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L26) | The refactored function uses `!mdns_priv_queue_action(action)` instead of the original `xQueueSend(_mdns_server->action_queue, &action, (TickType_t)0) != pdPASS`. This boolean logic inversion suggests that `mdns_priv_queue_action` returns true for success and false for failure, while `xQueueSend` returns `pdPASS` (typically 1) for success and other values for failure. If `mdns_priv_queue_action` doesn't properly replicate the exact queueing semantics (including the zero timeout behavior), this could introduce subtle behavioral changes in the action queueing mechanism, potentially affecting the MDNS browsing functionality under high load conditions. | +| [_mdns_browse_item_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7301) | [browse_item_free](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L49) | | +| [_mdns_browse_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7314) | [browse_init](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L141) | The refactored browse_init function has inconsistent error handling for memory allocation failures. When browse->service allocation fails, HOOK_MALLOC_FAILED is called twice (once for browse malloc and once for service strndup), but when browse->proto allocation fails, HOOK_MALLOC_FAILED is only called once (for browse malloc). This inconsistency could lead to incorrect memory failure tracking or logging. The original function had consistent behavior where HOOK_MALLOC_FAILED was only called for the initial browse allocation failure. | +| [mdns_browse_new](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7345) | [mdns_browse_new](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L617) | The refactored mdns_browse_new function has a critical logic error in the server initialization check. The original code returned NULL when `!_mdns_server` (server not initialized), but the refactored code returns NULL when `mdns_priv_is_server_init()` (server IS initialized). This logical inversion would prevent browsing from working when the MDNS server is properly initialized, making the function always return NULL in normal operation. | +| [mdns_browse_delete](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7366) | [mdns_browse_delete](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L638) | | +| [_mdns_browse_finish](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7389) | [browse_finish](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L119) | The refactored function uses a global variable 's_browse' instead of accessing '_mdns_server->browse'. This structural change could introduce subtle bugs if:
1. 's_browse' is not properly synchronized with the server state in other parts of the system
2. There are concurrent access issues since global variables are more prone to race conditions
3. Other functions that previously operated on '_mdns_server->browse' might not be updated to use 's_browse' consistently
4. The initialization and lifetime management of 's_browse' might differ from the server-based approach | +| [_mdns_browse_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7411) | [browse_add](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L176) | The refactored function uses a global variable 's_browse' instead of accessing it through '_mdns_server->browse'. This structural change could introduce subtle bugs if:
1. 's_browse' is not properly initialized or synchronized with the original server state
2. Other parts of the system still expect to access browse data through '_mdns_server->browse'
3. There are thread safety issues since global 's_browse' might not have the same protection as the original server structure
4. The browse queue management is now split between different data structures, potentially causing inconsistencies | +| [_mdns_browse_send](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7440) | [browse_send](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L80) | The refactored function replaces _mdns_search_send_pcb with mdns_priv_query_send, which changes the PCB readiness check from mdns_is_netif_ready(tcpip_if, ip_protocol) && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state > PCB_INIT to mdsn_priv_pcb_is_inited(tcpip_if, ip_protocol). This could change when queries are sent and there's a potential typo in "mdsn_priv_pcb_is_inited" (should likely be "mdns_priv_pcb_is_inited"). Additionally, the packet management in mdns_priv_query_send (create, dispatch, immediate free) may have different error handling characteristics than the original implementation. | +| [_mdns_add_browse_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7461) | [add_browse_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L288) | The function visibility has changed from static to potentially non-static (the refactored code snippet doesn't show the static keyword). This could lead to linkage issues or unintended external access. Additionally, all call sites in the original codebase need to be verified to ensure they now call the renamed function in the new file location (mdns_browser.c vs mdns.c). | +| [_mdns_browse_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7488) | [mdns_priv_browse_result_add_ip](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L315) | The refactored function replaces `_mdns_add_browse_result` with `add_browse_result` without the `_mdns_` prefix, which may indicate a missing namespace or different function implementation. Additionally, the TTL update logic changed from `_mdns_result_update_ttl` to `mdns_priv_query_update_result_ttl`, which could have different behavior for TTL calculations. The search results show no matches for these renamed functions in the refactored codebase, suggesting they may be missing or have different signatures/implementations. | +| [_mdns_browse_find_from](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7553) | [mdns_priv_browse_find](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L205) | The refactored function changed from taking a browse list parameter to using a global variable 's_browse', which could introduce thread safety issues and makes the function dependent on global state. Additionally, the original function was called with '_mdns_server->browse' as parameter, but the refactored version directly uses 's_browse' without clear evidence that these are equivalent. This change in data access pattern could lead to incorrect browse list traversal if the global variable is not properly synchronized with the original server state. | +| [is_txt_item_in_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7583) | [is_txt_item_in_list](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L376) | The refactored function appears to be identical to the original (100% similarity) but has been moved from mdns.c to mdns_browser.c. This change in location could introduce subtle issues if:
1. The function now has different visibility/scope in the new file
2. Callers in the original location (mdns.c) cannot access it if it remains static
3. The function assumes different context or dependencies in the browser component vs responder component
4. The TXT item comparison logic might need different behavior between browser and responder contexts | +| [_mdns_browse_result_add_txt](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7601) | ??? | | +| [_mdns_copy_address_in_previous_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7699) | [copy_address_in_previous_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L492) | | +| [_mdns_browse_result_add_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7720) | [mdns_priv_browse_result_add_srv](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L513) | The refactored function calls two helper functions without the expected 'mdns_priv_' prefix: 'copy_address_in_previous_result' and 'add_browse_result'. This naming inconsistency suggests these functions may not be properly declared or implemented in the refactored codebase, potentially leading to linker errors or incorrect function resolution. Additionally, the final explicit 'return' statement was removed, which could affect code clarity but likely doesn't impact functionality. | +| [_mdns_browse_sync](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7800) | [browse_sync](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_browser.c#L59) | | +| [_debug_printf_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7821) | [dbg_printf_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_debug.c#L367) | The refactored function dbg_printf_result has been changed from non-static to static, which may break external calls if the function was used outside its compilation unit. Additionally, the addition of mdns_dbg_flush() at the end changes the debug output behavior - it now forces immediate flushing which could impact performance in debug-heavy scenarios or embedded systems with constrained I/O resources. | +| [debug_printf_browse_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7852) | [mdns_debug_printf_browse_result](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_debug.c#L399) | The refactored function adds an unconditional call to mdns_dbg_flush() which was not present in the original function. This could potentially impact performance in debug mode, especially if called frequently, as it may force immediate output flushing that wasn't happening before. Additionally, the debug macro names have changed from _mdns_dbg_printf/_debug_printf_result to dbg_printf/dbg_printf_result, which could have different formatting or behavior if these macros are not functionally equivalent. | +| [debug_printf_browse_result_all](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns.c#L7859) | [mdns_debug_printf_browse_result_all](https://github.com/espressif/esp-protocols/blob/main/components/mdns/mdns_debug.c#L407) | The refactored function adds a call to mdns_dbg_flush() at the end. While this might be intentional to ensure debug output is flushed, it could introduce timing differences in debugging scenarios or potentially block if the flush operation has significant overhead. In embedded systems or real-time environments, this could affect system behavior during debugging sessions. The original function did not have any flush operation, so output buffering behavior may have changed. | diff --git a/managed_components/espressif__mdns/tests/host_test/CMakeLists.txt b/managed_components/espressif__mdns/tests/host_test/CMakeLists.txt new file mode 100644 index 0000000..5f0d7bd --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.5) + + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +if(${IDF_TARGET} STREQUAL "linux") + set(EXTRA_COMPONENT_DIRS "../../../../common_components/linux_compat") + set(COMPONENTS main) +endif() + +project(mdns_host) + +# Enable sanitizers only without console (we'd see some leaks on argtable when console exits) +if(NOT CONFIG_TEST_CONSOLE AND CONFIG_IDF_TARGET_LINUX) +idf_component_get_property(mdns mdns COMPONENT_LIB) +target_link_options(${mdns} INTERFACE -fsanitize=address -fsanitize=undefined) +endif() diff --git a/managed_components/espressif__mdns/tests/host_test/README.md b/managed_components/espressif__mdns/tests/host_test/README.md new file mode 100644 index 0000000..4953f0e --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/README.md @@ -0,0 +1,33 @@ +# Setup dummy network interfaces + +Note: Set two addresses so we could use one as source and another as destination +``` +sudo ip link add eth2 type dummy +sudo ip addr add 192.168.1.200/24 dev eth2 +sudo ip addr add 192.168.1.201/24 dev eth2 +sudo ip link set eth2 up +sudo ifconfig eth2 multicast +``` + +# Dig on a specified interface + +``` +dig +short -b 192.168.1.200 -p 5353 @224.0.0.251 myesp.local +``` + +or a reverse query: +``` +dig +short -b 192.168.2.200 -p 5353 @224.0.0.251 -x 192.168.1.200 +``` + +# Run avahi to browse services + +Avahi needs the netif to have the "multicast" flag set + +```bash +david@david-comp:~/esp/idf (feature/mdns_networking_socket)$ avahi-browse -a -r -p ++;eth2;IPv6;myesp-service2;Web Site;local ++;eth2;IPv4;myesp-service2;Web Site;local +=;eth2;IPv6;myesp-service2;Web Site;local;myesp.local;192.168.1.200;80;"board=esp32" "u=user" "p=password" +=;eth2;IPv4;myesp-service2;Web Site;local;myesp.local;192.168.1.200;80;"board=esp32" "u=user" "p=password" +``` diff --git a/managed_components/espressif__mdns/tests/host_test/bonjour_order_responder.py b/managed_components/espressif__mdns/tests/host_test/bonjour_order_responder.py new file mode 100644 index 0000000..b3d2964 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/bonjour_order_responder.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +"""Mock Bonjour-style mDNS responder for browse host tests. + +Default response order mimics Bonjour browse answers: + Answer: PTR + Additional: A, AAAA, SRV, TXT + +Use ``--goodbye-after N`` to answer the first N browse queries normally and then +reply with a standalone PTR TTL=0 (Bonjour service removal). + +Use ``--unsolicited-goodbye-after N`` to answer N browse queries normally and then +multicast an unsolicited PTR TTL=0 announcement (keeps the active browse item). +""" + +from __future__ import annotations + +import argparse +import logging +import socket +import struct +import sys +import time + +import dns.flags +import dns.message +import dns.name +import dns.rdataclass +import dns.rdatatype +import dns.rrset + +logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') +logger = logging.getLogger(__name__) + +MDNS_ADDR = '224.0.0.251' +MDNS_PORT = 5353 + +DEFAULTS = { + 'service': '_v301test', + 'proto': '_tcp', + 'instance': 'v301instance', + 'hostname': 'v301host', + 'port': 8080, + 'ipv4': '192.168.1.100', + 'ipv6': 'fe80::1234:5678:9abc:def0', + 'txt': 'vdv301=test', +} + + +def _fqdn(*labels: str) -> str: + return '.'.join(labels) + '.local.' + + +def build_goodbye_response( + query: dns.message.Message, + *, + service: str, + proto: str, + instance: str, +) -> dns.message.Message: + service_name = _fqdn(service, proto) + instance_name = _fqdn(instance, service, proto) + + response = dns.message.make_response(query) + response.flags |= dns.flags.AA + response.answer.append( + dns.rrset.from_text(service_name, 0, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name) + ) + return response + + +def build_unsolicited_goodbye( + *, + service: str, + proto: str, + instance: str, +) -> dns.message.Message: + """Build a multicast goodbye announcement (QR+AA, no question section).""" + service_name = _fqdn(service, proto) + instance_name = _fqdn(instance, service, proto) + + msg = dns.message.Message(id=0) + msg.flags = dns.flags.QR | dns.flags.AA + msg.answer.append( + dns.rrset.from_text(service_name, 0, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name) + ) + return msg + + +def build_ptr_response( + query: dns.message.Message, + *, + service: str, + proto: str, + instance: str, + hostname: str, + port: int, + ipv4: str, + ipv6: str, + txt: str, + srv_first: bool, +) -> dns.message.Message: + service_name = _fqdn(service, proto) + instance_name = _fqdn(instance, service, proto) + host_name = _fqdn(hostname) + + response = dns.message.make_response(query) + response.flags |= dns.flags.AA + + response.answer.append( + dns.rrset.from_text(service_name, 120, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name) + ) + + a_rr = dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4) + aaaa_rr = dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.AAAA, ipv6) + srv_rr = dns.rrset.from_text( + instance_name, + 120, + dns.rdataclass.IN, + dns.rdatatype.SRV, + f'0 0 {port} {host_name}', + ) + txt_rr = dns.rrset.from_text(instance_name, 120, dns.rdataclass.IN, dns.rdatatype.TXT, txt) + + if srv_first: + response.additional = [srv_rr, txt_rr, a_rr, aaaa_rr] + else: + response.additional = [a_rr, aaaa_rr, srv_rr, txt_rr] + + return response + + +def create_socket(interface: str | None) -> socket.socket: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except (AttributeError, OSError): + pass + + if interface: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0') + + sock.bind(('', MDNS_PORT)) + + membership = struct.pack( + '=4s4s', + socket.inet_aton(MDNS_ADDR), + socket.inet_aton('0.0.0.0'), + ) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership) + return sock + + +def query_matches(query: dns.message.Message, service: str, proto: str) -> bool: + target = dns.name.from_text(_fqdn(service, proto)) + for question in query.question: + if question.rdtype != dns.rdatatype.PTR: + continue + if question.name == target: + return True + return False + + +def send_mdns_response(sock: socket.socket, payload: bytes, source: tuple[str, int]) -> None: + if source[1] == MDNS_PORT: + destination = (MDNS_ADDR, MDNS_PORT) + else: + destination = source + sock.sendto(payload, destination) + logger.info('Sent %d byte response to %s (query source %s:%d)', len(payload), destination, *source) + + +def send_mdns_multicast(sock: socket.socket, payload: bytes) -> None: + destination = (MDNS_ADDR, MDNS_PORT) + sock.sendto(payload, destination) + logger.info('Sent %d byte multicast announcement to %s', len(payload), destination) + + +def maybe_send_unsolicited_goodbye(sock: socket.socket, args: argparse.Namespace, response_count: int) -> bool: + """After N normal answers, multicast one unsolicited PTR TTL=0. Returns True if sent.""" + if args.unsolicited_goodbye_after < 0 or response_count != args.unsolicited_goodbye_after: + return False + if args.unsolicited_goodbye_delay > 0: + time.sleep(args.unsolicited_goodbye_delay) + goodbye = build_unsolicited_goodbye( + service=args.service, + proto=args.proto, + instance=args.instance, + ) + send_mdns_multicast(sock, goodbye.to_wire()) + logger.info('Multicasted unsolicited PTR goodbye (TTL=0)') + return True + + +def serve(args: argparse.Namespace) -> None: + sock = create_socket(args.interface) + order = 'SRV, TXT, A, AAAA' if args.srv_first else 'A, AAAA, SRV, TXT' + logger.info( + 'Listening on %s:%d (%s) for PTR %s.%s.local; additional order: %s; ' + 'goodbye-after=%s; unsolicited-goodbye-after=%s', + MDNS_ADDR, + MDNS_PORT, + args.interface or 'all interfaces', + args.service, + args.proto, + order, + args.goodbye_after, + args.unsolicited_goodbye_after, + ) + + response_count = 0 + unsolicited_goodbye_sent = False + while True: + try: + data, source = sock.recvfrom(9000) + except KeyboardInterrupt: + logger.info('Stopping responder') + break + + try: + query = dns.message.from_wire(data) + except Exception as exc: # noqa: BLE001 - ignore malformed packets + logger.debug('Ignoring non-DNS payload from %s:%d (%s)', source[0], source[1], exc) + continue + + if query.flags & dns.flags.QR: + continue + if not query_matches(query, args.service, args.proto): + continue + + if args.goodbye_after >= 0 and response_count >= args.goodbye_after: + response = build_goodbye_response( + query, + service=args.service, + proto=args.proto, + instance=args.instance, + ) + logger.info('Answered PTR goodbye (TTL=0) from %s:%d', source[0], source[1]) + else: + response = build_ptr_response( + query, + service=args.service, + proto=args.proto, + instance=args.instance, + hostname=args.hostname, + port=args.port, + ipv4=args.ipv4, + ipv6=args.ipv6, + txt=args.txt, + srv_first=args.srv_first, + ) + logger.info('Answered PTR browse from %s:%d', source[0], source[1]) + + send_mdns_response(sock, response.to_wire(), source) + response_count += 1 + + if not unsolicited_goodbye_sent: + unsolicited_goodbye_sent = maybe_send_unsolicited_goodbye(sock, args, response_count) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--interface', default='eth0', help='Network interface for mDNS (default: eth0)') + parser.add_argument('--service', default=DEFAULTS['service'], help='Service type without domain') + parser.add_argument('--proto', default=DEFAULTS['proto'], help='Protocol (_tcp/_udp)') + parser.add_argument('--instance', default=DEFAULTS['instance'], help='Service instance name') + parser.add_argument('--hostname', default=DEFAULTS['hostname'], help='SRV target host label') + parser.add_argument('--port', type=int, default=DEFAULTS['port'], help='SRV port') + parser.add_argument('--ipv4', default=DEFAULTS['ipv4'], help='A record address') + parser.add_argument('--ipv6', default=DEFAULTS['ipv6'], help='AAAA record address') + parser.add_argument('--txt', default=DEFAULTS['txt'], help='TXT record payload') + parser.add_argument( + '--srv-first', + action='store_true', + help='Place SRV/TXT before A/AAAA (control case where browse gets addresses)', + ) + parser.add_argument( + '--goodbye-after', + type=int, + default=-1, + help='After N normal browse responses, reply with PTR TTL=0 only (-1 disables)', + ) + parser.add_argument( + '--unsolicited-goodbye-after', + type=int, + default=-1, + help='After N normal browse responses, multicast one unsolicited PTR TTL=0 (-1 disables)', + ) + parser.add_argument( + '--unsolicited-goodbye-delay', + type=float, + default=0.5, + help='Seconds to wait after the Nth normal response before multicasting goodbye', + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + try: + serve(args) + except PermissionError: + logger.error('Binding to port %d requires root or CAP_NET_BIND_SERVICE', MDNS_PORT) + return 1 + except OSError as exc: + logger.error('Failed to start responder: %s', exc) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/CMakeLists.txt b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/CMakeLists.txt new file mode 100644 index 0000000..6f8d51e --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/CMakeLists.txt @@ -0,0 +1,8 @@ +idf_build_get_property(idf_target IDF_TARGET) +if(${IDF_TARGET} STREQUAL "linux") + idf_component_register(SRCS esp_netif_linux.c + INCLUDE_DIRS include $ENV{IDF_PATH}/components/esp_netif/include + REQUIRES esp_event) +else() + idf_component_register() +endif() diff --git a/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/Kconfig b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/Kconfig new file mode 100644 index 0000000..3b3c309 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/Kconfig @@ -0,0 +1,15 @@ +menu "LWIP-MOCK-CONFIG" + + config LWIP_IPV6 + bool "Enable IPv6" + default y + help + Enable/disable IPv6 + + config LWIP_IPV4 + bool "Enable IPv4" + default y + help + Enable/disable IPv4 + +endmenu diff --git a/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c new file mode 100644 index 0000000..13cf412 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c @@ -0,0 +1,197 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include + +#include "esp_netif.h" +#include "esp_err.h" +#include //strlen +#include +#include //inet_addr +#include +#include +#include +#include "esp_netif_types.h" +#include "esp_log.h" + +#define MAX_NETIFS 4 + +static const char *TAG = "esp_netif_linux"; + +static esp_netif_t *s_netif_list[MAX_NETIFS] = { 0 }; + +struct esp_netif_obj { + const char *if_key; + const char *if_desc; +}; + +esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key) +{ + for (int i = 0; i < MAX_NETIFS; ++i) { + if (s_netif_list[i] && strcmp(s_netif_list[i]->if_key, if_key) == 0) { + return s_netif_list[i]; + } + } + return NULL; +} + +esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) +{ + if (esp_netif == NULL) { + return ESP_ERR_INVALID_STATE; + } + struct ifaddrs *addrs, *tmp; + getifaddrs(&addrs); + tmp = addrs; + + while (tmp) { + if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { + char addr[20]; + struct sockaddr_in *pAddr = (struct sockaddr_in *) tmp->ifa_addr; + inet_ntop(AF_INET, &pAddr->sin_addr, addr, sizeof(addr)); + if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) { + ESP_LOGD(TAG, "AF_INET4: %s: %s\n", tmp->ifa_name, addr); + memcpy(&ip_info->ip.addr, &pAddr->sin_addr, 4); + } + } + tmp = tmp->ifa_next; + } + freeifaddrs(addrs); + return ESP_OK; +} + +esp_err_t esp_netif_dhcpc_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status) +{ + return ESP_OK; +} + +int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) +{ + if (esp_netif == NULL) { + return 0; + } + struct ifaddrs *addrs, *tmp; + int addr_count = 0; + getifaddrs(&addrs); + tmp = addrs; + + while (tmp) { + if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET6) { + struct sockaddr_in6 *pAddr = (struct sockaddr_in6 *)tmp->ifa_addr; + if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) { + memcpy(&if_ip6[addr_count++], &pAddr->sin6_addr, 4 * 4); + } + } + tmp = tmp->ifa_next; + } + + freeifaddrs(addrs); + return addr_count; +} + +esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) +{ + if (esp_netif == NULL) { + return ESP_ERR_INVALID_STATE; + } + struct ifaddrs *addrs, *tmp; + getifaddrs(&addrs); + tmp = addrs; + + while (tmp) { + if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET6) { + char addr[64]; + struct sockaddr_in6 *pAddr = (struct sockaddr_in6 *)tmp->ifa_addr; + inet_ntop(AF_INET6, &pAddr->sin6_addr, addr, sizeof(addr)); + if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) { + ESP_LOGD(TAG, "AF_INET6: %s: %s\n", tmp->ifa_name, addr); + memcpy(if_ip6->addr, &pAddr->sin6_addr, 4 * 4); + break; + } + } + tmp = tmp->ifa_next; + } + + freeifaddrs(addrs); + return ESP_OK; +} + + +int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif) +{ + if (esp_netif == NULL) { + return -1; + } + uint32_t interfaceIndex = if_nametoindex(esp_netif->if_desc); + return interfaceIndex; +} + +esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char *name) +{ + if (esp_netif == NULL) { + return ESP_ERR_INVALID_STATE; + } + strcpy(name, esp_netif->if_desc); + return ESP_OK; +} + +const char *esp_netif_get_desc(esp_netif_t *esp_netif) +{ + if (esp_netif == NULL) { + return NULL; + } + return esp_netif->if_desc; +} + +esp_netif_t *esp_netif_new(const esp_netif_config_t *config) +{ + if (esp_netif_get_handle_from_ifkey(config->base->if_key)) { + return NULL; + } + esp_netif_t *netif = calloc(1, sizeof(struct esp_netif_obj)); + if (netif) { + netif->if_desc = config->base->if_desc; + netif->if_key = config->base->if_key; + } + + for (int i = 0; i < MAX_NETIFS; ++i) { + if (s_netif_list[i] == NULL) { + s_netif_list[i] = netif; + break; + } + } + + return netif; +} + +void esp_netif_destroy(esp_netif_t *esp_netif) +{ + for (int i = 0; i < MAX_NETIFS; ++i) { + if (s_netif_list[i] == esp_netif) { + s_netif_list[i] = NULL; + break; + } + } + free(esp_netif); +} + +const char *esp_netif_get_ifkey(esp_netif_t *esp_netif) +{ + return esp_netif->if_key; +} + +esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst) +{ + if (src == NULL || dst == NULL) { + return ESP_ERR_INVALID_ARG; + } + struct in_addr addr; + if (inet_pton(AF_INET, src, &addr) != 1) { + return ESP_FAIL; + } + dst->addr = addr.s_addr; + return ESP_OK; +} diff --git a/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/esp_wifi_types.h b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/esp_wifi_types.h new file mode 100644 index 0000000..e878e27 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/esp_wifi_types.h @@ -0,0 +1,7 @@ +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "esp_event.h" diff --git a/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/machine/endian.h b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/machine/endian.h new file mode 100644 index 0000000..488bce0 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/components/esp_netif_linux/include/machine/endian.h @@ -0,0 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include_next "endian.h" diff --git a/managed_components/espressif__mdns/tests/host_test/dnsfixture.py b/managed_components/espressif__mdns/tests/host_test/dnsfixture.py new file mode 100644 index 0000000..c16b061 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/dnsfixture.py @@ -0,0 +1,178 @@ +# SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +import logging +import re +import socket +import sys + +import dns.message +import dns.query +import dns.rdataclass +import dns.rdatatype +import dns.resolver + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +class DnsPythonWrapper: + def __init__(self, server='224.0.0.251', port=5353, retries=3): + self.server = server + self.port = port + self.retries = retries + + def send_and_receive_query(self, query, timeout=3): + logger.info(f'Sending DNS query to {self.server}:{self.port}') + try: + # Create a UDP socket + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + sock.settimeout(timeout) + + # Send the DNS query + query_data = query.to_wire() + sock.sendto(query_data, (self.server, self.port)) + + # Receive the DNS response + response_data, _ = sock.recvfrom(512) # 512 bytes is the typical size for a DNS response + + # Parse the response + response = dns.message.from_wire(response_data) + + return response + + except socket.timeout as e: + logger.warning(f'DNS query timed out: {e}') + return None + except dns.exception.DNSException as e: + logger.error(f'DNS query failed: {e}') + return None + + def run_query(self, name, query_type='PTR', timeout=3): + logger.info(f'Running DNS query for {name} with type {query_type}') + query = dns.message.make_query(name, dns.rdatatype.from_text(query_type), dns.rdataclass.IN) + + # Print the DNS question section + logger.info(f'DNS question section: {query.question}') + + # Send and receive the DNS query + response = None + for attempt in range(1, self.retries + 1): + logger.info(f'Attempt {attempt}/{self.retries}') + response = self.send_and_receive_query(query, timeout) + if response: + break + + if response: + logger.info(f'DNS query response:\n{response}') + else: + logger.warning('No response received or response was invalid.') + + return response + + def parse_answer_section(self, response, query_type): + answers = [] + if response: + for answer in response.answer: + if dns.rdatatype.to_text(answer.rdtype) == query_type: + for item in answer.items: + full_answer = ( + f'{answer.name} {answer.ttl} ' + f'{dns.rdataclass.to_text(answer.rdclass)} ' + f'{dns.rdatatype.to_text(answer.rdtype)} ' + f'{item.to_text()}' + ) + answers.append(full_answer) + return answers + + def check_record(self, name, query_type, expected=True, expect=None): + output = self.run_query(name, query_type=query_type) + answers = self.parse_answer_section(output, query_type) + logger.info(f'answers: {answers}') + if expect is None: + expect = name + if expected: + assert any(expect in answer for answer in answers), f"Expected record '{expect}' not in answer section" + else: + assert not any(expect in answer for answer in answers), f"Unexpected record '{expect}' found in answer section" + + def parse_section(self, response, section: str, rdtype_text: str): + """Parse a specific response section (answer, authority, additional) for given rdtype. + + Returns list of textual records for that rdtype. + """ + out = [] + if not response: + return out + rrsets = [] + if section == 'answer': + rrsets = response.answer + elif section == 'authority': + rrsets = response.authority + elif section == 'additional': + rrsets = response.additional + else: + raise ValueError('invalid section') + for rr in rrsets: + if dns.rdatatype.to_text(rr.rdtype) != rdtype_text: + continue + for item in rr.items: + full = ( + f'{rr.name} {rr.ttl} ' + f'{dns.rdataclass.to_text(rr.rdclass)} ' + f'{dns.rdatatype.to_text(rr.rdtype)} ' + f'{item.to_text()}' + ) + out.append(full) + return out + + def check_additional(self, response, rdtype_text: str, owner_contains: str, expected: bool = True, expect_substr: str | None = None): + """Check Additional section for an RR of type rdtype_text whose owner includes owner_contains. + + If expect_substr is provided, also require it to appear in the textual RR. + """ + records = self.parse_section(response, 'additional', rdtype_text) + logger.info(f'additional({rdtype_text}): {records}') + + def _matches(line: str) -> bool: + in_owner = owner_contains in line + has_val = (expect_substr in line) if expect_substr else True + return in_owner and has_val + found = any(_matches(r) for r in records) + if expected: + assert found, f"Expected {rdtype_text} for {owner_contains} in Additional not found" + else: + assert not found, f"Unexpected {rdtype_text} for {owner_contains} found in Additional" + + +if __name__ == '__main__': + if len(sys.argv) < 3: + print('Usage: python dns_fixture.py ') + sys.exit(1) + + query_type = sys.argv[1] + name = sys.argv[2] + ip_only = len(sys.argv) > 3 and sys.argv[3] == '--ip_only' + if ip_only: + logger.setLevel(logging.WARNING) + + dns_wrapper = DnsPythonWrapper() + if query_type == 'X' and '.' in name: + # Sends an IPv4 reverse query + reversed_ip = '.'.join(reversed(name.split('.'))) + name = f'{reversed_ip}.in-addr.arpa' + query_type = 'PTR' + response = dns_wrapper.run_query(name, query_type=query_type) + answers = dns_wrapper.parse_answer_section(response, query_type) + + if answers: + for answer in answers: + logger.info(f'DNS query response: {answer}') + if ip_only: + ipv4_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b') + ipv4_addresses = ipv4_pattern.findall(answer) + if ipv4_addresses: + print(f"{', '.join(ipv4_addresses)}") + else: + logger.info(f'No response for {name} with query type {query_type}') + exit(9) # Same as dig timeout diff --git a/managed_components/espressif__mdns/tests/host_test/main/CMakeLists.txt b/managed_components/espressif__mdns/tests/host_test/main/CMakeLists.txt new file mode 100644 index 0000000..0e6f226 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/main/CMakeLists.txt @@ -0,0 +1,4 @@ +idf_component_register(SRCS "main.c" + INCLUDE_DIRS + "." + REQUIRES mdns console nvs_flash) diff --git a/managed_components/espressif__mdns/tests/host_test/main/Kconfig.projbuild b/managed_components/espressif__mdns/tests/host_test/main/Kconfig.projbuild new file mode 100644 index 0000000..9bf4bba --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/main/Kconfig.projbuild @@ -0,0 +1,21 @@ +menu "Test Configuration" + + config TEST_HOSTNAME + string "mDNS Hostname" + default "esp32-mdns" + help + mDNS Hostname for example to use + + config TEST_NETIF_NAME + string "Network interface name" + default "eth2" + help + Name/ID if the network interface on which we run the mDNS host test + + config TEST_CONSOLE + bool "Start console" + default n + help + Test uses esp_console for interactive testing. + +endmenu diff --git a/managed_components/espressif__mdns/tests/host_test/main/idf_component.yml b/managed_components/espressif__mdns/tests/host_test/main/idf_component.yml new file mode 100644 index 0000000..e2d4fe9 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/main/idf_component.yml @@ -0,0 +1,7 @@ +dependencies: + idf: ">=5.0" + espressif/mdns: + version: "^1.0.0" + override_path: "../../.." + protocol_examples_common: + path: ${IDF_PATH}/examples/common_components/protocol_examples_common diff --git a/managed_components/espressif__mdns/tests/host_test/main/main.c b/managed_components/espressif__mdns/tests/host_test/main/main.c new file mode 100644 index 0000000..0b8cf91 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/main/main.c @@ -0,0 +1,151 @@ +/* + * SPDX-FileCopyrightText: 2022-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include +#include "esp_idf_version.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_console.h" +#include "mdns.h" +#include "mdns_console.h" + +static const char *TAG = "mdns-test"; + +static void mdns_test_app(esp_netif_t *interface); + +#ifdef CONFIG_TEST_CONSOLE +static EventGroupHandle_t s_exit_signal = NULL; + +static int exit_console(int argc, char **argv) +{ +#ifdef CONFIG_IDF_TARGET_LINUX + /* Host tests do not need graceful REPL teardown; exit hard so leftover + * console_repl / linenoise threads cannot keep the process alive. */ + ESP_LOGI(TAG, "Exit"); + exit(0); +#else + xEventGroupSetBits(s_exit_signal, 1); + return 0; +#endif +} + +#else +static void query_mdns_host(const char *host_name) +{ + ESP_LOGI(TAG, "Query A: %s.local", host_name); + + struct esp_ip4_addr addr; + addr.addr = 0; + + esp_err_t err = mdns_query_a(host_name, 2000, &addr); + if (err) { + if (err == ESP_ERR_NOT_FOUND) { + ESP_LOGW(TAG, "%x: Host was not found!", (err)); + return; + } + ESP_LOGE(TAG, "Query Failed: %x", (err)); + return; + } + + ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr)); +} +#endif // TEST_CONSOLE + +#ifndef CONFIG_IDF_TARGET_LINUX +#include "protocol_examples_common.h" +#include "esp_event.h" +#include "nvs_flash.h" + +/** + * @brief This is an entry point for the real target device, + * need to init few components and connect to a network interface + */ +void app_main(void) +{ + ESP_ERROR_CHECK(nvs_flash_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + ESP_ERROR_CHECK(example_connect()); + + mdns_test_app(EXAMPLE_INTERFACE); + + ESP_ERROR_CHECK(example_disconnect()); +} +#else + +/** + * @brief This is an entry point for the linux target (simulator on host) + * need to create a dummy WiFi station and use it as mdns network interface + */ +int main(int argc, char *argv[]) +{ + setvbuf(stdout, NULL, _IONBF, 0); + const esp_netif_inherent_config_t base_cg = { .if_key = "WIFI_STA_DEF", .if_desc = CONFIG_TEST_NETIF_NAME }; + esp_netif_config_t cfg = { .base = &base_cg }; + esp_netif_t *sta = esp_netif_new(&cfg); + + mdns_test_app(sta); + + esp_netif_destroy(sta); + return 0; +} +#endif + +static void mdns_test_app(esp_netif_t *interface) +{ + ESP_ERROR_CHECK(mdns_init()); + ESP_ERROR_CHECK(mdns_hostname_set(CONFIG_TEST_HOSTNAME)); + ESP_LOGI(TAG, "mdns hostname set to: [%s]", CONFIG_TEST_HOSTNAME); + ESP_ERROR_CHECK(mdns_register_netif(interface)); + ESP_ERROR_CHECK(mdns_netif_action(interface, MDNS_EVENT_ENABLE_IP4 /*| MDNS_EVENT_ENABLE_IP6 */ | MDNS_EVENT_IP4_REVERSE_LOOKUP | MDNS_EVENT_IP6_REVERSE_LOOKUP)); + // Query _services._dns-sd._udp to discover available service types + mdns_result_t *results = NULL; + esp_err_t err = mdns_query_ptr("_services._dns-sd", "_udp", 2000, 1, &results); + if (err) { + ESP_LOGE(TAG, "Query for _services._dns-sd._udp failed: 0x%x", err); + } + for (mdns_result_t *r = results; r; r = r->next) { + ESP_LOGI(TAG, "Discovered service: %s.%s", + r->service_type ? r->service_type : "?", + r->proto ? r->proto : "?"); + } + mdns_query_results_free(results); + +#ifdef CONFIG_TEST_CONSOLE + esp_console_repl_t *repl = NULL; + esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT(); + s_exit_signal = xEventGroupCreate(); + + repl_config.prompt = "mdns>"; + // init console REPL environment +#if CONFIG_IDF_TARGET_LINUX && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 1, 0) + ESP_ERROR_CHECK(esp_console_new_repl_stdio(&repl_config, &repl)); +#else + esp_console_dev_uart_config_t uart_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_console_new_repl_uart(&uart_config, &repl_config, &repl)); +#endif + + const esp_console_cmd_t cmd_exit = { + .command = "exit", + .help = "exit mDNS console application", + .hint = NULL, + .func = exit_console, + .argtable = NULL + }; + ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_exit)); + mdns_console_register(); + ESP_ERROR_CHECK(esp_console_start_repl(repl)); + xEventGroupWaitBits(s_exit_signal, 1, pdTRUE, pdFALSE, portMAX_DELAY); + repl->del(repl); +#else + vTaskDelay(pdMS_TO_TICKS(10000)); + query_mdns_host("david-work"); + vTaskDelay(pdMS_TO_TICKS(1000)); +#endif + mdns_free(); + ESP_LOGI(TAG, "Exit"); +} diff --git a/managed_components/espressif__mdns/tests/host_test/pytest_mdns.py b/managed_components/espressif__mdns/tests/host_test/pytest_mdns.py new file mode 100644 index 0000000..1bb451d --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/pytest_mdns.py @@ -0,0 +1,456 @@ +# SPDX-FileCopyrightText: 2024-2026 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +import logging +import subprocess +import sys +import time +from pathlib import Path + +import pexpect +import pytest +from bonjour_order_responder import DEFAULTS +from dnsfixture import DnsPythonWrapper +from querier_responder import DEFAULTS as QUERIER_DEFAULTS + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) +ipv6_enabled = False + + +def _console_line(label: str, value: str) -> str: + """Build a line as printed by mdns_print_results (avoids flake8 E203 on f'LABEL : {x}').""" + return label + value + + +class MdnsConsole: + def __init__(self, command): + self.process = pexpect.spawn(command, encoding='utf-8') + self.process.logfile = open('mdns_interaction.log', 'w') # Log all interactions + self.process.expect('mdns> ', timeout=10) + + def send_input(self, input_data): + logger.info(f'Sending to stdin: {input_data}') + self.process.sendline(input_data) + + def get_output(self, expected_data): + logger.info(f'Expecting: {expected_data}') + self.process.expect(expected_data, timeout=10) + output = self.process.before.strip() + logger.info(f'Received from stdout: {output}') + return output + + def wait_for_output(self, expected_data, timeout=10): + logger.info(f'Waiting for: {expected_data}') + self.process.expect(expected_data, timeout=timeout) + output = (self.process.before or '') + (self.process.after or '') + logger.info(f'Captured output while waiting: {output}') + return output + + def wait_for_browse_result(self, timeout=10): + """Wait until browse notifier printed the full result (A is last required field).""" + return self.wait_for_output(_console_line('A : ', DEFAULTS['ipv4']), timeout=timeout) + + def wait_for_browse_goodbye(self, timeout=10): + """Wait for Bonjour-style PTR TTL=0 removal notification (interface line then PTR).""" + self.wait_for_output('TTL: 0', timeout=timeout) + return self.wait_for_output(_console_line('PTR : ', DEFAULTS['instance']), timeout=timeout) + + def terminate(self): + self.send_input('exit') + self.get_output('Exit') + self.process.wait() + self.process.close() + assert self.process.exitstatus == 0 + + +def _bonjour_responder_cmd( + srv_first: bool = False, + goodbye_after: int = -1, + unsolicited_goodbye_after: int = -1, +) -> list[str]: + cmd = [ + sys.executable, + str(Path(__file__).with_name('bonjour_order_responder.py')), + '--interface', + 'eth0', + '--service', + DEFAULTS['service'], + '--proto', + DEFAULTS['proto'], + ] + if srv_first: + cmd.append('--srv-first') + if goodbye_after >= 0: + cmd.extend(['--goodbye-after', str(goodbye_after)]) + if unsolicited_goodbye_after >= 0: + cmd.extend(['--unsolicited-goodbye-after', str(unsolicited_goodbye_after)]) + return cmd + + +def _run_bonjour_responder( + *, + srv_first: bool = False, + goodbye_after: int = -1, + unsolicited_goodbye_after: int = -1, + label: str, +): + proc = subprocess.Popen( + _bonjour_responder_cmd( + srv_first=srv_first, + goodbye_after=goodbye_after, + unsolicited_goodbye_after=unsolicited_goodbye_after, + ), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + time.sleep(0.5) + # poll() stays None while the responder is still running after startup. + assert proc.poll() is None, f'{label} failed to start (need eth0 and port 5353?)' + return proc + + +def _stop_bonjour_responder(proc): + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=3) + + +def _run_querier_responder(): + proc = subprocess.Popen( + [ + sys.executable, + str(Path(__file__).with_name('querier_responder.py')), + '--interface', + 'eth0', + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + time.sleep(0.5) + assert proc.poll() is None, 'Querier responder failed to start (need eth0 and port 5353?)' + return proc + + +@pytest.fixture +def querier_responder(): + proc = _run_querier_responder() + yield proc + _stop_bonjour_responder(proc) + + +@pytest.fixture +def bonjour_responder(): + proc = _run_bonjour_responder(label='Bonjour-order responder') + yield proc + _stop_bonjour_responder(proc) + + +@pytest.fixture +def bonjour_responder_srv_first(): + proc = _run_bonjour_responder(srv_first=True, label='SRV-first responder') + yield proc + _stop_bonjour_responder(proc) + + +@pytest.fixture +def bonjour_responder_goodbye(): + proc = _run_bonjour_responder( + unsolicited_goodbye_after=1, + label='Unsolicited-goodbye responder', + ) + yield proc + _stop_bonjour_responder(proc) + + +@pytest.fixture(scope='module') +def mdns_console(): + app = MdnsConsole('./build_linux_console/mdns_host.elf') + yield app + app.terminate() + + +@pytest.fixture(scope='module') +def dig_app(): + return DnsPythonWrapper() + + +def test_mdns_init(mdns_console, dig_app): + mdns_console.send_input('mdns_init -h hostname') + mdns_console.get_output('MDNS: Hostname: hostname') + dig_app.check_record('hostname.local', query_type='A', expected=True) + if ipv6_enabled: + dig_app.check_record('hostname.local', query_type='AAAA', expected=True) + + +def test_add_service(mdns_console, dig_app): + mdns_console.send_input('mdns_service_add _http _tcp 80 -i test_service') + mdns_console.get_output('MDNS: Service Instance: test_service') + mdns_console.send_input('mdns_service_lookup _http _tcp') + mdns_console.get_output('PTR : test_service') + dig_app.check_record('_http._tcp.local', query_type='PTR', expected=True) + + +def test_ptr_additional_records_for_service(dig_app): + # Query PTR for the service type and ensure SRV/TXT are in Additional (RFC 6763 §12.1) + resp = dig_app.run_query('_http._tcp.local', query_type='PTR') + # Answer section should have at least one PTR to the instance + answers = dig_app.parse_answer_section(resp, 'PTR') + assert any('test_service._http._tcp.local' in a for a in answers) + # Additional section should include SRV and TXT for the same instance + dig_app.check_additional(resp, 'SRV', 'test_service._http._tcp.local', expected=True) + dig_app.check_additional(resp, 'TXT', 'test_service._http._tcp.local', expected=True) + + +def test_instance_any_answer_records(dig_app): + """Query ANY for the service instance and ensure SRV/TXT are in Answer (Q/A path).""" + resp = dig_app.run_query('test_service._http._tcp.local', query_type='ANY') + + # Answer section should contain SRV and TXT records for the instance + srv_answers = dig_app.parse_section(resp, 'answer', 'SRV') + txt_answers = dig_app.parse_section(resp, 'answer', 'TXT') + assert any('test_service._http._tcp.local' in a for a in srv_answers) + assert any('test_service._http._tcp.local' in a for a in txt_answers) + + # We should not see a PTR for the generic service name in the Answer section + ptr_answers = dig_app.parse_section(resp, 'answer', 'PTR') + assert not any('_http._tcp.local' in a for a in ptr_answers) + + +def test_remove_service(mdns_console, dig_app): + mdns_console.send_input('mdns_service_remove _http _tcp') + mdns_console.send_input('mdns_service_lookup _http _tcp') + mdns_console.get_output('No results found!') + dig_app.check_record('_http._tcp.local', query_type='PTR', expected=False) + + +def test_delegate_host(mdns_console, dig_app): + mdns_console.send_input('mdns_delegate_host delegated 1.2.3.4') + dig_app.check_record('delegated.local', query_type='A', expected=True) + + +def test_undelegate_host(mdns_console, dig_app): + mdns_console.send_input('mdns_undelegate_host delegated') + dig_app.check_record('delegated.local', query_type='A', expected=False) + + +def test_add_delegated_service(mdns_console, dig_app): + mdns_console.send_input('mdns_delegate_host delegated 1.2.3.4') + dig_app.check_record('delegated.local', query_type='A', expected=True) + mdns_console.send_input('mdns_service_add _test _tcp 80 -i local') + mdns_console.get_output('MDNS: Service Instance: local') + mdns_console.send_input('mdns_service_add _test2 _tcp 80 -i extern -h delegated') + mdns_console.get_output('MDNS: Service Instance: extern') + mdns_console.send_input('mdns_service_lookup _test _tcp') + mdns_console.get_output('PTR : local') + mdns_console.send_input('mdns_service_lookup _test2 _tcp -d') + mdns_console.get_output('PTR : extern') + dig_app.check_record('_test2._tcp.local', query_type='PTR', expected=True) + dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True) + + +def test_service_discovery_dns_sd(dig_app): + """Query _services._dns-sd._udp.local PTR to discover registered service types (RFC 6763 §9).""" + resp = dig_app.run_query('_services._dns-sd._udp.local', query_type='PTR') + answers = dig_app.parse_answer_section(resp, 'PTR') + assert any('_test._tcp.local' in a for a in answers), \ + f'Expected _test._tcp.local in DNS-SD response, got: {answers}' + assert any('_test2._tcp.local' in a for a in answers), \ + f'Expected _test2._tcp.local in DNS-SD response, got: {answers}' + + +def test_service_discovery_query(mdns_console): + """Test querier-side: query _services._dns-sd._udp via mdns_query_ptr (exercises multi-label splitting).""" + mdns_console.send_input('mdns_query_ptr _services._dns-sd _udp -t 2000 -m 10') + mdns_console.get_output('Query PTR: _services._dns-sd._udp.local') + mdns_console.get_output('mdns>') + + +def test_remove_delegated_service(mdns_console, dig_app): + mdns_console.send_input('mdns_service_remove _test2 _tcp -h delegated') + mdns_console.send_input('mdns_service_lookup _test2 _tcp -d') + mdns_console.get_output('No results found!') + dig_app.check_record('_test2._tcp.local', query_type='PTR', expected=False) + # add the delegated service again, would be used in the TXT test + mdns_console.send_input('mdns_service_add _test2 _tcp 80 -i extern -h delegated') + mdns_console.get_output('MDNS: Service Instance: extern') + + +def check_txt_for_service(instance, service, proto, mdns_console, dig_app, host=None, with_inst=False): + for_host_arg = f'-h {host}' if host is not None else '' + for_inst_arg = f'-i {instance}' if with_inst else '' + mdns_console.send_input(f'mdns_service_txt_set {service} {proto} {for_host_arg} {for_inst_arg} key1 value1') + dig_app.check_record(f'{instance}.{service}.{proto}.local', query_type='SRV', expected=True) + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key1=value1') + mdns_console.send_input(f'mdns_service_txt_set {service} {proto} {for_host_arg} {for_inst_arg} key2 value2') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key2=value2') + mdns_console.send_input(f'mdns_service_txt_remove {service} {proto} {for_host_arg} {for_inst_arg} key2') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=False, expect='key2=value2') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key1=value1') + mdns_console.send_input(f'mdns_service_txt_replace {service} {proto} {for_host_arg} {for_inst_arg} key3=value3 key4=value4') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=False, expect='key1=value1') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key3=value3') + dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key4=value4') + + +def test_update_txt(mdns_console, dig_app): + check_txt_for_service('local', '_test', '_tcp', mdns_console=mdns_console, dig_app=dig_app) + check_txt_for_service('local', '_test', '_tcp', mdns_console=mdns_console, dig_app=dig_app, with_inst=True) + + +def test_update_delegated_txt(mdns_console, dig_app): + check_txt_for_service('extern', '_test2', '_tcp', mdns_console=mdns_console, dig_app=dig_app, host='delegated') + check_txt_for_service('extern', '_test2', '_tcp', mdns_console=mdns_console, dig_app=dig_app, host='delegated', with_inst=True) + + +def test_service_port_set(mdns_console, dig_app): + dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True, expect='80') + mdns_console.send_input('mdns_service_port_set _test _tcp 81') + dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True, expect='81') + mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated 82') + dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='82') + mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated -i extern 83') + dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='83') + mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated -i invalid_inst 84') + mdns_console.get_output('ESP_ERR_NOT_FOUND') + dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='83') + + +def test_service_subtype(mdns_console, dig_app): + dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True) + mdns_console.send_input('mdns_service_subtype _test _tcp _subtest -i local') + dig_app.check_record('_subtest._sub._test._tcp.local', query_type='PTR', expected=True) + mdns_console.send_input('mdns_service_subtype _test2 _tcp _subtest2 -i extern -h delegated') + dig_app.check_record('_subtest2._sub._test2._tcp.local', query_type='PTR', expected=True) + + +def test_service_set_instance(mdns_console, dig_app): + dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True) + mdns_console.send_input('mdns_service_instance_set _test _tcp local2') + dig_app.check_record('local2._test._tcp.local', query_type='SRV', expected=True) + mdns_console.send_input('mdns_service_instance_set _test2 _tcp extern2 -h delegated') + mdns_console.send_input('mdns_service_lookup _test2 _tcp -d') + mdns_console.get_output('PTR : extern2') + dig_app.check_record('extern2._test2._tcp.local', query_type='SRV', expected=True) + mdns_console.send_input('mdns_service_instance_set _test2 _tcp extern3 -h delegated -i extern') + mdns_console.get_output('ESP_ERR_NOT_FOUND') + + +def test_service_remove_all(mdns_console, dig_app): + mdns_console.send_input('mdns_service_remove_all') + mdns_console.send_input('mdns_service_lookup _test2 _tcp -d') + mdns_console.get_output('No results found!') + mdns_console.send_input('mdns_service_lookup _test _tcp') + mdns_console.get_output('No results found!') + dig_app.check_record('_test._tcp.local', query_type='PTR', expected=False) + + +def _browse_v301test(mdns_console, *, reset_browse: bool = True): + service = DEFAULTS['service'] + proto = DEFAULTS['proto'] + if reset_browse: + mdns_console.send_input(f'mdns_browse_del {service} {proto}') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_browse {service} {proto}') + return mdns_console.wait_for_browse_result(timeout=10) + + +def test_browse_bonjour_additional_order_includes_ip(mdns_console, bonjour_responder): + """Bonjour order (A/AAAA before SRV) must populate browse addresses on first response.""" + output = _browse_v301test(mdns_console) + assert _console_line('PTR : ', DEFAULTS['instance']) in output + assert _console_line('A : ', DEFAULTS['ipv4']) in output + mdns_console.send_input(f"mdns_browse_del {DEFAULTS['service']} {DEFAULTS['proto']}") + mdns_console.get_output('mdns>') + + +def test_browse_srv_first_includes_ip(mdns_console, bonjour_responder_srv_first): + """Control case: SRV before A/AAAA should populate browse addresses.""" + output = _browse_v301test(mdns_console) + assert _console_line('PTR : ', DEFAULTS['instance']) in output + assert _console_line('A : ', DEFAULTS['ipv4']) in output + mdns_console.send_input(f"mdns_browse_del {DEFAULTS['service']} {DEFAULTS['proto']}") + mdns_console.get_output('mdns>') + + +def test_browse_ptr_goodbye_notifies_removal(mdns_console, bonjour_responder_goodbye): + """Same live browse must see normal result then unsolicited PTR TTL=0 removal.""" + service = DEFAULTS['service'] + proto = DEFAULTS['proto'] + mdns_console.send_input(f'mdns_browse_del {service} {proto}') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_browse {service} {proto}') + mdns_console.wait_for_browse_result(timeout=10) + output = mdns_console.wait_for_browse_goodbye(timeout=10) + assert _console_line('PTR : ', DEFAULTS['instance']) in output + mdns_console.send_input(f'mdns_browse_del {service} {proto}') + mdns_console.get_output('mdns>') + + +def test_browse_duplicate_rejected(mdns_console, bonjour_responder): + """Duplicate mdns_browse_new() for the same service/proto must fail and leave the original active.""" + service = DEFAULTS['service'] + proto = DEFAULTS['proto'] + mdns_console.send_input(f'mdns_browse_del {service} {proto}') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_browse {service} {proto}') + mdns_console.wait_for_browse_result(timeout=10) + + mdns_console.send_input(f'mdns_browse {service} {proto}') + mdns_console.get_output('Browse already exists') + mdns_console.get_output('Command returned non-zero error code') + mdns_console.get_output('mdns>') + + # Original browse remains usable (delete must succeed). + mdns_console.send_input(f'mdns_browse_del {service} {proto}') + out = mdns_console.get_output('mdns>') + assert 'Command returned non-zero' not in out + + +def test_query_a_against_peer(mdns_console, querier_responder): + """DUT-side sync mdns_query_a against a controlled peer (replaces test_apps QUERY_HOST).""" + host = QUERIER_DEFAULTS['hostname'] + ipv4 = QUERIER_DEFAULTS['ipv4'] + # Safe if suite already called mdns_init; required when this test runs alone. + mdns_console.send_input('mdns_init -h hostname') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_query_a {host} -t 2000') + mdns_console.get_output(f'Query A: {host}.local') + mdns_console.get_output(ipv4) + mdns_console.get_output('mdns>') + + +def test_query_a_async_against_peer(mdns_console, querier_responder): + """DUT-side async A query against a controlled peer (replaces test_apps QUERY_HOST_ASYNC).""" + host = QUERIER_DEFAULTS['hostname'] + ipv4 = QUERIER_DEFAULTS['ipv4'] + mdns_console.send_input('mdns_init -h hostname') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_query_a_async {host} -t 2000') + mdns_console.get_output(f'Query A async: {host}.local') + mdns_console.get_output(f'Async query resolved to A:{ipv4}') + mdns_console.get_output('mdns>') + + +def test_query_srv_against_peer(mdns_console, querier_responder): + """DUT-side mdns_query_srv against a controlled peer (replaces test_apps QUERY_SERVICE).""" + instance = QUERIER_DEFAULTS['instance'] + service = QUERIER_DEFAULTS['service'] + proto = QUERIER_DEFAULTS['proto'] + hostname = QUERIER_DEFAULTS['hostname'] + port = QUERIER_DEFAULTS['port'] + mdns_console.send_input('mdns_init -h hostname') + mdns_console.get_output('mdns>') + mdns_console.send_input(f'mdns_query_srv {instance} {service} {proto} -t 2000') + mdns_console.get_output(f'Query SRV: {instance}.{service}.{proto}.local') + mdns_console.get_output(_console_line('SRV : ', f'{hostname}.local:{port}')) + mdns_console.get_output('mdns>') + + +if __name__ == '__main__': + pytest.main(['-s', 'test_mdns.py']) diff --git a/managed_components/espressif__mdns/tests/host_test/querier_responder.py b/managed_components/espressif__mdns/tests/host_test/querier_responder.py new file mode 100644 index 0000000..d850709 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/querier_responder.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +"""Controlled mDNS peer for host querier tests (A / SRV only). + +Answers only the configured hostname A and instance SRV questions. Ignores all +other traffic so system mDNS probes cannot create an answer storm. +""" + +from __future__ import annotations + +import argparse +import logging +import socket +import struct +import sys + +import dns.flags +import dns.message +import dns.name +import dns.rdataclass +import dns.rdatatype +import dns.rrset + +logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') +logger = logging.getLogger(__name__) + +MDNS_ADDR = '224.0.0.251' +MDNS_PORT = 5353 + +DEFAULTS = { + 'hostname': 'tinytester', + 'ipv4': '127.0.0.1', + 'instance': 'ESP32', + 'service': '_http', + 'proto': '_tcp', + 'port': 100, +} + + +def _fqdn(*labels: str) -> str: + return '.'.join(labels) + '.local.' + + +def create_socket(interface: str | None) -> socket.socket: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except (AttributeError, OSError): + pass + + if interface: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0') + + sock.bind(('', MDNS_PORT)) + membership = struct.pack('=4s4s', socket.inet_aton(MDNS_ADDR), socket.inet_aton('0.0.0.0')) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership) + return sock + + +def build_a_response(query: dns.message.Message, hostname: str, ipv4: str) -> dns.message.Message: + host_name = _fqdn(hostname) + # Exact QR|AA (0x8400). dnspython make_response also sets RD, which is fine for + # answer parsing but keep mDNS-shaped packets consistent with bonjour fixtures. + response = dns.message.Message(id=query.id) + response.flags = dns.flags.QR | dns.flags.AA + response.answer.append( + dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4) + ) + return response + + +def build_srv_response( + query: dns.message.Message, + *, + instance: str, + service: str, + proto: str, + hostname: str, + port: int, + ipv4: str, +) -> dns.message.Message: + instance_name = _fqdn(instance, service, proto) + host_name = _fqdn(hostname) + response = dns.message.Message(id=query.id) + response.flags = dns.flags.QR | dns.flags.AA + response.answer.append( + dns.rrset.from_text( + instance_name, + 120, + dns.rdataclass.IN, + dns.rdatatype.SRV, + f'0 0 {port} {host_name}', + ) + ) + response.additional.append( + dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4) + ) + return response + + +def match_question(query: dns.message.Message, args: argparse.Namespace): + host_name = dns.name.from_text(_fqdn(args.hostname)) + instance_name = dns.name.from_text(_fqdn(args.instance, args.service, args.proto)) + for question in query.question: + if question.rdtype == dns.rdatatype.A and question.name == host_name: + return 'A' + if question.rdtype == dns.rdatatype.SRV and question.name == instance_name: + return 'SRV' + return None + + +def send_response(sock: socket.socket, payload: bytes, source: tuple[str, int]) -> None: + # mDNS queries usually come from port 5353 → multicast reply; one-shot dig uses ephemeral ports. + destination = (MDNS_ADDR, MDNS_PORT) if source[1] == MDNS_PORT else source + sock.sendto(payload, destination) + logger.info('Sent %d byte response to %s (from %s:%d)', len(payload), destination, *source) + + +def serve(args: argparse.Namespace) -> None: + sock = create_socket(args.interface) + logger.info( + 'Querier responder on %s:%d (%s): A %s.local -> %s; SRV %s.%s.%s.local -> %s.local:%d', + MDNS_ADDR, + MDNS_PORT, + args.interface or 'all interfaces', + args.hostname, + args.ipv4, + args.instance, + args.service, + args.proto, + args.hostname, + args.port, + ) + + while True: + try: + data, source = sock.recvfrom(9000) + except KeyboardInterrupt: + logger.info('Stopping querier responder') + break + + try: + query = dns.message.from_wire(data) + except Exception as exc: # noqa: BLE001 + logger.debug('Ignoring non-DNS payload from %s:%d (%s)', source[0], source[1], exc) + continue + + if query.flags & dns.flags.QR: + continue + + kind = match_question(query, args) + if kind == 'A': + response = build_a_response(query, args.hostname, args.ipv4) + elif kind == 'SRV': + response = build_srv_response( + query, + instance=args.instance, + service=args.service, + proto=args.proto, + hostname=args.hostname, + port=args.port, + ipv4=args.ipv4, + ) + else: + continue + + send_response(sock, response.to_wire(), source) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--interface', default='eth0') + parser.add_argument('--hostname', default=DEFAULTS['hostname']) + parser.add_argument('--ipv4', default=DEFAULTS['ipv4']) + parser.add_argument('--instance', default=DEFAULTS['instance']) + parser.add_argument('--service', default=DEFAULTS['service']) + parser.add_argument('--proto', default=DEFAULTS['proto']) + parser.add_argument('--port', type=int, default=DEFAULTS['port']) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + serve(args) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.app b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.app new file mode 100644 index 0000000..809c518 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.app @@ -0,0 +1,4 @@ +CONFIG_IDF_TARGET="linux" +CONFIG_TEST_HOSTNAME="myesp" +CONFIG_MDNS_ENABLE_DEBUG_PRINTS=y +CONFIG_MDNS_RESPOND_REVERSE_QUERIES=y diff --git a/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.console b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.console new file mode 100644 index 0000000..3b6dcb6 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.console @@ -0,0 +1,4 @@ +CONFIG_IDF_TARGET="linux" +CONFIG_ESP_EVENT_POST_FROM_ISR=n +CONFIG_MDNS_ENABLE_CONSOLE_CLI=y +CONFIG_TEST_CONSOLE=y diff --git a/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.target b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.target new file mode 100644 index 0000000..2a43df1 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/sdkconfig.ci.target @@ -0,0 +1 @@ +CONFIG_IDF_TARGET="esp32" diff --git a/managed_components/espressif__mdns/tests/host_test/sdkconfig.defaults b/managed_components/espressif__mdns/tests/host_test/sdkconfig.defaults new file mode 100644 index 0000000..7e79ce4 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_test/sdkconfig.defaults @@ -0,0 +1,6 @@ +CONFIG_TEST_NETIF_NAME="eth0" +CONFIG_ESP_EVENT_POST_FROM_ISR=n +CONFIG_MDNS_NETWORKING_SOCKET=y +CONFIG_MDNS_SKIP_SUPPRESSING_OWN_QUERIES=y +CONFIG_MDNS_PREDEF_NETIF_STA=n +CONFIG_MDNS_PREDEF_NETIF_AP=n diff --git a/managed_components/espressif__mdns/tests/host_unit_test/CMakeLists.txt b/managed_components/espressif__mdns/tests/host_unit_test/CMakeLists.txt new file mode 100644 index 0000000..af94169 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/CMakeLists.txt @@ -0,0 +1,94 @@ +cmake_minimum_required(VERSION 3.5) +if(ESP_PLATFORM) + # Used for reconfiguration of the project + # Executed by idf.py reconfigure + set(EXTRA_COMPONENT_DIRS ../../) + include($ENV{IDF_PATH}/tools/cmake/project.cmake) + project(mdns_host_unit_test_config) + return() +endif() + +project(mdns_host_unit_test C) + +# Set ENABLE_UNIT_TESTS with a default of OFF +if(NOT DEFINED UNIT_TESTS) + set(UNIT_TESTS "OFF" CACHE STRING "Unit tests: OFF, test_receiver, test_sender, test_cache, test_browse") +else() + set(ENABLE_UNIT_TESTS 1) + message(STATUS "Unit testing enabled with UNIT_TESTS=${UNIT_TESTS}") +endif() + +# Set variables for directories +set(TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +set(STUB_DIR ${TEST_DIR}/stubs) +set(MDNS_DIR ${TEST_DIR}/../../) +set(COMPONENT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../) +set(ESP_NETIF_LINUX_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../host_test/components/esp_netif_linux/include) +set(COMMON_COMPONENTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../common_components/linux_compat/) +set(IDF_COMPONENTS_DIR "$ENV{IDF_PATH}/components") + +include_directories( + ${TEST_DIR} + ${STUB_DIR} + ${TEST_DIR}/build/config + ${COMMON_COMPONENTS_DIR}/freertos/include + ${COMMON_COMPONENTS_DIR}/esp_timer/include + ${IDF_COMPONENTS_DIR}/esp_event/include + ${IDF_COMPONENTS_DIR}/esp_netif/include + ${IDF_COMPONENTS_DIR}/esp_common/include + ${IDF_COMPONENTS_DIR}/esp_system/include + ${IDF_COMPONENTS_DIR}/log/include + ${IDF_COMPONENTS_DIR}/esp_hw_support/etm/include + ${IDF_COMPONENTS_DIR}/soc/linux/include + ${IDF_COMPONENTS_DIR}/esp_rom/include + ${IDF_COMPONENTS_DIR}/heap/include + ${IDF_COMPONENTS_DIR}/esp_rom/linux/include/linux/ + ${ESP_NETIF_LINUX_DIR} + ${COMPONENT_DIR} + ${COMPONENT_DIR}/include + ${COMPONENT_DIR}/private_include +) + +# Source files +set(SOURCES + ${STUB_DIR}/mdns_mem_caps.c + ${STUB_DIR}/esp_idf.c + ${STUB_DIR}/mdns_networking.c + ${STUB_DIR}/mdns_engine.c + ${MDNS_DIR}/mdns_receive.c + ${MDNS_DIR}/mdns_utils.c + ${MDNS_DIR}/mdns_browser.c + ${MDNS_DIR}/mdns_querier.c + ${MDNS_DIR}/mdns_responder.c + ${MDNS_DIR}/mdns_send.c + ${MDNS_DIR}/mdns_pcb.c + ${MDNS_DIR}/mdns_netif.c + ${MDNS_DIR}/mdns_cache.c +) + +if(ENABLE_UNIT_TESTS) + include(unity/unit_test.cmake) +else() + list(APPEND SOURCES main.c) +endif() + +add_executable(${PROJECT_NAME} ${SOURCES}) + +# Add libbsd if available +find_library(LIB_BSD bsd) +if(LIB_BSD) + target_link_libraries(${PROJECT_NAME} PRIVATE ${LIB_BSD}) +elseif(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") + message(WARNING "Missing LIBBSD library. Install libbsd-dev package and/or check linker directories.") +endif() + +# Sanitizers for AFL fuzzing (unit tests enable these in unity/enable_testing.cmake) +if(NOT ENABLE_UNIT_TESTS) + target_compile_options(${PROJECT_NAME} PRIVATE -fsanitize=address -fsanitize=undefined) + target_link_options(${PROJECT_NAME} PRIVATE -fsanitize=address -fsanitize=undefined) +endif() + +# Enable testing if unit tests are enabled +if(ENABLE_UNIT_TESTS) + include(unity/enable_testing.cmake) +endif() diff --git a/managed_components/espressif__mdns/tests/host_unit_test/README.md b/managed_components/espressif__mdns/tests/host_unit_test/README.md new file mode 100644 index 0000000..01eac66 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/README.md @@ -0,0 +1,81 @@ +# mDNS host unit tests and fuzzing + +This directory builds the mDNS component as a Linux host binary with stubs for ESP-IDF networking. It supports two modes: + +- **Unit tests** — Unity/CMock regression tests (ASan/UBSan enabled) +- **Fuzzing** — AFL++ harness that feeds random packets into the receive path + +## Prerequisites + +- ESP-IDF installed and `IDF_PATH` set (`. $IDF_PATH/export.sh`) +- `libbsd-dev` +- For unit tests: `ruby` (CMock code generation) +- For fuzzing: AFL++ (`afl-cc`, `afl-fuzz`) and `dnslib` (`pip install dnslib`) + +From the repository root: + +```bash +cd components/mdns/tests/host_unit_test +``` + +Run `idf.py reconfigure` once before building. This generates `build/config/` headers used by the host build. + +## Unit tests + +Available test suites (pass one to `-DUNIT_TESTS=`): + +| Suite | Description | +|-------|-------------| +| `test_receiver` | Packet receive / parse path | +| `test_sender` | Packet send path | +| `test_browse` | Browse lifecycle, cache replay, service filtering, goodbye/rediscovery | +| `test_cache` | Cached record insert/update/remove, sync batching, and result projection | + +Example — build and run the receiver tests: + +```bash +. $IDF_PATH/export.sh +idf.py reconfigure + +mkdir -p build2 && cd build2 +cmake -DUNIT_TESTS=test_receiver .. +cmake --build . +ctest --extra-verbose +``` + +Or run the binary directly: + +```bash +./mdns_host_unit_test --test +``` + +Repeat with `-DUNIT_TESTS=test_sender` or `-DUNIT_TESTS=test_browse` in a separate build directory. + +## Fuzzer tests + +Build the AFL-instrumented harness (no `-DUNIT_TESTS`; uses `main.c`): + +```bash +export IDF_PATH=/path/to/esp-idf # required in the fuzz container + +cd input && python generate_cases.py && cd .. + +cmake -B build2 -S . -G Ninja -DCMAKE_C_COMPILER=afl-cc +cmake --build build2 + +afl-fuzz -i input -o out -- build2/mdns_host_unit_test +``` + +The harness reads packets from stdin and exercises IPv4/IPv6 and port 5353/53 combinations. Crashes are written to `out/default/crashes/`. + +### Reproducing a crash + +Build the non-unit-test binary with a normal compiler, then pass a crash file: + +```bash +cmake -B build2 -S . +cmake --build build2 +./build2/mdns_host_unit_test out/default/crashes/id_000000,... +``` + +With sanitizers enabled, ASan/UBSan report buffer overruns and undefined behaviour directly during unit tests and fuzzing. diff --git a/managed_components/espressif__mdns/tests/host_unit_test/input/generate_cases.py b/managed_components/espressif__mdns/tests/host_unit_test/input/generate_cases.py new file mode 100644 index 0000000..5bf0193 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/input/generate_cases.py @@ -0,0 +1,166 @@ +# SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +from dnslib import (AAAA, PTR, RR, SRV, TXT, A, DNSHeader, DNSQuestion, + DNSRecord) + + +def create_mdns_packet(queries, answers, additional, output_file='mdns_packet.bin'): + dns_header = DNSHeader(id=0, qr=1, aa=1, ra=0) + dns_record = DNSRecord(dns_header) + for qname, qtype in queries: + dns_record.add_question(DNSQuestion(qname, qtype)) + for name, qtype, value, ttl in answers: + if qtype == 'A': + rr = RR(name, rdata=A(value), ttl=ttl) + elif qtype == 'PTR': + rr = RR(name, rdata=PTR(value), ttl=ttl) + elif qtype == 'TXT': + rr = RR(name, rdata=TXT(value), ttl=ttl) + elif qtype == 'AAAA': + rr = RR(name, rdata=AAAA(value), ttl=ttl) + elif qtype == 'SRV': + # SRV value should be in format: "priority weight port target" + parts = value.split() + priority, weight, port = map(int, parts[:3]) + target = parts[3] + rr = RR(name, rdata=SRV(priority, weight, port, target), ttl=ttl) + else: + print(f'Unsupported type: {qtype}') + continue + dns_record.add_answer(rr) + for name, qtype, value, ttl in additional: + if qtype == 'A': + rr = RR(name, rdata=A(value), ttl=ttl) + elif qtype == 'TXT': + rr = RR(name, rdata=TXT(value), ttl=ttl) + elif qtype == 'AAAA': + rr = RR(name, rdata=AAAA(value), ttl=ttl) + elif qtype == 'SRV': + parts = value.split() + priority, weight, port = map(int, parts[:3]) + target = parts[3] + rr = RR(name, rdata=SRV(priority, weight, port, target), ttl=ttl) + else: + print(f'Unsupported type: {qtype}') + continue + dns_record.add_ar(rr) + mdns_payload = dns_record.pack() + + with open(output_file, 'wb') as f: + f.write(mdns_payload) + + print(f'mDNS packet saved as {output_file}') + + +# Test case 1: Basic hostname queries +queries = [ + ('test4.local.', 1), # A record for main hostname + ('test.local.', 1), # A record for main hostname +] +answers = [ +] +additional = [ +] +create_mdns_packet(queries, answers, additional, 'test_hostname_queries.bin') +print('Test case 1: Hostname queries') + +# Test case 2: HTTP service discovery with subtypes +queries = [ + ('_http._tcp.local.', 12), # PTR query + ('subtype._sub._http._tcp.local.', 12), # Subtype query +] +answers = [ + ('_http._tcp.local.', 'PTR', 'inst1._http._tcp.local.', 120), + ('_http._tcp.local.', 'PTR', 'inst2._http._tcp.local.', 120), + ('subtype._sub._http._tcp.local.', 'PTR', 'inst1._http._tcp.local.', 120), +] +additional = [ + ('inst1._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('inst1._http._tcp.local.', 'TXT', 'board=esp32\0tcp_check=no\0ssh_upload=no\0auth_upload=no', 120), + ('inst2._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('inst2._http._tcp.local.', 'TXT', 'board=esp32\0tcp_check=no\0ssh_upload=no\0auth_upload=no', 120), +] +create_mdns_packet(queries, answers, additional, 'test_http_services.bin') +print('Test case 2: HTTP service discovery with subtypes') + +# Test case 3: Scanner service discovery +queries = [ + ('_scanner._tcp.local.', 12), # PTR query +] +answers = [ + ('_scanner._tcp.local.', 'PTR', 'inst4._scanner._tcp.local.', 120), + ('_scanner._tcp.local.', 'PTR', 'inst5._scanner._tcp.local.', 120), +] +additional = [ + ('inst4._scanner._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('inst5._scanner._tcp.local.', 'SRV', '0 0 80 test.local.', 120), +] +create_mdns_packet(queries, answers, additional, 'test_scanner_services.bin') +print('Test case 3: Scanner service discovery') + +# Test case 4: UDP service (sleep protocol) +queries = [ + ('_sleep._udp.local.', 12), # PTR query +] +answers = [ + ('_sleep._udp.local.', 'PTR', 'inst7._sleep._udp.local.', 120), +] +additional = [ + ('inst7._sleep._udp.local.', 'SRV', '0 0 80 test.local.', 120), +] +create_mdns_packet(queries, answers, additional, 'test_udp_service.bin') +print('Test case 4: UDP service discovery') + +# Test case 5: Async queries from main.c +queries = [ + ('host_name.local.', 1), # A query + ('host_name2.local.', 28), # AAAA query + ('minifritz._http._tcp.local.', 12), # PTR query +] +answers = [ + ('host_name.local.', 'A', '192.168.1.10', 120), + ('host_name2.local.', 'AAAA', 'fe80::1234', 120), + ('minifritz._http._tcp.local.', 'PTR', 'minifritz._http._tcp.local.', 120), +] +additional = [ + ('minifritz._http._tcp.local.', 'SRV', '0 0 80 minifritz.local.', 120), + ('minifritz.local.', 'A', '192.168.1.20', 120), +] +create_mdns_packet(queries, answers, additional, 'test_async_queries.bin') +print('Test case 5: Async queries') + +# Test case 6: Multiple services on same instance +queries = [ + ('_http._tcp.local.', 12), + ('_scanner._tcp.local.', 12), +] +answers = [ + ('_http._tcp.local.', 'PTR', 'inst1._http._tcp.local.', 120), + ('_http._tcp.local.', 'PTR', 'inst2._http._tcp.local.', 120), + ('_http._tcp.local.', 'PTR', 'inst3._http._tcp.local.', 120), + ('_scanner._tcp.local.', 'PTR', 'inst4._scanner._tcp.local.', 120), +] +additional = [ + ('inst1._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('inst2._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('test.local.', 'A', '192.168.1.100', 120), +] +create_mdns_packet(queries, answers, additional, 'test_multiple_services.bin') +print('Test case 6: Multiple services') + +# Test case 7: Subtype queries for different hosts +queries = [ + ('subtype._sub._http._tcp.local.', 12), + ('subtype3._sub._http._tcp.local.', 12), +] +answers = [ + ('subtype._sub._http._tcp.local.', 'PTR', 'inst1._http._tcp.local.', 120), + ('subtype3._sub._http._tcp.local.', 'PTR', 'inst2._http._tcp.local.', 120), +] +additional = [ + ('inst1._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('inst2._http._tcp.local.', 'SRV', '0 0 80 test.local.', 120), + ('test.local.', 'A', '192.168.1.100', 120), +] +create_mdns_packet(queries, answers, additional, 'test_subtype_queries.bin') +print('Test case 7: Subtype queries') diff --git a/managed_components/espressif__mdns/tests/host_unit_test/main.c b/managed_components/espressif__mdns/tests/host_unit_test/main.c new file mode 100644 index 0000000..d89f477 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/main.c @@ -0,0 +1,129 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include +#include +#include +#include "esp_err.h" +#include "mdns.h" +#include "mdns_receive.h" +#include "mdns_responder.h" +#include "mdns_querier.h" +#include "mdns_browser.h" +#include "mdns_mem_caps.h" + +esp_err_t mdns_packet_push(esp_ip_addr_t *addr, int port, mdns_if_t tcpip_if, uint8_t*data, size_t len); + +mdns_search_once_t *s_a, *s_aaaa, *s_ptr, *s_srv, *s_txt; + +static void browse_notifier(mdns_result_t *result) +{ + (void)result; +} + +void init_responder(void) +{ + mdns_ip_addr_t addr = { .addr = { .u_addr = ESP_IPADDR_TYPE_V4 } }; + addr.addr.u_addr.ip4.addr = 0x11111111; + mdns_txt_item_t txt[4] = { + {"board", "esp32"}, + {"tcp_check", "no"}, + {"ssh_upload", "no"}, + {"auth_upload", "no"} + }; + mdns_priv_responder_init(); + mdns_hostname_set("test"); + mdns_instance_name_set("test2"); + mdns_delegate_hostname_add("test3", NULL); + mdns_delegate_hostname_add("test4", &addr); + mdns_service_add("inst1", "_http", "_tcp", 80, txt, 4); + mdns_service_subtype_add_for_host("inst1", "_http", "_tcp", "test", "subtype"); + mdns_service_add("inst2", "_http", "_tcp", 80, txt, 1); + mdns_service_subtype_add_for_host("inst2", "_http", "_tcp", "test", "subtype3"); + mdns_service_add("inst3", "_http", "_tcp", 80, NULL, 0); + mdns_service_add_for_host("deleg1", "_http", "_tcp", "test3", 80, txt, 2); + mdns_service_add_for_host(NULL, "_http", "_tcp", "test4", 80, txt, 2); + mdns_service_add(NULL, "_scanner", "_tcp", 80, NULL, 0); + mdns_service_add("inst5", "_scanner", "_tcp", 80, NULL, 0); + mdns_service_add("inst6", "_http", "_tcp", 80, NULL, 0); + mdns_service_add("inst7", "_sleep", "_udp", 80, NULL, 0); + + s_a = mdns_query_async_new("host_name", NULL, NULL, MDNS_TYPE_A, 1000, 1, NULL); + s_aaaa = mdns_query_async_new("host_name2", NULL, NULL, MDNS_TYPE_AAAA, 1000, 1, NULL); + s_ptr = mdns_query_async_new("minifritz", "_http", "_tcp", MDNS_TYPE_PTR, 1000, 1, NULL); + s_srv = mdns_query_async_new("fritz", "_http", "_tcp", MDNS_TYPE_SRV, 1000, 1, NULL); + s_txt = mdns_query_async_new("fritz", "_http", "_tcp", MDNS_TYPE_TXT, 1000, 1, NULL); + + mdns_browse_new("_http", "_tcp", browse_notifier); + mdns_browse_new("_scanner", "_tcp", browse_notifier); + mdns_browse_new("_sleep", "_udp", browse_notifier); +} + +void deinit_responder(void) +{ + mdns_priv_search_once_free(s_a); + mdns_priv_search_once_free(s_aaaa); + mdns_priv_search_once_free(s_ptr); + mdns_priv_search_once_free(s_srv); + mdns_priv_search_once_free(s_txt); + mdns_priv_query_free(); + mdns_priv_browse_free(); + mdns_service_remove_all(); + mdns_priv_responder_free(); + s_a = NULL; + s_aaaa = NULL; + s_ptr = NULL; + s_srv = NULL; + s_txt = NULL; +} + +static void send_packet(bool ip4, bool mdns_port, uint8_t*data, size_t len) +{ + esp_ip_addr_t addr4 = ESP_IP4ADDR_INIT(192, 168, 1, 1); + esp_ip_addr_t addr6 = ESP_IP6ADDR_INIT(0x000002ff, 0, 0, 0xfe800000); + esp_ip_addr_t *addr = ip4 ? &addr4 : &addr6; + int port = mdns_port ? 53 : 5353; + + if (mdns_packet_push(addr, port, 0, data, len) != ESP_OK) { + printf("Failed to push packet\n"); + } +} + +int main(int argc, char **argv) +{ + init_responder(); + + // Original fuzzing code + uint8_t buf[1460]; + FILE *file; + size_t len = 1460; + memset(buf, 0, len); +#ifndef __AFL_LOOP + // + // Note: parameter1 is a file (mangled packet) which caused the crash + if (argc != 2) { + printf("Non-instrumentation mode: please supply a file name created by AFL to reproduce crash\n"); + return 1; + } + file = fopen(argv[1], "r"); + assert(file >= 0); + len = fread(buf, 1, 1460, file); + fclose(file); + { +#else + while (__AFL_LOOP(1000)) { + memset(buf, 0, 1460); + size_t len = read(0, buf, 1460); +#endif + send_packet(true, true, buf, len); + send_packet(true, false, buf, len); + send_packet(false, true, buf, len); + send_packet(false, false, buf, len); + } + deinit_responder(); + + return 0; +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/sdkconfig.defaults b/managed_components/espressif__mdns/tests/host_unit_test/sdkconfig.defaults new file mode 100644 index 0000000..cd903ad --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/sdkconfig.defaults @@ -0,0 +1,6 @@ +# This file was generated using idf.py save-defconfig. It can be edited manually. +# Espressif IoT Development Framework (ESP-IDF) 5.5.0 Project Minimal Configuration +# +CONFIG_MDNS_PREDEF_NETIF_STA=n +CONFIG_MDNS_PREDEF_NETIF_AP=n +CONFIG_MDNS_PREDEF_NETIF_ETH=n diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_assert.h b/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_assert.h new file mode 100644 index 0000000..3ddf440 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_assert.h @@ -0,0 +1,10 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#if __has_include("esp_assert.h") +#include_next "esp_assert.h" +#else +#define ESP_STATIC_ASSERT _Static_assert +#endif diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_idf.c b/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_idf.c new file mode 100644 index 0000000..24b506d --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_idf.c @@ -0,0 +1,105 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include "esp_log.h" +#include "esp_netif.h" +#include "freertos/FreeRTOS.h" +#include "mdns_test_clock.h" + +static int64_t s_clock_us = 0; + +void mdns_test_clock_reset(void) +{ + s_clock_us = 0; +} + +bool mdns_test_clock_advance_us(int64_t delta_us) +{ + if (delta_us < 0 || delta_us > INT64_MAX - s_clock_us) { + return false; + } + + s_clock_us += delta_us; + return true; +} + +void esp_log(esp_log_config_t config, const char* tag, const char* format, ...) +{} + +uint32_t esp_log_timestamp(void) +{ + return 0; +} + +uint32_t esp_get_free_heap_size(void) +{ + return 0; +} + +esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key) +{ + return (esp_netif_t*)1; +} + +esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) +{ + ip_info->ip.addr = 0xC0A80164; // 192.168.1.100 + ip_info->netmask.addr = 0xFFFFFF00; // 255.255.255.0 + ip_info->gw.addr = 0xC0A80101; // 192.168.1.1 + return ESP_OK; +} + +esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) +{ + if_ip6->addr[0] = 0xFE80; + if_ip6->addr[1] = 0x0000; + if_ip6->addr[2] = 0x0000; + if_ip6->addr[3] = 0x0001; + return ESP_OK; +} + +uint32_t esp_random(void) +{ + return 0; +} + +TickType_t xTaskGetTickCount(void) +{ + return (TickType_t)(s_clock_us / 1000 / portTICK_PERIOD_MS); +} + +int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) +{ + if_ip6[0].addr[0] = 0xFE80; + if_ip6[0].addr[1] = 0x0000; + if_ip6[0].addr[2] = 0x0000; + if_ip6[0].addr[3] = 0x0001; + return 1; +} + + +BaseType_t xSemaphoreGive(QueueHandle_t xQueue) +{ + return pdPASS; +} + +BaseType_t xSemaphoreTake(QueueHandle_t xQueue, TickType_t xTicksToWait) +{ + return pdPASS; +} + +QueueHandle_t xSemaphoreCreateBinary(void) +{ + return (QueueHandle_t)1; +} + +void vQueueDelete(QueueHandle_t xQueue) +{ +} + +int64_t esp_timer_get_time(void) +{ + return s_clock_us; +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_random.h b/managed_components/espressif__mdns/tests/host_unit_test/stubs/esp_random.h new file mode 100644 index 0000000..e69de29 diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_engine.c b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_engine.c new file mode 100644 index 0000000..d2a243e --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_engine.c @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include "mdns.h" +#include "mdns_private.h" +#include "mdns_querier.h" +#include "mdns_browser.h" +#include "mdns_send.h" +#include "mdns_responder.h" +#include "mdns_receive.h" +#include "mdns_mem_caps.h" + +static void execute_action(mdns_action_t *action) +{ + switch (action->type) { + case ACTION_SYSTEM_EVENT: + break; + case ACTION_SEARCH_ADD: + case ACTION_SEARCH_SEND: + case ACTION_SEARCH_END: + mdns_priv_query_action(action, ACTION_RUN); + break; + case ACTION_BROWSE_START: + case ACTION_BROWSE_END: + mdns_priv_browse_action(action, ACTION_RUN); + break; + + case ACTION_TX_HANDLE: + mdns_priv_send_action(action, ACTION_RUN); + break; + case ACTION_RX_HANDLE: + mdns_priv_receive_action(action, ACTION_RUN); + break; + case ACTION_HOSTNAME_SET: + case ACTION_INSTANCE_SET: + case ACTION_DELEGATE_HOSTNAME_ADD: + case ACTION_DELEGATE_HOSTNAME_SET_ADDR: + case ACTION_DELEGATE_HOSTNAME_REMOVE: + mdns_priv_responder_action(action, ACTION_RUN); + break; + default: + break; + } + mdns_mem_free(action); +} + +bool mdns_priv_queue_action(mdns_action_t *action) +{ + execute_action(action); + return true; +} + +void mdns_priv_service_lock(void) +{ +} + +void mdns_priv_service_unlock(void) +{ +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps.c b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps.c new file mode 100644 index 0000000..67d6673 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps.c @@ -0,0 +1,89 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include "mdns_mem_caps.h" +#include "mdns_mem_caps_test.h" + +static size_t s_allocation_counts; + +size_t mdns_mem_get_allocation_counts(void) +{ + return s_allocation_counts; +} + +void *mdns_mem_malloc(size_t size) +{ + void *ptr = malloc(size); + if (ptr) { + s_allocation_counts++; + } + return ptr; +} + +void *mdns_mem_calloc(size_t num, size_t size) +{ + void *ptr = calloc(num, size); + if (ptr) { + s_allocation_counts++; + } + return ptr; +} + +void mdns_mem_free(void *ptr) +{ + if (ptr) { + if (s_allocation_counts > 0) { + s_allocation_counts--; + } + free(ptr); + } +} + +char *mdns_mem_strdup(const char *s) +{ + if (s == NULL) { + return NULL; + } + + size_t len = strlen(s) + 1; + char *new_str = mdns_mem_malloc(len); + if (new_str == NULL) { + return NULL; + } + + return memcpy(new_str, s, len); +} + +char *mdns_mem_strndup(const char *s, size_t n) +{ + if (s == NULL) { + return NULL; + } + + size_t len = strnlen(s, n); + + char *new_str = mdns_mem_malloc(len + 1); + if (new_str == NULL) { + return NULL; + } + + memcpy(new_str, s, len); + new_str[len] = '\0'; + + return new_str; +} + +void *mdns_mem_task_malloc(size_t size) +{ + return mdns_mem_malloc(size); +} + +void mdns_mem_task_free(void *ptr) +{ + mdns_mem_free(ptr); +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps_test.h b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps_test.h new file mode 100644 index 0000000..f9c9a0c --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_mem_caps_test.h @@ -0,0 +1,10 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#pragma once + +#include + +size_t mdns_mem_get_allocation_counts(void); diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_networking.c b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_networking.c new file mode 100644 index 0000000..2bca2e5 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_networking.c @@ -0,0 +1,90 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "mdns_networking.h" +#include "mdns_mem_caps.h" +#include "mdns_service.h" + +struct pbuf { + void *payload; + size_t len; +}; + +bool mdns_priv_if_ready(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return true; // Default to ready for testing +} + +esp_err_t mdns_priv_if_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return ESP_OK; +} + +esp_err_t mdns_priv_if_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +{ + return ESP_OK; +} + +size_t mdns_priv_if_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, const esp_ip_addr_t *ip, uint16_t port, uint8_t *data, size_t len) +{ + return len; // Return the input length as if all data was sent successfully +} + +void *mdns_priv_get_packet_data(mdns_rx_packet_t *packet) +{ + return packet->pb->payload; +} + +size_t mdns_priv_get_packet_len(mdns_rx_packet_t *packet) +{ + return packet->pb->len; +} + +void mdns_priv_packet_free(mdns_rx_packet_t *packet) +{ + mdns_mem_free(packet->pb->payload); + mdns_mem_free(packet->pb); + mdns_mem_free(packet); +} + +esp_err_t mdns_packet_push(esp_ip_addr_t *addr, int port, mdns_if_t tcpip_if, uint8_t*data, size_t len) +{ + // Allocate the packet structure and pass it to the mdns main engine + mdns_rx_packet_t *packet = (mdns_rx_packet_t *) mdns_mem_calloc(1, sizeof(mdns_rx_packet_t)); + struct pbuf *packet_pbuf = mdns_mem_calloc(1, sizeof(struct pbuf)); + uint8_t *buf = mdns_mem_malloc(len); + if (packet == NULL || packet_pbuf == NULL || buf == NULL) { + mdns_mem_free(buf); + mdns_mem_free(packet_pbuf); + mdns_mem_free(packet); + return ESP_ERR_NO_MEM; + } + memcpy(buf, data, len); + packet_pbuf->payload = buf; + packet_pbuf->len = len; + packet->tcpip_if = tcpip_if; + packet->pb = packet_pbuf; + packet->src_port = port; + memcpy(&packet->src, addr, sizeof(esp_ip_addr_t)); + memset(&packet->dest, 0, sizeof(esp_ip_addr_t)); + packet->multicast = 1; + packet->dest.type = packet->src.type; + packet->ip_protocol = packet->src.type == ESP_IPADDR_TYPE_V4 ? MDNS_IP_PROTOCOL_V4 : MDNS_IP_PROTOCOL_V6; + mdns_action_t *action = (mdns_action_t *)mdns_mem_malloc(sizeof(mdns_action_t)); + if (!action) { + return ESP_ERR_NO_MEM; + } + + action->type = ACTION_RX_HANDLE; + action->data.rx_handle.packet = packet; + if (!mdns_priv_queue_action(action)) { + mdns_mem_free(action); + mdns_mem_free(packet->pb->payload); + mdns_mem_free(packet->pb); + mdns_mem_free(packet); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_test_clock.h b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_test_clock.h new file mode 100644 index 0000000..521c35a --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/mdns_test_clock.h @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void mdns_test_clock_reset(void); + +bool mdns_test_clock_advance_us(int64_t delta_us); + +#ifdef __cplusplus +} +#endif diff --git a/managed_components/espressif__mdns/tests/host_unit_test/stubs/sdkconfig.h b/managed_components/espressif__mdns/tests/host_unit_test/stubs/sdkconfig.h new file mode 100644 index 0000000..9fab009 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/stubs/sdkconfig.h @@ -0,0 +1,886 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +/* + * Automatically generated file. DO NOT EDIT. + * Espressif IoT Development Framework (ESP-IDF) 5.5.0 Configuration Header + */ +#pragma once +#define CONFIG_SOC_BROWNOUT_RESET_SUPPORTED "Not determined" +#define CONFIG_SOC_TWAI_BRP_DIV_SUPPORTED "Not determined" +#define CONFIG_SOC_DPORT_WORKAROUND "Not determined" +#define CONFIG_SOC_CAPS_ECO_VER_MAX 301 +#define CONFIG_SOC_ADC_SUPPORTED 1 +#define CONFIG_SOC_DAC_SUPPORTED 1 +#define CONFIG_SOC_UART_SUPPORTED 1 +#define CONFIG_SOC_MCPWM_SUPPORTED 1 +#define CONFIG_SOC_GPTIMER_SUPPORTED 1 +#define CONFIG_SOC_SDMMC_HOST_SUPPORTED 1 +#define CONFIG_SOC_BT_SUPPORTED 1 +#define CONFIG_SOC_PCNT_SUPPORTED 1 +#define CONFIG_SOC_PHY_SUPPORTED 1 +#define CONFIG_SOC_WIFI_SUPPORTED 1 +#define CONFIG_SOC_SDIO_SLAVE_SUPPORTED 1 +#define CONFIG_SOC_TWAI_SUPPORTED 1 +#define CONFIG_SOC_EFUSE_SUPPORTED 1 +#define CONFIG_SOC_EMAC_SUPPORTED 1 +#define CONFIG_SOC_ULP_SUPPORTED 1 +#define CONFIG_SOC_CCOMP_TIMER_SUPPORTED 1 +#define CONFIG_SOC_RTC_FAST_MEM_SUPPORTED 1 +#define CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED 1 +#define CONFIG_SOC_RTC_MEM_SUPPORTED 1 +#define CONFIG_SOC_I2S_SUPPORTED 1 +#define CONFIG_SOC_RMT_SUPPORTED 1 +#define CONFIG_SOC_SDM_SUPPORTED 1 +#define CONFIG_SOC_GPSPI_SUPPORTED 1 +#define CONFIG_SOC_LEDC_SUPPORTED 1 +#define CONFIG_SOC_I2C_SUPPORTED 1 +#define CONFIG_SOC_SUPPORT_COEXISTENCE 1 +#define CONFIG_SOC_AES_SUPPORTED 1 +#define CONFIG_SOC_MPI_SUPPORTED 1 +#define CONFIG_SOC_SHA_SUPPORTED 1 +#define CONFIG_SOC_FLASH_ENC_SUPPORTED 1 +#define CONFIG_SOC_SECURE_BOOT_SUPPORTED 1 +#define CONFIG_SOC_TOUCH_SENSOR_SUPPORTED 1 +#define CONFIG_SOC_BOD_SUPPORTED 1 +#define CONFIG_SOC_ULP_FSM_SUPPORTED 1 +#define CONFIG_SOC_CLK_TREE_SUPPORTED 1 +#define CONFIG_SOC_MPU_SUPPORTED 1 +#define CONFIG_SOC_WDT_SUPPORTED 1 +#define CONFIG_SOC_SPI_FLASH_SUPPORTED 1 +#define CONFIG_SOC_RNG_SUPPORTED 1 +#define CONFIG_SOC_LIGHT_SLEEP_SUPPORTED 1 +#define CONFIG_SOC_DEEP_SLEEP_SUPPORTED 1 +#define CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT 1 +#define CONFIG_SOC_PM_SUPPORTED 1 +#define CONFIG_SOC_DPORT_WORKAROUND_DIS_INTERRUPT_LVL 5 +#define CONFIG_SOC_XTAL_SUPPORT_26M 1 +#define CONFIG_SOC_XTAL_SUPPORT_40M 1 +#define CONFIG_SOC_XTAL_SUPPORT_AUTO_DETECT 1 +#define CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED 1 +#define CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED 1 +#define CONFIG_SOC_ADC_DMA_SUPPORTED 1 +#define CONFIG_SOC_ADC_PERIPH_NUM 2 +#define CONFIG_SOC_ADC_MAX_CHANNEL_NUM 10 +#define CONFIG_SOC_ADC_ATTEN_NUM 4 +#define CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM 2 +#define CONFIG_SOC_ADC_PATT_LEN_MAX 16 +#define CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH 9 +#define CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH 12 +#define CONFIG_SOC_ADC_DIGI_RESULT_BYTES 2 +#define CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV 4 +#define CONFIG_SOC_ADC_DIGI_MONITOR_NUM 0 +#define CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH 2 +#define CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW 20 +#define CONFIG_SOC_ADC_RTC_MIN_BITWIDTH 9 +#define CONFIG_SOC_ADC_RTC_MAX_BITWIDTH 12 +#define CONFIG_SOC_ADC_SHARED_POWER 1 +#define CONFIG_SOC_SHARED_IDCACHE_SUPPORTED 1 +#define CONFIG_SOC_IDCACHE_PER_CORE 1 +#define CONFIG_SOC_CPU_CORES_NUM 2 +#define CONFIG_SOC_CPU_INTR_NUM 32 +#define CONFIG_SOC_CPU_HAS_FPU 1 +#define CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES 1 +#define CONFIG_SOC_CPU_BREAKPOINTS_NUM 2 +#define CONFIG_SOC_CPU_WATCHPOINTS_NUM 2 +#define CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE 64 +#define CONFIG_SOC_DAC_CHAN_NUM 2 +#define CONFIG_SOC_DAC_RESOLUTION 8 +#define CONFIG_SOC_DAC_DMA_16BIT_ALIGN 1 +#define CONFIG_SOC_GPIO_PORT 1 +#define CONFIG_SOC_GPIO_PIN_COUNT 40 +#define CONFIG_SOC_GPIO_VALID_GPIO_MASK 0xFFFFFFFFFF +#define CONFIG_SOC_GPIO_IN_RANGE_MAX 39 +#define CONFIG_SOC_GPIO_OUT_RANGE_MAX 33 +#define CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK 0xEF0FEA +#define CONFIG_SOC_GPIO_CLOCKOUT_BY_IO_MUX 1 +#define CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM 3 +#define CONFIG_SOC_GPIO_SUPPORT_HOLD_IO_IN_DSLP 1 +#define CONFIG_SOC_I2C_NUM 2 +#define CONFIG_SOC_HP_I2C_NUM 2 +#define CONFIG_SOC_I2C_FIFO_LEN 32 +#define CONFIG_SOC_I2C_CMD_REG_NUM 16 +#define CONFIG_SOC_I2C_SUPPORT_SLAVE 1 +#define CONFIG_SOC_I2C_SUPPORT_APB 1 +#define CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR 1 +#define CONFIG_SOC_I2C_STOP_INDEPENDENT 1 +#define CONFIG_SOC_I2S_NUM 2 +#define CONFIG_SOC_I2S_HW_VERSION_1 1 +#define CONFIG_SOC_I2S_SUPPORTS_APLL 1 +#define CONFIG_SOC_I2S_SUPPORTS_PLL_F160M 1 +#define CONFIG_SOC_I2S_SUPPORTS_PDM 1 +#define CONFIG_SOC_I2S_SUPPORTS_PDM_TX 1 +#define CONFIG_SOC_I2S_SUPPORTS_PCM2PDM 1 +#define CONFIG_SOC_I2S_SUPPORTS_PDM_RX 1 +#define CONFIG_SOC_I2S_SUPPORTS_PDM2PCM 1 +#define CONFIG_SOC_I2S_PDM_MAX_TX_LINES 1 +#define CONFIG_SOC_I2S_PDM_MAX_RX_LINES 1 +#define CONFIG_SOC_I2S_SUPPORTS_ADC_DAC 1 +#define CONFIG_SOC_I2S_SUPPORTS_ADC 1 +#define CONFIG_SOC_I2S_SUPPORTS_DAC 1 +#define CONFIG_SOC_I2S_SUPPORTS_LCD_CAMERA 1 +#define CONFIG_SOC_I2S_MAX_DATA_WIDTH 24 +#define CONFIG_SOC_I2S_TRANS_SIZE_ALIGN_WORD 1 +#define CONFIG_SOC_I2S_LCD_I80_VARIANT 1 +#define CONFIG_SOC_LCD_I80_SUPPORTED 1 +#define CONFIG_SOC_LCD_I80_BUSES 2 +#define CONFIG_SOC_LCD_I80_BUS_WIDTH 24 +#define CONFIG_SOC_LEDC_HAS_TIMER_SPECIFIC_MUX 1 +#define CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK 1 +#define CONFIG_SOC_LEDC_SUPPORT_REF_TICK 1 +#define CONFIG_SOC_LEDC_SUPPORT_HS_MODE 1 +#define CONFIG_SOC_LEDC_TIMER_NUM 4 +#define CONFIG_SOC_LEDC_CHANNEL_NUM 8 +#define CONFIG_SOC_LEDC_TIMER_BIT_WIDTH 20 +#define CONFIG_SOC_MCPWM_GROUPS 2 +#define CONFIG_SOC_MCPWM_TIMERS_PER_GROUP 3 +#define CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP 3 +#define CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR 2 +#define CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR 2 +#define CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR 2 +#define CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP 3 +#define CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP 1 +#define CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER 3 +#define CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP 3 +#define CONFIG_SOC_MMU_PERIPH_NUM 2 +#define CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM 3 +#define CONFIG_SOC_MPU_MIN_REGION_SIZE 0x20000000 +#define CONFIG_SOC_MPU_REGIONS_MAX_NUM 8 +#define CONFIG_SOC_PCNT_GROUPS 1 +#define CONFIG_SOC_PCNT_UNITS_PER_GROUP 8 +#define CONFIG_SOC_PCNT_CHANNELS_PER_UNIT 2 +#define CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT 2 +#define CONFIG_SOC_RMT_GROUPS 1 +#define CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP 8 +#define CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP 8 +#define CONFIG_SOC_RMT_CHANNELS_PER_GROUP 8 +#define CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL 64 +#define CONFIG_SOC_RMT_SUPPORT_REF_TICK 1 +#define CONFIG_SOC_RMT_SUPPORT_APB 1 +#define CONFIG_SOC_RMT_CHANNEL_CLK_INDEPENDENT 1 +#define CONFIG_SOC_RTCIO_PIN_COUNT 18 +#define CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED 1 +#define CONFIG_SOC_RTCIO_HOLD_SUPPORTED 1 +#define CONFIG_SOC_RTCIO_WAKE_SUPPORTED 1 +#define CONFIG_SOC_SDM_GROUPS 1 +#define CONFIG_SOC_SDM_CHANNELS_PER_GROUP 8 +#define CONFIG_SOC_SDM_CLK_SUPPORT_APB 1 +#define CONFIG_SOC_SPI_HD_BOTH_INOUT_SUPPORTED 1 +#define CONFIG_SOC_SPI_AS_CS_SUPPORTED 1 +#define CONFIG_SOC_SPI_PERIPH_NUM 3 +#define CONFIG_SOC_SPI_DMA_CHAN_NUM 2 +#define CONFIG_SOC_SPI_MAX_CS_NUM 3 +#define CONFIG_SOC_SPI_SUPPORT_CLK_APB 1 +#define CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE 64 +#define CONFIG_SOC_SPI_MAX_PRE_DIVIDER 8192 +#define CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED 1 +#define CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED 1 +#define CONFIG_SOC_MEMSPI_SRC_FREQ_26M_SUPPORTED 1 +#define CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED 1 +#define CONFIG_SOC_TIMER_GROUPS 2 +#define CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP 2 +#define CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH 64 +#define CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS 4 +#define CONFIG_SOC_TIMER_GROUP_SUPPORT_APB 1 +#define CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO 32 +#define CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI 16 +#define CONFIG_SOC_TOUCH_SENSOR_VERSION 1 +#define CONFIG_SOC_TOUCH_SENSOR_NUM 10 +#define CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP 1 +#define CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM 1 +#define CONFIG_SOC_TWAI_CONTROLLER_NUM 1 +#define CONFIG_SOC_TWAI_BRP_MIN 2 +#define CONFIG_SOC_TWAI_CLK_SUPPORT_APB 1 +#define CONFIG_SOC_TWAI_SUPPORT_MULTI_ADDRESS_LAYOUT 1 +#define CONFIG_SOC_UART_NUM 3 +#define CONFIG_SOC_UART_HP_NUM 3 +#define CONFIG_SOC_UART_SUPPORT_APB_CLK 1 +#define CONFIG_SOC_UART_SUPPORT_REF_TICK 1 +#define CONFIG_SOC_UART_FIFO_LEN 128 +#define CONFIG_SOC_UART_BITRATE_MAX 5000000 +#define CONFIG_SOC_UART_WAKEUP_SUPPORT_ACTIVE_THRESH_MODE 1 +#define CONFIG_SOC_SPIRAM_SUPPORTED 1 +#define CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE 1 +#define CONFIG_SOC_SHA_SUPPORT_PARALLEL_ENG 1 +#define CONFIG_SOC_SHA_ENDIANNESS_BE 1 +#define CONFIG_SOC_SHA_SUPPORT_SHA1 1 +#define CONFIG_SOC_SHA_SUPPORT_SHA256 1 +#define CONFIG_SOC_SHA_SUPPORT_SHA384 1 +#define CONFIG_SOC_SHA_SUPPORT_SHA512 1 +#define CONFIG_SOC_MPI_MEM_BLOCKS_NUM 4 +#define CONFIG_SOC_MPI_OPERATIONS_NUM 1 +#define CONFIG_SOC_RSA_MAX_BIT_LEN 4096 +#define CONFIG_SOC_AES_SUPPORT_AES_128 1 +#define CONFIG_SOC_AES_SUPPORT_AES_192 1 +#define CONFIG_SOC_AES_SUPPORT_AES_256 1 +#define CONFIG_SOC_SECURE_BOOT_V1 1 +#define CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS 1 +#define CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX 32 +#define CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE 21 +#define CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP 1 +#define CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP 1 +#define CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP 1 +#define CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP 1 +#define CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD 1 +#define CONFIG_SOC_PM_SUPPORT_RTC_FAST_MEM_PD 1 +#define CONFIG_SOC_PM_SUPPORT_RTC_SLOW_MEM_PD 1 +#define CONFIG_SOC_PM_SUPPORT_RC_FAST_PD 1 +#define CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD 1 +#define CONFIG_SOC_PM_SUPPORT_MODEM_PD 1 +#define CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED 1 +#define CONFIG_SOC_PM_MODEM_PD_BY_SW 1 +#define CONFIG_SOC_CLK_APLL_SUPPORTED 1 +#define CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED 1 +#define CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256 1 +#define CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION 1 +#define CONFIG_SOC_CLK_XTAL32K_SUPPORTED 1 +#define CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL_D4 1 +#define CONFIG_SOC_SDMMC_USE_IOMUX 1 +#define CONFIG_SOC_SDMMC_NUM_SLOTS 2 +#define CONFIG_SOC_WIFI_WAPI_SUPPORT 1 +#define CONFIG_SOC_WIFI_CSI_SUPPORT 1 +#define CONFIG_SOC_WIFI_MESH_SUPPORT 1 +#define CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW 1 +#define CONFIG_SOC_WIFI_NAN_SUPPORT 1 +#define CONFIG_SOC_BLE_SUPPORTED 1 +#define CONFIG_SOC_BLE_MESH_SUPPORTED 1 +#define CONFIG_SOC_BT_CLASSIC_SUPPORTED 1 +#define CONFIG_SOC_BLUFI_SUPPORTED 1 +#define CONFIG_SOC_BT_H2C_ENC_KEY_CTRL_ENH_VSC_SUPPORTED 1 +#define CONFIG_SOC_ULP_HAS_ADC 1 +#define CONFIG_SOC_PHY_COMBO_MODULE 1 +#define CONFIG_SOC_EMAC_RMII_CLK_OUT_INTERNAL_LOOPBACK 1 +#define CONFIG_IDF_CMAKE 1 +#define CONFIG_IDF_TOOLCHAIN "gcc" +#define CONFIG_IDF_TOOLCHAIN_GCC 1 +#define CONFIG_IDF_TARGET_ARCH_XTENSA 1 +#define CONFIG_IDF_TARGET_ARCH "xtensa" +#define CONFIG_IDF_TARGET "esp32" +#define CONFIG_IDF_INIT_VERSION "5.5.0" +#define CONFIG_IDF_TARGET_ESP32 1 +#define CONFIG_IDF_FIRMWARE_CHIP_ID 0x0000 +#define CONFIG_APP_BUILD_TYPE_APP_2NDBOOT 1 +#define CONFIG_APP_BUILD_GENERATE_BINARIES 1 +#define CONFIG_APP_BUILD_BOOTLOADER 1 +#define CONFIG_APP_BUILD_USE_FLASH_SECTIONS 1 +#define CONFIG_BOOTLOADER_COMPILE_TIME_DATE 1 +#define CONFIG_BOOTLOADER_PROJECT_VER 1 +#define CONFIG_BOOTLOADER_OFFSET_IN_FLASH 0x1000 +#define CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE 1 +#define CONFIG_BOOTLOADER_LOG_VERSION_1 1 +#define CONFIG_BOOTLOADER_LOG_VERSION 1 +#define CONFIG_BOOTLOADER_LOG_LEVEL_INFO 1 +#define CONFIG_BOOTLOADER_LOG_LEVEL 3 +#define CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS 1 +#define CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT 1 +#define CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V 1 +#define CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE 1 +#define CONFIG_BOOTLOADER_WDT_ENABLE 1 +#define CONFIG_BOOTLOADER_WDT_TIME_MS 9000 +#define CONFIG_BOOTLOADER_RESERVE_RTC_SIZE 0x0 +#define CONFIG_SECURE_BOOT_V1_SUPPORTED 1 +#define CONFIG_APP_COMPILE_TIME_DATE 1 +#define CONFIG_APP_RETRIEVE_LEN_ELF_SHA 9 +#define CONFIG_ESP_ROM_HAS_CRC_LE 1 +#define CONFIG_ESP_ROM_HAS_CRC_BE 1 +#define CONFIG_ESP_ROM_HAS_MZ_CRC32 1 +#define CONFIG_ESP_ROM_HAS_JPEG_DECODE 1 +#define CONFIG_ESP_ROM_HAS_UART_BUF_SWITCH 1 +#define CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND 1 +#define CONFIG_ESP_ROM_HAS_NEWLIB 1 +#define CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT 1 +#define CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME 1 +#define CONFIG_ESP_ROM_HAS_SW_FLOAT 1 +#define CONFIG_ESP_ROM_USB_OTG_NUM -1 +#define CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM -1 +#define CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB 1 +#define CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC 1 +#define CONFIG_ESPTOOLPY_FLASHMODE_DIO 1 +#define CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR 1 +#define CONFIG_ESPTOOLPY_FLASHMODE "dio" +#define CONFIG_ESPTOOLPY_FLASHFREQ_40M 1 +#define CONFIG_ESPTOOLPY_FLASHFREQ "40m" +#define CONFIG_ESPTOOLPY_FLASHSIZE_2MB 1 +#define CONFIG_ESPTOOLPY_FLASHSIZE "2MB" +#define CONFIG_ESPTOOLPY_BEFORE_RESET 1 +#define CONFIG_ESPTOOLPY_BEFORE "default_reset" +#define CONFIG_ESPTOOLPY_AFTER_RESET 1 +#define CONFIG_ESPTOOLPY_AFTER "hard_reset" +#define CONFIG_ESPTOOLPY_MONITOR_BAUD 115200 +#define CONFIG_PARTITION_TABLE_SINGLE_APP 1 +#define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" +#define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv" +#define CONFIG_PARTITION_TABLE_OFFSET 0x8000 +#define CONFIG_PARTITION_TABLE_MD5 1 +#define CONFIG_COMPILER_OPTIMIZATION_DEBUG 1 +#define CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE 1 +#define CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE 1 +#define CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB 1 +#define CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL 2 +#define CONFIG_COMPILER_HIDE_PATHS_MACROS 1 +#define CONFIG_COMPILER_STACK_CHECK_MODE_NONE 1 +#define CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS 1 +#define CONFIG_COMPILER_RT_LIB_GCCLIB 1 +#define CONFIG_COMPILER_RT_LIB_NAME "gcc" +#define CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING 1 +#define CONFIG_APPTRACE_DEST_NONE 1 +#define CONFIG_APPTRACE_DEST_UART_NONE 1 +#define CONFIG_APPTRACE_UART_TASK_PRIO 1 +#define CONFIG_APPTRACE_LOCK_ENABLE 1 +#define CONFIG_TWAI_ERRATA_FIX_BUS_OFF_REC 1 +#define CONFIG_TWAI_ERRATA_FIX_TX_INTR_LOST 1 +#define CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID 1 +#define CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT 1 +#define CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM 1 +#define CONFIG_ADC_DISABLE_DAC 1 +#define CONFIG_ADC_CAL_EFUSE_TP_ENABLE 1 +#define CONFIG_ADC_CAL_EFUSE_VREF_ENABLE 1 +#define CONFIG_ADC_CAL_LUT_ENABLE 1 +#define CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4 1 +#define CONFIG_EFUSE_MAX_BLK_LEN 192 +#define CONFIG_ESP_TLS_USING_MBEDTLS 1 +#define CONFIG_ADC_CALI_EFUSE_TP_ENABLE 1 +#define CONFIG_ADC_CALI_EFUSE_VREF_ENABLE 1 +#define CONFIG_ADC_CALI_LUT_ENABLE 1 +#define CONFIG_ADC_DISABLE_DAC_OUTPUT 1 +#define CONFIG_ESP_COEX_ENABLED 1 +#define CONFIG_ESP_ERR_TO_NAME_LOOKUP 1 +#define CONFIG_DAC_DMA_AUTO_16BIT_ALIGN 1 +#define CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM 1 +#define CONFIG_GPTIMER_OBJ_CACHE_SAFE 1 +#define CONFIG_I2C_MASTER_ISR_HANDLER_IN_IRAM 1 +#define CONFIG_RMT_ISR_HANDLER_IN_IRAM 1 +#define CONFIG_RMT_OBJ_CACHE_SAFE 1 +#define CONFIG_SPI_MASTER_ISR_IN_IRAM 1 +#define CONFIG_SPI_SLAVE_ISR_IN_IRAM 1 +#define CONFIG_ETH_ENABLED 1 +#define CONFIG_ETH_USE_ESP32_EMAC 1 +#define CONFIG_ETH_PHY_INTERFACE_RMII 1 +#define CONFIG_ETH_RMII_CLK_INPUT 1 +#define CONFIG_ETH_RMII_CLK_IN_GPIO 0 +#define CONFIG_ETH_DMA_BUFFER_SIZE 512 +#define CONFIG_ETH_DMA_RX_BUFFER_NUM 10 +#define CONFIG_ETH_DMA_TX_BUFFER_NUM 10 +#define CONFIG_ETH_USE_SPI_ETHERNET 1 +#define CONFIG_ESP_EVENT_POST_FROM_ISR 1 +#define CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR 1 +#define CONFIG_ESP_GDBSTUB_ENABLED 1 +#define CONFIG_ESP_GDBSTUB_SUPPORT_TASKS 1 +#define CONFIG_ESP_GDBSTUB_MAX_TASKS 32 +#define CONFIG_ESPHID_TASK_SIZE_BT 2048 +#define CONFIG_ESPHID_TASK_SIZE_BLE 4096 +#define CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS 1 +#define CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT 2000 +#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 1024 +#define CONFIG_HTTPD_MAX_URI_LEN 512 +#define CONFIG_HTTPD_ERR_RESP_NO_DELAY 1 +#define CONFIG_HTTPD_PURGE_BUF_LEN 32 +#define CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT 2000 +#define CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT 2000 +#define CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT 2000 +#define CONFIG_ESP32_REV_MIN_0 1 +#define CONFIG_ESP32_REV_MIN 0 +#define CONFIG_ESP32_REV_MIN_FULL 0 +#define CONFIG_ESP_REV_MIN_FULL 0 +#define CONFIG_ESP32_REV_MAX_FULL 399 +#define CONFIG_ESP_REV_MAX_FULL 399 +#define CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL 0 +#define CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL 99 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_BT 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH 1 +#define CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR 1 +#define CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES 4 +#define CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR 1 +#define CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES 4 +#define CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND 1 +#define CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND 1 +#define CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY 2000 +#define CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS 1 +#define CONFIG_RTC_CLK_SRC_INT_RC 1 +#define CONFIG_RTC_CLK_CAL_CYCLES 1024 +#define CONFIG_PERIPH_CTRL_FUNC_IN_IRAM 1 +#define CONFIG_XTAL_FREQ_40 1 +#define CONFIG_XTAL_FREQ 40 +#define CONFIG_ESP_BROWNOUT_DET 1 +#define CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0 1 +#define CONFIG_ESP_BROWNOUT_DET_LVL 0 +#define CONFIG_ESP_BROWNOUT_USE_INTR 1 +#define CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM 1 +#define CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL 120 +#define CONFIG_ESP_NETIF_TCPIP_LWIP 1 +#define CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API 1 +#define CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC 1 +#define CONFIG_ESP_PHY_ENABLED 1 +#define CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE 1 +#define CONFIG_ESP_PHY_MAX_WIFI_TX_POWER 20 +#define CONFIG_ESP_PHY_MAX_TX_POWER 20 +#define CONFIG_ESP_PHY_RF_CAL_PARTIAL 1 +#define CONFIG_ESP_PHY_CALIBRATION_MODE 0 +#define CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 1 +#define CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ 160 +#define CONFIG_ESP32_TRACEMEM_RESERVE_DRAM 0x0 +#define CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT 1 +#define CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS 0 +#define CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE 32 +#define CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE 2304 +#define CONFIG_ESP_MAIN_TASK_STACK_SIZE 3584 +#define CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0 1 +#define CONFIG_ESP_MAIN_TASK_AFFINITY 0x0 +#define CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE 2048 +#define CONFIG_ESP_CONSOLE_UART_DEFAULT 1 +#define CONFIG_ESP_CONSOLE_UART 1 +#define CONFIG_ESP_CONSOLE_UART_NUM 0 +#define CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM 0 +#define CONFIG_ESP_CONSOLE_UART_BAUDRATE 115200 +#define CONFIG_ESP_INT_WDT 1 +#define CONFIG_ESP_INT_WDT_TIMEOUT_MS 300 +#define CONFIG_ESP_INT_WDT_CHECK_CPU1 1 +#define CONFIG_ESP_TASK_WDT_EN 1 +#define CONFIG_ESP_TASK_WDT_INIT 1 +#define CONFIG_ESP_TASK_WDT_TIMEOUT_S 5 +#define CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 1 +#define CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1 1 +#define CONFIG_ESP_DEBUG_OCDAWARE 1 +#define CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4 1 +#define CONFIG_ESP_IPC_TASK_STACK_SIZE 1024 +#define CONFIG_ESP_IPC_USES_CALLERS_PRIORITY 1 +#define CONFIG_ESP_IPC_ISR_ENABLE 1 +#define CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER 1 +#define CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER 1 +#define CONFIG_ESP_TIMER_TASK_STACK_SIZE 3584 +#define CONFIG_ESP_TIMER_INTERRUPT_LEVEL 1 +#define CONFIG_ESP_TIMER_TASK_AFFINITY 0x0 +#define CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0 1 +#define CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0 1 +#define CONFIG_ESP_TIMER_IMPL_TG0_LAC 1 +#define CONFIG_ESP_WIFI_ENABLED 1 +#define CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM 10 +#define CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM 32 +#define CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER 1 +#define CONFIG_ESP_WIFI_TX_BUFFER_TYPE 1 +#define CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM 32 +#define CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER 1 +#define CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF 0 +#define CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF 5 +#define CONFIG_ESP_WIFI_AMPDU_TX_ENABLED 1 +#define CONFIG_ESP_WIFI_TX_BA_WIN 6 +#define CONFIG_ESP_WIFI_AMPDU_RX_ENABLED 1 +#define CONFIG_ESP_WIFI_RX_BA_WIN 6 +#define CONFIG_ESP_WIFI_NVS_ENABLED 1 +#define CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0 1 +#define CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN 752 +#define CONFIG_ESP_WIFI_MGMT_SBUF_NUM 32 +#define CONFIG_ESP_WIFI_IRAM_OPT 1 +#define CONFIG_ESP_WIFI_RX_IRAM_OPT 1 +#define CONFIG_ESP_WIFI_ENABLE_WPA3_SAE 1 +#define CONFIG_ESP_WIFI_ENABLE_SAE_PK 1 +#define CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT 1 +#define CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA 1 +#define CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME 50 +#define CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME 10 +#define CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME 15 +#define CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE 1 +#define CONFIG_ESP_WIFI_GMAC_SUPPORT 1 +#define CONFIG_ESP_WIFI_SOFTAP_SUPPORT 1 +#define CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM 7 +#define CONFIG_ESP_WIFI_MBEDTLS_CRYPTO 1 +#define CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT 1 +#define CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT 1 +#define CONFIG_ESP_COREDUMP_ENABLE_TO_NONE 1 +#define CONFIG_FATFS_VOLUME_COUNT 2 +#define CONFIG_FATFS_LFN_NONE 1 +#define CONFIG_FATFS_SECTOR_4096 1 +#define CONFIG_FATFS_CODEPAGE_437 1 +#define CONFIG_FATFS_CODEPAGE 437 +#define CONFIG_FATFS_FS_LOCK 0 +#define CONFIG_FATFS_TIMEOUT_MS 10000 +#define CONFIG_FATFS_PER_FILE_CACHE 1 +#define CONFIG_FATFS_USE_STRFUNC_NONE 1 +#define CONFIG_FATFS_VFS_FSTAT_BLKSIZE 0 +#define CONFIG_FATFS_LINK_LOCK 1 +#define CONFIG_FREERTOS_HZ 100 +#define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1 +#define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1 +#define CONFIG_FREERTOS_IDLE_TASK_STACKSIZE 1536 +#define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 +#define CONFIG_FREERTOS_USE_TIMERS 1 +#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME "Tmr Svc" +#define CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY 1 +#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY 0x7FFFFFFF +#define CONFIG_FREERTOS_TIMER_TASK_PRIORITY 1 +#define CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH 2048 +#define CONFIG_FREERTOS_TIMER_QUEUE_LENGTH 10 +#define CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE 0 +#define CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES 1 +#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1 +#define CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS 1 +#define CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER 1 +#define CONFIG_FREERTOS_ISR_STACKSIZE 1536 +#define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1 +#define CONFIG_FREERTOS_TICK_SUPPORT_CORETIMER 1 +#define CONFIG_FREERTOS_CORETIMER_0 1 +#define CONFIG_FREERTOS_SYSTICK_USES_CCOUNT 1 +#define CONFIG_FREERTOS_PORT 1 +#define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF +#define CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION 1 +#define CONFIG_FREERTOS_DEBUG_OCDAWARE 1 +#define CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT 1 +#define CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH 1 +#define CONFIG_FREERTOS_NUMBER_OF_CORES 2 +#define CONFIG_HAL_ASSERTION_EQUALS_SYSTEM 1 +#define CONFIG_HAL_DEFAULT_ASSERTION_LEVEL 2 +#define CONFIG_HEAP_POISONING_DISABLED 1 +#define CONFIG_HEAP_TRACING_OFF 1 +#define CONFIG_LOG_VERSION_1 1 +#define CONFIG_LOG_VERSION 1 +#define CONFIG_LOG_DEFAULT_LEVEL_INFO 1 +#define CONFIG_LOG_DEFAULT_LEVEL 3 +#define CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT 1 +#define CONFIG_LOG_MAXIMUM_LEVEL 3 +#define CONFIG_LOG_DYNAMIC_LEVEL_CONTROL 1 +#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST 1 +#define CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP 1 +#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE 31 +#define CONFIG_LOG_TIMESTAMP_SOURCE_RTOS 1 +#define CONFIG_LWIP_ENABLE 1 +#define CONFIG_LWIP_LOCAL_HOSTNAME "espressif" +#define CONFIG_LWIP_TCPIP_TASK_PRIO 18 +#define CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES 1 +#define CONFIG_LWIP_TIMERS_ONDEMAND 1 +#define CONFIG_LWIP_ND6 1 +#define CONFIG_LWIP_MAX_SOCKETS 10 +#define CONFIG_LWIP_SO_REUSE 1 +#define CONFIG_LWIP_SO_REUSE_RXTOALL 1 +#define CONFIG_LWIP_IP_DEFAULT_TTL 64 +#define CONFIG_LWIP_IP4_FRAG 1 +#define CONFIG_LWIP_IP6_FRAG 1 +#define CONFIG_LWIP_IP_REASS_MAX_PBUFS 10 +#define CONFIG_LWIP_ESP_GRATUITOUS_ARP 1 +#define CONFIG_LWIP_GARP_TMR_INTERVAL 60 +#define CONFIG_LWIP_ESP_MLDV6_REPORT 1 +#define CONFIG_LWIP_MLDV6_TMR_INTERVAL 40 +#define CONFIG_LWIP_TCPIP_RECVMBOX_SIZE 32 +#define CONFIG_LWIP_DHCP_DOES_ARP_CHECK 1 +#define CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID 1 +#define CONFIG_LWIP_DHCP_OPTIONS_LEN 68 +#define CONFIG_LWIP_NUM_NETIF_CLIENT_DATA 0 +#define CONFIG_LWIP_DHCP_COARSE_TIMER_SECS 1 +#define CONFIG_LWIP_DHCPS 1 +#define CONFIG_LWIP_DHCPS_LEASE_UNIT 60 +#define CONFIG_LWIP_DHCPS_MAX_STATION_NUM 8 +#define CONFIG_LWIP_DHCPS_STATIC_ENTRIES 1 +#define CONFIG_LWIP_DHCPS_ADD_DNS 1 +#define CONFIG_LWIP_IPV4 1 +#define CONFIG_LWIP_IPV6 1 +#define CONFIG_LWIP_IPV6_NUM_ADDRESSES 3 +#define CONFIG_LWIP_NETIF_LOOPBACK 1 +#define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8 +#define CONFIG_LWIP_MAX_ACTIVE_TCP 16 +#define CONFIG_LWIP_MAX_LISTENING_TCP 16 +#define CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION 1 +#define CONFIG_LWIP_TCP_MAXRTX 12 +#define CONFIG_LWIP_TCP_SYNMAXRTX 12 +#define CONFIG_LWIP_TCP_MSS 1440 +#define CONFIG_LWIP_TCP_TMR_INTERVAL 250 +#define CONFIG_LWIP_TCP_MSL 60000 +#define CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT 20000 +#define CONFIG_LWIP_TCP_SND_BUF_DEFAULT 5760 +#define CONFIG_LWIP_TCP_WND_DEFAULT 5760 +#define CONFIG_LWIP_TCP_RECVMBOX_SIZE 6 +#define CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE 6 +#define CONFIG_LWIP_TCP_QUEUE_OOSEQ 1 +#define CONFIG_LWIP_TCP_OOSEQ_TIMEOUT 6 +#define CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS 4 +#define CONFIG_LWIP_TCP_OVERSIZE_MSS 1 +#define CONFIG_LWIP_TCP_RTO_TIME 1500 +#define CONFIG_LWIP_MAX_UDP_PCBS 16 +#define CONFIG_LWIP_UDP_RECVMBOX_SIZE 6 +#define CONFIG_LWIP_CHECKSUM_CHECK_ICMP 1 +#define CONFIG_LWIP_TCPIP_TASK_STACK_SIZE 3072 +#define CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY 1 +#define CONFIG_LWIP_TCPIP_TASK_AFFINITY 0x7FFFFFFF +#define CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE 3 +#define CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS 5 +#define CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES 5 +#define CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS 3 +#define CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS 10 +#define CONFIG_LWIP_ICMP 1 +#define CONFIG_LWIP_MAX_RAW_PCBS 16 +#define CONFIG_LWIP_SNTP_MAX_SERVERS 1 +#define CONFIG_LWIP_SNTP_UPDATE_DELAY 3600000 +#define CONFIG_LWIP_SNTP_STARTUP_DELAY 1 +#define CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY 5000 +#define CONFIG_LWIP_DNS_MAX_HOST_IP 1 +#define CONFIG_LWIP_DNS_MAX_SERVERS 3 +#define CONFIG_LWIP_BRIDGEIF_MAX_PORTS 7 +#define CONFIG_LWIP_ESP_LWIP_ASSERT 1 +#define CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT 1 +#define CONFIG_LWIP_HOOK_IP6_ROUTE_NONE 1 +#define CONFIG_LWIP_HOOK_ND6_GET_GW_NONE 1 +#define CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE 1 +#define CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE 1 +#define CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE 1 +#define CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE 1 +#define CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT 1 +#define CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC 1 +#define CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN 1 +#define CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN 16384 +#define CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN 4096 +#define CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 1 +#define CONFIG_MBEDTLS_PKCS7_C 1 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE 1 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL 1 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS 200 +#define CONFIG_MBEDTLS_CMAC_C 1 +#define CONFIG_MBEDTLS_HARDWARE_AES 1 +#define CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER 1 +#define CONFIG_MBEDTLS_HARDWARE_MPI 1 +#define CONFIG_MBEDTLS_HARDWARE_SHA 1 +#define CONFIG_MBEDTLS_ROM_MD5 1 +#define CONFIG_MBEDTLS_HAVE_TIME 1 +#define CONFIG_MBEDTLS_ECDSA_DETERMINISTIC 1 +#define CONFIG_MBEDTLS_SHA512_C 1 +#define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1 +#define CONFIG_MBEDTLS_TLS_SERVER 1 +#define CONFIG_MBEDTLS_TLS_CLIENT 1 +#define CONFIG_MBEDTLS_TLS_ENABLED 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA 1 +#define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1 +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1 +#define CONFIG_MBEDTLS_SSL_ALPN 1 +#define CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS 1 +#define CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS 1 +#define CONFIG_MBEDTLS_AES_C 1 +#define CONFIG_MBEDTLS_CCM_C 1 +#define CONFIG_MBEDTLS_GCM_C 1 +#define CONFIG_MBEDTLS_PEM_PARSE_C 1 +#define CONFIG_MBEDTLS_PEM_WRITE_C 1 +#define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1 +#define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1 +#define CONFIG_MBEDTLS_ECP_C 1 +#define CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED 1 +#define CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED 1 +#define CONFIG_MBEDTLS_ECDH_C 1 +#define CONFIG_MBEDTLS_ECDSA_C 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1 +#define CONFIG_MBEDTLS_ERROR_STRINGS 1 +#define CONFIG_MBEDTLS_FS_IO 1 +#define CONFIG_MQTT_PROTOCOL_311 1 +#define CONFIG_MQTT_TRANSPORT_SSL 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE 1 +#define CONFIG_LIBC_NEWLIB 1 +#define CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF 1 +#define CONFIG_LIBC_STDIN_LINE_ENDING_CR 1 +#define CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT 1 +#define CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0 1 +#define CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1 1 +#define CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2 1 +#define CONFIG_PTHREAD_TASK_PRIO_DEFAULT 5 +#define CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT 3072 +#define CONFIG_PTHREAD_STACK_MIN 768 +#define CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY 1 +#define CONFIG_PTHREAD_TASK_CORE_DEFAULT -1 +#define CONFIG_PTHREAD_TASK_NAME_DEFAULT "pthread" +#define CONFIG_MMU_PAGE_SIZE_64KB 1 +#define CONFIG_MMU_PAGE_MODE "64KB" +#define CONFIG_MMU_PAGE_SIZE 0x10000 +#define CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC 1 +#define CONFIG_SPI_FLASH_BROWNOUT_RESET 1 +#define CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US 50 +#define CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM 1 +#define CONFIG_SPI_FLASH_ROM_DRIVER_PATCH 1 +#define CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS 1 +#define CONFIG_SPI_FLASH_YIELD_DURING_ERASE 1 +#define CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS 20 +#define CONFIG_SPI_FLASH_ERASE_YIELD_TICKS 1 +#define CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE 8192 +#define CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED 1 +#define CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED 1 +#define CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED 1 +#define CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED 1 +#define CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED 1 +#define CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_GD_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP 1 +#define CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE 1 +#define CONFIG_SPIFFS_MAX_PARTITIONS 3 +#define CONFIG_SPIFFS_CACHE 1 +#define CONFIG_SPIFFS_CACHE_WR 1 +#define CONFIG_SPIFFS_PAGE_CHECK 1 +#define CONFIG_SPIFFS_GC_MAX_RUNS 10 +#define CONFIG_SPIFFS_PAGE_SIZE 256 +#define CONFIG_SPIFFS_OBJ_NAME_LEN 32 +#define CONFIG_SPIFFS_USE_MAGIC 1 +#define CONFIG_SPIFFS_USE_MAGIC_LENGTH 1 +#define CONFIG_SPIFFS_META_LENGTH 4 +#define CONFIG_SPIFFS_USE_MTIME 1 +#define CONFIG_WS_TRANSPORT 1 +#define CONFIG_WS_BUFFER_SIZE 1024 +#define CONFIG_UNITY_ENABLE_FLOAT 1 +#define CONFIG_UNITY_ENABLE_DOUBLE 1 +#define CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER 1 +#define CONFIG_VFS_SUPPORT_IO 1 +#define CONFIG_VFS_SUPPORT_DIR 1 +#define CONFIG_VFS_SUPPORT_SELECT 1 +#define CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT 1 +#define CONFIG_VFS_SUPPORT_TERMIOS 1 +#define CONFIG_VFS_MAX_COUNT 8 +#define CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS 1 +#define CONFIG_VFS_INITIALIZE_DEV_NULL 1 +#define CONFIG_WL_SECTOR_SIZE_4096 1 +#define CONFIG_WL_SECTOR_SIZE 4096 +#define CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES 16 +#define CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT 30 +#define CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN 1 +#define CONFIG_MDNS_MAX_INTERFACES 3 +#define CONFIG_MDNS_MAX_SERVICES 10 +#define CONFIG_MDNS_TASK_PRIORITY 1 +#define CONFIG_MDNS_ACTION_QUEUE_LEN 16 +#define CONFIG_MDNS_TASK_STACK_SIZE 4096 +#define CONFIG_MDNS_TASK_AFFINITY_CPU0 1 +#define CONFIG_MDNS_TASK_AFFINITY 0x0 +#define CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL 1 +#define CONFIG_MDNS_MEMORY_ALLOC_INTERNAL 1 +#define CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS 2000 +#define CONFIG_MDNS_TIMER_PERIOD_MS 100 +#define CONFIG_MDNS_ENABLE_CONSOLE_CLI 1 +#define CONFIG_MDNS_ENABLE_BROWSE 1 +#define CONFIG_MDNS_MULTIPLE_INSTANCE 1 + +/* List of deprecated options */ +#define CONFIG_ADC2_DISABLE_DAC CONFIG_ADC_DISABLE_DAC +#define CONFIG_BROWNOUT_DET CONFIG_ESP_BROWNOUT_DET +#define CONFIG_BROWNOUT_DET_LVL CONFIG_ESP_BROWNOUT_DET_LVL +#define CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0 +#define CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_COMPILER_OPTIMIZATION_DEBUG +#define CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG +#define CONFIG_CONSOLE_UART CONFIG_ESP_CONSOLE_UART +#define CONFIG_CONSOLE_UART_BAUDRATE CONFIG_ESP_CONSOLE_UART_BAUDRATE +#define CONFIG_CONSOLE_UART_DEFAULT CONFIG_ESP_CONSOLE_UART_DEFAULT +#define CONFIG_CONSOLE_UART_NUM CONFIG_ESP_CONSOLE_UART_NUM +#define CONFIG_ESP32_APPTRACE_DEST_NONE CONFIG_APPTRACE_DEST_NONE +#define CONFIG_ESP32_APPTRACE_LOCK_ENABLE CONFIG_APPTRACE_LOCK_ENABLE +#define CONFIG_ESP32_BROWNOUT_DET CONFIG_ESP_BROWNOUT_DET +#define CONFIG_ESP32_BROWNOUT_DET_LVL CONFIG_ESP_BROWNOUT_DET_LVL +#define CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_0 CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0 +#define CONFIG_ESP32_DEBUG_OCDAWARE CONFIG_ESP_DEBUG_OCDAWARE +#define CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY +#define CONFIG_ESP32_DEFAULT_CPU_FREQ_160 CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 +#define CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ +#define CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY +#define CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE CONFIG_ESP_COREDUMP_ENABLE_TO_NONE +#define CONFIG_ESP32_PANIC_PRINT_REBOOT CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT +#define CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE +#define CONFIG_ESP32_PHY_MAX_TX_POWER CONFIG_ESP_PHY_MAX_TX_POWER +#define CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER CONFIG_ESP_PHY_MAX_WIFI_TX_POWER +#define CONFIG_ESP32_PTHREAD_STACK_MIN CONFIG_PTHREAD_STACK_MIN +#define CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT CONFIG_PTHREAD_TASK_CORE_DEFAULT +#define CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT CONFIG_PTHREAD_TASK_NAME_DEFAULT +#define CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT CONFIG_PTHREAD_TASK_PRIO_DEFAULT +#define CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT +#define CONFIG_ESP32_RTC_CLK_CAL_CYCLES CONFIG_RTC_CLK_CAL_CYCLES +#define CONFIG_ESP32_RTC_CLK_SRC_INT_RC CONFIG_RTC_CLK_SRC_INT_RC +#define CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC CONFIG_RTC_CLK_SRC_INT_RC +#define CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT +#define CONFIG_ESP32_TIME_SYSCALL_USE_RTC_HRT CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT +#define CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED CONFIG_ESP_WIFI_AMPDU_RX_ENABLED +#define CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED CONFIG_ESP_WIFI_AMPDU_TX_ENABLED +#define CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM +#define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER +#define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM +#define CONFIG_ESP32_WIFI_ENABLED CONFIG_ESP_WIFI_ENABLED +#define CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA +#define CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE CONFIG_ESP_WIFI_ENABLE_WPA3_SAE +#define CONFIG_ESP32_WIFI_IRAM_OPT CONFIG_ESP_WIFI_IRAM_OPT +#define CONFIG_ESP32_WIFI_MGMT_SBUF_NUM CONFIG_ESP_WIFI_MGMT_SBUF_NUM +#define CONFIG_ESP32_WIFI_NVS_ENABLED CONFIG_ESP_WIFI_NVS_ENABLED +#define CONFIG_ESP32_WIFI_RX_BA_WIN CONFIG_ESP_WIFI_RX_BA_WIN +#define CONFIG_ESP32_WIFI_RX_IRAM_OPT CONFIG_ESP_WIFI_RX_IRAM_OPT +#define CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN +#define CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM +#define CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0 +#define CONFIG_ESP32_WIFI_TX_BA_WIN CONFIG_ESP_WIFI_TX_BA_WIN +#define CONFIG_ESP32_WIFI_TX_BUFFER_TYPE CONFIG_ESP_WIFI_TX_BUFFER_TYPE +#define CONFIG_ESP32_XTAL_FREQ CONFIG_XTAL_FREQ +#define CONFIG_ESP32_XTAL_FREQ_40 CONFIG_XTAL_FREQ_40 +#define CONFIG_ESP_GRATUITOUS_ARP CONFIG_LWIP_ESP_GRATUITOUS_ARP +#define CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY +#define CONFIG_ESP_SYSTEM_BROWNOUT_INTR CONFIG_ESP_BROWNOUT_USE_INTR +#define CONFIG_ESP_TASK_WDT CONFIG_ESP_TASK_WDT_INIT +#define CONFIG_FLASHMODE_DIO CONFIG_ESPTOOLPY_FLASHMODE_DIO +#define CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR +#define CONFIG_GARP_TMR_INTERVAL CONFIG_LWIP_GARP_TMR_INTERVAL +#define CONFIG_GDBSTUB_MAX_TASKS CONFIG_ESP_GDBSTUB_MAX_TASKS +#define CONFIG_GDBSTUB_SUPPORT_TASKS CONFIG_ESP_GDBSTUB_SUPPORT_TASKS +#define CONFIG_INT_WDT CONFIG_ESP_INT_WDT +#define CONFIG_INT_WDT_CHECK_CPU1 CONFIG_ESP_INT_WDT_CHECK_CPU1 +#define CONFIG_INT_WDT_TIMEOUT_MS CONFIG_ESP_INT_WDT_TIMEOUT_MS +#define CONFIG_IPC_TASK_STACK_SIZE CONFIG_ESP_IPC_TASK_STACK_SIZE +#define CONFIG_LOG_BOOTLOADER_LEVEL CONFIG_BOOTLOADER_LOG_LEVEL +#define CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_BOOTLOADER_LOG_LEVEL_INFO +#define CONFIG_MAIN_TASK_STACK_SIZE CONFIG_ESP_MAIN_TASK_STACK_SIZE +#define CONFIG_MONITOR_BAUD CONFIG_ESPTOOLPY_MONITOR_BAUD +#define CONFIG_NEWLIB_STDIN_LINE_ENDING_CR CONFIG_LIBC_STDIN_LINE_ENDING_CR +#define CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF +#define CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT +#define CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES +#define CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE +#define CONFIG_OPTIMIZATION_ASSERTION_LEVEL CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL +#define CONFIG_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG +#define CONFIG_POST_EVENTS_FROM_IRAM_ISR CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR +#define CONFIG_POST_EVENTS_FROM_ISR CONFIG_ESP_EVENT_POST_FROM_ISR +#define CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS +#define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS +#define CONFIG_STACK_CHECK_NONE CONFIG_COMPILER_STACK_CHECK_MODE_NONE +#define CONFIG_SUPPORT_TERMIOS CONFIG_VFS_SUPPORT_TERMIOS +#define CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT +#define CONFIG_SYSTEM_EVENT_QUEUE_SIZE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE +#define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE +#define CONFIG_TASK_WDT CONFIG_ESP_TASK_WDT_INIT +#define CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 +#define CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1 +#define CONFIG_TASK_WDT_TIMEOUT_S CONFIG_ESP_TASK_WDT_TIMEOUT_S +#define CONFIG_TCPIP_RECVMBOX_SIZE CONFIG_LWIP_TCPIP_RECVMBOX_SIZE +#define CONFIG_TCPIP_TASK_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY +#define CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY +#define CONFIG_TCPIP_TASK_STACK_SIZE CONFIG_LWIP_TCPIP_TASK_STACK_SIZE +#define CONFIG_TCP_MAXRTX CONFIG_LWIP_TCP_MAXRTX +#define CONFIG_TCP_MSL CONFIG_LWIP_TCP_MSL +#define CONFIG_TCP_MSS CONFIG_LWIP_TCP_MSS +#define CONFIG_TCP_OVERSIZE_MSS CONFIG_LWIP_TCP_OVERSIZE_MSS +#define CONFIG_TCP_QUEUE_OOSEQ CONFIG_LWIP_TCP_QUEUE_OOSEQ +#define CONFIG_TCP_RECVMBOX_SIZE CONFIG_LWIP_TCP_RECVMBOX_SIZE +#define CONFIG_TCP_SND_BUF_DEFAULT CONFIG_LWIP_TCP_SND_BUF_DEFAULT +#define CONFIG_TCP_SYNMAXRTX CONFIG_LWIP_TCP_SYNMAXRTX +#define CONFIG_TCP_WND_DEFAULT CONFIG_LWIP_TCP_WND_DEFAULT +#define CONFIG_TIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH +#define CONFIG_TIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY +#define CONFIG_TIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH +#define CONFIG_TIMER_TASK_STACK_SIZE CONFIG_ESP_TIMER_TASK_STACK_SIZE +#define CONFIG_TRACEMEM_RESERVE_DRAM CONFIG_ESP32_TRACEMEM_RESERVE_DRAM +#define CONFIG_UDP_RECVMBOX_SIZE CONFIG_LWIP_UDP_RECVMBOX_SIZE +#define CONFIG_WPA_MBEDTLS_CRYPTO CONFIG_ESP_WIFI_MBEDTLS_CRYPTO +#define CONFIG_WPA_MBEDTLS_TLS_CLIENT CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/cmock_config.yml b/managed_components/espressif__mdns/tests/host_unit_test/unity/cmock_config.yml new file mode 100644 index 0000000..2487467 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/cmock_config.yml @@ -0,0 +1,17 @@ +--- +:cmock: + :mock_prefix: mock_ + :plugins: + - :callback + - :ignore + - :expect_any_args + - :array + - :return_thru_ptr + :strippables: + - '(?:extern|static)\s+' + :treat_as: + uint8_t: HEX8 + uint16_t: HEX16 + uint32_t: UINT32 + int8_t: INT8 + bool: UINT8 diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.c new file mode 100644 index 0000000..eb25a22 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.c @@ -0,0 +1,160 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include +#include +#include +#include "esp_err.h" +#include "unity.h" +#include "create_test_packet.h" + +// Encode a domain name in DNS format (length byte + characters) +size_t encode_dns_name(uint8_t* buffer, const char* name) +{ + size_t pos = 0; + const char* segment_start = name; + + // Process each segment (separated by dots) + for (const char* p = name; ; p++) { + if (*p == '.' || *p == 0) { + // Calculate segment length + size_t segment_len = p - segment_start; + + // Write length byte + buffer[pos++] = segment_len; + + // Write segment characters + for (size_t i = 0; i < segment_len; i++) { + buffer[pos++] = segment_start[i]; + } + + // If at end of string, exit loop + if (*p == 0) { + break; + } + + // Move to next segment + segment_start = p + 1; + } + } + + // Add null terminator + buffer[pos++] = 0; + + return pos; +} + +// Create an mDNS test packet from arrays of queries and answers +uint8_t* create_mdns_test_packet( + mdns_test_query_t queries[], size_t query_count, + mdns_test_answer_t answers[], size_t answer_count, + mdns_test_answer_t additional[], size_t additional_count, + size_t* packet_len) +{ + // Allocate buffer for packet (max reasonable size for test) + uint8_t* packet = malloc(1460); + size_t pos = 0; + + // DNS Header (12 bytes) + // Transaction ID + packet[pos++] = 0x00; + packet[pos++] = 0x00; + + // Flags (QR=1 for response if there are answers, AA=1) + uint16_t flags = 0x0000; + if (answer_count > 0) { + flags |= 0x8400; // QR=1, AA=1 + } + packet[pos++] = (flags >> 8) & 0xFF; + packet[pos++] = flags & 0xFF; + + // Counts + packet[pos++] = 0x00; + packet[pos++] = query_count & 0xFF; // QDCOUNT + packet[pos++] = 0x00; + packet[pos++] = answer_count & 0xFF; // ANCOUNT + packet[pos++] = 0x00; + packet[pos++] = 0x00; // NSCOUNT + packet[pos++] = 0x00; + packet[pos++] = additional_count & 0xFF; // ARCOUNT + + // Add queries + for (size_t i = 0; i < query_count; i++) { + // Encode name + pos += encode_dns_name(packet + pos, queries[i].name); + + // Type + packet[pos++] = (queries[i].type >> 8) & 0xFF; + packet[pos++] = queries[i].type & 0xFF; + + // Class + packet[pos++] = (queries[i].class >> 8) & 0xFF; + packet[pos++] = queries[i].class & 0xFF; + } + + // Add answers + for (size_t i = 0; i < answer_count; i++) { + // Encode name + pos += encode_dns_name(packet + pos, answers[i].name); + + // Type + packet[pos++] = (answers[i].type >> 8) & 0xFF; + packet[pos++] = answers[i].type & 0xFF; + + // Class + packet[pos++] = (answers[i].class >> 8) & 0xFF; + packet[pos++] = answers[i].class & 0xFF; + + // TTL (4 bytes) + packet[pos++] = (answers[i].ttl >> 24) & 0xFF; + packet[pos++] = (answers[i].ttl >> 16) & 0xFF; + packet[pos++] = (answers[i].ttl >> 8) & 0xFF; + packet[pos++] = answers[i].ttl & 0xFF; + + // Data length + packet[pos++] = (answers[i].data_len >> 8) & 0xFF; + packet[pos++] = answers[i].data_len & 0xFF; + + // Data + if (answers[i].data && answers[i].data_len > 0) { + memcpy(packet + pos, answers[i].data, answers[i].data_len); + pos += answers[i].data_len; + } + } + + // Add additional records + for (size_t i = 0; i < additional_count; i++) { + // Encode name + pos += encode_dns_name(packet + pos, additional[i].name); + + // Type + packet[pos++] = (additional[i].type >> 8) & 0xFF; + packet[pos++] = additional[i].type & 0xFF; + + // Class + packet[pos++] = (additional[i].class >> 8) & 0xFF; + packet[pos++] = additional[i].class & 0xFF; + + // TTL (4 bytes) + packet[pos++] = (additional[i].ttl >> 24) & 0xFF; + packet[pos++] = (additional[i].ttl >> 16) & 0xFF; + packet[pos++] = (additional[i].ttl >> 8) & 0xFF; + packet[pos++] = additional[i].ttl & 0xFF; + + // Data length + packet[pos++] = (additional[i].data_len >> 8) & 0xFF; + packet[pos++] = additional[i].data_len & 0xFF; + + // Data + if (additional[i].data && additional[i].data_len > 0) { + memcpy(packet + pos, additional[i].data, additional[i].data_len); + pos += additional[i].data_len; + } + } + + *packet_len = pos; + return packet; +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.h b/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.h new file mode 100644 index 0000000..25201c9 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/create_test_packet.h @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#pragma once +// Structure for a DNS query +typedef struct { + const char* name; // Name to query (e.g., "test.local") + uint16_t type; // Query type (e.g., MDNS_TYPE_A) + uint16_t class; // Query class (typically 1 for IN) +} mdns_test_query_t; + +// Structure for a DNS answer record +typedef struct { + const char* name; // Name this record refers to + uint16_t type; // Record type + uint16_t class; // Record class + uint32_t ttl; // Time to live + uint16_t data_len; // Length of data + uint8_t* data; // Record data +} mdns_test_answer_t; + + +uint8_t* create_mdns_test_packet( + mdns_test_query_t queries[], size_t query_count, + mdns_test_answer_t answers[], size_t answer_count, + mdns_test_answer_t additional[], size_t additional_count, + size_t* packet_len); + +size_t encode_dns_name(uint8_t* buffer, const char* name); diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/enable_testing.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/enable_testing.cmake new file mode 100644 index 0000000..5812cf4 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/enable_testing.cmake @@ -0,0 +1,11 @@ +enable_testing() +add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME} --test) + +add_custom_target(generate_mocks + DEPENDS ${MOCK_OUTPUTS} +) +add_dependencies(${PROJECT_NAME} generate_mocks) + +# Add sanitizers: Please comment out when debugging +target_link_options(${PROJECT_NAME} PRIVATE -fsanitize=address -fsanitize=undefined) +target_compile_options(${PROJECT_NAME} PRIVATE -fsanitize=address -fsanitize=undefined) diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/test_browse.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/test_browse.c new file mode 100644 index 0000000..6593228 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/test_browse.c @@ -0,0 +1,311 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include + +#include "mdns.h" +#include "mdns_browser.h" +#include "mdns_cache.h" +#include "mdns_mem_caps.h" +#include "mdns_private.h" +#include "mock_mdns_pcb.h" +#include "unity.h" + +#define INSTANCE "cached-service" +#define SERVICE "_cachetest" +#define PROTO "_tcp" +#define HOSTNAME "cache-host" +#define PORT 8080 +#define TTL 120 +#define SUBTYPE "alpha" + +#define TXT_VAL "value" +#define TXT_VAL_LEN 5 + +static uint8_t s_netif_storage; +static const mdns_txt_linked_item_t s_txt = { + .key = "key", + .value = TXT_VAL, + .value_len = TXT_VAL_LEN, + .next = NULL, +}; +static const esp_ip_addr_t s_addr = ESP_IP4ADDR_INIT(192, 168, 1, 100); + +static size_t s_notify_calls; +static uint32_t s_last_ttl; +static size_t s_subtype_calls; +static uint32_t s_subtype_ttl; + +static esp_netif_t *test_netif(void) +{ + return (esp_netif_t *)&s_netif_storage; +} + +static void assert_browse_result(const mdns_result_t *result) +{ + // Results belong to the browser and are only valid during this callback. + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_NULL(result->next); + TEST_ASSERT_EQUAL_PTR(test_netif(), result->esp_netif); + TEST_ASSERT_EQUAL(MDNS_IP_PROTOCOL_V4, result->ip_protocol); + TEST_ASSERT_EQUAL_STRING(INSTANCE, result->instance_name); + TEST_ASSERT_EQUAL_STRING(SERVICE, result->service_type); + TEST_ASSERT_EQUAL_STRING(PROTO, result->proto); + TEST_ASSERT_EQUAL_STRING(HOSTNAME, result->hostname); + TEST_ASSERT_EQUAL_UINT16(PORT, result->port); + TEST_ASSERT_NOT_NULL(result->txt); + TEST_ASSERT_EQUAL_UINT8(TXT_VAL_LEN, result->txt_value_len[0]); + TEST_ASSERT_EQUAL_size_t(1, result->txt_count); + TEST_ASSERT_NOT_NULL(result->addr); + TEST_ASSERT_EQUAL(ESP_IPADDR_TYPE_V4, result->addr->addr.type); + TEST_ASSERT_EQUAL_UINT32(s_addr.u_addr.ip4.addr, result->addr->addr.u_addr.ip4.addr); +} + +static void browse_callback(mdns_result_t *result) +{ + assert_browse_result(result); + TEST_ASSERT_NULL(result->subtype); + s_notify_calls++; + s_last_ttl = result->ttl; +} + +static void subtype_callback(mdns_result_t *result) +{ + assert_browse_result(result); + TEST_ASSERT_EQUAL_STRING(SUBTYPE, result->subtype); + s_subtype_calls++; + s_subtype_ttl = result->ttl; +} + +static void unexpected_callback(mdns_result_t *result) +{ + (void)result; + TEST_FAIL_MESSAGE("A non-matching browse received a notification"); +} + +static mdns_txt_linked_item_t *clone_txt(const mdns_txt_linked_item_t *src_txt) +{ + mdns_txt_linked_item_t *item = mdns_mem_calloc(1, sizeof(mdns_txt_linked_item_t)); + TEST_ASSERT_NOT_NULL(item); + + item->key = mdns_mem_strdup(src_txt->key); + TEST_ASSERT_NOT_NULL(item->key); + + item->value_len = src_txt->value_len; + + if (src_txt->value_len > 0) { + item->value = mdns_mem_malloc(src_txt->value_len); + TEST_ASSERT_NOT_NULL(item->value); + memcpy(item->value, src_txt->value, src_txt->value_len); + } + + return item; +} + +static void cache_service_details(void) +{ + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_srv(test_netif(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, INSTANCE, SERVICE, PROTO, + 0, 0, PORT, TTL)); + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_txt(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, clone_txt(&s_txt), TTL)); + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_addr(test_netif(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &s_addr, TTL)); +} + +static void cache_service(void) +{ + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, TTL)); + cache_service_details(); +} + +void mdns_test_set_up(void) +{ + mdns_priv_browse_free(); + mdns_priv_cache_clear(); + s_notify_calls = 0; + s_last_ttl = 0; + s_subtype_calls = 0; + s_subtype_ttl = 0; +} + +void mdns_test_tear_down(void) +{ + mdns_priv_browse_free(); + mdns_priv_cache_clear(); +} + +void setup_cmock(void) +{ + mdns_priv_probe_all_pcbs_CMockIgnore(); + mdns_priv_pcb_announce_CMockIgnore(); + mdns_priv_pcb_send_bye_service_CMockIgnore(); + mdns_priv_pcb_check_probing_services_CMockIgnore(); + mdns_priv_pcb_is_after_probing_IgnoreAndReturn(true); + mdsn_priv_pcb_is_inited_IgnoreAndReturn(false); +} + +static void test_browse_add_delete_sequence(void) +{ + const char *other_service = "_other"; + + // Register A and reject an immediate duplicate. + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(SERVICE, PROTO)); + + TEST_ASSERT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(SERVICE, PROTO)); + + // Register B without affecting A. + TEST_ASSERT_NOT_NULL(mdns_browse_new(other_service, PROTO, unexpected_callback)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(SERVICE, PROTO)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(other_service, PROTO)); + + // Delete A. B remains registered, and deleting A again must fail. + TEST_ASSERT_EQUAL(ESP_OK, mdns_browse_delete(SERVICE, PROTO)); + TEST_ASSERT_FALSE(mdns_priv_browse_has_service(SERVICE, PROTO)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(other_service, PROTO)); + + TEST_ASSERT_EQUAL(ESP_FAIL, mdns_browse_delete(SERVICE, PROTO)); + + // A can be registered again immediately after deletion. + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(SERVICE, PROTO)); + TEST_ASSERT_TRUE(mdns_priv_browse_has_service(other_service, PROTO)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_browse_delete(SERVICE, PROTO)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_browse_delete(other_service, PROTO)); + TEST_ASSERT_FALSE(mdns_priv_browse_has_service(SERVICE, PROTO)); + TEST_ASSERT_FALSE(mdns_priv_browse_has_service(other_service, PROTO)); +} + +static void test_browse_cached_result_and_delete(void) +{ + // Consume pending updates before registering the browse. + // The initial callback must come from replaying the cache on browse start. + cache_service(); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(0, s_notify_calls); + + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_EQUAL_size_t(1, s_notify_calls); + TEST_ASSERT_EQUAL_UINT32(TTL, s_last_ttl); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_browse_delete(SERVICE, PROTO)); + TEST_ASSERT_FALSE(mdns_priv_browse_has_service(SERVICE, PROTO)); + + // Further cache changes must not call the deleted browse notifier. + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_srv(test_netif(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, INSTANCE, SERVICE, PROTO, + 0, 0, PORT + 1, TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_notify_calls); +} + +static void test_browse_matches_service_and_requires_ptr(void) +{ + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_NOT_NULL(mdns_browse_new("_other", PROTO, unexpected_callback)); + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, "_udp", unexpected_callback)); + + // SRV, TXT and addresses alone do not establish a browse result. + cache_service_details(); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(0, s_notify_calls); + + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_notify_calls); + TEST_ASSERT_EQUAL_UINT32(TTL, s_last_ttl); +} + +static void test_browse_goodbye_and_rediscovery(void) +{ + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + + cache_service(); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_notify_calls); + TEST_ASSERT_EQUAL_UINT32(TTL, s_last_ttl); + + // Cache goodbye should notify the browse. + TEST_ASSERT_NOT_EQUAL(MDNS_CACHE_ERROR, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_notify_calls); + TEST_ASSERT_EQUAL_UINT32(0, s_last_ttl); + + // The same browse remains active and can discover the service again. + cache_service(); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_notify_calls); + TEST_ASSERT_EQUAL_UINT32(TTL, s_last_ttl); +} + +static void test_browse_subtype_update_filtering(void) +{ + TEST_ASSERT_NOT_NULL(mdns_browse_new(SERVICE, PROTO, browse_callback)); + TEST_ASSERT_NOT_NULL(mdns_browse_new_with_subtype(SERVICE, PROTO, SUBTYPE, subtype_callback)); + cache_service(); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_notify_calls); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE, TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_subtype_calls); + + // Changes to shared record (SRV/TXT/ADDR) TTLs reach both browsers. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_srv(test_netif(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, INSTANCE, SERVICE, PROTO, + 0, 0, PORT, TTL + 1)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_notify_calls); + TEST_ASSERT_EQUAL_size_t(2, s_subtype_calls); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_txt(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, clone_txt(&s_txt), TTL + 1)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_notify_calls); + TEST_ASSERT_EQUAL_size_t(3, s_subtype_calls); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &s_addr, TTL + 1)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(4, s_notify_calls); + TEST_ASSERT_EQUAL_size_t(4, s_subtype_calls); + + // Base and subtype PTR updates notify only their matching browser. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, TTL + 1)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(5, s_notify_calls); + TEST_ASSERT_EQUAL_size_t(4, s_subtype_calls); + TEST_ASSERT_EQUAL_UINT32(TTL + 1, s_last_ttl); + TEST_ASSERT_EQUAL_UINT32(TTL, s_subtype_ttl); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE, TTL + 2)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(5, s_notify_calls); + TEST_ASSERT_EQUAL_size_t(5, s_subtype_calls); + TEST_ASSERT_EQUAL_UINT32(TTL + 1, s_last_ttl); + TEST_ASSERT_EQUAL_UINT32(TTL + 2, s_subtype_ttl); +} + +void run_unity_tests(void) +{ + UNITY_BEGIN(); + RUN_TEST(test_browse_add_delete_sequence); + RUN_TEST(test_browse_cached_result_and_delete); + RUN_TEST(test_browse_matches_service_and_requires_ptr); + RUN_TEST(test_browse_goodbye_and_rediscovery); + RUN_TEST(test_browse_subtype_update_filtering); + UNITY_END(); +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/unit_test.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/unit_test.cmake new file mode 100644 index 0000000..b18feb9 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_browse/unit_test.cmake @@ -0,0 +1,6 @@ +# Mock pcb to disable network queries. Use real browser and cache. +set(MOCK_FILES + "mdns_pcb" +) + +list(APPEND SOURCES unity/${UNIT_TESTS}/test_browse.c) diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/test_cache.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/test_cache.c new file mode 100644 index 0000000..0cc3745 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/test_cache.c @@ -0,0 +1,982 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include +#include +#include + +#include "esp_netif_ip_addr.h" +#include "esp_netif_types.h" +#include "mdns.h" +#include "mdns_cache.h" +#include "mdns_mem_caps.h" +#include "mdns_mem_caps_test.h" +#include "mdns_private.h" +#include "mdns_test_clock.h" +#include "mock_mdns_browser.h" +#include "unity.h" +#include "unity_internals.h" + +#define INSTANCE "_instance" +#define SERVICE "_http" +#define PROTO "_tcp" +#define HOSTNAME "device" +#define SUBTYPE_A "alpha" +#define SUBTYPE_B "beta" + +#define PTR_TTL 120 +#define SRV_TTL 130 +#define TXT_TTL 140 +#define ADDR_TTL 150 + +#define SRV_PRIORITY 10 +#define SRV_WEIGHT 20 +#define SRV_PORT 8080 + +typedef struct { + size_t update_calls; + size_t goodbye_calls; + + bool update_result; + bool goodbye_result; + + mdns_cache_record_mask_t records; + mdns_ip_protocol_t ip_protocol; + const esp_netif_t *esp_netif; + + bool ptr_present; + bool srv_present; + bool txt_present; + + uint32_t ptr_ttl; + uint32_t srv_ttl; + uint32_t txt_ttl; + + uint16_t priority; + uint16_t weight; + uint16_t port; + + size_t address_count; + size_t txt_count; + size_t subtype_count; + + // These pointers are references to the pointers in service cache item during tests, + // and should only be used after SUBTYPE/TXT/ADDR cache has been updated and before service cache is cleaned! + // Do not manually free them, they should be maintained by mdns_cache. + const mdns_txt_linked_item_t *txt; + const mdns_cache_addr_t *addr; + const mdns_cache_subtype_t *subtype; + const mdns_cache_entry_t *entry; + const mdns_service_cache_t *service_cache; + + char hostname[MDNS_NAME_BUF_LEN]; + char instance[MDNS_NAME_BUF_LEN]; + char service[MDNS_NAME_BUF_LEN]; + char proto[MDNS_NAME_BUF_LEN]; + char goodbye_subtype[MDNS_NAME_BUF_LEN]; +} cache_observer_t; + +static cache_observer_t s_observer; +// Provide mock `esp_netif_t` pointers +static uint8_t s_netif_storage_a; + +// ----------------- Helper functions ----------------- + +static esp_netif_t *test_netif_a(void) +{ + return (esp_netif_t *)&s_netif_storage_a; +} + +static void reset_observer(void) +{ + memset(&s_observer, 0, sizeof(s_observer)); + s_observer.update_result = true; + s_observer.goodbye_result = true; +} + +static void copy_optional_string(char *dst, size_t dst_size, const char *src) +{ + if (!src) { + dst[0] = '\0'; + return; + } + + strncpy(dst, src, dst_size - 1); + dst[dst_size - 1] = '\0'; +} + +static size_t count_addresses(const mdns_cache_addr_t *addr) +{ + size_t count = 0; + + while (addr) { + count++; + addr = addr->next; + } + + return count; +} + +static size_t count_txt(const mdns_txt_linked_item_t *txt) +{ + size_t count = 0; + + while (txt) { + count++; + txt = txt->next; + } + + return count; +} + +static size_t count_subtype(const mdns_cache_subtype_t *subtype) +{ + size_t count = 0; + + while (subtype) { + count++; + subtype = subtype->next; + } + + return count; +} + +static void capture_cache(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_cache_record_mask_t records) +{ + TEST_ASSERT_NOT_NULL(entry); + TEST_ASSERT_NOT_NULL(service); + s_observer.records = records; + s_observer.ip_protocol = entry->ip_protocol; + s_observer.esp_netif = entry->esp_netif; + + s_observer.ptr_present = service->ptr_present; + s_observer.srv_present = service->srv_present; + s_observer.txt_present = service->txt_present; + + s_observer.ptr_ttl = service->ptr_ttl; + s_observer.srv_ttl = service->srv_ttl; + s_observer.txt_ttl = service->txt_ttl; + + s_observer.priority = service->priority; + s_observer.weight = service->weight; + s_observer.port = service->port; + + s_observer.address_count = count_addresses(entry->addr_list); + s_observer.txt_count = count_txt(service->txt_list); + s_observer.subtype_count = count_subtype(service->subtype_list); + + s_observer.txt = service->txt_list; + s_observer.addr = entry->addr_list; + s_observer.subtype = service->subtype_list; + s_observer.entry = entry; + s_observer.service_cache = service; + + copy_optional_string(s_observer.hostname, sizeof(s_observer.hostname), entry->hostname); + copy_optional_string(s_observer.instance, sizeof(s_observer.instance), service->instance_name); + copy_optional_string(s_observer.service, sizeof(s_observer.service), service->service); + copy_optional_string(s_observer.proto, sizeof(s_observer.proto), service->proto); +} + +static bool browse_update_callback(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + mdns_cache_record_mask_t records, int cmock_num_calls) +{ + (void)cmock_num_calls; + s_observer.update_calls++; + capture_cache(entry, service, records); + return s_observer.update_result; +} + +static bool browse_goodbye_callback(const mdns_cache_entry_t *entry, const mdns_service_cache_t *service, + const char *subtype, int cmock_num_calls) +{ + (void)cmock_num_calls; + s_observer.goodbye_calls++; + capture_cache(entry, service, 0); + copy_optional_string(s_observer.goodbye_subtype, sizeof(s_observer.goodbye_subtype), subtype); + return s_observer.goodbye_result; +} + +static mdns_txt_linked_item_t *clone_txt(const mdns_txt_linked_item_t *src_txt) +{ + mdns_txt_linked_item_t *item = mdns_mem_calloc(1, sizeof(mdns_txt_linked_item_t)); + TEST_ASSERT_NOT_NULL(item); + + item->key = mdns_mem_strdup(src_txt->key); + TEST_ASSERT_NOT_NULL(item->key); + + item->value_len = src_txt->value_len; + + if (src_txt->value_len > 0) { + item->value = mdns_mem_malloc(src_txt->value_len); + TEST_ASSERT_NOT_NULL(item->value); + memcpy(item->value, src_txt->value, src_txt->value_len); + } + + return item; +} + +static bool find_txt_in_txt_list(const mdns_txt_linked_item_t *txt_list, const mdns_txt_linked_item_t *target) +{ + if (!txt_list || !target) { + return false; + } + + for (const mdns_txt_linked_item_t *it = txt_list; it; it = it->next) { + if (strcasecmp(it->key, target->key) == 0) { + if (it->value_len != target->value_len) { + return false; // Do not allow duplicated keys + } + return it->value_len == 0 || memcmp(it->value, target->value, it->value_len) == 0; + } + } + + return false; +} + +static bool assert_subtype_in_list(const mdns_cache_subtype_t *subtype_list, const char *subtype, uint32_t ttl) +{ + if (!subtype_list || !subtype) { + return false; + } + + for (const mdns_cache_subtype_t *it = subtype_list; it; it = it->next) { + if (strcasecmp(it->subtype, subtype) == 0) { + return it->ttl == ttl; + } + } + + return false; +} + +static esp_ip_addr_t make_ipv4(uint32_t address) +{ + esp_ip_addr_t addr = {0}; + + addr.type = ESP_IPADDR_TYPE_V4; + addr.u_addr.ip4.addr = address; + return addr; +} + +static esp_ip_addr_t make_ipv6(const uint32_t address[4]) +{ + esp_ip_addr_t addr = {0}; + + addr.type = ESP_IPADDR_TYPE_V6; + for (int i = 0; i < 4; i++) { + addr.u_addr.ip6.addr[i] = address[i]; + } + return addr; +} + +static void assert_memory(size_t baseline) +{ + TEST_ASSERT_EQUAL_size_t(baseline, mdns_mem_get_allocation_counts()); +} + +static mdns_cache_update_result_t update_test_record(mdns_cache_record_type_t record_type, bool goodbye) +{ + static const mdns_txt_linked_item_t txt = { + .key = "key", + .value = "value", + .value_len = 5, + .next = NULL, + }; + const esp_ip_addr_t addr = make_ipv4(0x0101A8C0); + + switch (record_type) { + case MDNS_CACHE_RECORD_PTR: + return mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, goodbye ? 0 : PTR_TTL); + case MDNS_CACHE_RECORD_SRV: + return mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, goodbye ? 0 : SRV_TTL); + case MDNS_CACHE_RECORD_TXT: + return mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, clone_txt(&txt), goodbye ? 0 : TXT_TTL); + case MDNS_CACHE_RECORD_ADDR: + return mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, + &addr, goodbye ? 0 : ADDR_TTL); + default: + TEST_FAIL_MESSAGE("Invalid record type"); + return MDNS_CACHE_ERROR; + } +} + +static void insert_complete_service(void) +{ + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, update_test_record(MDNS_CACHE_RECORD_PTR, false)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_SRV, false)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_TXT, false)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_ADDR, false)); +} + +static void assert_observed_complete_service(void) +{ + TEST_ASSERT_EQUAL_PTR(test_netif_a(), s_observer.esp_netif); + TEST_ASSERT_EQUAL(MDNS_IP_PROTOCOL_V4, s_observer.ip_protocol); + + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_TRUE(s_observer.srv_present); + TEST_ASSERT_TRUE(s_observer.txt_present); + + TEST_ASSERT_EQUAL_UINT32(PTR_TTL, s_observer.ptr_ttl); + TEST_ASSERT_EQUAL_UINT32(SRV_TTL, s_observer.srv_ttl); + TEST_ASSERT_EQUAL_UINT32(TXT_TTL, s_observer.txt_ttl); + + TEST_ASSERT_EQUAL_UINT16(SRV_PRIORITY, s_observer.priority); + TEST_ASSERT_EQUAL_UINT16(SRV_WEIGHT, s_observer.weight); + TEST_ASSERT_EQUAL_UINT16(SRV_PORT, s_observer.port); + + TEST_ASSERT_EQUAL_size_t(1, s_observer.txt_count); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + + TEST_ASSERT_EQUAL_STRING(HOSTNAME, s_observer.hostname); + TEST_ASSERT_EQUAL_STRING(INSTANCE, s_observer.instance); + TEST_ASSERT_EQUAL_STRING(SERVICE, s_observer.service); + TEST_ASSERT_EQUAL_STRING(PROTO, s_observer.proto); +} + +// Project only while the cache pointers captured by the callback are still valid. +static mdns_result_t *project_observed_service(void) +{ + mdns_result_t *result = NULL; + TEST_ASSERT_EQUAL(ESP_OK, mdns_priv_service_cache_to_result(s_observer.entry, s_observer.service_cache, &result)); + TEST_ASSERT_NOT_NULL(result); + return result; +} + +static void assert_complete_result(const mdns_result_t *result) +{ + TEST_ASSERT_EQUAL_PTR(test_netif_a(), result->esp_netif); + TEST_ASSERT_EQUAL(MDNS_IP_PROTOCOL_V4, result->ip_protocol); + TEST_ASSERT_EQUAL_STRING(INSTANCE, result->instance_name); + TEST_ASSERT_EQUAL_STRING(SERVICE, result->service_type); + TEST_ASSERT_EQUAL_STRING(PROTO, result->proto); + TEST_ASSERT_EQUAL_UINT32(PTR_TTL, result->ttl); + TEST_ASSERT_EQUAL_STRING(HOSTNAME, result->hostname); + TEST_ASSERT_EQUAL_UINT16(SRV_PORT, result->port); + TEST_ASSERT_EQUAL_size_t(1, result->txt_count); + TEST_ASSERT_NOT_NULL(result->txt); + TEST_ASSERT_NOT_NULL(result->txt_value_len); + TEST_ASSERT_EQUAL_STRING("key", result->txt[0].key); + TEST_ASSERT_EQUAL_UINT8(5, result->txt_value_len[0]); + TEST_ASSERT_EQUAL_MEMORY("value", result->txt[0].value, 5); + TEST_ASSERT_NOT_NULL(result->addr); + TEST_ASSERT_EQUAL(ESP_IPADDR_TYPE_V4, result->addr->addr.type); + TEST_ASSERT_EQUAL_UINT32(0x0101A8C0, result->addr->addr.u_addr.ip4.addr); + TEST_ASSERT_NULL(result->addr->next); + TEST_ASSERT_NULL(result->next); +} + +// ----------------- Test functions ----------------- + +void mdns_test_set_up(void) +{ + mdns_priv_cache_clear(); + mdns_test_clock_reset(); + reset_observer(); +} + +void mdns_test_tear_down(void) +{ + mdns_priv_cache_clear(); +} + +void setup_cmock(void) +{ + mdns_priv_browse_update_from_service_cache_Stub(browse_update_callback); + mdns_priv_browse_notify_ptr_goodbye_from_service_cache_Stub(browse_goodbye_callback); + + mdns_priv_browse_notify_from_service_cache_IgnoreAndReturn(true); +} + +static void test_cache_ptr_add_repeat_update_remove(void) +{ + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Add new PTR record + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, PTR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_PTR, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_EQUAL_UINT32(PTR_TTL, s_observer.ptr_ttl); + TEST_ASSERT_EQUAL_STRING(INSTANCE, s_observer.instance); + TEST_ASSERT_EQUAL_STRING(SERVICE, s_observer.service); + TEST_ASSERT_EQUAL_STRING(PROTO, s_observer.proto); + + // Scenario 2: Update the same service cache with identical PTR TTL + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, PTR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + + // Scenario 3: Update the same service cache with different PTR TTL + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.ptr_ttl); + + // Scenario 4: Remove cache with PTR TTL=0 + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.goodbye_calls); + assert_memory(baseline); +} + +static void test_cache_srv_add_repeat_update_remove(void) +{ + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Add new SRV record + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, SRV_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_SRV, s_observer.records); + TEST_ASSERT_TRUE(s_observer.srv_present); + TEST_ASSERT_EQUAL_UINT32(SRV_TTL, s_observer.srv_ttl); + TEST_ASSERT_EQUAL_STRING(HOSTNAME, s_observer.hostname); + TEST_ASSERT_EQUAL_STRING(INSTANCE, s_observer.instance); + TEST_ASSERT_EQUAL_STRING(SERVICE, s_observer.service); + TEST_ASSERT_EQUAL_STRING(PROTO, s_observer.proto); + TEST_ASSERT_EQUAL_UINT16(SRV_PRIORITY, s_observer.priority); + TEST_ASSERT_EQUAL_UINT16(SRV_WEIGHT, s_observer.weight); + TEST_ASSERT_EQUAL_UINT16(SRV_PORT, s_observer.port); + + // Scenario 2: Update the same service cache with identical priority, weight, port, and SRV TTL + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, SRV_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + + // Scenario 3: Update the same service cache with different SRV record + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, 30, 40, 8081, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.srv_ttl); + TEST_ASSERT_EQUAL_UINT16(30, s_observer.priority); + TEST_ASSERT_EQUAL_UINT16(40, s_observer.weight); + TEST_ASSERT_EQUAL_UINT16(8081, s_observer.port); + + // Scenario 4: Remove cache with SRV TTL=0 + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + assert_memory(baseline); +} + +static void test_cache_txt_add_repeat_update_remove(void) +{ + static const uint8_t binary_arr[] = {0, 0, 0, 0, 255}; + // Normal TXT item + static const mdns_txt_linked_item_t txt_1 = { + .key = "key1", + .value = "value", + .value_len = 5, + .next = NULL, + }; + // Simulate TXT item with no value + static const mdns_txt_linked_item_t txt_2 = { + .key = "key2", + .value = NULL, + .value_len = 0, + .next = NULL, + }; + // Simulate TXT item with binary value + static const mdns_txt_linked_item_t txt_3 = { + .key = "key2", + .value = (char *)binary_arr, + .value_len = sizeof(binary_arr), + .next = NULL, + }; + + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Add new TXT record + mdns_txt_linked_item_t *test1_txt1 = clone_txt(&txt_1); + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, test1_txt1, TXT_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_TXT, s_observer.records); + TEST_ASSERT_TRUE(s_observer.txt_present); + TEST_ASSERT_EQUAL_UINT32(TXT_TTL, s_observer.txt_ttl); + TEST_ASSERT_EQUAL_STRING(INSTANCE, s_observer.instance); + TEST_ASSERT_EQUAL_STRING(SERVICE, s_observer.service); + TEST_ASSERT_EQUAL_STRING(PROTO, s_observer.proto); + TEST_ASSERT_EQUAL_size_t(1, s_observer.txt_count); + + // Scenario 2: Update the same service cache with identical TXT item and TTL + mdns_txt_linked_item_t *test2_txt1 = clone_txt(&txt_1); + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, test2_txt1, TXT_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + + // Scenario 3: Update the same service cache with different TXT item and TTL + mdns_txt_linked_item_t *test3_txt1 = clone_txt(&txt_1); + mdns_txt_linked_item_t *test3_txt2 = clone_txt(&txt_2); + test3_txt1->next = test3_txt2; + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, test3_txt1, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.txt_ttl); + TEST_ASSERT_EQUAL_size_t(2, s_observer.txt_count); + + // Scenario 4: Update the same service cache with a TXT item different in value + mdns_txt_linked_item_t *test4_txt1 = clone_txt(&txt_1); + mdns_txt_linked_item_t *test4_txt3 = clone_txt(&txt_3); + test4_txt1->next = test4_txt3; + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, test4_txt1, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(2, s_observer.txt_count); + TEST_ASSERT_TRUE(find_txt_in_txt_list(s_observer.txt, &txt_3)); + + // Scenario 5: Remove cache with TXT TTL=0 + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, NULL, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + assert_memory(baseline); +} + +static void test_cache_addr_add_repeat_update_remove(void) +{ + static const uint32_t ip6_addr[4] = {0x20010db8, 0, 0, 0x00000001}; + static const uint32_t ip4_addr_1 = 0x0101A8C0; + static const uint32_t ip4_addr_2 = 0x0201A8C0; + + const esp_ip_addr_t addr_1 = make_ipv4(ip4_addr_1); + const esp_ip_addr_t addr_2 = make_ipv4(ip4_addr_2); + const esp_ip_addr_t addr_3 = make_ipv6(ip6_addr); + + // Because currently `mdns_priv_cache_process_sync()` only notifies browses, we need to setup an SRV record to establish a service cache. + // So that `browse_update_callback()` stub can update `s_observer`. + (void)mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, SRV_TTL); + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Add new A record + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_1, ADDR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_ADDR | MDNS_CACHE_RECORD_SRV, s_observer.records); + TEST_ASSERT_NOT_NULL(s_observer.addr); + TEST_ASSERT_EQUAL_UINT32(ADDR_TTL, s_observer.addr->ttl); + TEST_ASSERT_EQUAL_UINT32(ip4_addr_1, s_observer.addr->addr.u_addr.ip4.addr); + TEST_ASSERT_EQUAL_STRING(HOSTNAME, s_observer.hostname); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + + // Scenario 2: Update the same service cache with identical A record + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_1, ADDR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + + // Scenario 3: Update the A record with new TTL + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_1, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.addr->ttl); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + + // Scenario 4: Add new A record + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_2, ADDR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(2, s_observer.address_count); + + // Scenario 5: Add new AAAA record + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_3, ADDR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(4, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(3, s_observer.address_count); + + // Scenario 6: Remove all addresses with TTL=0 + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_1, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(5, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(2, s_observer.address_count); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_2, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(6, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V6, HOSTNAME, + &addr_3, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(7, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(0, s_observer.address_count); + assert_memory(baseline); + + // Scenario 7: `mdns_priv_cache_update_existing_addr()` cannot create new entry + size_t baseline_s7 = mdns_mem_get_allocation_counts(); + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_existing_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &addr_1, ADDR_TTL)); + assert_memory(baseline_s7); + + (void)mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, SRV_TTL); + baseline_s7 = mdns_mem_get_allocation_counts(); + + // `mdns_priv_cache_update_existing_addr()` only updates if a consumer is subscribing to a service under the same entry + mdns_priv_browse_has_service_IgnoreAndReturn(true); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_existing_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &addr_1, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(8, s_observer.update_calls); + mdns_priv_browse_has_service_IgnoreAndReturn(false); + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_existing_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &addr_1, 300)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(8, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.addr->ttl); + mdns_priv_browse_has_service_IgnoreAndReturn(true); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_existing_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + HOSTNAME, &addr_1, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(9, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(0, s_observer.address_count); + + assert_memory(baseline_s7); +} + +static void test_cache_record_order_and_result_projection(void) +{ + const mdns_cache_record_type_t orders[][4] = { + { MDNS_CACHE_RECORD_PTR, MDNS_CACHE_RECORD_SRV, MDNS_CACHE_RECORD_TXT, MDNS_CACHE_RECORD_ADDR }, + { MDNS_CACHE_RECORD_PTR, MDNS_CACHE_RECORD_ADDR, MDNS_CACHE_RECORD_TXT, MDNS_CACHE_RECORD_SRV }, + }; + + for (size_t i = 0; i < sizeof(orders) / sizeof(orders[0]); i++) { + mdns_priv_cache_clear(); + reset_observer(); + for (size_t j = 0; j < sizeof(orders[i]) / sizeof(orders[i][0]); j++) { + mdns_cache_update_result_t status = update_test_record(orders[i][j], false); + TEST_ASSERT_TRUE(status == MDNS_CACHE_ADDED || status == MDNS_CACHE_UPDATED); + } + // All record updates are delivered in a single notification + TEST_ASSERT_EQUAL_size_t(0, s_observer.update_calls); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + assert_observed_complete_service(); + + mdns_result_t *result = project_observed_service(); + assert_complete_result(result); + mdns_query_results_free(result); + } +} + +static void test_cache_service_record_goodbyes(void) +{ + insert_complete_service(); + mdns_priv_cache_process_sync(); + assert_observed_complete_service(); + reset_observer(); + + // Remove TXT while preserving SRV and addresses. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_TXT, true)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_TXT, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_TRUE(s_observer.srv_present); + TEST_ASSERT_FALSE(s_observer.txt_present); + + mdns_result_t *result = project_observed_service(); + TEST_ASSERT_NULL(result->txt); + TEST_ASSERT_NULL(result->txt_value_len); + TEST_ASSERT_EQUAL_size_t(0, result->txt_count); + TEST_ASSERT_EQUAL_STRING(HOSTNAME, result->hostname); + TEST_ASSERT_EQUAL_UINT16(SRV_PORT, result->port); + TEST_ASSERT_NOT_NULL(result->addr); + mdns_query_results_free(result); + + // Remove SRV. Cached addresses remain but must not appear in the result. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_SRV, true)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_SRV, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_FALSE(s_observer.srv_present); + TEST_ASSERT_NOT_NULL(s_observer.addr); + + result = project_observed_service(); + TEST_ASSERT_NULL(result->hostname); + TEST_ASSERT_EQUAL_UINT16(0, result->port); + TEST_ASSERT_NULL(result->addr); + mdns_query_results_free(result); + + // Remove the remaining address without removing PTR. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, update_test_record(MDNS_CACHE_RECORD_ADDR, true)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_ADDR, s_observer.records); + TEST_ASSERT_NULL(s_observer.addr); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_EQUAL_UINT32(PTR_TTL, s_observer.ptr_ttl); + TEST_ASSERT_EQUAL_size_t(0, s_observer.goodbye_calls); +} + +static void test_cache_expiry_extend_and_notify(void) +{ + static const mdns_txt_linked_item_t txt = { + .key = "key", + .value = "value", + .value_len = 5, + .next = NULL, + }; + const esp_ip_addr_t addr = make_ipv4(0x0101A8C0); + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Extend PTR TTL and test records expire one by one. + // Initial state: t = 0s + insert_complete_service(); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_A, 160)); + mdns_priv_cache_process_sync(); + assert_observed_complete_service(); + reset_observer(); + + // t = 60s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(60 * MDNS_US_PER_SEC)); + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, PTR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(0, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(0, s_observer.goodbye_calls); + + // PTR, SRV, TXT, ADDR will be expired at t = 180s, 130s, 140s, 150s respectively. + // subtype A will expire at t = 160s. + // t = 120s: Base PTR survives the original expiration time. + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(60 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(0, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(0, s_observer.goodbye_calls); + // t = 129s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(9 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(0, s_observer.update_calls); + // t = 130s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_SRV, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_FALSE(s_observer.srv_present); + TEST_ASSERT_TRUE(s_observer.txt_present); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + // t = 139s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(9 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + // t = 140s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_TXT, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_FALSE(s_observer.txt_present); + TEST_ASSERT_EQUAL_size_t(0, s_observer.txt_count); + TEST_ASSERT_EQUAL_size_t(1, s_observer.address_count); + // t = 149s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(9 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + // t = 150s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_ADDR, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_EQUAL_size_t(0, s_observer.address_count); + // t = 159s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(9 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + // t = 160s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_STRING(SUBTYPE_A, s_observer.goodbye_subtype); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + // t = 179s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(19 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.goodbye_calls); + // t = 180s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_STRING("", s_observer.goodbye_subtype); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + assert_memory(baseline); + + // Scenario 2: Records expire at the same time. + // Initial state: t = 0s + mdns_priv_cache_clear(); + mdns_test_clock_reset(); + reset_observer(); + baseline = mdns_mem_get_allocation_counts(); + + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, update_test_record(MDNS_CACHE_RECORD_PTR, false)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_srv(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, INSTANCE, + SERVICE, PROTO, SRV_PRIORITY, SRV_WEIGHT, SRV_PORT, 60)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_txt(test_netif_a(), MDNS_IP_PROTOCOL_V4, INSTANCE, + SERVICE, PROTO, clone_txt(&txt), 60)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_addr(test_netif_a(), MDNS_IP_PROTOCOL_V4, HOSTNAME, + &addr, 60)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + // t = 59s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(59 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + // t = 60s, SRV, TXT, ADDR will be expired at the same time. + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(1 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(0, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_SRV | MDNS_CACHE_RECORD_TXT | MDNS_CACHE_RECORD_ADDR, s_observer.records); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_FALSE(s_observer.srv_present); + TEST_ASSERT_FALSE(s_observer.txt_present); + TEST_ASSERT_EQUAL_size_t(0, s_observer.address_count); + TEST_ASSERT_EQUAL_size_t(0, s_observer.txt_count); + // t = 120s + TEST_ASSERT_TRUE(mdns_test_clock_advance_us(60 * MDNS_US_PER_SEC)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_size_t(1, s_observer.goodbye_calls); + assert_memory(baseline); +} + +static void test_cache_subtype_add_repeat_update_remove(void) +{ + size_t baseline = mdns_mem_get_allocation_counts(); + + // Scenario 1: Add a subtype without establishing a base PTR. + TEST_ASSERT_EQUAL(MDNS_CACHE_ADDED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_A, PTR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT8(MDNS_CACHE_RECORD_SUBTYPE, s_observer.records); + TEST_ASSERT_FALSE(s_observer.ptr_present); + TEST_ASSERT_NOT_NULL(s_observer.subtype); + TEST_ASSERT_EQUAL_STRING(SUBTYPE_A, s_observer.subtype->subtype); + TEST_ASSERT_EQUAL_UINT32(PTR_TTL, s_observer.subtype->ttl); + TEST_ASSERT_EQUAL_size_t(1, s_observer.subtype_count); + + // Scenario 2: Repeating the subtype does not add a duplicate or notify again. + TEST_ASSERT_EQUAL(MDNS_CACHE_NO_CHANGE, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_A, PTR_TTL)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.update_calls); + + // Scenario 3: Changing the TTL notifies the browser. + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_A, 240)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.update_calls); + TEST_ASSERT_EQUAL_UINT32(240, s_observer.subtype->ttl); + + // Scenario 4: Base PTR/specific subtype update/removal will not notify others + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, PTR_TTL)); + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_B, 180)); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_TRUE(s_observer.ptr_present); + TEST_ASSERT_EQUAL_size_t(2, s_observer.subtype_count); + TEST_ASSERT_EQUAL_UINT32(s_observer.ptr_ttl, PTR_TTL); + TEST_ASSERT_TRUE(assert_subtype_in_list(s_observer.subtype, SUBTYPE_A, 240)); + TEST_ASSERT_TRUE(assert_subtype_in_list(s_observer.subtype, SUBTYPE_B, 180)); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, NULL, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(1, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + TEST_ASSERT_FALSE(s_observer.ptr_present); + TEST_ASSERT_EQUAL_size_t(2, s_observer.subtype_count); + TEST_ASSERT_EQUAL_STRING("", s_observer.goodbye_subtype); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_A, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(2, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + // Goodbye captures the last subtype before removal; no update follows cache deletion. + TEST_ASSERT_EQUAL_size_t(2, s_observer.subtype_count); + TEST_ASSERT_EQUAL_STRING(SUBTYPE_A, s_observer.goodbye_subtype); + TEST_ASSERT_TRUE(assert_subtype_in_list(s_observer.subtype, SUBTYPE_B, 180)); + + TEST_ASSERT_EQUAL(MDNS_CACHE_UPDATED, mdns_priv_cache_update_ptr(test_netif_a(), MDNS_IP_PROTOCOL_V4, + INSTANCE, SERVICE, PROTO, SUBTYPE_B, 0)); + mdns_priv_cache_remove_expired_records(esp_timer_get_time()); + mdns_priv_cache_process_sync(); + TEST_ASSERT_EQUAL_size_t(3, s_observer.goodbye_calls); + TEST_ASSERT_EQUAL_size_t(3, s_observer.update_calls); + // Goodbye captures the last subtype before removal; no update follows cache deletion. + TEST_ASSERT_EQUAL_size_t(1, s_observer.subtype_count); + TEST_ASSERT_EQUAL_STRING(SUBTYPE_B, s_observer.goodbye_subtype); + assert_memory(baseline); +} + +void run_unity_tests(void) +{ + UNITY_BEGIN(); + RUN_TEST(test_cache_ptr_add_repeat_update_remove); + RUN_TEST(test_cache_srv_add_repeat_update_remove); + RUN_TEST(test_cache_txt_add_repeat_update_remove); + RUN_TEST(test_cache_addr_add_repeat_update_remove); + RUN_TEST(test_cache_record_order_and_result_projection); + RUN_TEST(test_cache_service_record_goodbyes); + RUN_TEST(test_cache_expiry_extend_and_notify); + RUN_TEST(test_cache_subtype_add_repeat_update_remove); + UNITY_END(); +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/unit_test.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/unit_test.cmake new file mode 100644 index 0000000..72e7cc8 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_cache/unit_test.cmake @@ -0,0 +1,6 @@ +# Test mdns_cache in isolation. Browse-facing functions are mocked. +set(MOCK_FILES + "mdns_browser" +) + +list(APPEND SOURCES unity/${UNIT_TESTS}/test_cache.c) diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/test_receiver.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/test_receiver.c new file mode 100644 index 0000000..e92ceba --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/test_receiver.c @@ -0,0 +1,244 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include "unity.h" +#include "create_test_packet.h" +#include "unity_main.h" +#include "mock_mdns_pcb.h" +#include "mock_mdns_send.h" +#include "mdns_private.h" +#include "mdns_utils.h" +#include "mdns_responder.h" + +typedef struct { + size_t count; + char hostname[MDNS_NAME_BUF_LEN]; +} hostname_changed_callback_context_t; + +static void hostname_changed_callback(const char *hostname, void *arg) +{ + hostname_changed_callback_context_t *context = arg; + + ++context->count; + strncpy(context->hostname, hostname, sizeof(context->hostname)); + context->hostname[sizeof(context->hostname) - 1] = '\0'; +} + +static void test_hostname_changed_callback(void) +{ + hostname_changed_callback_context_t context = { 0 }; + + TEST_ASSERT_EQUAL(ESP_OK, mdns_register_hostname_changed_callback(hostname_changed_callback, &context)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set("renamed-hostname")); + TEST_ASSERT_EQUAL_UINT(1, context.count); + TEST_ASSERT_EQUAL_STRING("renamed-hostname", context.hostname); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set("renamed-hostname")); + TEST_ASSERT_EQUAL_UINT(1, context.count); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set("renamed-hostname-again")); + TEST_ASSERT_EQUAL_UINT(2, context.count); + TEST_ASSERT_EQUAL_STRING("renamed-hostname-again", context.hostname); +} + +static void test_mdns_hostname_queries(void) +{ + // Define the queries for test4.local and test.local + mdns_test_query_t queries[] = { + { "test4.local", 1, 1 }, // A record for test4.local + { "test.local", 1, 1 } // A record for test.local + }; + + // Create and send the packet + size_t packet_len; + uint8_t* packet = create_mdns_test_packet( + queries, 2, // Queries + NULL, 0, // No answers + NULL, 0, // No additional records + &packet_len + ); + + send_test_packet_multiple(packet, packet_len); +} + +// Example of a more complex test with answers and additional records +static void test_mdns_with_answers(void) +{ + // Define a query for _http._tcp.local PTR record + mdns_test_query_t queries[] = { + { "_http._tcp.local", 12, 1 } // PTR record + }; + + // Example data for a PTR record (simplified) + uint8_t ptr_data[200]; + size_t ptr_data_len = encode_dns_name(ptr_data, "test._http._tcp.local"); + + // Define an answer for the PTR record + mdns_test_answer_t answers[] = { + { "_http._tcp.local", 12, 1, 120, ptr_data_len, ptr_data } + }; + + // Create and send the packet + size_t packet_len; + uint8_t* packet = create_mdns_test_packet( + queries, 1, // Single query + answers, 1, // Single answer + NULL, 0, // No additional records + &packet_len + ); + + send_test_packet_multiple(packet, packet_len); + +} + +/* + * Regression test for fa84ee6: packets shorter than MDNS_HEAD_LEN (12) must + * be rejected before reading the additional RR count at offset 10. + * An 11-byte AFL input (id_000005) previously passed the old check and read + * one byte past the RX buffer. + */ +static void test_mdns_reject_short_packet(void) +{ + static const uint8_t eleven_byte_packet[] = { + 0x00, 0xc0, 0x32, 0x00, 0x01, 0x00, 0x14, 0x00, 0x00, 0x54, 0x01 + }; + + for (size_t len = 0; len < MDNS_HEAD_LEN; len++) { + const uint8_t *data = eleven_byte_packet; + send_packet(true, true, (uint8_t *)data, len); + send_packet(true, false, (uint8_t *)data, len); + send_packet(false, true, (uint8_t *)data, len); + send_packet(false, false, (uint8_t *)data, len); + } +} + +static void test_mdns_subtype_any_question_is_not_a_probe(void) +{ + mdns_test_query_t queries[] = { + { "subtype._sub._http._tcp.local", MDNS_TYPE_ANY, 1 }, + }; + size_t packet_len; + uint8_t *packet = create_mdns_test_packet(queries, 1, NULL, 0, NULL, 0, &packet_len); + + send_test_packet_multiple(packet, packet_len); +} + +static void test_mdns_reject_misplaced_sub_label(void) +{ + uint8_t fqdn[MDNS_NAME_BUF_LEN] = {}; + mdns_name_t name = {}; + size_t fqdn_len = encode_dns_name(fqdn, "instance._http._sub._tcp.local"); + + TEST_ASSERT_NOT_NULL(mdns_utils_parse_fqdn(fqdn, fqdn, &name, fqdn_len)); + TEST_ASSERT_TRUE(name.invalid); + + fqdn_len = encode_dns_name(fqdn, "subtype._sub._http._tcp.local"); + TEST_ASSERT_NOT_NULL(mdns_utils_parse_fqdn(fqdn, fqdn, &name, fqdn_len)); + TEST_ASSERT_FALSE(name.invalid); + TEST_ASSERT_TRUE(name.sub); +} + +static void mdns_priv_create_answer_from_parsed_packet_Callback(mdns_parsed_packet_t* parsed_packet, int cmock_num_calls) +{ + printf("callback\n"); + if (parsed_packet->questions && parsed_packet->questions->sub && parsed_packet->questions->type == MDNS_TYPE_ANY) { + TEST_ASSERT_FALSE(parsed_packet->probe); + } +} + +static size_t count_registered_services(void) +{ + size_t count = 0; + for (mdns_srv_item_t *a = mdns_priv_get_services(); a; a = a->next) { + count++; + } + return count; +} + +static size_t s_parsed_question_count; +static size_t s_parsed_sdptr_count; + +static void discovery_dedup_answer_callback(mdns_parsed_packet_t *parsed_packet, int cmock_num_calls) +{ + (void)cmock_num_calls; + s_parsed_question_count = 0; + s_parsed_sdptr_count = 0; + TEST_ASSERT_TRUE(parsed_packet->discovery); + for (mdns_parsed_question_t *q = parsed_packet->questions; q; q = q->next) { + s_parsed_question_count++; + if (q->type == MDNS_TYPE_SDPTR) { + s_parsed_sdptr_count++; + } + } +} + +/* + * Duplicate _services._dns-sd._udp.local PTR questions must expand the service + * list only once. Without the guard, each copy allocates one SDPTR question per + * registered service (heap amplification). + */ +static void test_mdns_discovery_questions_deduped(void) +{ + size_t service_count = count_registered_services(); + TEST_ASSERT_GREATER_THAN(0, service_count); + + mdns_test_query_t queries[] = { + { "_services._dns-sd._udp.local", MDNS_TYPE_PTR, 1 }, + { "_services._dns-sd._udp.local", MDNS_TYPE_PTR, 1 }, + { "_services._dns-sd._udp.local", MDNS_TYPE_PTR, 1 }, + { "_services._dns-sd._udp.local", MDNS_TYPE_PTR, 1 }, + }; + + mdns_priv_create_answer_from_parsed_packet_Stub(discovery_dedup_answer_callback); + + size_t packet_len; + uint8_t *packet = create_mdns_test_packet(queries, 4, NULL, 0, NULL, 0, &packet_len); + TEST_ASSERT_NOT_NULL(packet); + send_packet(true, true, packet, packet_len); + free(packet); + + TEST_ASSERT_EQUAL(service_count, s_parsed_sdptr_count); + TEST_ASSERT_EQUAL(service_count, s_parsed_question_count); + + mdns_priv_create_answer_from_parsed_packet_Stub(mdns_priv_create_answer_from_parsed_packet_Callback); +} + +void setup_cmock(void) +{ + mdns_priv_probe_all_pcbs_CMockIgnore(); + mdns_priv_pcb_announce_CMockIgnore(); + mdns_priv_pcb_send_bye_service_CMockIgnore(); + mdns_priv_pcb_check_probing_services_CMockIgnore(); + mdns_priv_pcb_is_after_probing_IgnoreAndReturn(true); + + mdns_priv_clear_tx_queue_CMockIgnore(); + mdns_priv_remove_scheduled_service_packets_CMockIgnore(); + mdns_priv_create_answer_from_parsed_packet_Stub(mdns_priv_create_answer_from_parsed_packet_Callback); +} + +void run_unity_tests(void) +{ + UNITY_BEGIN(); + + // Run hostname queries test + RUN_TEST(test_mdns_hostname_queries); + + RUN_TEST(test_hostname_changed_callback); + + // Run test with answers + RUN_TEST(test_mdns_with_answers); + + RUN_TEST(test_mdns_reject_short_packet); + + RUN_TEST(test_mdns_subtype_any_question_is_not_a_probe); + + RUN_TEST(test_mdns_reject_misplaced_sub_label); + + RUN_TEST(test_mdns_discovery_questions_deduped); + + UNITY_END(); +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/unit_test.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/unit_test.cmake new file mode 100644 index 0000000..b08bbe6 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_receiver/unit_test.cmake @@ -0,0 +1,7 @@ +# Testing mDNS receiver, so mocking pbb and send +set(MOCK_FILES + "mdns_pcb" + "mdns_send" +) + +list(APPEND SOURCES unity/${UNIT_TESTS}/test_receiver.c) diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/test_sender.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/test_sender.c new file mode 100644 index 0000000..df41b51 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/test_sender.c @@ -0,0 +1,58 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include "unity.h" +#include "unity_main.h" +#include "mock_mdns_pcb.h" +#include "mdns_send.h" +#include "mdns_mem_caps_test.h" + +void setup_cmock(void) +{ + mdns_priv_probe_all_pcbs_CMockIgnore(); + mdns_priv_pcb_announce_CMockIgnore(); + mdns_priv_pcb_send_bye_service_CMockIgnore(); + mdns_priv_pcb_check_probing_services_CMockIgnore(); + mdns_priv_pcb_is_after_probing_IgnoreAndReturn(true); +} + +static void test_dispatch_tx_packet(void) +{ + mdns_tx_packet_t p = {}; + mdns_priv_dispatch_tx_packet(&p); +} + +static void test_cleanup_tx_action_of_scheduled_packet(void) +{ + size_t baseline = mdns_mem_get_allocation_counts(); + mdns_tx_packet_t *packet = mdns_priv_alloc_packet(0, MDNS_IP_PROTOCOL_V4); + TEST_ASSERT_NOT_NULL(packet); + mdns_priv_send_after(packet, 0); + + // State left by mdns_priv_send_packets() for a due packet whose action has not run yet: + // the packet is marked as queued and stays linked in the TX queue + packet->queued = true; + mdns_action_t action = { .type = ACTION_TX_HANDLE }; + action.data.tx_handle.packet = packet; + + // mdns_free() cleans up the pending actions first, then clears the TX queue + mdns_priv_send_action(&action, ACTION_CLEANUP); + mdns_priv_clear_tx_queue(); + + TEST_ASSERT_EQUAL_size_t(baseline, mdns_mem_get_allocation_counts()); +} + +void run_unity_tests(void) +{ + UNITY_BEGIN(); + + // Run hostname queries test + RUN_TEST(test_dispatch_tx_packet); + RUN_TEST(test_cleanup_tx_action_of_scheduled_packet); + + + UNITY_END(); +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/unit_test.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/unit_test.cmake new file mode 100644 index 0000000..2fa0b64 --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/test_sender/unit_test.cmake @@ -0,0 +1,6 @@ +# Testing mDNS sender, need to mock pbb +set(MOCK_FILES + "mdns_pcb" +) + +list(APPEND SOURCES unity/${UNIT_TESTS}/test_sender.c) diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/unit_test.cmake b/managed_components/espressif__mdns/tests/host_unit_test/unity/unit_test.cmake new file mode 100644 index 0000000..8379b4b --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/unit_test.cmake @@ -0,0 +1,67 @@ +set(UNITY_DIR "$ENV{IDF_PATH}/components/unity") +set(CMOCK_DIR "$ENV{IDF_PATH}/components/cmock") + +include_directories(${UNITY_DIR}/unity/src) +add_definitions(-DENABLE_UNIT_TESTS) + +# Use ruby command directly instead of looking for ruby.exe +find_program(RUBY_EXECUTABLE ruby) +if(NOT RUBY_EXECUTABLE) + message(FATAL_ERROR "Ruby is required for CMock but was not found!") +endif() + +include(unity/${UNIT_TESTS}/unit_test.cmake) + +# Verify headers exist and create mock commands for each +foreach(mock_file ${MOCK_FILES}) + set(header_path "${COMPONENT_DIR}/private_include/${mock_file}.h") + if(NOT EXISTS ${header_path}) + message(FATAL_ERROR "Cannot find ${mock_file}.h at ${header_path}") + endif() + + list(APPEND MOCK_OUTPUTS + ${CMAKE_CURRENT_BINARY_DIR}/mocks/mock_${mock_file}.c + ${CMAKE_CURRENT_BINARY_DIR}/mocks/mock_${mock_file}.h + ) + + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mocks/mock_${mock_file}.c + ${CMAKE_CURRENT_BINARY_DIR}/mocks/mock_${mock_file}.h + COMMAND ${RUBY_EXECUTABLE} + ${CMOCK_DIR}/CMock/lib/cmock.rb + -o${CMAKE_CURRENT_SOURCE_DIR}/unity/cmock_config.yml + ${header_path} + DEPENDS ${header_path} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + COMMENT "Generating mock for ${mock_file}.h" + ) +endforeach() + +# Include CMock headers +include_directories( + ${CMOCK_DIR}/CMock/src + ${CMAKE_CURRENT_BINARY_DIR}/mocks + ${UNITY_DIR}/unity/src + ${UNITY_DIR}/include + unity +) + +# Create directory for generated mocks +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/mocks) + +foreach(mock_file ${MOCK_FILES}) + list(REMOVE_ITEM SOURCES ${MDNS_DIR}/${mock_file}.c) +endforeach() + +# Add test-related sources +list(APPEND SOURCES + ${UNITY_DIR}/unity/src/unity.c + ${CMOCK_DIR}/CMock/src/cmock.c + unity/unity_main.c + unity/create_test_packet.c +) + +# Add all generated mock files +foreach(mock_file ${MOCK_FILES}) + list(APPEND SOURCES ${CMAKE_CURRENT_BINARY_DIR}/mocks/mock_${mock_file}.c) +endforeach() diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.c b/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.c new file mode 100644 index 0000000..ed9904c --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.c @@ -0,0 +1,162 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include +#include +#include +#include "esp_err.h" +#include "unity.h" +#include "mdns_receive.h" +#include "mdns_responder.h" +#include "mdns_mem_caps.h" +#include "mdns_test_clock.h" + +// Weak set-up and tear-down functions that can be overridden by unit tests +void __attribute__((weak)) mdns_test_set_up(void) +{ +} +void __attribute__((weak)) mdns_test_tear_down(void) +{ +} + +void setUp(void) +{ + mdns_test_set_up(); +} + +void tearDown(void) +{ + mdns_test_tear_down(); +} + +// Sample test case - update based on the actual functionality in mdns_receive.c +void test_init(void) +{ + + +} + +esp_err_t mdns_packet_push(esp_ip_addr_t *addr, int port, mdns_if_t tcpip_if, uint8_t*data, size_t len); + +mdns_search_once_t *s_a, *s_aaaa, *s_ptr, *s_srv, *s_txt; + +void init_responder(void) +{ + mdns_ip_addr_t addr = { .addr = { .u_addr = ESP_IPADDR_TYPE_V4 } }; + addr.addr.u_addr.ip4.addr = 0x11111111; + mdns_txt_item_t txt[4] = { + {"board", "esp32"}, + {"tcp_check", "no"}, + {"ssh_upload", "no"}, + {"auth_upload", "no"} + }; + mdns_priv_responder_init(); + mdns_hostname_set("test"); + mdns_instance_name_set("test2"); + mdns_delegate_hostname_add("test3", NULL); + mdns_delegate_hostname_add("test4", &addr); + mdns_service_add("inst1", "_http", "_tcp", 80, txt, 4); + mdns_service_subtype_add_for_host("inst1", "_http", "_tcp", "test", "subtype"); + mdns_service_add("inst2", "_http", "_tcp", 80, txt, 1); + mdns_service_subtype_add_for_host("inst2", "_http", "_tcp", "test", "subtype3"); + mdns_service_add("inst3", "_http", "_tcp", 80, NULL, 0); + mdns_service_add_for_host("deleg1", "_http", "_tcp", "test3", 80, txt, 2); + mdns_service_add_for_host(NULL, "_http", "_tcp", "test4", 80, txt, 2); + mdns_service_add(NULL, "_scanner", "_tcp", 80, NULL, 0); + mdns_service_add("inst5", "_scanner", "_tcp", 80, NULL, 0); + mdns_service_add("inst6", "_http", "_tcp", 80, NULL, 0); + mdns_service_add("inst7", "_sleep", "_udp", 80, NULL, 0); + + s_a = mdns_query_async_new("host_name", NULL, NULL, MDNS_TYPE_A, 1000, 1, NULL); + s_aaaa = mdns_query_async_new("host_name2", NULL, NULL, MDNS_TYPE_AAAA, 1000, 1, NULL); + s_ptr = mdns_query_async_new("minifritz", "_http", "_tcp", MDNS_TYPE_PTR, 1000, 1, NULL); + s_srv = mdns_query_async_new("fritz", "_http", "_tcp", MDNS_TYPE_SRV, 1000, 1, NULL); + s_txt = mdns_query_async_new("fritz", "_http", "_tcp", MDNS_TYPE_TXT, 1000, 1, NULL); + +} + +void deinit_responder(void) +{ + mdns_query_async_delete(s_a); + mdns_query_async_delete(s_aaaa); + mdns_query_async_delete(s_ptr); + mdns_query_async_delete(s_srv); + mdns_query_async_delete(s_txt); + mdns_service_remove_all(); + mdns_priv_responder_free(); +} + +void send_packet(bool ip4, bool mdns_port, uint8_t*data, size_t len) +{ + esp_ip_addr_t addr4 = ESP_IP4ADDR_INIT(192, 168, 1, 1); + esp_ip_addr_t addr6 = ESP_IP6ADDR_INIT(0x000002ff, 0, 0, 0xfe800000); + esp_ip_addr_t *addr = ip4 ? &addr4 : &addr6; + int port = mdns_port ? 53 : 5353; + + if (mdns_packet_push(addr, port, 0, data, len) != ESP_OK) { + printf("Failed to push packet\n"); + } +} + +// Helper function to send a test packet with different configurations and clean up +void send_test_packet_multiple(uint8_t* packet, size_t packet_len) +{ + if (packet) { + // Test with different packet configurations + send_packet(true, true, packet, packet_len); + send_packet(true, false, packet, packet_len); + send_packet(false, true, packet, packet_len); + send_packet(false, false, packet, packet_len); + + // Free the packet + free(packet); + } else { + printf("Failed to create test packet\n"); + } +} + +void test_mdns_receive_from_file(const char* filename) +{ + uint8_t buf[1460]; + FILE *file = fopen(filename, "r"); + TEST_ASSERT_NOT_NULL_MESSAGE(file, "Failed to open test packet file"); + + size_t len = fread(buf, 1, 1460, file); + fclose(file); + + // Test with different packet configurations + send_packet(true, true, buf, len); + send_packet(true, false, buf, len); + send_packet(false, true, buf, len); + send_packet(false, false, buf, len); + + // Add assertions here based on expected behavior + // For example: + // TEST_ASSERT_EQUAL(expected_result, actual_result); +} + + +void run_unity_tests(void); +void setup_cmock(void); + +int main(int argc, char **argv) +{ + if (argc >= 2 && strcmp(argv[1], "--test") == 0) { + mdns_test_clock_reset(); + setup_cmock(); + + init_responder(); + run_unity_tests(); + + // Propagate Unity assertion failures to CTest through the process exit code. + const int test_status = Unity.TestFailures == 0U ? 0 : 1; + + deinit_responder(); + return test_status; + } + printf("Unit test configuration: run with --test argument\n"); + return 1; +} diff --git a/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.h b/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.h new file mode 100644 index 0000000..b69098d --- /dev/null +++ b/managed_components/espressif__mdns/tests/host_unit_test/unity/unity_main.h @@ -0,0 +1,10 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#pragma once +#include + +void send_packet(bool ip4, bool mdns_port, uint8_t*data, size_t len); +void send_test_packet_multiple(uint8_t* packet, size_t packet_len); diff --git a/managed_components/espressif__mdns/tests/unit_test/CMakeLists.txt b/managed_components/espressif__mdns/tests/unit_test/CMakeLists.txt new file mode 100644 index 0000000..32bdad8 --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/CMakeLists.txt @@ -0,0 +1,15 @@ +# This is the project CMakeLists.txt file for the test subproject +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "6.0") + set(test_component_dir $ENV{IDF_PATH}/tools/test_apps/components) +else() + set(test_component_dir $ENV{IDF_PATH}/tools/unit-test-app/components) +endif() + +set(EXTRA_COMPONENT_DIRS ../.. + ${test_component_dir}) + +project(mdns_test) diff --git a/managed_components/espressif__mdns/tests/unit_test/main/CMakeLists.txt b/managed_components/espressif__mdns/tests/unit_test/main/CMakeLists.txt new file mode 100644 index 0000000..d04d217 --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/main/CMakeLists.txt @@ -0,0 +1,5 @@ + +idf_component_register(SRCS "test_mdns.c" + REQUIRES test_utils + INCLUDE_DIRS "." + PRIV_REQUIRES unity mdns) diff --git a/managed_components/espressif__mdns/tests/unit_test/main/test_mdns.c b/managed_components/espressif__mdns/tests/unit_test/main/test_mdns.c new file mode 100644 index 0000000..0882c9d --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/main/test_mdns.c @@ -0,0 +1,404 @@ +/* + * SPDX-FileCopyrightText: 2022-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + +#include +#include "mdns.h" +#include "esp_event.h" +#include "unity.h" +#include "test_utils.h" + +#include "unity_fixture.h" +#include "memory_checks.h" + +#define MDNS_HOSTNAME "test-hostname" +#define MDNS_DELEGATE_HOSTNAME "delegate-hostname" +#define MDNS_INSTANCE "test-instance" +#define MDNS_SERVICE_NAME "_http" +#define MDNS_SERVICE_PROTO "_tcp" +#define MDNS_SERVICE_SUBTYPE "_printer" +#define MDNS_SERVICE_PORT 80 + +TEST_GROUP(mdns); + +TEST_SETUP(mdns) +{ + test_utils_record_free_mem(); + TEST_ESP_OK(test_utils_set_leak_level(0, ESP_LEAK_TYPE_CRITICAL, ESP_COMP_LEAK_GENERAL)); +} + +TEST_TEAR_DOWN(mdns) +{ + test_utils_finish_and_evaluate_leaks(32, 64); +} + +static void yield_to_all_priorities(void) +{ + // Lower the test-task priority before testing to ensure other tasks got executed on forced context switch + size_t test_task_prio_before = uxTaskPriorityGet(NULL); + vTaskPrioritySet(NULL, tskIDLE_PRIORITY); + taskYIELD(); // Let the RTOS to switch context + vTaskPrioritySet(NULL, test_task_prio_before); +} + +typedef struct { + size_t count; + char hostname[MDNS_NAME_BUF_LEN]; +} hostname_changed_callback_context_t; + +static void hostname_changed_callback(const char *hostname, void *arg) +{ + hostname_changed_callback_context_t *context = arg; + + ++context->count; + strncpy(context->hostname, hostname, sizeof(context->hostname)); + context->hostname[sizeof(context->hostname) - 1] = '\0'; +} + +TEST(mdns, api_fails_with_invalid_state) +{ + TEST_ASSERT_NOT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_NOT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + TEST_ASSERT_NOT_EQUAL(ESP_OK, mdns_instance_name_set(MDNS_INSTANCE)); + TEST_ASSERT_NOT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + TEST_ASSERT_EQUAL(ESP_ERR_INVALID_STATE, mdns_register_hostname_changed_callback(hostname_changed_callback, NULL)); +} + +TEST(mdns, init_deinit) +{ + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + yield_to_all_priorities(); // Make sure that mdns task has executed to complete initialization + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, hostname_changed_callback) +{ + hostname_changed_callback_context_t context = { 0 }; + + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, mdns_register_hostname_changed_callback(NULL, NULL)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_register_hostname_changed_callback(hostname_changed_callback, &context)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + yield_to_all_priorities(); + TEST_ASSERT_EQUAL_UINT(1, context.count); + TEST_ASSERT_EQUAL_STRING(MDNS_HOSTNAME, context.hostname); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + yield_to_all_priorities(); + TEST_ASSERT_EQUAL_UINT(1, context.count); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set("renamed-hostname")); + yield_to_all_priorities(); + TEST_ASSERT_EQUAL_UINT(2, context.count); + TEST_ASSERT_EQUAL_STRING("renamed-hostname", context.hostname); + + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, boolean_txt_null_value) +{ + mdns_result_t *results = NULL; + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + + mdns_txt_item_t txt_data[] = { + {"bool", NULL}, + {"key", "value"}, + }; + const size_t txt_data_count = sizeof(txt_data) / sizeof(txt_data[0]); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, txt_data, txt_data_count)); + yield_to_all_priorities(); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_NOT_EQUAL(NULL, results->txt); + TEST_ASSERT_EQUAL(txt_data_count, results->txt_count); + + bool found_bool = false; + for (size_t i = 0; i < results->txt_count; ++i) { + if (strcmp(results->txt[i].key, "bool") == 0) { + TEST_ASSERT_NOT_EQUAL(NULL, results->txt_value_len); + TEST_ASSERT_EQUAL_UINT8(0, results->txt_value_len[i]); + found_bool = true; + } + } + TEST_ASSERT_TRUE(found_bool); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_remove(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO)); + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, api_fails_with_expected_err) +{ + mdns_txt_item_t serviceTxtData[CONFIG_MDNS_MAX_SERVICES] = { {NULL, NULL}, + }; + mdns_ip_addr_t addr; + addr.addr.type = ESP_IPADDR_TYPE_V4; + addr.addr.u_addr.ip4.addr = esp_ip4addr_aton("127.0.0.1"); + addr.next = NULL; + for (int i = 0; i < CONFIG_MDNS_MAX_SERVICES; ++i) { + serviceTxtData[i].key = "Key"; + serviceTxtData[i].value = "Value"; + } + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_delegate_hostname_add(MDNS_DELEGATE_HOSTNAME, &addr)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_TRUE(mdns_hostname_exists(MDNS_DELEGATE_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_instance_name_set(MDNS_INSTANCE)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, serviceTxtData, CONFIG_MDNS_MAX_SERVICES)); + TEST_ASSERT_FALSE(mdns_service_exists(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add_for_host(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME, + MDNS_SERVICE_PORT, serviceTxtData, CONFIG_MDNS_MAX_SERVICES)); + TEST_ASSERT_TRUE(mdns_service_exists(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, serviceTxtData, CONFIG_MDNS_MAX_SERVICES)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_item_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, "key1", "value1")); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_item_remove(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, "key1")); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_port_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 8080)); + yield_to_all_priorities(); // to remove the service with the updated txt records + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_remove(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO)); + yield_to_all_priorities(); // Make sure that mdns task has executed to remove the service + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_delegate_hostname_remove(MDNS_DELEGATE_HOSTNAME)); + yield_to_all_priorities(); // Make sure that mdns task has executed to remove the hostname + TEST_ASSERT_FALSE(mdns_service_exists(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_remove_all()); + yield_to_all_priorities(); // Make sure that mdns task has executed to remove all services + + TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, mdns_service_port_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 8080)); + + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, query_api_fails_with_expected_err) +{ + mdns_result_t *results = NULL; + esp_ip6_addr_t addr6; + esp_ip4_addr_t addr4; + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + // check it is not possible to register a service or set an instance without configuring the hostname + TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + TEST_ASSERT_EQUAL(ESP_ERR_INVALID_ARG, mdns_instance_name_set(MDNS_INSTANCE)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + // hostname is set, now adding a service and instance should succeed + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_instance_name_set(MDNS_INSTANCE)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_query_ptr(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 10, CONFIG_MDNS_MAX_SERVICES, &results)); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_query_srv(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 10, &results)); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_query_txt(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 10, &results)); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_ERR_NOT_FOUND, mdns_query_a(MDNS_HOSTNAME, 10, &addr4)); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_ERR_NOT_FOUND, mdns_query_aaaa(MDNS_HOSTNAME, 10, &addr6)); + mdns_query_results_free(results); + + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, add_remove_service) +{ + mdns_result_t *results = NULL; + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT, NULL, 0)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE, results->instance_name); + TEST_ASSERT_EQUAL_STRING(MDNS_SERVICE_NAME, results->service_type); + TEST_ASSERT_EQUAL(MDNS_SERVICE_PORT, results->port); + TEST_ASSERT_EQUAL(NULL, results->txt); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_subtype_add_for_host(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + NULL, MDNS_SERVICE_SUBTYPE)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service_with_subtype(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + MDNS_SERVICE_SUBTYPE, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE, results->instance_name); + mdns_query_results_free(results); + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service_with_subtype(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + "_unknown", 1, &results)); + TEST_ASSERT_EQUAL(NULL, results); + + // Update service properties: port + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_port_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_SERVICE_PORT + 1)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL(MDNS_SERVICE_PORT + 1, results->port); + mdns_query_results_free(results); + + // Update service properties: instance + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_instance_name_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_INSTANCE "1")); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(MDNS_INSTANCE "1", MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE "1", results->instance_name); + mdns_query_results_free(results); + + // Update service properties: txt + mdns_txt_item_t txt_data[] = { + {"key1", "esp32"}, + {"key2", "value"}, + {"key3", "value3"}, + }; + const size_t txt_data_cout = sizeof(txt_data) / sizeof(txt_data[0]); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_set(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, txt_data, txt_data_cout)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_NOT_EQUAL(NULL, results->txt); + TEST_ASSERT_EQUAL(txt_data_cout, results->txt_count); + // compare txt values by keys + size_t matches = 0; + for (int i = 0; i < results->txt_count; ++i) // iterates over the results we get from mdns_lookup() + for (int j = 0; j < txt_data_cout; ++j) // iterates over our test records + if (strcmp(results->txt[i].key, txt_data[j].key) == 0) { // we compare the value only if the key matches + TEST_ASSERT_EQUAL_STRING(results->txt[i].value, txt_data[j].value); + ++matches; + } + TEST_ASSERT_EQUAL(txt_data_cout, matches); // checks that we went over all our txt items + mdns_query_results_free(results); + + // Now remove the service + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_remove(MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_selfhosted_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_EQUAL(NULL, results); + + mdns_free(); + esp_event_loop_delete_default(); +} + +TEST(mdns, add_remove_deleg_service) +{ + mdns_ip_addr_t addr; + addr.addr.type = ESP_IPADDR_TYPE_V4; + addr.addr.u_addr.ip4.addr = esp_ip4addr_aton("127.0.0.1"); + addr.next = NULL; + mdns_result_t *results = NULL; + test_case_uses_tcpip(); + TEST_ASSERT_EQUAL(ESP_OK, esp_event_loop_create_default()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_init()); + TEST_ASSERT_EQUAL(ESP_OK, mdns_hostname_set(MDNS_HOSTNAME)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_delegate_hostname_add(MDNS_DELEGATE_HOSTNAME, &addr)); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_add_for_host(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME, MDNS_SERVICE_PORT, NULL, 0)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE, results->instance_name); + TEST_ASSERT_EQUAL_STRING(MDNS_SERVICE_NAME, results->service_type); + TEST_ASSERT_EQUAL(MDNS_SERVICE_PORT, results->port); + TEST_ASSERT_EQUAL(NULL, results->txt); + mdns_query_results_free(results); + + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_subtype_add_for_host(MDNS_INSTANCE, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + MDNS_DELEGATE_HOSTNAME, MDNS_SERVICE_SUBTYPE)); + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service_with_subtype(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + MDNS_SERVICE_SUBTYPE, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE, results->instance_name); + mdns_query_results_free(results); + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service_with_subtype(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, + "_unknown", 1, &results)); + TEST_ASSERT_EQUAL(NULL, results); + + // Update service properties: port + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_port_set_for_host(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME, MDNS_SERVICE_PORT + 1)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL(MDNS_SERVICE_PORT + 1, results->port); + mdns_query_results_free(results); + + // Update service properties: instance + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_instance_name_set_for_host(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME, MDNS_INSTANCE "1")); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service(MDNS_INSTANCE "1", MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_EQUAL_STRING(MDNS_INSTANCE "1", results->instance_name); + mdns_query_results_free(results); + + // Update service properties: txt + mdns_txt_item_t txt_data[] = { + {"key1", "esp32"}, + {"key2", "value"}, + }; + const size_t txt_data_cout = sizeof(txt_data) / sizeof(txt_data[0]); + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_txt_set_for_host(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME, txt_data, txt_data_cout)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_NOT_EQUAL(NULL, results); + TEST_ASSERT_NOT_EQUAL(NULL, results->txt); + TEST_ASSERT_EQUAL(txt_data_cout, results->txt_count); + // compare txt values by keys + size_t matches = 0; + for (int i = 0; i < results->txt_count; ++i) // iterates over the results we get from mdns_lookup() + for (int j = 0; j < txt_data_cout; ++j) // iterates over our test records + if (strcmp(results->txt[i].key, txt_data[j].key) == 0) { // we compare the value only if the key matches + TEST_ASSERT_EQUAL_STRING(results->txt[i].value, txt_data[j].value); + ++matches; + } + TEST_ASSERT_EQUAL(txt_data_cout, matches); // checks that we went over all our txt items + mdns_query_results_free(results); + + // Now remove the service + TEST_ASSERT_EQUAL(ESP_OK, mdns_service_remove_for_host(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, MDNS_DELEGATE_HOSTNAME)); + yield_to_all_priorities(); // Make sure that mdns task has executed to add the hostname + TEST_ASSERT_EQUAL(ESP_OK, mdns_lookup_delegated_service(NULL, MDNS_SERVICE_NAME, MDNS_SERVICE_PROTO, 1, &results)); + TEST_ASSERT_EQUAL(NULL, results); + + mdns_free(); + esp_event_loop_delete_default(); +} +TEST_GROUP_RUNNER(mdns) +{ + RUN_TEST_CASE(mdns, api_fails_with_invalid_state) + RUN_TEST_CASE(mdns, api_fails_with_expected_err) + RUN_TEST_CASE(mdns, query_api_fails_with_expected_err) + RUN_TEST_CASE(mdns, init_deinit) + RUN_TEST_CASE(mdns, add_remove_service) + RUN_TEST_CASE(mdns, add_remove_deleg_service) + RUN_TEST_CASE(mdns, boolean_txt_null_value) + +} + +void app_main(void) +{ + UNITY_MAIN(mdns); +} diff --git a/managed_components/espressif__mdns/tests/unit_test/pytest_app_mdns.py b/managed_components/espressif__mdns/tests/unit_test/pytest_app_mdns.py new file mode 100644 index 0000000..5106112 --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/pytest_app_mdns.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +from pytest_embedded import Dut + + +def test_mdns(dut: Dut) -> None: + dut.expect_unity_test_output() diff --git a/managed_components/espressif__mdns/tests/unit_test/sdkconfig.ci b/managed_components/espressif__mdns/tests/unit_test/sdkconfig.ci new file mode 100644 index 0000000..9660719 --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/sdkconfig.ci @@ -0,0 +1,3 @@ +CONFIG_IDF_TARGET="esp32" +CONFIG_UNITY_ENABLE_FIXTURE=y +CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=n diff --git a/managed_components/espressif__mdns/tests/unit_test/sdkconfig.defaults b/managed_components/espressif__mdns/tests/unit_test/sdkconfig.defaults new file mode 100644 index 0000000..168e08d --- /dev/null +++ b/managed_components/espressif__mdns/tests/unit_test/sdkconfig.defaults @@ -0,0 +1,2 @@ +CONFIG_UNITY_ENABLE_FIXTURE=y +CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=n diff --git a/tools/ddp_test.py b/tools/ddp_test.py index 289ef72..ef53b42 100644 --- a/tools/ddp_test.py +++ b/tools/ddp_test.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 """ -Test the LED driver's DDP receiver (UDP port 4048). +Test the LED driver's DDP receiver (UDP port 4048) and its frame sync (UDP broadcast port 4049). -Sends frames of RGB pixels the way a DDP controller does: a version 1 header, the pixel data split -across two packets, and the PUSH flag on the last packet of a frame. Then checks through the driver's -HTTP API that the pixels were shown, runs a few test animations, and that the pattern comes back once -the pixels stop. Every device is tested at the same time, one thread each. +Every frame goes to each device as unicast DDP: a version 1 header, the pixel data split across two +packets, and the PUSH flag on the last packet. After each tick, one broadcast sync ("LSY1" + seq) tells +all devices to show the frame they hold. The devices are driven together, from one sender. Through the +driver's HTTP API the test checks that the pixels were shown, that a frame waits for a sync, runs a few +test animations, and that the pattern comes back once the pixels stop. python3 tools/ddp_test.py # finds every device on this machine's subnet (/24) python3 tools/ddp_test.py --subnet=192.168.4 # or pick the subnet @@ -26,11 +27,14 @@ import urllib.request from concurrent.futures import ThreadPoolExecutor PORT = 4048 +SYNC_PORT = 4049 LEDS = 119 PUSH = 0x01 VER1 = 0x40 RGB = 0x01 -ANIM_FRAMES = 40 # about 1 s at 40 fps +TICK = 0.025 # seconds between ticks (40 fps) +ACK_WAIT = 0.02 # seconds to wait for each device's ack before the sync goes out anyway +ANIM_FRAMES = 40 # about 1 s def packet(seq, offset, data, push): @@ -40,25 +44,29 @@ def packet(seq, offset, data, push): def send_frame(sock, host, pixels, seq): - """Send pixels (a list of (r, g, b)) as two packets, PUSH on the second.""" + """Unicast pixels (a list of (r, g, b)) as two packets, PUSH on the second.""" raw = bytes(c for px in pixels for c in px) split = (len(pixels) // 2) * 3 sock.sendto(packet(seq, 0, raw[:split], False), (host, PORT)) sock.sendto(packet(seq, split, raw[split:], True), (host, PORT)) +def send_sync(sock, seq): + """Broadcast a sync: every device shows the frame it holds.""" + sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), ("255.255.255.255", SYNC_PORT)) + + def frame_sum(pixels): """The driver's checksum of a frame: the sum of its bytes, as an unsigned 32-bit value.""" return sum(c for px in pixels for c in px) & 0xFFFFFFFF -def read_serial(port, seconds, lines): - """Collect the driver's log lines from the USB serial port for a few seconds.""" +def read_serial(port, stop, lines): + """Collect the driver's log lines from the USB serial port until stop is set.""" import serial ser = serial.Serial(port, 115200, timeout=0.2) - end = time.time() + seconds buf = b"" - while time.time() < end: + while not stop.is_set(): buf += ser.read(4096) ser.close() lines.extend(buf.decode("utf-8", "replace").splitlines()) @@ -114,6 +122,11 @@ def anim_breathe(i, k): ANIMATIONS = {"chase": anim_chase, "rainbow": anim_rainbow, "breathe": anim_breathe} +def frame(k): + """A frame: LED i is a colour that depends on i, so every LED is distinguishable.""" + return [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)] + + def output_scale(host): """The factor the driver applies to every pixel before it is shown: global x master x max brightness, with the same integer steps as the firmware (patterns.cpp).""" @@ -131,121 +144,214 @@ def mismatch_detail(bad): return "" if not bad else f"first mismatch LED {bad[0][0]}: got {bad[0][1]} want {bad[0][2]}" -def verify_frame(host, sock, pixels, scale): - """Read every LED back while keeping the frame on the strip (the readback is slower than the DDP - timeout). Returns the LEDs that do not match what the driver should show.""" - want_all = expected(pixels, scale) - stop = threading.Event() +class Sender: + """Drives every device from one thread. Each tick sends each device its current frame (unicast), + then one sync broadcast that all devices show their frame on.""" - def keep_sending(): - seq = 100 - while not stop.is_set(): - send_frame(sock, host, pixels, seq) - seq += 1 - time.sleep(0.025) + def __init__(self, sock, hosts): + self.sock = sock + self.hosts = hosts + self.ip_of = {h: socket.gethostbyname(h) for h in hosts} + self.host_of = {ip: h for h, ip in self.ip_of.items()} + self.missed = {h: 0 for h in hosts} # frames a device did not ack in time + self.sock.settimeout(ACK_WAIT) + self.frames = {h: None for h in hosts} + self.seq = 0 + self.paused = False + self.lock = threading.Lock() + self.stop_event = threading.Event() + self.thread = threading.Thread(target=self._run, daemon=True) - sender = threading.Thread(target=keep_sending, daemon=True) - sender.start() - bad = [] - for i in range(LEDS): - got = get(host, f"/api/ddp?led={i}")["rgb"] - want = want_all[i] - if got != want: - bad.append((i, got, want)) - stop.set() - sender.join() - return bad + def set_frames(self, pixels_by_host): + with self.lock: + self.frames.update(pixels_by_host) + + def tick(self): + with self.lock: + frames = dict(self.frames) + self.seq = (self.seq + 1) & 0xFFFFFFFF + sent = [h for h in self.hosts if frames[h] is not None] + for h in sent: + send_frame(self.sock, h, frames[h], self.seq) + self.wait_acks(self.seq & 0x0F, sent) + send_sync(self.sock, self.seq) + + def wait_acks(self, nibble, hosts): + """Wait until each device acks this frame (the driver acks a completed frame with "LAK1" and its + DDP seq), up to ACK_WAIT. Devices that do not ack in time are counted as missed.""" + waiting = {self.ip_of[h] for h in hosts} + deadline = time.time() + ACK_WAIT + while waiting and time.time() < deadline: + try: + data, addr = self.sock.recvfrom(64) + except OSError: + continue + if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble: + waiting.discard(addr[0]) + for ip in waiting: + self.missed[self.host_of[ip]] += 1 + + def _run(self): + # Fixed rate: ticks start every TICK seconds on a schedule, so the ack waits don't stretch the rate + next_tick = time.monotonic() + while not self.stop_event.is_set(): + if not self.paused: + self.tick() + next_tick += TICK + delay = next_tick - time.monotonic() + if delay > 0: + time.sleep(delay) + else: + next_tick = time.monotonic() # fell behind: start the schedule again from now + + def start(self): + self.thread.start() + + def stop(self): + self.stop_event.set() + self.thread.join() -def run(host, serial_port): - """Run every check against one device. Returns (failures, output lines).""" - out = [] - failures = 0 - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +def run_all(hosts, serial_port): + """Run every check against every device together. Returns (output lines, failures) per host.""" + out = {h: [] for h in hosts} + fails = {h: 0 for h in hosts} - def log(line=""): - out.append(line) - - def check(name, ok, detail=""): - nonlocal failures - log(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else "")) + def check(h, name, ok, detail=""): + out[h].append(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else "")) if not ok: - failures += 1 + fails[h] += 1 - before = get(host, "/api/ddp") - log(f"before: active={before['active']} packets={before['packets']}") - scale = output_scale(host) - log(f"output scale: {scale}/255") + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - # A frame: LED i is a colour that depends on i, so every LED is distinguishable - def frame(k): - return [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)] + before, scale = {}, {} + for h in hosts: + before[h] = get(h, "/api/ddp") + scale[h] = 255 # DDP frames are shown at full brightness, whatever the device's brightness settings + out[h].append(f"before: active={before[h]['active']} packets={before[h]['packets']}") + out[h].append(f"output scale: {scale[h]}/255") + sender = Sender(sock, hosts) + sent = {} # frame checksum -> pixels, for the serial log check + stop_serial = threading.Event() serial_lines = [] reader = None if serial_port: - reader = threading.Thread(target=read_serial, args=(serial_port, 3.0, serial_lines), daemon=True) + reader = threading.Thread(target=read_serial, args=(serial_port, stop_serial, serial_lines), daemon=True) reader.start() - sent_sums = {} - last = None - for k in range(60): # about 1.5 s at 40 fps - last = frame(k) - sent_sums[frame_sum(last)] = k - send_frame(sock, host, last, k) - time.sleep(0.025) + + sender.start() + for k in range(60): # about 1.5 s + px = frame(k) + sent[frame_sum(px)] = px + sender.set_frames({h: px for h in hosts}) + time.sleep(TICK) time.sleep(0.2) - mid = get(host, "/api/ddp") - check("receiving while sending", mid["active"], f"packets={mid['packets']}") - check("packets counted", mid["packets"] - before["packets"] >= 120, - f"+{mid['packets'] - before['packets']}") + for h in hosts: + out[h].append(f"frames not acked in time while streaming: {sender.missed[h]}") + for h in hosts: + mid = get(h, "/api/ddp") + check(h, "receiving while sending", mid["active"], f"packets={mid['packets']}") + check(h, "packets counted", mid["packets"] - before[h]["packets"] >= 120, + f"+{mid['packets'] - before[h]['packets']}") - bad = verify_frame(host, sock, last, scale) - check(f"all {LEDS} LEDs show the frame", not bad, mismatch_detail(bad)) - shown = last + # A frame waits for a sync: send one by unicast alone, then a sync, and check the strip changes + sender.paused = True + time.sleep(0.1) + waiting = frame(200) + sent[frame_sum(waiting)] = waiting + send_sync(sock, sender.seq + 1) # sync mode is on: a sync was sent a moment ago + time.sleep(0.06) # later than the devices' 30 ms sync window, so the frame is held + for h in hosts: + send_frame(sock, h, waiting, sender.seq + 1) + time.sleep(0.3) + for h in hosts: + got = get(h, "/api/ddp?led=0")["rgb"] + check(h, "frame waits for a sync", got != expected([waiting[0]], scale[h])[0], + f"LED 0 shows {got} before the sync") + send_sync(sock, sender.seq + 2) + time.sleep(0.2) + for h in hosts: + got = get(h, "/api/ddp?led=0")["rgb"] + check(h, "frame shows on the sync", got == expected([waiting[0]], scale[h])[0], f"LED 0 {got}") + sender.paused = False + stop_serial.set() if reader is not None: reader.join() + h = hosts[0] pat = re.compile(r"DDP frames=\d+ packets=\d+ sum=(\d+) led0=(\d+),(\d+),(\d+) led_last=(\d+),(\d+),(\d+)") summaries = [m for m in (pat.search(line) for line in serial_lines) if m] - check("serial log has DDP summaries", len(summaries) > 0, f"{len(summaries)} lines") - matched = [m for m in summaries if int(m.group(1)) in sent_sums] - check("logged checksums are of sent frames", len(matched) == len(summaries), + check(h, "serial log has DDP summaries", len(summaries) > 0, f"{len(summaries)} lines") + matched = [m for m in summaries if int(m.group(1)) in sent] + check(h, "logged checksums are of sent frames", len(matched) == len(summaries), f"{len(matched)}/{len(summaries)} match") for m in summaries[-1:]: - k = sent_sums.get(int(m.group(1))) - if k is not None: - sent = frame(k) - check("serial led0 and last LED match that frame", - [int(m.group(i)) for i in (2, 3, 4)] == list(sent[0]) and - [int(m.group(i)) for i in (5, 6, 7)] == list(sent[-1]), + px = sent.get(int(m.group(1))) + if px is not None: + check(h, "serial led0 and last LED match that frame", + [int(m.group(i)) for i in (2, 3, 4)] == list(px[0]) and + [int(m.group(i)) for i in (5, 6, 7)] == list(px[-1]), f"led0 {m.group(2, 3, 4)} led_last {m.group(5, 6, 7)}") - # Test animations: send each one, then check the last frame is shown + def readback(h, pixels): + """Read every LED back and return the ones that do not match what the driver should show.""" + want_all = expected(pixels, scale[h]) + bad = [] + for i in range(LEDS): + got = get(h, f"/api/ddp?led={i}")["rgb"] + if got != want_all[i]: + bad.append((i, got, want_all[i])) + return bad + + def check_readback(name, pixels): + # Lost frames are expected, and the sender repeats each frame, so give the strips up to 1 s to + # settle on it before reading back: the check passes once every LED matches + deadline = time.time() + 1.0 + while True: + with ThreadPoolExecutor(len(hosts)) as pool: + bads = list(pool.map(lambda h: readback(h, pixels), hosts)) + if all(not bad for bad in bads) or time.time() > deadline: + break + time.sleep(0.05) + for h, bad in zip(hosts, bads): + check(h, name, not bad, mismatch_detail(bad)) + + shown = frame(59) + sender.set_frames({h: shown for h in hosts}) + time.sleep(0.1) + check_readback(f"all {LEDS} LEDs show the frame", shown) + for name, fn in ANIMATIONS.items(): - pixels = None for k in range(ANIM_FRAMES): - pixels = [fn(i, k) for i in range(LEDS)] - send_frame(sock, host, pixels, k) - time.sleep(0.025) - time.sleep(0.2) - bad = verify_frame(host, sock, pixels, scale) - check(f"animation {name} shows its last frame", not bad, mismatch_detail(bad)) - shown = pixels + px = [fn(i, k) for i in range(LEDS)] + sender.set_frames({h: px for h in hosts}) + time.sleep(TICK) + time.sleep(0.1) + check_readback(f"animation {name} shows its last frame", px) + shown = px # Pixels past the strip end are ignored and don't break the rest - sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (host, PORT)) - time.sleep(0.1) - check("out-of-range packet ignored", get(host, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale)[0]) + for h in hosts: + sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (h, PORT)) + time.sleep(0.2) + for h in hosts: + check(h, "out-of-range packet ignored", + get(h, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale[h])[0]) # Stop sending: the pattern should come back after the timeout + sender.stop() time.sleep(3.0) - after = get(host, "/api/ddp") - check("inactive after pixels stop", not after["active"]) - now_led0 = get(host, "/api/ddp?led=0")["rgb"] - check("pattern is shown again", now_led0 != expected([shown[0]], scale)[0], f"LED 0 now {now_led0}") + for h in hosts: + after = get(h, "/api/ddp") + check(h, "inactive after pixels stop", not after["active"]) + now0 = get(h, "/api/ddp?led=0")["rgb"] + check(h, "pattern is shown again", now0 != expected([shown[0]], scale[h])[0], f"LED 0 now {now0}") - return failures, out + sock.close() + return out, fails def main(): @@ -264,16 +370,13 @@ def main(): print("note: --serial is only used when testing one device\n") serial_port = None - # All devices at the same time, one thread each - with ThreadPoolExecutor(max_workers=len(hosts)) as pool: - results = list(pool.map(lambda h: run(h, serial_port), hosts)) - + out, fails = run_all(hosts, serial_port) failures = 0 - for host, (device_failures, out) in zip(hosts, results): - print(f"== {host}") - print("\n".join(out)) + for h in hosts: + print(f"== {h}") + print("\n".join(out[h])) print() - failures += device_failures + failures += fails[h] print("RESULT:", "all passed" if not failures else f"{failures} failed") sys.exit(1 if failures else 0) diff --git a/web/app.js b/web/app.js index beaef0a..a1a276d 100644 --- a/web/app.js +++ b/web/app.js @@ -17,31 +17,88 @@ return direct(path, opts); } - // This device's own API - async function direct(path, opts) { - const r = await fetch(path, opts); - const j = await r.json().catch(() => ({})); - if (!r.ok) throw new Error(j.error || r.statusText); - return j; + // The page talks to this device over one WebSocket (/ws). Replies come back in the order the + // requests were sent, so each reply belongs to the oldest request still waiting. + const WS_TIMEOUT_MS = 15000; + let sock = null; + const waiting = []; // {text, resolve, reject}, oldest first + let watchdog = null; + + function kick() { + clearTimeout(watchdog); + watchdog = waiting.length ? setTimeout(() => closeSock(new Error('The device did not answer.')), WS_TIMEOUT_MS) : null; } - // Another device: this driver makes the call (POST /api/relay), so the browser only talks to this one. - async function relayTo(host, path, opts) { - const method = (opts && opts.method) || 'GET'; - const body = opts && typeof opts.body === 'string' ? opts.body : ''; - const r = await fetch('/api/relay', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ host, method, path, body }), + function closeSock(err) { + const s = sock; + sock = null; + clearTimeout(watchdog); + watchdog = null; + if (s) { + s.onopen = s.onmessage = s.onclose = s.onerror = null; + try { s.close(); } catch (_) { /* already closed */ } + } + while (waiting.length) waiting.shift().reject(err); + } + + function openSock() { + const s = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws'); + sock = s; + s.onopen = () => { + if (sock === s) for (const w of waiting) s.send(w.text); + }; + s.onmessage = (ev) => { + const w = waiting.shift(); + kick(); + if (!w) return; + try { w.resolve(JSON.parse(ev.data)); } catch (e) { w.reject(e); } + }; + s.onclose = () => { if (sock === s) closeSock(new Error('Lost the connection to the device.')); }; + s.onerror = () => {}; // onclose follows + } + + // One request over the WebSocket; resolves to the reply envelope {status, body}. + function wsCall(msg) { + return new Promise((resolve, reject) => { + const text = JSON.stringify(msg); + waiting.push({ text, resolve, reject }); + if (!sock) openSock(); + else if (sock.readyState === WebSocket.OPEN) sock.send(text); + kick(); }); - const env = await r.json().catch(() => ({})); - if (!r.ok) throw new Error(env.error || r.statusText); + } + + // An API call. host is another driver's address; it is left out for this device. + async function wsApi(method, path, body, host) { + const msg = { method, path, body }; + if (host) msg.host = host; + const env = await wsCall(msg); let j = {}; try { j = JSON.parse(env.body || '{}'); } catch (_) { j = {}; } if (env.status < 200 || env.status >= 300) throw new Error(j.error || 'HTTP ' + env.status); return j; } + // This device's own API, over the WebSocket. Firmware upload and info stay on plain HTTP (/ota). + async function direct(path, opts) { + if (path.startsWith('/ota')) { + const r = await fetch(path, opts); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error || r.statusText); + return j; + } + const method = (opts && opts.method) || 'GET'; + const body = opts && typeof opts.body === 'string' ? opts.body : ''; + return wsApi(method, path, body); + } + + // Another device: this driver makes the call, so the browser only talks to this one. + async function relayTo(host, path, opts) { + const method = (opts && opts.method) || 'GET'; + const body = opts && typeof opts.body === 'string' ? opts.body : ''; + return wsApi(method, path, body, host); + } + // All devices: the same change goes to every device at once. Reads come from this device. async function fanOut(path, opts) { const method = (opts && opts.method) || 'GET'; @@ -513,22 +570,30 @@ status.patterns.forEach((name) => $('pattern').add(new Option(name, name))); } + // One brightness slider. With one device selected it sets that device's own level. + // With All devices selected it is a master scale: each device's level is multiplied by it, so + // the devices keep their own levels relative to each other. + const brightKey = () => (base === ALL ? 'master' : 'brightness'); let globalTimer; $('globalBright').addEventListener('input', () => { $('globalOut').textContent = $('globalBright').value; clearTimeout(globalTimer); globalTimer = setTimeout(() => { - post('/api/brightness', { brightness: Number($('globalBright').value) }).catch((e) => { + post('/api/brightness', { [brightKey()]: Number($('globalBright').value) }).catch((e) => { $('status').textContent = e.message; }); }, 150); }); async function loadStatus() { + const host = base; const s = await api('/api/status'); + // Another device may have been selected while this answer was on its way: drop it + if (host !== base) return; if (document.activeElement !== $('globalBright')) { - $('globalBright').value = s.global_brightness; - $('globalOut').textContent = s.global_brightness; + const level = base === ALL ? s.master_brightness : s.global_brightness; + $('globalBright').value = level; + $('globalOut').textContent = level; } $('apName').textContent = s.ap_ssid; $('staState').textContent = s.sta_connected ? 'connected (' + s.sta_ip + ')' : 'not connected'; @@ -822,6 +887,8 @@ $('sMask').value = n.netmask; $('sGw').value = n.gateway; $('sDns').value = n.dns; + $('apOn').checked = n.ap_enabled !== false; + $('ddpOn').checked = n.ddp_enabled !== false; updateStaticFields(); } @@ -873,6 +940,8 @@ netmask: $('sMask').value.trim(), gateway: $('sGw').value.trim(), dns: $('sDns').value.trim(), + ap_enabled: $('apOn').checked, + ddp_enabled: $('ddpOn').checked, }; $('netMsg').textContent = 'Saving…'; try { @@ -933,9 +1002,7 @@ async function discoverDevices() { try { // Both asked of this device, which is the one the page came from - const [dr, sr] = await Promise.all([fetch('/api/devices'), fetch('/api/status')]); - const j = await dr.json(); - const st = await sr.json(); + const [j, st] = await Promise.all([direct('/api/devices'), direct('/api/status')]); const next = Array.isArray(j.devices) ? j.devices.filter((d) => d && d.host) : []; const name = typeof st.hostname === 'string' ? st.hostname : ''; if (JSON.stringify(next) !== JSON.stringify(found) || name !== localName) { @@ -1096,6 +1163,19 @@ setMenu(false); }); }); + + // Settings is split into sections: one visible at a time + function showSub(id) { + document.querySelectorAll('.subtab').forEach((b) => { + const on = b.dataset.sub === id; + b.classList.toggle('active', on); + b.setAttribute('aria-selected', String(on)); + }); + document.querySelectorAll('.subpage').forEach((p) => { p.hidden = p.dataset.sub !== id; }); + } + document.querySelectorAll('.subtab').forEach((btn) => { + btn.addEventListener('click', () => showSub(btn.dataset.sub)); + }); $('modeToggle').addEventListener('click', () => setMode(isEditMode() ? 'run' : 'edit')); $('newPreset').addEventListener('click', () => setMenu(false)); applyMode(); diff --git a/web/index.html b/web/index.html index 8d7d5bb..456c27e 100644 --- a/web/index.html +++ b/web/index.html @@ -35,6 +35,15 @@ diff --git a/web/style.css b/web/style.css index 77baf48..ad6a09c 100644 --- a/web/style.css +++ b/web/style.css @@ -304,6 +304,28 @@ button.tab-action { button.tab-action:hover { background-color: #7b6bdb; } +/* Settings sections: a second row of tabs inside Settings */ +.subnav { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + margin: 1rem 0 0.5rem; +} + +button.subtab { + padding: 0.35rem 0.75rem; + border: none; + border-radius: 4px; + background-color: #3a3a3a; + color: white; + font-size: 0.85rem; + font-weight: 500; + cursor: pointer; +} + +button.subtab:hover { background-color: #4a4a4a; } +button.subtab.active { background-color: #6a5acd; } + .preset-tile-name { font-weight: 600; font-size: 0.9rem; @@ -517,6 +539,7 @@ button.menu-toggle { /* Bigger touch targets */ button, button.tab, + button.subtab, button.tab-action, button.preset-edit { min-height: 2.75rem;