diff --git a/.flake8 b/.flake8 index 6d0fcc89b..e19d2cfb5 100644 --- a/.flake8 +++ b/.flake8 @@ -136,6 +136,5 @@ show_source = True statistics = True -per-file-ignores = - # Sphinx conf.py files use star imports to setup config variables - docs/conf_common.py: F405 +exclude = + components/asio/docs/conf_common.py diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..9f3cb8b08 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Formating according pre-commit hooks +3e1c3cc647b6f6d4da20b3ab979879f60229bfee diff --git a/.github/workflows/target-test.yml b/.github/workflows/target-test.yml index c0c53e7f7..106dae7b3 100644 --- a/.github/workflows/target-test.yml +++ b/.github/workflows/target-test.yml @@ -8,7 +8,7 @@ jobs: matrix: idf_ver: ["latest", "release-v4.1", "release-v4.2", "release-v4.3", "release-v4.4"] example: ["pppos_client", "modem_console", "ap_to_pppos", "simple_cmux_client"] - idf_target: ["esp32"] + idf_target: ["esp32"] exclude: - idf_ver: "release-v4.1" example: modem_console @@ -57,30 +57,30 @@ jobs: cat sdkconfig.ci.usb >> sdkconfig.defaults idf.py build - build_mdns: - strategy: - matrix: - idf_ver: ["latest"] + build_mdns: + strategy: + matrix: + idf_ver: ["latest"] idf_target: ["esp32", "esp32s2", "esp32c3"] config: ["eth_custom_netif", "eth_def", "eth_no_ipv6", "eth_socket"] - runs-on: ubuntu-20.04 - container: espressif/idf:${{ matrix.idf_ver }} - steps: - - name: Checkout esp-protocols - uses: actions/checkout@v3 - with: - submodules: recursive - - name: Build ${{ matrix.example }} with IDF-${{ matrix.idf_ver }} for ${{ matrix.idf_target }} for ${{ matrix.config }} - env: - IDF_TARGET: ${{ matrix.idf_target }} - shell: bash + runs-on: ubuntu-20.04 + container: espressif/idf:${{ matrix.idf_ver }} + steps: + - name: Checkout esp-protocols + uses: actions/checkout@v3 + with: + submodules: recursive + - name: Build ${{ matrix.example }} with IDF-${{ matrix.idf_ver }} for ${{ matrix.idf_target }} for ${{ matrix.config }} + env: + IDF_TARGET: ${{ matrix.idf_target }} + shell: bash working-directory: components/mdns/examples/ - run: | - . ${IDF_PATH}/export.sh + run: | + . ${IDF_PATH}/export.sh rm -rf sdkconfig sdkconfig.defaults build build_${{ matrix.config }} - cat sdkconfig.ci.${{ matrix.config }} >> sdkconfig.defaults - idf.py set-target ${{ matrix.idf_target }} - idf.py build + cat sdkconfig.ci.${{ matrix.config }} >> sdkconfig.defaults + idf.py set-target ${{ matrix.idf_target }} + idf.py build mv build build_${{ matrix.config }} - name: Merge binaries with IDF-${{ matrix.idf_ver }} for ${{ matrix.config }} working-directory: components/mdns/examples @@ -118,7 +118,7 @@ jobs: - name: Checkout esp-protocols uses: actions/checkout@v3 with: - submodules: recursive + submodules: recursive - name: Build ${{ matrix.example }} with IDF-${{ matrix.idf_ver }} for ${{ matrix.idf_target }} working-directory: components/asio/examples/${{ matrix.example }} env: @@ -234,9 +234,9 @@ jobs: path: components/esp_websocket_client/examples/*.xml run-target-mdns: - strategy: - matrix: - idf_ver: ["latest"] + strategy: + matrix: + idf_ver: ["latest"] idf_target: ["esp32"] config: ["eth_custom_netif", "eth_def", "eth_no_ipv6", "eth_socket"] name: Run mDNS Example Test on target @@ -267,7 +267,7 @@ jobs: run: | rm -rf build mv build_${{ matrix.config }} build - cat sdkconfig.ci.${{ matrix.config }} >> sdkconfig.defaults + cat sdkconfig.ci.${{ matrix.config }} >> sdkconfig.defaults python -m pytest --log-cli-level DEBUG --junit-xml=./examples_results_${{ matrix.idf_target }}_${{ matrix.idf_ver }}_${{ matrix.config }}.xml --target=${{ matrix.idf_target }} rm -rf build sdkconfig.defaults - uses: actions/upload-artifact@v2 @@ -277,9 +277,9 @@ jobs: path: components/mdns/examples/*.xml run-target-asio: - strategy: - matrix: - idf_ver: ["latest"] + strategy: + matrix: + idf_ver: ["latest"] idf_target: ["esp32"] example: ["asio_chat", "tcp_echo_server", "udp_echo_server", "ssl_client_server"] name: Run ASIO Example Test on target diff --git a/.mypy.ini b/.mypy.ini new file mode 100644 index 000000000..e4f451ca2 --- /dev/null +++ b/.mypy.ini @@ -0,0 +1,26 @@ +[mypy] + +# Specifies the Python version used to parse and check the target program +python_version = 3.9 + +# Disallows defining functions without type annotations or with incomplete type annotations +# True => enforce type annotation in all function definitions +disallow_untyped_defs = True + +# Shows a warning when returning a value with type Any from a function declared with a non- Any return type +warn_return_any = True + +# Shows errors for missing return statements on some execution paths +warn_no_return = True + +# Suppress error messages about imports that cannot be resolved +# True => ignore all import errors +ignore_missing_imports = True + +# Disallows defining functions with incomplete type annotations +disallow_incomplete_defs = False + +# Directs what to do with imports when the imported module is found as a .py file and not part of the files, +# modules and packages provided on the command line. +# SKIP -> mypy checks only single file, not included imports +follow_imports = skip diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a667388cf..1934ced13 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,6 +20,10 @@ repos: rev: v0.981 hooks: - id: mypy + exclude: > + (?x)^( + .*.py + )$ - repo: https://github.com/myint/unify rev: v0.5 hooks: diff --git a/ci/check_copyright_config.yaml b/ci/check_copyright_config.yaml index e91974fc9..fe99e2ac1 100644 --- a/ci/check_copyright_config.yaml +++ b/ci/check_copyright_config.yaml @@ -46,9 +46,19 @@ asio_component: - Apache-2.0 - BSL-1.0 +slim_modem_examples: + include: + - 'examples/esp_netif/slip_custom_netif/**' + allowed_licenses: + - Apache-2.0 + - Unlicense + - CC0-1.0 + ignore: perform_check: no include: - 'components/**/docs/**' - 'components/esp_modem/port/linux/**' - - 'components/asio/examples/asio_chat/main/*' + - 'components/asio/examples/**' + - 'components/mdns/**/esp_system_protocols_linux/**' + - 'common_components/protocol_examples_common/**' diff --git a/common_components/protocol_examples_common/addr_from_stdin.c b/common_components/protocol_examples_common/addr_from_stdin.c index c907ffd96..0ea452b59 100644 --- a/common_components/protocol_examples_common/addr_from_stdin.c +++ b/common_components/protocol_examples_common/addr_from_stdin.c @@ -26,7 +26,7 @@ esp_err_t get_addr_from_stdin(int port, int sock_type, int *ip_protocol, int *ad do { fgets(host_ip, HOST_IP_SIZE, stdin); len = strlen(host_ip); - } while (len<=1 && host_ip[0] == '\n'); + } while (len <= 1 && host_ip[0] == '\n'); host_ip[len - 1] = '\0'; struct addrinfo hints, *addr_list, *cur; @@ -36,16 +36,16 @@ esp_err_t get_addr_from_stdin(int port, int sock_type, int *ip_protocol, int *ad hints.ai_family = AF_UNSPEC; hints.ai_socktype = sock_type; hints.ai_protocol = IPPROTO_TCP; - if( getaddrinfo( host_ip, NULL, &hints, &addr_list ) != 0 ) { + if ( getaddrinfo( host_ip, NULL, &hints, &addr_list ) != 0 ) { return ESP_FAIL; } - for( cur = addr_list; cur != NULL; cur = cur->ai_next ) { + for ( cur = addr_list; cur != NULL; cur = cur->ai_next ) { memcpy(dest_addr, cur->ai_addr, sizeof(*dest_addr)); if (cur->ai_family == AF_INET) { *ip_protocol = IPPROTO_IP; *addr_family = AF_INET; // add port number and return on first IPv4 match - ((struct sockaddr_in*)dest_addr)->sin_port = htons(port); + ((struct sockaddr_in *)dest_addr)->sin_port = htons(port); freeaddrinfo( addr_list ); return ESP_OK; @@ -55,8 +55,8 @@ esp_err_t get_addr_from_stdin(int port, int sock_type, int *ip_protocol, int *ad *ip_protocol = IPPROTO_IPV6; *addr_family = AF_INET6; // add port and interface number and return on first IPv6 match - ((struct sockaddr_in6*)dest_addr)->sin6_port = htons(port); - ((struct sockaddr_in6*)dest_addr)->sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE); + ((struct sockaddr_in6 *)dest_addr)->sin6_port = htons(port); + ((struct sockaddr_in6 *)dest_addr)->sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE); freeaddrinfo( addr_list ); return ESP_OK; } diff --git a/common_components/protocol_examples_common/connect.c b/common_components/protocol_examples_common/connect.c index 08cc348d1..3fae508bd 100644 --- a/common_components/protocol_examples_common/connect.c +++ b/common_components/protocol_examples_common/connect.c @@ -1,10 +1,11 @@ -/* Common functions for protocol examples, to establish Wi-Fi or Ethernet connection. +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Common functions for protocol examples, to establish Wi-Fi or Ethernet connection. */ #include diff --git a/common_components/protocol_examples_common/include/addr_from_stdin.h b/common_components/protocol_examples_common/include/addr_from_stdin.h index 9a059c149..823f98883 100644 --- a/common_components/protocol_examples_common/include/addr_from_stdin.h +++ b/common_components/protocol_examples_common/include/addr_from_stdin.h @@ -1,13 +1,14 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + /* Common utilities for socket address input interface: The API get_addr_from_stdin() is mainly used by socket client examples which read IP address from stdin (if configured). This option is typically used in the CI, but could be enabled in the project configuration. In that case this component is used to receive a string that is evaluated and processed to output socket structures to open a connectio - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. */ #pragma once diff --git a/common_components/protocol_examples_common/include/protocol_examples_common.h b/common_components/protocol_examples_common/include/protocol_examples_common.h index d43e94e0d..44506264d 100644 --- a/common_components/protocol_examples_common/include/protocol_examples_common.h +++ b/common_components/protocol_examples_common/include/protocol_examples_common.h @@ -1,10 +1,11 @@ -/* Common functions for protocol examples, to establish Wi-Fi or Ethernet connection. +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Common functions for protocol examples, to establish Wi-Fi or Ethernet connection. */ #pragma once diff --git a/common_components/protocol_examples_common/stdin_out.c b/common_components/protocol_examples_common/stdin_out.c index b57e0e715..e3c3aa151 100644 --- a/common_components/protocol_examples_common/stdin_out.c +++ b/common_components/protocol_examples_common/stdin_out.c @@ -1,10 +1,11 @@ -/* Common functions for protocol examples, to configure stdin and stdout. +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Common functions for protocol examples, to configure stdin and stdout. */ #include "protocol_examples_common.h" @@ -19,7 +20,7 @@ esp_err_t example_configure_stdin_stdout(void) setvbuf(stdin, NULL, _IONBF, 0); /* Install UART driver for interrupt-driven reads and writes */ ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_ESP_CONSOLE_UART_NUM, - 256, 0, 0, NULL, 0) ); + 256, 0, 0, NULL, 0) ); /* Tell VFS to use UART driver */ esp_vfs_dev_uart_use_driver(CONFIG_ESP_CONSOLE_UART_NUM); esp_vfs_dev_uart_port_set_rx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CR); diff --git a/components/asio/docs/conf_common.py b/components/asio/docs/conf_common.py index 10d1e997e..6202f9696 100644 --- a/components/asio/docs/conf_common.py +++ b/components/asio/docs/conf_common.py @@ -1,10 +1,11 @@ from esp_docs.conf_docs import * # noqa: F403,F401 -extensions += ['sphinx_copybutton', - # Needed as a trigger for running doxygen - 'esp_docs.esp_extensions.dummy_build_system', - 'esp_docs.esp_extensions.run_doxygen', - ] +extensions += [ + 'sphinx_copybutton', + # Needed as a trigger for running doxygen + 'esp_docs.esp_extensions.dummy_build_system', + 'esp_docs.esp_extensions.run_doxygen', +] # link roles config github_repo = 'espressif/esp-protocols' @@ -14,7 +15,7 @@ html_context['github_user'] = 'espressif' html_context['github_repo'] = 'esp-protocols' # Extra options required by sphinx_idf_theme -project_slug = 'esp-idf' # >=5.0 +project_slug = 'esp-idf' # >=5.0 versions_url = 'https://github.com/espressif/esp-protocols/docs/docs_versions.js' idf_targets = ['esp32'] diff --git a/components/asio/docs/generate_docs b/components/asio/docs/generate_docs index e60c1a8f9..def507c5e 100755 --- a/components/asio/docs/generate_docs +++ b/components/asio/docs/generate_docs @@ -13,7 +13,7 @@ window.onload =(function() { mySpan.value = 'latest'; mySpan.setAttribute('disabled', true); myAnchor.parentNode.replaceChild(mySpan, myAnchor); - + var myAnchor = document.getElementById('target-select'); var mySpan = document.createElement('input'); mySpan.setAttribute('type', 'text'); @@ -24,4 +24,3 @@ window.onload =(function() { })(); " >> html/index.html - diff --git a/components/asio/docs/zh_CN/index.rst b/components/asio/docs/zh_CN/index.rst index d1afa231e..7f23ce3fd 100644 --- a/components/asio/docs/zh_CN/index.rst +++ b/components/asio/docs/zh_CN/index.rst @@ -1 +1 @@ -.. include:: ../../../en/api-reference/protocols/asio.rst \ No newline at end of file +.. include:: ../../../en/api-reference/protocols/asio.rst diff --git a/components/asio/examples/asio_chat/main/asio_chat.cpp b/components/asio/examples/asio_chat/main/asio_chat.cpp index be2329d15..de3188a71 100644 --- a/components/asio/examples/asio_chat/main/asio_chat.cpp +++ b/components/asio/examples/asio_chat/main/asio_chat.cpp @@ -53,14 +53,15 @@ void start_client(void) #ifdef CONFIG_EXAMPLE_CHAT_SERVER std::lock_guard guard(server_ready); #endif - std::thread t([&io_context]() { try { - io_context.run(); - } catch (const std::exception &e) { - ESP_LOGE(TAG, "Exception occured during client thread execution %s", e.what()); - } - catch (...) { - ESP_LOGE(TAG, "Unknown exception"); - }}); + std::thread t([&io_context]() { + try { + io_context.run(); + } catch (const std::exception &e) { + ESP_LOGE(TAG, "Exception occured during client thread execution %s", e.what()); + } catch (...) { + ESP_LOGE(TAG, "Unknown exception"); + } + }); do { ESP_LOGI(TAG, "CLIENT: Waiting for input"); get_string(line, sizeof(line)); @@ -95,14 +96,14 @@ extern "C" void app_main(void) asio::io_context io_context; chat_server server(io_context, tcp::endpoint(tcp::v4(), std::atoi(CONFIG_EXAMPLE_CHAT_SERVER_BIND_PORT))); std::thread t = std::thread([&io_context]() { // Chat server starting here - try { - io_context.run(); - } catch (const std::exception &e) { - ESP_LOGE(TAG, "Exception occured during server thread execution %s", e.what()); - } - catch (...) { - ESP_LOGE(TAG, "Unknown exception"); - }});; + try { + io_context.run(); + } catch (const std::exception &e) { + ESP_LOGE(TAG, "Exception occured during server thread execution %s", e.what()); + } catch (...) { + ESP_LOGE(TAG, "Unknown exception"); + } + });; #endif #ifdef CONFIG_EXAMPLE_CHAT_CLIENT start_client(); diff --git a/components/asio/examples/asio_chat/main/chat_message.hpp b/components/asio/examples/asio_chat/main/chat_message.hpp index a6ffc83b8..bb2650b9b 100644 --- a/components/asio/examples/asio_chat/main/chat_message.hpp +++ b/components/asio/examples/asio_chat/main/chat_message.hpp @@ -15,77 +15,76 @@ #include #include -class chat_message -{ +class chat_message { public: - static constexpr std::size_t header_length = 4; - static constexpr std::size_t max_body_length = 512; + static constexpr std::size_t header_length = 4; + static constexpr std::size_t max_body_length = 512; - chat_message() - : body_length_(0) - { - } - - const char* data() const - { - return data_; - } - - char* data() - { - return data_; - } - - std::size_t length() const - { - return header_length + body_length_; - } - - const char* body() const - { - return data_ + header_length; - } - - char* body() - { - return data_ + header_length; - } - - std::size_t body_length() const - { - return body_length_; - } - - void body_length(std::size_t new_length) - { - body_length_ = new_length; - if (body_length_ > max_body_length) - body_length_ = max_body_length; - } - - bool decode_header() - { - char header[header_length + 1] = ""; - std::strncat(header, data_, header_length); - body_length_ = std::atoi(header); - if (body_length_ > max_body_length) + chat_message() + : body_length_(0) { - body_length_ = 0; - return false; } - return true; - } - void encode_header() - { - char header[header_length + 1] = ""; - std::sprintf(header, "%4d", static_cast(body_length_)); - std::memcpy(data_, header, header_length); - } + const char *data() const + { + return data_; + } + + char *data() + { + return data_; + } + + std::size_t length() const + { + return header_length + body_length_; + } + + const char *body() const + { + return data_ + header_length; + } + + char *body() + { + return data_ + header_length; + } + + std::size_t body_length() const + { + return body_length_; + } + + void body_length(std::size_t new_length) + { + body_length_ = new_length; + if (body_length_ > max_body_length) { + body_length_ = max_body_length; + } + } + + bool decode_header() + { + char header[header_length + 1] = ""; + std::strncat(header, data_, header_length); + body_length_ = std::atoi(header); + if (body_length_ > max_body_length) { + body_length_ = 0; + return false; + } + return true; + } + + void encode_header() + { + char header[header_length + 1] = ""; + std::sprintf(header, "%4d", static_cast(body_length_)); + std::memcpy(data_, header, header_length); + } private: - char data_[header_length + max_body_length]; - std::size_t body_length_; + char data_[header_length + max_body_length]; + std::size_t body_length_; }; #endif // CHAT_MESSAGE_HPP diff --git a/components/asio/examples/asio_chat/main/client.hpp b/components/asio/examples/asio_chat/main/client.hpp index 09baece98..ee45a7ab4 100644 --- a/components/asio/examples/asio_chat/main/client.hpp +++ b/components/asio/examples/asio_chat/main/client.hpp @@ -17,107 +17,91 @@ typedef std::deque chat_message_queue; -class chat_client -{ +class chat_client { public: - chat_client(asio::io_context& io_context, - const asio::ip::tcp::resolver::results_type& endpoints) - : io_context_(io_context), - socket_(io_context) - { - do_connect(endpoints); - } + chat_client(asio::io_context &io_context, + const asio::ip::tcp::resolver::results_type &endpoints) + : io_context_(io_context), + socket_(io_context) + { + do_connect(endpoints); + } - void write(const chat_message& msg) - { - asio::post(io_context_, - [this, msg]() - { - bool write_in_progress = !write_msgs_.empty(); - write_msgs_.push_back(msg); - if (!write_in_progress) - { - do_write(); - } + void write(const chat_message &msg) + { + asio::post(io_context_, + [this, msg]() { + bool write_in_progress = !write_msgs_.empty(); + write_msgs_.push_back(msg); + if (!write_in_progress) { + do_write(); + } }); - } + } - void close() - { - asio::post(io_context_, [this]() { socket_.close(); }); - } + void close() + { + asio::post(io_context_, [this]() { + socket_.close(); + }); + } private: -void do_connect(const asio::ip::tcp::resolver::results_type& endpoints) + void do_connect(const asio::ip::tcp::resolver::results_type &endpoints) { - asio::async_connect(socket_, endpoints, - [this](std::error_code ec, asio::ip::tcp::endpoint) - { - if (!ec) - { - do_read_header(); + asio::async_connect(socket_, endpoints, + [this](std::error_code ec, asio::ip::tcp::endpoint) { + if (!ec) { + do_read_header(); } - }); + }); } void do_read_header() { - asio::async_read(socket_, - asio::buffer(read_msg_.data(), chat_message::header_length), - [this](std::error_code ec, std::size_t /*length*/) - { - if (!ec && read_msg_.decode_header()) - { - do_read_body(); + asio::async_read(socket_, + asio::buffer(read_msg_.data(), chat_message::header_length), + [this](std::error_code ec, std::size_t /*length*/) { + if (!ec && read_msg_.decode_header()) { + do_read_body(); + } else { + socket_.close(); } - else - { - socket_.close(); - } - }); + }); } void do_read_body() { - asio::async_read(socket_, - asio::buffer(read_msg_.body(), read_msg_.body_length()), - [this](std::error_code ec, std::size_t /*length*/) - { - if (!ec) - { - do_read_header(); + asio::async_read(socket_, + asio::buffer(read_msg_.body(), read_msg_.body_length()), + [this](std::error_code ec, std::size_t /*length*/) { + if (!ec) { + do_read_header(); + } else { + socket_.close(); } - else - { - socket_.close(); - } - }); + }); } - void do_write() - { - asio::async_write(socket_, - asio::buffer(write_msgs_.front().data(), - write_msgs_.front().length()), - [this](std::error_code ec, std::size_t /*length*/) - { - if (!ec) - { - write_msgs_.pop_front(); - if (!write_msgs_.empty()) - { - do_write(); - } + void do_write() + { + asio::async_write(socket_, + asio::buffer(write_msgs_.front().data(), + write_msgs_.front().length()), + [this](std::error_code ec, std::size_t /*length*/) { + if (!ec) { + write_msgs_.pop_front(); + if (!write_msgs_.empty()) { + do_write(); + } + } else { + socket_.close(); } - else - { - socket_.close(); - } - }); - } + }); + } private: - asio::io_context& io_context_; + asio::io_context &io_context_; asio::ip::tcp::socket socket_; chat_message read_msg_; chat_message_queue write_msgs_; diff --git a/components/asio/examples/asio_chat/main/server.hpp b/components/asio/examples/asio_chat/main/server.hpp index 450e255a4..971c19d2f 100644 --- a/components/asio/examples/asio_chat/main/server.hpp +++ b/components/asio/examples/asio_chat/main/server.hpp @@ -27,176 +27,159 @@ extern std::mutex server_ready; //---------------------------------------------------------------------- -class chat_participant -{ +class chat_participant { public: - virtual ~chat_participant() {} - virtual void deliver(const chat_message& msg) = 0; + virtual ~chat_participant() {} + virtual void deliver(const chat_message &msg) = 0; }; typedef std::shared_ptr chat_participant_ptr; //---------------------------------------------------------------------- -class chat_room -{ +class chat_room { public: - void join(chat_participant_ptr participant) - { - participants_.insert(participant); - for (auto msg: recent_msgs_) - participant->deliver(msg); - } + void join(chat_participant_ptr participant) + { + participants_.insert(participant); + for (auto msg : recent_msgs_) { + participant->deliver(msg); + } + } - void leave(chat_participant_ptr participant) - { - participants_.erase(participant); - } + void leave(chat_participant_ptr participant) + { + participants_.erase(participant); + } - void deliver(const chat_message& msg) - { - recent_msgs_.push_back(msg); - while (recent_msgs_.size() > max_recent_msgs) - recent_msgs_.pop_front(); + void deliver(const chat_message &msg) + { + recent_msgs_.push_back(msg); + while (recent_msgs_.size() > max_recent_msgs) { + recent_msgs_.pop_front(); + } - for (auto participant: participants_) - participant->deliver(msg); - } + for (auto participant : participants_) { + participant->deliver(msg); + } + } private: - std::set participants_; - enum { max_recent_msgs = 100 }; - chat_message_queue recent_msgs_; + std::set participants_; + enum { max_recent_msgs = 100 }; + chat_message_queue recent_msgs_; }; //---------------------------------------------------------------------- class chat_session - : public chat_participant, - public std::enable_shared_from_this -{ + : public chat_participant, + public std::enable_shared_from_this { public: - chat_session(asio::ip::tcp::socket socket, chat_room& room) - : socket_(std::move(socket)), - room_(room) - { - } - - void start() - { - room_.join(shared_from_this()); - do_read_header(); - } - - void deliver(const chat_message& msg) - { - bool write_in_progress = !write_msgs_.empty(); - write_msgs_.push_back(msg); - if (!write_in_progress) + chat_session(asio::ip::tcp::socket socket, chat_room &room) + : socket_(std::move(socket)), + room_(room) { - do_write(); } - } + + void start() + { + room_.join(shared_from_this()); + do_read_header(); + } + + void deliver(const chat_message &msg) + { + bool write_in_progress = !write_msgs_.empty(); + write_msgs_.push_back(msg); + if (!write_in_progress) { + do_write(); + } + } private: - void do_read_header() - { - auto self(shared_from_this()); - asio::async_read(socket_, - asio::buffer(read_msg_.data(), chat_message::header_length), - [this, self](std::error_code ec, std::size_t /*length*/) - { - if (!ec && read_msg_.decode_header()) - { - do_read_body(); - } - else - { - room_.leave(shared_from_this()); - } - }); - } + void do_read_header() + { + auto self(shared_from_this()); + asio::async_read(socket_, + asio::buffer(read_msg_.data(), chat_message::header_length), + [this, self](std::error_code ec, std::size_t /*length*/) { + if (!ec && read_msg_.decode_header()) { + do_read_body(); + } else { + room_.leave(shared_from_this()); + } + }); + } - void do_read_body() - { - auto self(shared_from_this()); - asio::async_read(socket_, - asio::buffer(read_msg_.body(), read_msg_.body_length()), - [this, self](std::error_code ec, std::size_t /*length*/) - { - if (!ec) - { - ESP_LOGD("asio-chat:", "%s", read_msg_.body()); - room_.deliver(read_msg_); - do_read_header(); - } - else - { - room_.leave(shared_from_this()); - } - }); - } + void do_read_body() + { + auto self(shared_from_this()); + asio::async_read(socket_, + asio::buffer(read_msg_.body(), read_msg_.body_length()), + [this, self](std::error_code ec, std::size_t /*length*/) { + if (!ec) { + ESP_LOGD("asio-chat:", "%s", read_msg_.body()); + room_.deliver(read_msg_); + do_read_header(); + } else { + room_.leave(shared_from_this()); + } + }); + } - void do_write() - { - auto self(shared_from_this()); - asio::async_write(socket_, - asio::buffer(write_msgs_.front().data(), - write_msgs_.front().length()), - [this, self](std::error_code ec, std::size_t /*length*/) - { - if (!ec) - { - write_msgs_.pop_front(); - if (!write_msgs_.empty()) - { - do_write(); - } - } - else - { - room_.leave(shared_from_this()); - } - }); - } + void do_write() + { + auto self(shared_from_this()); + asio::async_write(socket_, + asio::buffer(write_msgs_.front().data(), + write_msgs_.front().length()), + [this, self](std::error_code ec, std::size_t /*length*/) { + if (!ec) { + write_msgs_.pop_front(); + if (!write_msgs_.empty()) { + do_write(); + } + } else { + room_.leave(shared_from_this()); + } + }); + } - asio::ip::tcp::socket socket_; - chat_room& room_; - chat_message read_msg_; - chat_message_queue write_msgs_; - }; + asio::ip::tcp::socket socket_; + chat_room &room_; + chat_message read_msg_; + chat_message_queue write_msgs_; +}; //---------------------------------------------------------------------- -class chat_server -{ +class chat_server { public: - chat_server(asio::io_context& io_context, - const asio::ip::tcp::endpoint& endpoint) - : acceptor_(io_context, endpoint) - { - do_accept(); - } + chat_server(asio::io_context &io_context, + const asio::ip::tcp::endpoint &endpoint) + : acceptor_(io_context, endpoint) + { + do_accept(); + } private: - void do_accept() - { - std::lock_guard guard(server_ready); - acceptor_.async_accept( - [this](std::error_code ec, asio::ip::tcp::socket socket) - { - if (!ec) - { - std::make_shared(std::move(socket), room_)->start(); - } + void do_accept() + { + std::lock_guard guard(server_ready); + acceptor_.async_accept( + [this](std::error_code ec, asio::ip::tcp::socket socket) { + if (!ec) { + std::make_shared(std::move(socket), room_)->start(); + } - do_accept(); - }); - } + do_accept(); + }); + } - asio::ip::tcp::acceptor acceptor_; - chat_room room_; + asio::ip::tcp::acceptor acceptor_; + chat_room room_; }; #endif // CHAT_SERVER_HPP diff --git a/components/asio/examples/asio_chat/pytest_example_test.py b/components/asio/examples/asio_chat/pytest_asio_chat_test.py similarity index 54% rename from components/asio/examples/asio_chat/pytest_example_test.py rename to components/asio/examples/asio_chat/pytest_asio_chat_test.py index fc354226f..d1893ff20 100644 --- a/components/asio/examples/asio_chat/pytest_example_test.py +++ b/components/asio/examples/asio_chat/pytest_asio_chat_test.py @@ -1,14 +1,9 @@ -# This example code is in the Public Domain (or CC0 licensed, at your option.) - -# Unless required by applicable law or agreed to in writing, this -# software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -# CONDITIONS OF ANY KIND, either express or implied. +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 # -*- coding: utf-8 -*- import re -import pytest -from pytest_embedded import Dut def test_examples_asio_chat(dut): diff --git a/components/asio/examples/async_request/README.md b/components/asio/examples/async_request/README.md index c2b114511..3a9744978 100644 --- a/components/asio/examples/async_request/README.md +++ b/components/asio/examples/async_request/README.md @@ -9,7 +9,7 @@ The application aims to show how to compose async operations using ASIO to build # Configure and Building example -This example doesn't require any configuration, just build it with +This example doesn't require any configuration, just build it with ``` idf.py build @@ -17,12 +17,12 @@ idf.py build # Async operations composition and automatic lifetime control -On this example we compose the operation by starting the next step in the chain inside the completion handler of the -previous operation. Also we pass the `Connection` class itself as the parameter of its final handler to be owned by +On this example we compose the operation by starting the next step in the chain inside the completion handler of the +previous operation. Also we pass the `Connection` class itself as the parameter of its final handler to be owned by the following operation. This is possible due to the control of lifetime by the usage of `std::shared_ptr`. -The control of lifetime of the class, done by `std::shared_ptr` usage, guarantee that the data will be available for -async operations until it's not needed any more. This makes necessary that all of the async operation class must start +The control of lifetime of the class, done by `std::shared_ptr` usage, guarantee that the data will be available for +async operations until it's not needed any more. This makes necessary that all of the async operation class must start its lifetime as a `std::shared_ptr` due to the usage of `std::enable_shared_from_this`. @@ -48,5 +48,5 @@ its lifetime as a `std::shared_ptr` due to the usage of `std::enable_shared_from └────►Completion Handler() -The previous diagram shows the process and the life span of each of the tasks in this examples. At each stage the +The previous diagram shows the process and the life span of each of the tasks in this examples. At each stage the object responsible for the last action inject itself to the completion handler of the next stage for reuse. diff --git a/components/asio/examples/socks4/README.md b/components/asio/examples/socks4/README.md index f9cc88b46..56c4cbb5f 100644 --- a/components/asio/examples/socks4/README.md +++ b/components/asio/examples/socks4/README.md @@ -5,64 +5,64 @@ (See the README.md file in the upper level 'examples' directory for more information about examples.) -The application aims to show how to connect to a Socks4 proxy using async operations with ASIO. The SOCKS protocol is -briefly described by the diagram below. +The application aims to show how to connect to a Socks4 proxy using async operations with ASIO. The SOCKS protocol is +briefly described by the diagram below. - ┌──────┐ ┌─────┐ ┌──────┐ - │Client│ │Proxy│ │Target│ - └──┬───┘ └──┬──┘ └──┬───┘ - │ │ │ - │ ╔═╧══════════════╗ │ + ┌──────┐ ┌─────┐ ┌──────┐ + │Client│ │Proxy│ │Target│ + └──┬───┘ └──┬──┘ └──┬───┘ + │ │ │ + │ ╔═╧══════════════╗ │ ══════════════════════╪════════════════════════╣ Initialization ╠═══╪════════════════════════════════════════════ - │ ╚═╤══════════════╝ │ - │ │ │ - ╔══════════════════╗│ │ │ - ║We establish a ░║│ Socket Connection │ │ - ║TCP connection ║│ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ > │ - ║and get a socket ║│ │ │ - ╚══════════════════╝│ │ │ - │ │ │ - │ ╔═╧══════════════╗ │ + │ ╚═╤══════════════╝ │ + │ │ │ + ╔══════════════════╗│ │ │ + ║We establish a ░║│ Socket Connection │ │ + ║TCP connection ║│ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ > │ + ║and get a socket ║│ │ │ + ╚══════════════════╝│ │ │ + │ │ │ + │ ╔═╧══════════════╗ │ ══════════════════════╪════════════════════════╣ Socks Protocol ╠═══╪════════════════════════════════════════════ - │ ╚═╤══════════════╝ │ - │ │ │ - │ Client Connection Request│ │ - │ ─────────────────────────> │ - │ │ │ - │ │ │ - │ ╔════════════╪═══════╤══════════╪════════════════════════════════╗ - │ ║ TARGET CONNECTION │ │ ║ - │ ╟────────────────────┘ │ ╔═══════════════════╗ ║ - │ ║ │ Socket Connection│ ║Proxy establishes ░║ ║ - │ ║ │ <─ ─ ─ ─ ─ ─ ─ ─ > ║ TCPconnection ║ ║ - │ ║ │ │ ║ with target host ║ ║ - │ ╚════════════╪══════════════════╪══╚═══════════════════╝═════════╝ - │ │ │ - │ Response packet │ │ - │ <───────────────────────── │ - │ │ │ - │ │ │ - │ │ ╔═══════╗ │ + │ ╚═╤══════════════╝ │ + │ │ │ + │ Client Connection Request│ │ + │ ─────────────────────────> │ + │ │ │ + │ │ │ + │ ╔════════════╪═══════╤══════════╪════════════════════════════════╗ + │ ║ TARGET CONNECTION │ │ ║ + │ ╟────────────────────┘ │ ╔═══════════════════╗ ║ + │ ║ │ Socket Connection│ ║Proxy establishes ░║ ║ + │ ║ │ <─ ─ ─ ─ ─ ─ ─ ─ > ║ TCPconnection ║ ║ + │ ║ │ │ ║ with target host ║ ║ + │ ╚════════════╪══════════════════╪══╚═══════════════════╝═════════╝ + │ │ │ + │ Response packet │ │ + │ <───────────────────────── │ + │ │ │ + │ │ │ + │ │ ╔═══════╗ │ ══════════════════════╪══════════════════════════╪══╣ Usage ╠═══════╪════════════════════════════════════════════ - │ │ ╚═══════╝ │ - │ │ │ - ╔═════════════════╗│ │ │ - ║Client uses the ░║│ │ │ - ║ socket opened ║│ │ │ - ║ with proxy ║│ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─> - ║to communicate ║│ │ │ - ║ ║│ │ │ - ╚═════════════════╝┴───┐ ┌──┴──┐ ┌──┴───┐ - │Client│ │Proxy│ │Target│ - └──────┘ └─────┘ └──────┘ + │ │ ╚═══════╝ │ + │ │ │ + ╔═════════════════╗│ │ │ + ║Client uses the ░║│ │ │ + ║ socket opened ║│ │ │ + ║ with proxy ║│ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─> + ║to communicate ║│ │ │ + ║ ║│ │ │ + ╚═════════════════╝┴───┐ ┌──┴──┐ ┌──┴───┐ + │Client│ │Proxy│ │Target│ + └──────┘ └─────┘ └──────┘ # Configure and Building example This example requires the proxy address to be configured. You can do this using the menuconfig option. -Proxy address and port must be configured in order for this example to work. +Proxy address and port must be configured in order for this example to work. -If using Linux ssh can be used as a proxy for testing. +If using Linux ssh can be used as a proxy for testing. ``` ssh -N -v -D 0.0.0.0:1080 localhost @@ -70,4 +70,3 @@ ssh -N -v -D 0.0.0.0:1080 localhost # Async operations composition and automatic lifetime control For documentation about the structure of this example look into [async\_request README](../async_request/README.md). - diff --git a/components/asio/examples/socks4/main/socks4.cpp b/components/asio/examples/socks4/main/socks4.cpp index 5bd0011ed..d0bcf8b7b 100644 --- a/components/asio/examples/socks4/main/socks4.cpp +++ b/components/asio/examples/socks4/main/socks4.cpp @@ -183,7 +183,7 @@ void async_connect(asio::io_context &context, std::string proxy, std::string pro std::make_shared(context)->start(proxy_resolution, [resolver, host_resolution, completion_handler](std::shared_ptr connection) { auto connect_data = std::make_shared(socks4::request::connect, *host_resolution, ""); - ESP_LOGI(TAG, "Sending Request to proxy for host connection."); + ESP_LOGI(TAG, "Sending Request to proxy for host connection."); connection->write_async(connect_data->request.buffers(), [connection, connect_data, completion_handler](std::error_code error, std::size_t bytes_received) { if (error) { ESP_LOGE(TAG, "Proxy request write error: %s", error.message().c_str()); diff --git a/components/asio/examples/socks4/main/socks4.hpp b/components/asio/examples/socks4/main/socks4.hpp index a039c07ca..5a029f38b 100644 --- a/components/asio/examples/socks4/main/socks4.hpp +++ b/components/asio/examples/socks4/main/socks4.hpp @@ -20,122 +20,115 @@ namespace socks4 { const unsigned char version = 0x04; -class request -{ +class request { public: - enum command_type - { - connect = 0x01, - bind = 0x02 - }; + enum command_type { + connect = 0x01, + bind = 0x02 + }; - request(command_type cmd, const asio::ip::tcp::endpoint& endpoint, - const std::string& user_id) - : version_(version), - command_(cmd), - user_id_(user_id), - null_byte_(0) - { - // Only IPv4 is supported by the SOCKS 4 protocol. - if (endpoint.protocol() != asio::ip::tcp::v4()) + request(command_type cmd, const asio::ip::tcp::endpoint &endpoint, + const std::string &user_id) + : version_(version), + command_(cmd), + user_id_(user_id), + null_byte_(0) { - throw asio::system_error( - asio::error::address_family_not_supported); + // Only IPv4 is supported by the SOCKS 4 protocol. + if (endpoint.protocol() != asio::ip::tcp::v4()) { + throw asio::system_error( + asio::error::address_family_not_supported); + } + + // Convert port number to network byte order. + unsigned short port = endpoint.port(); + port_high_byte_ = (port >> 8) & 0xff; + port_low_byte_ = port & 0xff; + + // Save IP address in network byte order. + address_ = endpoint.address().to_v4().to_bytes(); } - // Convert port number to network byte order. - unsigned short port = endpoint.port(); - port_high_byte_ = (port >> 8) & 0xff; - port_low_byte_ = port & 0xff; - - // Save IP address in network byte order. - address_ = endpoint.address().to_v4().to_bytes(); - } - - std::array buffers() const - { - return + std::array buffers() const { - { - asio::buffer(&version_, 1), - asio::buffer(&command_, 1), - asio::buffer(&port_high_byte_, 1), - asio::buffer(&port_low_byte_, 1), - asio::buffer(address_), - asio::buffer(user_id_), - asio::buffer(&null_byte_, 1) - } - }; - } + return { + { + asio::buffer(&version_, 1), + asio::buffer(&command_, 1), + asio::buffer(&port_high_byte_, 1), + asio::buffer(&port_low_byte_, 1), + asio::buffer(address_), + asio::buffer(user_id_), + asio::buffer(&null_byte_, 1) + } + }; + } private: - unsigned char version_; - unsigned char command_; - unsigned char port_high_byte_; - unsigned char port_low_byte_; - asio::ip::address_v4::bytes_type address_; - std::string user_id_; - unsigned char null_byte_; + unsigned char version_; + unsigned char command_; + unsigned char port_high_byte_; + unsigned char port_low_byte_; + asio::ip::address_v4::bytes_type address_; + std::string user_id_; + unsigned char null_byte_; }; -class reply -{ +class reply { public: - enum status_type - { - request_granted = 0x5a, - request_failed = 0x5b, - request_failed_no_identd = 0x5c, - request_failed_bad_user_id = 0x5d - }; - - reply() - : null_byte_(0), - status_() - { - } - - std::array buffers() - { - return - { - { - asio::buffer(&null_byte_, 1), - asio::buffer(&status_, 1), - asio::buffer(&port_high_byte_, 1), - asio::buffer(&port_low_byte_, 1), - asio::buffer(address_) - } + enum status_type { + request_granted = 0x5a, + request_failed = 0x5b, + request_failed_no_identd = 0x5c, + request_failed_bad_user_id = 0x5d }; - } - bool success() const - { - return null_byte_ == 0 && status_ == request_granted; - } + reply() + : null_byte_(0), + status_() + { + } - unsigned char status() const - { - return status_; - } + std::array buffers() + { + return { + { + asio::buffer(&null_byte_, 1), + asio::buffer(&status_, 1), + asio::buffer(&port_high_byte_, 1), + asio::buffer(&port_low_byte_, 1), + asio::buffer(address_) + } + }; + } - asio::ip::tcp::endpoint endpoint() const - { - unsigned short port = port_high_byte_; - port = (port << 8) & 0xff00; - port = port | port_low_byte_; + bool success() const + { + return null_byte_ == 0 && status_ == request_granted; + } - asio::ip::address_v4 address(address_); + unsigned char status() const + { + return status_; + } - return asio::ip::tcp::endpoint(address, port); - } + asio::ip::tcp::endpoint endpoint() const + { + unsigned short port = port_high_byte_; + port = (port << 8) & 0xff00; + port = port | port_low_byte_; + + asio::ip::address_v4 address(address_); + + return asio::ip::tcp::endpoint(address, port); + } private: - unsigned char null_byte_; - unsigned char status_; - unsigned char port_high_byte_; - unsigned char port_low_byte_; - asio::ip::address_v4::bytes_type address_; + unsigned char null_byte_; + unsigned char status_; + unsigned char port_high_byte_; + unsigned char port_low_byte_; + asio::ip::address_v4::bytes_type address_; }; } // namespace socks4 diff --git a/components/asio/examples/ssl_client_server/pytest_example_test.py b/components/asio/examples/ssl_client_server/pytest_asio_ssl_client_server_test.py similarity index 50% rename from components/asio/examples/ssl_client_server/pytest_example_test.py rename to components/asio/examples/ssl_client_server/pytest_asio_ssl_client_server_test.py index 7b1dd217b..ec3e39208 100644 --- a/components/asio/examples/ssl_client_server/pytest_example_test.py +++ b/components/asio/examples/ssl_client_server/pytest_asio_ssl_client_server_test.py @@ -1,8 +1,7 @@ +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 from __future__ import unicode_literals -import pytest -from pytest_embedded import Dut - def test_examples_asio_ssl(dut): dut.expect('Reply: GET / HTTP/1.1') diff --git a/components/asio/examples/tcp_echo_server/main/echo_server.cpp b/components/asio/examples/tcp_echo_server/main/echo_server.cpp index 5c520aeac..f5b7d7f57 100644 --- a/components/asio/examples/tcp_echo_server/main/echo_server.cpp +++ b/components/asio/examples/tcp_echo_server/main/echo_server.cpp @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include "asio.hpp" #include #include @@ -8,78 +13,70 @@ using asio::ip::tcp; class session - : public std::enable_shared_from_this -{ + : public std::enable_shared_from_this { public: - session(tcp::socket socket) - : socket_(std::move(socket)) - { - } + session(tcp::socket socket) + : socket_(std::move(socket)) + { + } - void start() - { - do_read(); - } + void start() + { + do_read(); + } private: - void do_read() - { - auto self(shared_from_this()); - socket_.async_read_some(asio::buffer(data_, max_length), - [this, self](std::error_code ec, std::size_t length) - { - if (!ec) - { - data_[length] = 0; - std::cout << data_ << std::endl; - do_write(length); - } + void do_read() + { + auto self(shared_from_this()); + socket_.async_read_some(asio::buffer(data_, max_length), + [this, self](std::error_code ec, std::size_t length) { + if (!ec) { + data_[length] = 0; + std::cout << data_ << std::endl; + do_write(length); + } }); - } + } - void do_write(std::size_t length) - { - auto self(shared_from_this()); - asio::async_write(socket_, asio::buffer(data_, length), - [this, self](std::error_code ec, std::size_t length) - { - if (!ec) - { - do_read(); - } + void do_write(std::size_t length) + { + auto self(shared_from_this()); + asio::async_write(socket_, asio::buffer(data_, length), + [this, self](std::error_code ec, std::size_t length) { + if (!ec) { + do_read(); + } }); - } + } - tcp::socket socket_; - enum { max_length = 1024 }; - char data_[max_length]; + tcp::socket socket_; + enum { max_length = 1024 }; + char data_[max_length]; }; -class server -{ +class server { public: - server(asio::io_context& io_context, short port) - : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) - { - do_accept(); - } + server(asio::io_context &io_context, short port) + : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) + { + do_accept(); + } private: - void do_accept() - { - acceptor_.async_accept( - [this](std::error_code ec, tcp::socket socket) - { - if (!ec) - { - std::make_shared(std::move(socket))->start(); - } + void do_accept() + { + acceptor_.async_accept( + [this](std::error_code ec, tcp::socket socket) { + if (!ec) { + std::make_shared(std::move(socket))->start(); + } - do_accept(); + do_accept(); }); - } + } - tcp::acceptor acceptor_; + tcp::acceptor acceptor_; }; diff --git a/components/asio/examples/tcp_echo_server/pytest_asio_tcp_server_test.py b/components/asio/examples/tcp_echo_server/pytest_asio_tcp_server_test.py index 1b6ecab7a..3d54de915 100644 --- a/components/asio/examples/tcp_echo_server/pytest_asio_tcp_server_test.py +++ b/components/asio/examples/tcp_echo_server/pytest_asio_tcp_server_test.py @@ -1,7 +1,7 @@ -import os +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 import re import socket -from pytest_embedded import Dut def test_examples_protocol_asio_tcp_server(dut): @@ -15,7 +15,10 @@ def test_examples_protocol_asio_tcp_server(dut): """ test_msg = b'echo message from client to server' # 2. get the server IP address - data = dut.expect(re.compile(b' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30).group(1).decode() + data = dut.expect( + re.compile( + b' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), # noqa: W605 + timeout=30).group(1).decode() # 3. create tcp client and connect to server dut.expect('ASIO engine is up and running', timeout=1) cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -29,7 +32,8 @@ def test_examples_protocol_asio_tcp_server(dut): pass else: print('Failure!') - raise ValueError('Wrong data received from asi tcp server: {} (expected:{})'.format(data, test_msg)) + raise ValueError( + 'Wrong data received from asi tcp server: {} (expected:{})'.format( + data, test_msg)) # 5. check the client message appears also on server terminal dut.expect(test_msg.decode()) - diff --git a/components/asio/examples/udp_echo_server/main/udp_echo_server.cpp b/components/asio/examples/udp_echo_server/main/udp_echo_server.cpp index 5e21d5100..39746ffbd 100644 --- a/components/asio/examples/udp_echo_server/main/udp_echo_server.cpp +++ b/components/asio/examples/udp_echo_server/main/udp_echo_server.cpp @@ -20,49 +20,43 @@ using asio::ip::udp; -class server -{ +class server { public: - server(asio::io_context& io_context, short port) - : socket_(io_context, udp::endpoint(udp::v4(), port)) - { - do_receive(); - } + server(asio::io_context &io_context, short port) + : socket_(io_context, udp::endpoint(udp::v4(), port)) + { + do_receive(); + } - void do_receive() - { - socket_.async_receive_from( - asio::buffer(data_, max_length), sender_endpoint_, - [this](std::error_code ec, std::size_t bytes_recvd) - { - if (!ec && bytes_recvd > 0) - { - data_[bytes_recvd] = 0; - std::cout << data_ << std::endl; - do_send(bytes_recvd); - } - else - { + void do_receive() + { + socket_.async_receive_from( + asio::buffer(data_, max_length), sender_endpoint_, + [this](std::error_code ec, std::size_t bytes_recvd) { + if (!ec && bytes_recvd > 0) { + data_[bytes_recvd] = 0; + std::cout << data_ << std::endl; + do_send(bytes_recvd); + } else { + do_receive(); + } + }); + } + + void do_send(std::size_t length) + { + socket_.async_send_to( + asio::buffer(data_, length), sender_endpoint_, + [this](std::error_code /*ec*/, std::size_t bytes /*bytes_sent*/) { do_receive(); - } }); - } - - void do_send(std::size_t length) - { - socket_.async_send_to( - asio::buffer(data_, length), sender_endpoint_, - [this](std::error_code /*ec*/, std::size_t bytes /*bytes_sent*/) - { - do_receive(); - }); - } + } private: - udp::socket socket_; - udp::endpoint sender_endpoint_; - enum { max_length = 1024 }; - char data_[max_length]; + udp::socket socket_; + udp::endpoint sender_endpoint_; + enum { max_length = 1024 }; + char data_[max_length]; }; extern "C" void app_main(void) diff --git a/components/asio/examples/udp_echo_server/pytest_asio_udp_server_test.py b/components/asio/examples/udp_echo_server/pytest_asio_udp_server_test.py index 1f2e03e2e..7a016a5b0 100644 --- a/components/asio/examples/udp_echo_server/pytest_asio_udp_server_test.py +++ b/components/asio/examples/udp_echo_server/pytest_asio_udp_server_test.py @@ -1,9 +1,8 @@ -import os +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 import re import socket -import pytest -from pytest_embedded import Dut def test_examples_protocol_asio_udp_server(dut): """ @@ -15,7 +14,10 @@ def test_examples_protocol_asio_udp_server(dut): 5. Test evaluates received test message on server stdout """ test_msg = b'echo message from client to server' - data = dut.expect(re.compile(b' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30).group(1).decode() + data = dut.expect( + re.compile( + b' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), # noqa: W605 + timeout=30).group(1).decode() dut.expect('ASIO engine is up and running', timeout=1) cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cli.settimeout(30) @@ -28,6 +30,8 @@ def test_examples_protocol_asio_udp_server(dut): pass else: print('Failure!') - raise ValueError('Wrong data received from asio udp server: {} (expected:{})'.format(data, test_msg)) + raise ValueError( + 'Wrong data received from asio udp server: {} (expected:{})'. + format(data, test_msg)) # 5. check the client message appears also on server terminal dut.expect(test_msg.decode()) diff --git a/components/asio/port/include/esp_exception.h b/components/asio/port/include/esp_exception.h index 15cada7a7..41cc99b13 100644 --- a/components/asio/port/include/esp_exception.h +++ b/components/asio/port/include/esp_exception.h @@ -19,12 +19,13 @@ namespace asio { namespace detail { template -void throw_exception(const Exception& e) +void throw_exception(const Exception &e) { - ESP_LOGE("esp32_asio_exception", "Caught exception: %s!", e.what()); - abort(); + ESP_LOGE("esp32_asio_exception", "Caught exception: %s!", e.what()); + abort(); +} +} } -}} #endif // CONFIG_COMPILER_CXX_EXCEPTIONS==1 && defined (ASIO_NO_EXCEPTIONS) #endif // _ESP_EXCEPTION_H_ diff --git a/components/asio/port/include/openssl_stub.hpp b/components/asio/port/include/openssl_stub.hpp index 175879542..d90a0bd8d 100644 --- a/components/asio/port/include/openssl_stub.hpp +++ b/components/asio/port/include/openssl_stub.hpp @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // @@ -16,9 +16,9 @@ #define SSL_OP_SINGLE_DH_USE 0 #define SSL_OP_NO_COMPRESSION 0 -#define SSL_OP_NO_SSLv2 0x01000000L -#define SSL_OP_NO_SSLv3 0x02000000L -#define SSL_OP_NO_TLSv1 0x04000000L +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L +#define SSL_OP_NO_TLSv1 0x04000000L #define SSL_VERIFY_NONE 0x00 #define SSL_VERIFY_PEER 0x01 @@ -35,12 +35,14 @@ namespace mbedtls { class engine; class bio; class shared_ctx; -} } } // namespace asio::ssl::mbedtls +} +} +} // namespace asio::ssl::mbedtls // // Supply OpenSSL types as aliases to mbedtls classes // -using X509_STORE_CTX=void; -using BIO=asio::ssl::mbedtls::bio; -using SSL_CTX=asio::ssl::mbedtls::shared_ctx; -using SSL=asio::ssl::mbedtls::engine; +using X509_STORE_CTX = void; +using BIO = asio::ssl::mbedtls::bio; +using SSL_CTX = asio::ssl::mbedtls::shared_ctx; +using SSL = asio::ssl::mbedtls::engine; diff --git a/components/asio/port/mbedtls/include/mbedtls_bio.hpp b/components/asio/port/mbedtls/include/mbedtls_bio.hpp index d5348a052..c408a1682 100644 --- a/components/asio/port/mbedtls/include/mbedtls_bio.hpp +++ b/components/asio/port/mbedtls/include/mbedtls_bio.hpp @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // @@ -87,7 +87,7 @@ public: return flags_ & BIO_FLAGS_READ; } - static std::pair, std::shared_ptr> new_pair(const char* error_location) + static std::pair, std::shared_ptr> new_pair(const char *error_location) { auto b1 = std::shared_ptr(new (std::nothrow) bio); auto b2 = std::shared_ptr(new (std::nothrow) bio); @@ -110,4 +110,6 @@ private: size_t flags_ {0}; }; -} } } // namespace asio::ssl::mbedtls +} +} +} // namespace asio::ssl::mbedtls diff --git a/components/asio/port/mbedtls/include/mbedtls_context.hpp b/components/asio/port/mbedtls/include/mbedtls_context.hpp index 27d135b5d..41b1345f7 100644 --- a/components/asio/port/mbedtls/include/mbedtls_context.hpp +++ b/components/asio/port/mbedtls/include/mbedtls_context.hpp @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // @@ -11,13 +11,13 @@ namespace asio { namespace error { -const asio::error_category& get_mbedtls_category(); +const asio::error_category &get_mbedtls_category(); } // namespace error namespace ssl { namespace mbedtls { -void throw_alloc_failure(const char* location); +void throw_alloc_failure(const char *location); const char *error_message(int error_code); @@ -26,11 +26,10 @@ enum class container { }; template -inline T* create(const char * location, Args &&... args) +inline T *create(const char *location, Args &&... args) { - T* t = new (std::nothrow) T(std::forward(args)...); - if (t == nullptr) - { + T *t = new (std::nothrow) T(std::forward(args)...); + if (t == nullptr) { throw_alloc_failure(location); } return t; @@ -43,12 +42,12 @@ public: const unsigned char *data(container c) const { switch (c) { - case container::CERT: - return static_cast(cert_chain_.data()); - case container::CA_CERT: - return static_cast(ca_cert_.data()); - case container::PRIVKEY: - return static_cast(private_key_.data()); + case container::CERT: + return static_cast(cert_chain_.data()); + case container::CA_CERT: + return static_cast(ca_cert_.data()); + case container::PRIVKEY: + return static_cast(private_key_.data()); } return nullptr; } @@ -56,12 +55,12 @@ public: std::size_t size(container c) const { switch (c) { - case container::CERT: - return cert_chain_.size(); - case container::CA_CERT: - return ca_cert_.size(); - case container::PRIVKEY: - return private_key_.size(); + case container::CERT: + return cert_chain_.size(); + case container::CA_CERT: + return ca_cert_.size(); + case container::PRIVKEY: + return private_key_.size(); } return 0; } @@ -80,11 +79,10 @@ public: */ class shared_ctx { public: - static SSL_CTX *create(const char* location, context_base::method m) + static SSL_CTX *create(const char *location, context_base::method m) { auto wrapped = asio::ssl::mbedtls::create(location, m); - if (wrapped->ctx_ == nullptr) - { + if (wrapped->ctx_ == nullptr) { throw_alloc_failure(location); } return wrapped; @@ -96,10 +94,12 @@ public: } explicit shared_ctx(context_base::method m) - :ctx_(std::shared_ptr(new (std::nothrow) context(m))) { } + : ctx_(std::shared_ptr(new (std::nothrow) context(m))) { } private: std::shared_ptr ctx_; }; -} } } // namespace asio::ssl::mbedtls +} +} +} // namespace asio::ssl::mbedtls diff --git a/components/asio/port/mbedtls/include/mbedtls_engine.hpp b/components/asio/port/mbedtls/include/mbedtls_engine.hpp index a52ba459d..4d0258c35 100644 --- a/components/asio/port/mbedtls/include/mbedtls_engine.hpp +++ b/components/asio/port/mbedtls/include/mbedtls_engine.hpp @@ -23,7 +23,7 @@ const char *error_message(int error_code) return error_buf; } -void throw_alloc_failure(const char* location) +void throw_alloc_failure(const char *location) { asio::error_code ec( MBEDTLS_ERR_SSL_ALLOC_FAILED, asio::error::get_mbedtls_category()); asio::detail::throw_error(ec, location); @@ -62,7 +62,7 @@ public: verify_mode_ = mode; } - bio* ext_bio() const + bio *ext_bio() const { return bio_.second.get(); } @@ -95,14 +95,14 @@ public: int write(const void *buffer, int len) { int ret = impl_.write(buffer, len); - state_ = ret == len ? IDLE: WRITING; + state_ = ret == len ? IDLE : WRITING; return ret; } int read(void *buffer, int len) { int ret = impl_.read(buffer, len); - state_ = ret == len ? IDLE: READING; + state_ = ret == len ? IDLE : READING; return ret; } @@ -117,7 +117,7 @@ private: static int bio_read(void *ctx, unsigned char *buf, size_t len) { - auto bio = static_cast(ctx); + auto bio = static_cast(ctx); int read = bio->read(buf, len); if (read <= 0 && bio->should_read()) { return MBEDTLS_ERR_SSL_WANT_READ; @@ -127,7 +127,7 @@ private: static int bio_write(void *ctx, const unsigned char *buf, size_t len) { - auto bio = static_cast(ctx); + auto bio = static_cast(ctx); int written = bio->write(buf, len); if (written <= 0 && bio->should_write()) { return MBEDTLS_ERR_SSL_WANT_WRITE; @@ -163,25 +163,27 @@ private: { int mode = MBEDTLS_SSL_VERIFY_UNSET; if (is_client_not_server) { - if (verify_mode_ & SSL_VERIFY_PEER) + if (verify_mode_ & SSL_VERIFY_PEER) { mode = MBEDTLS_SSL_VERIFY_REQUIRED; - else if (verify_mode_ == SSL_VERIFY_NONE) + } else if (verify_mode_ == SSL_VERIFY_NONE) { mode = MBEDTLS_SSL_VERIFY_NONE; + } } else { - if (verify_mode_ & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) + if (verify_mode_ & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) { mode = MBEDTLS_SSL_VERIFY_REQUIRED; - else if (verify_mode_ & SSL_VERIFY_PEER) + } else if (verify_mode_ & SSL_VERIFY_PEER) { mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - else if (verify_mode_ == SSL_VERIFY_NONE) + } else if (verify_mode_ == SSL_VERIFY_NONE) { mode = MBEDTLS_SSL_VERIFY_NONE; + } } return mode; } struct impl { - static void print_error(const char* function, int error_code) + static void print_error(const char *function, int error_code) { - constexpr const char *TAG="mbedtls-engine-impl"; + constexpr const char *TAG = "mbedtls-engine-impl"; ESP_LOGE(TAG, "%s() returned -0x%04X", function, -error_code); ESP_LOGI(TAG, "-0x%04X: %s", -error_code, error_message(error_code)); } @@ -230,7 +232,7 @@ private: mbedtls_x509_crt_init(&public_cert_); mbedtls_pk_init(&pk_key_); mbedtls_x509_crt_init(&ca_cert_); - int ret = mbedtls_ssl_config_defaults(&conf_, is_client_not_server ? MBEDTLS_SSL_IS_CLIENT: MBEDTLS_SSL_IS_SERVER, + int ret = mbedtls_ssl_config_defaults(&conf_, is_client_not_server ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (ret) { print_error("mbedtls_ssl_config_defaults", ret); @@ -290,4 +292,6 @@ private: asio::ssl::verify_mode verify_mode_; }; -} } } // namespace asio::ssl::mbedtls +} +} +} // namespace asio::ssl::mbedtls diff --git a/components/asio/port/mbedtls/include/mbedtls_error.hpp b/components/asio/port/mbedtls/include/mbedtls_error.hpp index 083cf6c88..d760b0079 100644 --- a/components/asio/port/mbedtls/include/mbedtls_error.hpp +++ b/components/asio/port/mbedtls/include/mbedtls_error.hpp @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // @@ -14,30 +14,29 @@ namespace asio { namespace error { namespace detail { -class mbedtls_category : public asio::error_category -{ +class mbedtls_category : public asio::error_category { public: - const char* name() const ASIO_ERROR_CATEGORY_NOEXCEPT + const char *name() const ASIO_ERROR_CATEGORY_NOEXCEPT { return "asio.ssl"; } std::string message(int value) const { - const char* s = asio::ssl::mbedtls::error_message(value); + const char *s = asio::ssl::mbedtls::error_message(value); return s ? s : "asio.mbedtls error"; } }; } // namespace detail -const asio::error_category& get_mbedtls_category() +const asio::error_category &get_mbedtls_category() { static detail::mbedtls_category instance; return instance; } -const asio::error_category& get_ssl_category() +const asio::error_category &get_ssl_category() { return asio::error::get_mbedtls_category(); } @@ -47,9 +46,11 @@ const asio::error_category& get_ssl_category() namespace ssl { namespace error { -const asio::error_category& get_stream_category() +const asio::error_category &get_stream_category() { return asio::error::get_mbedtls_category(); } -} } } // namespace asio::ssl::error +} +} +} // namespace asio::ssl::error diff --git a/components/asio/port/mbedtls/include/openssl/conf.h b/components/asio/port/mbedtls/include/openssl/conf.h index dc024544e..bb24a5dcd 100644 --- a/components/asio/port/mbedtls/include/openssl/conf.h +++ b/components/asio/port/mbedtls/include/openssl/conf.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/include/openssl/dh.h b/components/asio/port/mbedtls/include/openssl/dh.h index dc024544e..bb24a5dcd 100644 --- a/components/asio/port/mbedtls/include/openssl/dh.h +++ b/components/asio/port/mbedtls/include/openssl/dh.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/include/openssl/err.h b/components/asio/port/mbedtls/include/openssl/err.h index dc024544e..bb24a5dcd 100644 --- a/components/asio/port/mbedtls/include/openssl/err.h +++ b/components/asio/port/mbedtls/include/openssl/err.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/include/openssl/rsa.h b/components/asio/port/mbedtls/include/openssl/rsa.h index dc024544e..bb24a5dcd 100644 --- a/components/asio/port/mbedtls/include/openssl/rsa.h +++ b/components/asio/port/mbedtls/include/openssl/rsa.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/include/openssl/ssl.h b/components/asio/port/mbedtls/include/openssl/ssl.h index be147bc00..766b3f238 100644 --- a/components/asio/port/mbedtls/include/openssl/ssl.h +++ b/components/asio/port/mbedtls/include/openssl/ssl.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/include/openssl/x509v3.h b/components/asio/port/mbedtls/include/openssl/x509v3.h index dc024544e..bb24a5dcd 100644 --- a/components/asio/port/mbedtls/include/openssl/x509v3.h +++ b/components/asio/port/mbedtls/include/openssl/x509v3.h @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: BSL-1.0 // diff --git a/components/asio/port/mbedtls/src/mbedtls_context.cpp b/components/asio/port/mbedtls/src/mbedtls_context.cpp index 36ba700dd..bf9220ad5 100644 --- a/components/asio/port/mbedtls/src/mbedtls_context.cpp +++ b/components/asio/port/mbedtls/src/mbedtls_context.cpp @@ -4,7 +4,7 @@ // // SPDX-License-Identifier: BSL-1.0 // -// SPDX-FileContributor: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileContributor: 2021-2022 Espressif Systems (Shanghai) CO LTD // #include "asio/detail/config.hpp" @@ -22,19 +22,19 @@ namespace ssl { context::context(context::method m) - : handle_(0) + : handle_(0) { handle_ = mbedtls::shared_ctx::create("mbedtls-context", m); set_options(no_compression); } -context::context(context&& other) +context::context(context &&other) { handle_ = other.handle_; other.handle_ = 0; } -context& context::operator=(context&& other) +context &context::operator=(context &&other) { context tmp(ASIO_MOVE_CAST(context)(*this)); handle_ = other.handle_; @@ -60,14 +60,14 @@ void context::set_options(context::options o) } ASIO_SYNC_OP_VOID context::set_options( - context::options o, asio::error_code& ec) + context::options o, asio::error_code &ec) { handle_->get()->options_ = o; ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } -void context::add_certificate_authority(const const_buffer& ca) +void context::add_certificate_authority(const const_buffer &ca) { asio::error_code ec; add_certificate_authority(ca, ec); @@ -75,13 +75,13 @@ void context::add_certificate_authority(const const_buffer& ca) } ASIO_SYNC_OP_VOID context::add_certificate_authority( - const const_buffer& ca, asio::error_code& ec) + const const_buffer &ca, asio::error_code &ec) { handle_->get()->ca_cert_ = ca; ASIO_SYNC_OP_VOID_RETURN(asio::error_code()); } -void context::use_certificate_chain(const const_buffer& chain) +void context::use_certificate_chain(const const_buffer &chain) { asio::error_code ec; use_certificate_chain(chain, ec); @@ -89,14 +89,14 @@ void context::use_certificate_chain(const const_buffer& chain) } ASIO_SYNC_OP_VOID context::use_certificate_chain( - const const_buffer& chain, asio::error_code& ec) + const const_buffer &chain, asio::error_code &ec) { handle_->get()->cert_chain_ = chain; ASIO_SYNC_OP_VOID_RETURN(asio::error_code()); } void context::use_private_key( - const const_buffer& private_key, context::file_format format) + const const_buffer &private_key, context::file_format format) { asio::error_code ec; use_private_key(private_key, format, ec); @@ -104,8 +104,8 @@ void context::use_private_key( } ASIO_SYNC_OP_VOID context::use_private_key( - const const_buffer& private_key, context::file_format format, - asio::error_code& ec) + const const_buffer &private_key, context::file_format format, + asio::error_code &ec) { handle_->get()->private_key_ = private_key; ASIO_SYNC_OP_VOID_RETURN(asio::error_code()); diff --git a/components/asio/port/mbedtls/src/mbedtls_engine.cpp b/components/asio/port/mbedtls/src/mbedtls_engine.cpp index c3ff91842..1d97b3a73 100644 --- a/components/asio/port/mbedtls/src/mbedtls_engine.cpp +++ b/components/asio/port/mbedtls/src/mbedtls_engine.cpp @@ -3,7 +3,7 @@ // // SPDX-License-Identifier: BSL-1.0 // -// SPDX-FileContributor: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileContributor: 2021-2022 Espressif Systems (Shanghai) CO LTD // #include "asio/detail/config.hpp" @@ -24,8 +24,8 @@ namespace ssl { namespace detail { -engine::engine(SSL_CTX* context) - : ssl_(nullptr) +engine::engine(SSL_CTX *context) + : ssl_(nullptr) { ssl_ = mbedtls::create("mbedtls-engine", context->get()); } @@ -35,49 +35,47 @@ engine::~engine() delete ssl_; } -SSL* engine::native_handle() +SSL *engine::native_handle() { return ssl_; } asio::error_code engine::set_verify_mode( - verify_mode v, asio::error_code& ec) + verify_mode v, asio::error_code &ec) { ssl_->set_verify_mode(v); return {}; } engine::want engine::handshake( - stream_base::handshake_type type, asio::error_code& ec) + stream_base::handshake_type type, asio::error_code &ec) { return perform((type == asio::ssl::stream_base::client) ? &engine::do_connect : &engine::do_accept, 0, 0, ec, 0); } -engine::want engine::shutdown(asio::error_code& ec) +engine::want engine::shutdown(asio::error_code &ec) { return perform(&engine::do_shutdown, 0, 0, ec, 0); } -engine::want engine::write(const asio::const_buffer& data, - asio::error_code& ec, std::size_t& bytes_transferred) +engine::want engine::write(const asio::const_buffer &data, + asio::error_code &ec, std::size_t &bytes_transferred) { - if (data.size() == 0) - { + if (data.size() == 0) { ec = asio::error_code(); return engine::want_nothing; } return perform(&engine::do_write, - const_cast(data.data()), + const_cast(data.data()), data.size(), ec, &bytes_transferred); } -engine::want engine::read(const asio::mutable_buffer& data, - asio::error_code& ec, std::size_t& bytes_transferred) +engine::want engine::read(const asio::mutable_buffer &data, + asio::error_code &ec, std::size_t &bytes_transferred) { - if (data.size() == 0) - { + if (data.size() == 0) { ec = asio::error_code(); return engine::want_nothing; } @@ -87,7 +85,7 @@ engine::want engine::read(const asio::mutable_buffer& data, } asio::mutable_buffer engine::get_output( - const asio::mutable_buffer& data) + const asio::mutable_buffer &data) { int length = ssl_->ext_bio()->read(data.data(), static_cast(data.size())); @@ -96,7 +94,7 @@ asio::mutable_buffer engine::get_output( } asio::const_buffer engine::put_input( - const asio::const_buffer& data) + const asio::const_buffer &data) { int length = ssl_->ext_bio()->write(data.data(), static_cast(data.size())); @@ -104,23 +102,22 @@ asio::const_buffer engine::put_input( (length > 0 ? static_cast(length) : 0)); } -const asio::error_code& engine::map_error_code( - asio::error_code& ec) const +const asio::error_code &engine::map_error_code( + asio::error_code &ec) const { // We only want to map the error::eof code. - if (ec != asio::error::eof) + if (ec != asio::error::eof) { return ec; + } // If there's data yet to be read, it's an error. - if (ssl_->ext_bio()->wpending()) - { + if (ssl_->ext_bio()->wpending()) { ec = asio::ssl::error::stream_truncated; return ec; } // Otherwise, the peer should have negotiated a proper shutdown. - if (ssl_->shutdown() != 0) - { + if (ssl_->shutdown() != 0) { ec = asio::ssl::error::stream_truncated; } @@ -129,47 +126,39 @@ const asio::error_code& engine::map_error_code( // This is a simplified implementation of a generic ssl io operation // original implementation using openssl's SSL object is in asio/include/asio/ssl/detail/impl/engine.ipp -engine::want engine::perform(int (engine::* op)(void*, std::size_t), - void* data, std::size_t length, asio::error_code& ec, - std::size_t* bytes_transferred) +engine::want engine::perform(int (engine::* op)(void *, std::size_t), + void *data, std::size_t length, asio::error_code &ec, + std::size_t *bytes_transferred) { std::size_t pending_output_before = ssl_->ext_bio()->ctrl_pending(); int result = (this->*op)(data, length); std::size_t pending_output_after = ssl_->ext_bio()->ctrl_pending(); - if (mbedtls::error_codes::is_error(result)) - { + if (mbedtls::error_codes::is_error(result)) { ec = asio::error_code(result, asio::error::get_mbedtls_category()); return pending_output_after > pending_output_before ? want_output : want_nothing; } - if (result == 0) - { + if (result == 0) { return pending_output_after > pending_output_before ? want_output : want_nothing; } - if (result > 0 && bytes_transferred) + if (result > 0 && bytes_transferred) { *bytes_transferred = static_cast(result); + } - if (mbedtls::error_codes::want_write(result)) - { + if (mbedtls::error_codes::want_write(result)) { ec = asio::error_code(); return want_output_and_retry; - } - else if (pending_output_after > pending_output_before) - { + } else if (pending_output_after > pending_output_before) { ec = asio::error_code(); return result > 0 ? want_output : want_output_and_retry; - } - else if (mbedtls::error_codes::want_read(result)) - { + } else if (mbedtls::error_codes::want_read(result)) { ec = asio::error_code(); return want_input_and_retry; - } - else if (ssl_->get_state() == mbedtls::CLOSED) - { + } else if (ssl_->get_state() == mbedtls::CLOSED) { ec = asio::error::eof; return want_nothing; } @@ -178,27 +167,27 @@ engine::want engine::perform(int (engine::* op)(void*, std::size_t), return want_nothing; } -int engine::do_accept(void*, std::size_t) +int engine::do_accept(void *, std::size_t) { return ssl_->accept(); } -int engine::do_connect(void*, std::size_t) +int engine::do_connect(void *, std::size_t) { return ssl_->connect(); } -int engine::do_shutdown(void*, std::size_t) +int engine::do_shutdown(void *, std::size_t) { return ssl_->shutdown(); } -int engine::do_read(void* data, std::size_t length) +int engine::do_read(void *data, std::size_t length) { return ssl_->read(data, length < INT_MAX ? static_cast(length) : INT_MAX); } -int engine::do_write(void* data, std::size_t length) +int engine::do_write(void *data, std::size_t length) { return ssl_->write(data, length < INT_MAX ? static_cast(length) : INT_MAX); } diff --git a/components/asio/port/src/asio_ssl_impl.cpp b/components/asio/port/src/asio_ssl_impl.cpp index 8f387dd7b..562420597 100644 --- a/components/asio/port/src/asio_ssl_impl.cpp +++ b/components/asio/port/src/asio_ssl_impl.cpp @@ -1,5 +1,5 @@ // -// SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD +// SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD // // SPDX-License-Identifier: Apache-2.0 // @@ -17,4 +17,6 @@ asio::detail::shared_ptr openssl_init_base::instance return nullptr; } -} } } // namespace asio::ssl::detail +} +} +} // namespace asio::ssl::detail diff --git a/components/esp_modem/.gitignore b/components/esp_modem/.gitignore index 01f34e62e..9cf987f7e 100644 --- a/components/esp_modem/.gitignore +++ b/components/esp_modem/.gitignore @@ -93,4 +93,4 @@ dependencies.lock docs/html # esp-idf managed components -**/managed_components/** \ No newline at end of file +**/managed_components/** diff --git a/components/esp_modem/docs/Doxyfile b/components/esp_modem/docs/Doxyfile index 8faf43db4..b00d43fe3 100644 --- a/components/esp_modem/docs/Doxyfile +++ b/components/esp_modem/docs/Doxyfile @@ -2522,4 +2522,3 @@ DOT_CLEANUP = YES #DOT_GRAPH_MAX_NODES = 100 #MAX_DOT_GRAPH_DEPTH = 0 #DOT_TRANSPARENT = YES - diff --git a/components/esp_modem/docs/README.md b/components/esp_modem/docs/README.md index dc1e0639c..6e50d9bcd 100644 --- a/components/esp_modem/docs/README.md +++ b/components/esp_modem/docs/README.md @@ -1,14 +1,14 @@ # ESP MODEM This component is used to communicate with modems in the command mode (using AT commands), as well as the data mode -(over PPPoS protocol). +(over PPPoS protocol). The modem device is modeled with a DCE (Data Communication Equipment) object, which is composed of: * DTE (Data Terminal Equipment), which abstracts the terminal (currently only UART implemented). * PPP Netif representing a network interface communicating with the DTE using PPP protocol. * Module abstracting the specific device model and its commands. ``` - +-----+ + +-----+ | DTE |--+ +-----+ | +-------+ +-->| DCE | @@ -16,17 +16,17 @@ The modem device is modeled with a DCE (Data Communication Equipment) object, wh | Module|--->| | +-------+ | |o--- send_commands +->| | - +------+ | +-------+ - | PPP |--+ + +------+ | +-------+ + | PPP |--+ | netif|------------------> network events - +------+ + +------+ ``` ## Modem components ### DCE This is the basic operational unit of the esp_modem component, abstracting a specific module in software, -which is basically configured by +which is basically configured by * the I/O communication media (UART), defined by the DTE configuration * the specific command library supported by the device model, defined with the module type * network interface configuration (PPPoS config in lwip) @@ -52,7 +52,7 @@ Users interact with the esp-modem using the DCE's interface, to basically * Switch between command and data mode to connect to the internet via cellular network. * Send various commands to the device (e.g. send SMS) -The applications typically register handlers for network events to receive notification on the network availability and +The applications typically register handlers for network events to receive notification on the network availability and IP address changes. Common use cases of the esp-modem are also listed as the examples: diff --git a/components/esp_modem/docs/advanced_api.rst b/components/esp_modem/docs/advanced_api.rst index 8fc939b15..a487398b3 100644 --- a/components/esp_modem/docs/advanced_api.rst +++ b/components/esp_modem/docs/advanced_api.rst @@ -46,4 +46,3 @@ a custom DTE object and supply it into :ref:`the DCE factory`. The - Create the DTE which uses the custom Terminal Please refer to the implementation of the existing UART DTE. - diff --git a/components/esp_modem/docs/api_docs.rst b/components/esp_modem/docs/api_docs.rst index 6727de13e..4ace0e1ac 100644 --- a/components/esp_modem/docs/api_docs.rst +++ b/components/esp_modem/docs/api_docs.rst @@ -6,7 +6,7 @@ C API Documentation The C API is very simple and consist of these two basic parts: -- :ref:`lifecycle_api` +- :ref:`lifecycle_api` - :ref:`modem_commands` The Typical application workflow is to: @@ -54,4 +54,4 @@ Configuration structures .. doxygengroup:: ESP_MODEM_CONFIG - :members: \ No newline at end of file + :members: diff --git a/components/esp_modem/docs/conf.py b/components/esp_modem/docs/conf.py index 8a41ca248..b88b51b0a 100644 --- a/components/esp_modem/docs/conf.py +++ b/components/esp_modem/docs/conf.py @@ -2,11 +2,6 @@ # # English Language RTD & Sphinx config file # -import os -import os.path -import re -import subprocess -import sys # General information about the project. project = u'esp-modem' @@ -18,11 +13,12 @@ language = 'en' extensions = ['breathe', 'recommonmark'] - breathe_projects = {'esp_modem': 'xml'} -breathe_default_project = "esp_modem" +breathe_default_project = 'esp_modem' source_suffix = ['.rst', '.md'] -source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser', } \ No newline at end of file +source_parsers = { + '.md': 'recommonmark.parser.CommonMarkParser', +} diff --git a/components/esp_modem/docs/cxx_api_docs.rst b/components/esp_modem/docs/cxx_api_docs.rst index 5544c368a..94fdb94e1 100644 --- a/components/esp_modem/docs/cxx_api_docs.rst +++ b/components/esp_modem/docs/cxx_api_docs.rst @@ -41,4 +41,4 @@ Destroy the DCE --------------- The DCE object is created as ``std::unique_ptr`` by default and as such doesn't have to be explicitly destroyed. -It simply gets destroyed and cleaned-up automatically if the object goes out of the block scope. \ No newline at end of file +It simply gets destroyed and cleaned-up automatically if the object goes out of the block scope. diff --git a/components/esp_modem/docs/internal_design.md b/components/esp_modem/docs/internal_design.md index 379855de6..c132bede0 100644 --- a/components/esp_modem/docs/internal_design.md +++ b/components/esp_modem/docs/internal_design.md @@ -5,16 +5,16 @@ * Use C++ with additional C API * Use exceptions - - Use macro wrapper over `try-catch` blocks when exceptions off (use `abort()` if `THROW()`) + - Use macro wrapper over `try-catch` blocks when exceptions off (use `abort()` if `THROW()`) * Initializes and allocates in the constructor (might throw) - easier code with exceptions ON, with exceptions OFF alloc/init failures are not treated as runtime error (program aborts) - break down long initialization in constructor into more private methods * Implements different devices using inheritance from `GenericModule`, which is the most general implementation of a common modem - - Internally uses templates with device specialization (modeled as `DCE`) which could be used as well for some special cases, + - Internally uses templates with device specialization (modeled as `DCE`) which could be used as well for some special cases, such as implantation of a minimal device (ModuleIf), add new AT commands (oOnly in compile time), or using the Module with DTE only (no DCE, no Netif) for sending AT commands without network - + ## DCE collaboration model The diagram describes how the DCE class collaborates with DTE, PPP and the device abstraction diff --git a/components/esp_modem/docs/internal_docs.rst b/components/esp_modem/docs/internal_docs.rst index 1416edcc3..bd2d269de 100644 --- a/components/esp_modem/docs/internal_docs.rst +++ b/components/esp_modem/docs/internal_docs.rst @@ -115,8 +115,3 @@ Modem types .. doxygengroup:: ESP_MODEM_TYPES :members: - - - - - diff --git a/components/esp_modem/examples/ap_to_pppos/README.md b/components/esp_modem/examples/ap_to_pppos/README.md index 6f8d184ce..715c846fd 100644 --- a/components/esp_modem/examples/ap_to_pppos/README.md +++ b/components/esp_modem/examples/ap_to_pppos/README.md @@ -18,4 +18,4 @@ Also, to demonstrate the dce_factory functionality, a new `NetDCE_Factory` is im ### Supported IDF versions -This example is only supported from `v4.2`, since is uses NAPT feature. \ No newline at end of file +This example is only supported from `v4.2`, since is uses NAPT feature. diff --git a/components/esp_modem/examples/ap_to_pppos/main/ap_to_pppos.c b/components/esp_modem/examples/ap_to_pppos/main/ap_to_pppos.c index 709bf4ecc..c0547a7e7 100644 --- a/components/esp_modem/examples/ap_to_pppos/main/ap_to_pppos.c +++ b/components/esp_modem/examples/ap_to_pppos/main/ap_to_pppos.c @@ -1,10 +1,11 @@ -/* softAP to PPPoS Example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * softAP to PPPoS Example */ #include #include "esp_system.h" @@ -18,8 +19,8 @@ #include "freertos/event_groups.h" #include "network_dce.h" #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) - #include "esp_mac.h" - #include "dhcpserver/dhcpserver.h" +#include "esp_mac.h" +#include "dhcpserver/dhcpserver.h" #endif #define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID @@ -77,15 +78,15 @@ static esp_err_t set_dhcps_dns(esp_netif_t *netif, uint32_t addr) return ESP_OK; } -static void wifi_event_handler(void* arg, esp_event_base_t event_base, - int32_t event_id, void* event_data) +static void wifi_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) { if (event_id == WIFI_EVENT_AP_STACONNECTED) { - wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data; + wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *) event_data; ESP_LOGI(TAG, "station "MACSTR" join, AID=%d", MAC2STR(event->mac), event->aid); } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) { - wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data; + wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *) event_data; ESP_LOGI(TAG, "station "MACSTR" leave, AID=%d", MAC2STR(event->mac), event->aid); } @@ -98,10 +99,10 @@ void wifi_init_softap(void) ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, - ESP_EVENT_ANY_ID, - &wifi_event_handler, - NULL, - NULL)); + ESP_EVENT_ANY_ID, + &wifi_event_handler, + NULL, + NULL)); wifi_config_t wifi_config = { .ap = { @@ -162,8 +163,8 @@ void app_main(void) // Initialize NVS esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { - ESP_ERROR_CHECK(nvs_flash_erase()); - ret = nvs_flash_init(); + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); diff --git a/components/esp_modem/examples/ap_to_pppos/main/network_dce.c b/components/esp_modem/examples/ap_to_pppos/main/network_dce.c index f79a46c5c..8ba8f3181 100644 --- a/components/esp_modem/examples/ap_to_pppos/main/network_dce.c +++ b/components/esp_modem/examples/ap_to_pppos/main/network_dce.c @@ -1,10 +1,11 @@ -/* softAP to PPPoS Example (network_dce) +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * softAP to PPPoS Example (network_dce) */ #include diff --git a/components/esp_modem/examples/ap_to_pppos/main/network_dce.cpp b/components/esp_modem/examples/ap_to_pppos/main/network_dce.cpp index 13e0c0c84..aef91f87c 100644 --- a/components/esp_modem/examples/ap_to_pppos/main/network_dce.cpp +++ b/components/esp_modem/examples/ap_to_pppos/main/network_dce.cpp @@ -1,10 +1,11 @@ -/* softAP to PPPoS Example (network_dce) +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * softAP to PPPoS Example (network_dce) */ #include "cxx_include/esp_modem_dte.hpp" @@ -92,8 +93,9 @@ public: bool check_signal() { int rssi, ber; - if (dce_commands::get_signal_quality(dte.get(), rssi, ber) != command_result::OK) + if (dce_commands::get_signal_quality(dte.get(), rssi, ber) != command_result::OK) { return false; + } return rssi != 99 && rssi > 5; } @@ -215,4 +217,4 @@ extern "C" bool modem_check_signal() return dce->get_module()->check_signal(); } -} \ No newline at end of file +} diff --git a/components/esp_modem/examples/ap_to_pppos/main/network_dce.h b/components/esp_modem/examples/ap_to_pppos/main/network_dce.h index 5c7d4a96f..308bb045d 100644 --- a/components/esp_modem/examples/ap_to_pppos/main/network_dce.h +++ b/components/esp_modem/examples/ap_to_pppos/main/network_dce.h @@ -1,10 +1,11 @@ -/* softAP to PPPoS Example (network_dce) +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * softAP to PPPoS Example (network_dce) */ #pragma once diff --git a/components/esp_modem/examples/linux_modem/README.md b/components/esp_modem/examples/linux_modem/README.md index c480dde00..25f670f7b 100644 --- a/components/esp_modem/examples/linux_modem/README.md +++ b/components/esp_modem/examples/linux_modem/README.md @@ -20,4 +20,4 @@ over PPPoS, i.e. over the modem serial line. ### Supported IDF versions -This example (using the default CMake IDF build system) is only supported from `v4.4`, since is uses `idf.py`'s linux target. \ No newline at end of file +This example (using the default CMake IDF build system) is only supported from `v4.4`, since is uses `idf.py`'s linux target. diff --git a/components/esp_modem/examples/linux_modem/main/modem_main.cpp b/components/esp_modem/examples/linux_modem/main/modem_main.cpp index afb2f8628..174c36926 100644 --- a/components/esp_modem/examples/linux_modem/main/modem_main.cpp +++ b/components/esp_modem/examples/linux_modem/main/modem_main.cpp @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include #include #include @@ -79,4 +84,4 @@ int main() usleep(15'000'000); esp_netif_destroy(tun_netif); -} \ No newline at end of file +} diff --git a/components/esp_modem/examples/modem_console/Makefile b/components/esp_modem/examples/modem_console/Makefile index 1adbf2ba1..70855c84d 100644 --- a/components/esp_modem/examples/modem_console/Makefile +++ b/components/esp_modem/examples/modem_console/Makefile @@ -8,4 +8,3 @@ PROJECT_NAME := modem-console EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/common_components/protocol_examples_common include $(IDF_PATH)/make/project.mk - diff --git a/components/esp_modem/examples/modem_console/README.md b/components/esp_modem/examples/modem_console/README.md index c76e82b75..1b4db2881 100644 --- a/components/esp_modem/examples/modem_console/README.md +++ b/components/esp_modem/examples/modem_console/README.md @@ -30,4 +30,4 @@ You must send a character to it (via idf.py monitor), so it unblocks and properl This example is only supported from `v4.2`, due to support of the console repl mode. -USB example is supported from `v4.4`. \ No newline at end of file +USB example is supported from `v4.4`. diff --git a/components/esp_modem/examples/modem_console/main/Kconfig.projbuild b/components/esp_modem/examples/modem_console/main/Kconfig.projbuild index 915448d3e..1415229f1 100644 --- a/components/esp_modem/examples/modem_console/main/Kconfig.projbuild +++ b/components/esp_modem/examples/modem_console/main/Kconfig.projbuild @@ -83,7 +83,7 @@ menu "Example Configuration" default EXAMPLE_FLOW_CONTROL_NONE help Set the modem's preferred control flow - + config EXAMPLE_FLOW_CONTROL_NONE bool "No control flow" config EXAMPLE_FLOW_CONTROL_SW diff --git a/components/esp_modem/examples/modem_console/main/console_helper.cpp b/components/esp_modem/examples/modem_console/main/console_helper.cpp index 6adca8970..be8d369c6 100644 --- a/components/esp_modem/examples/modem_console/main/console_helper.cpp +++ b/components/esp_modem/examples/modem_console/main/console_helper.cpp @@ -1,10 +1,11 @@ -/* Modem console example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Modem console example */ #include "console_helper.hpp" diff --git a/components/esp_modem/examples/modem_console/main/console_helper.hpp b/components/esp_modem/examples/modem_console/main/console_helper.hpp index cae138309..c6012a7e0 100644 --- a/components/esp_modem/examples/modem_console/main/console_helper.hpp +++ b/components/esp_modem/examples/modem_console/main/console_helper.hpp @@ -1,10 +1,11 @@ -/* Modem console example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Modem console example */ #pragma once diff --git a/components/esp_modem/examples/modem_console/main/httpget_handle.c b/components/esp_modem/examples/modem_console/main/httpget_handle.c index 471562581..055c026a6 100644 --- a/components/esp_modem/examples/modem_console/main/httpget_handle.c +++ b/components/esp_modem/examples/modem_console/main/httpget_handle.c @@ -1,10 +1,12 @@ -/* Modem console example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Modem console example + * */ #include @@ -19,34 +21,34 @@ static const char *TAG = "modem_console_httpget"; static esp_err_t http_event_handler(esp_http_client_event_t *evt) { - switch(evt->event_id) { - case HTTP_EVENT_ERROR: - ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); - break; - case HTTP_EVENT_ON_CONNECTED: - ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED"); - break; - case HTTP_EVENT_HEADER_SENT: - ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); - break; - case HTTP_EVENT_ON_HEADER: - ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value); - break; - case HTTP_EVENT_ON_DATA: - ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); - if ((bool)evt->user_data && + switch (evt->event_id) { + case HTTP_EVENT_ERROR: + ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); + break; + case HTTP_EVENT_ON_CONNECTED: + ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED"); + break; + case HTTP_EVENT_HEADER_SENT: + ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); + break; + case HTTP_EVENT_ON_HEADER: + ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value); + break; + case HTTP_EVENT_ON_DATA: + ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); + if ((bool)evt->user_data && !esp_http_client_is_chunked_response(evt->client)) { - ESP_LOG_BUFFER_HEXDUMP(TAG, evt->data, evt->data_len, ESP_LOG_INFO); - } + ESP_LOG_BUFFER_HEXDUMP(TAG, evt->data, evt->data_len, ESP_LOG_INFO); + } - break; - case HTTP_EVENT_ON_FINISH: - ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); - break; - case HTTP_EVENT_DISCONNECTED: - ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED"); - break; - default: break; + break; + case HTTP_EVENT_ON_FINISH: + ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); + break; + case HTTP_EVENT_DISCONNECTED: + ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED"); + break; + default: break; } return ESP_OK; } @@ -65,7 +67,7 @@ static int do_http_client(int argc, char **argv) return 1; } esp_http_client_config_t config = { - .event_handler = http_event_handler, + .event_handler = http_event_handler, }; if (http_args.host->count > 0) { @@ -76,11 +78,11 @@ static int do_http_client(int argc, char **argv) if (http_args.hex->count > 0) { // show hex data from http-get - config.user_data = (void*)true; + config.user_data = (void *)true; } - esp_http_client_handle_t client = esp_http_client_init(&config); + esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { @@ -99,11 +101,11 @@ void modem_console_register_http(void) http_args.hex = arg_litn("p", "print-hex", 0, 1, "print hex output"), http_args.end = arg_end(1); const esp_console_cmd_t http_cmd = { - .command = "httpget", - .help = "http get command to test data mode", - .hint = NULL, - .func = &do_http_client, - .argtable = &http_args + .command = "httpget", + .help = "http get command to test data mode", + .hint = NULL, + .func = &do_http_client, + .argtable = &http_args }; ESP_ERROR_CHECK(esp_console_cmd_register(&http_cmd)); } diff --git a/components/esp_modem/examples/modem_console/main/idf_component.yml b/components/esp_modem/examples/modem_console/main/idf_component.yml index ffcae2a6b..4c9e8c885 100644 --- a/components/esp_modem/examples/modem_console/main/idf_component.yml +++ b/components/esp_modem/examples/modem_console/main/idf_component.yml @@ -9,4 +9,4 @@ dependencies: version: "^1.0.0" rules: - if: "idf_version >=4.4" - - if: "target in [esp32s2, esp32s3]" \ No newline at end of file + - if: "target in [esp32s2, esp32s3]" diff --git a/components/esp_modem/examples/modem_console/main/modem_console_main.cpp b/components/esp_modem/examples/modem_console/main/modem_console_main.cpp index 9ace57c1e..795a36524 100644 --- a/components/esp_modem/examples/modem_console/main/modem_console_main.cpp +++ b/components/esp_modem/examples/modem_console/main/modem_console_main.cpp @@ -1,10 +1,11 @@ -/* Modem console example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Modem console example */ #include diff --git a/components/esp_modem/examples/modem_console/main/my_module_dce.hpp b/components/esp_modem/examples/modem_console/main/my_module_dce.hpp index 0a62df76d..907a5a744 100644 --- a/components/esp_modem/examples/modem_console/main/my_module_dce.hpp +++ b/components/esp_modem/examples/modem_console/main/my_module_dce.hpp @@ -1,10 +1,11 @@ -/* Modem console example: Custom DCE +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * Modem console example: Custom DCE */ #pragma once diff --git a/components/esp_modem/examples/modem_console/main/ping_handle.c b/components/esp_modem/examples/modem_console/main/ping_handle.c index cc01cdfb3..1e2477865 100644 --- a/components/esp_modem/examples/modem_console/main/ping_handle.c +++ b/components/esp_modem/examples/modem_console/main/ping_handle.c @@ -1,10 +1,10 @@ -/* Ping handle example - - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +/* + * Ping handle example */ #include @@ -29,7 +29,7 @@ static void cmd_ping_on_ping_success(esp_ping_handle_t hdl, void *args) esp_ping_get_profile(hdl, ESP_PING_PROF_SIZE, &recv_len, sizeof(recv_len)); esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_time)); ESP_LOGI(TAG, "%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n", - recv_len, inet_ntoa(target_addr.u_addr.ip4), seqno, ttl, elapsed_time); + recv_len, inet_ntoa(target_addr.u_addr.ip4), seqno, ttl, elapsed_time); } static void cmd_ping_on_ping_timeout(esp_ping_handle_t hdl, void *args) @@ -58,7 +58,7 @@ static void cmd_ping_on_ping_end(esp_ping_handle_t hdl, void *args) ESP_LOGI(TAG, "\n--- %s ping statistics ---\n", inet6_ntoa(*ip_2_ip6(&target_addr))); } ESP_LOGI(TAG, "%d packets transmitted, %d received, %d%% packet loss, time %dms\n", - transmitted, received, loss, total_time_ms); + transmitted, received, loss, total_time_ms); // delete the ping sessions, so that we clean up all resources and can create a new ping session // we don't have to call delete function in the callback, instead we can call delete function from other tasks esp_ping_delete_session(hdl); @@ -112,10 +112,10 @@ static int do_ping_cmd(int argc, char **argv) /* set callback functions */ esp_ping_callbacks_t cbs = { - .on_ping_success = cmd_ping_on_ping_success, - .on_ping_timeout = cmd_ping_on_ping_timeout, - .on_ping_end = cmd_ping_on_ping_end, - .cb_args = NULL + .on_ping_success = cmd_ping_on_ping_success, + .on_ping_timeout = cmd_ping_on_ping_timeout, + .on_ping_end = cmd_ping_on_ping_end, + .cb_args = NULL }; esp_ping_handle_t ping; esp_ping_new_session(&config, &cbs, &ping); @@ -131,11 +131,11 @@ void modem_console_register_ping(void) ping_args.host = arg_str1(NULL, NULL, "", "Host address"); ping_args.end = arg_end(1); const esp_console_cmd_t ping_cmd = { - .command = "ping", - .help = "send ICMP ECHO_REQUEST to network hosts", - .hint = NULL, - .func = &do_ping_cmd, - .argtable = &ping_args + .command = "ping", + .help = "send ICMP ECHO_REQUEST to network hosts", + .hint = NULL, + .func = &do_ping_cmd, + .argtable = &ping_args }; ESP_ERROR_CHECK(esp_console_cmd_register(&ping_cmd)); -} \ No newline at end of file +} diff --git a/components/esp_modem/examples/modem_console/sdkconfig.ci.usb b/components/esp_modem/examples/modem_console/sdkconfig.ci.usb index 0014fb451..ae535ca26 100644 --- a/components/esp_modem/examples/modem_console/sdkconfig.ci.usb +++ b/components/esp_modem/examples/modem_console/sdkconfig.ci.usb @@ -1 +1 @@ -CONFIG_EXAMPLE_SERIAL_CONFIG_USB=y \ No newline at end of file +CONFIG_EXAMPLE_SERIAL_CONFIG_USB=y diff --git a/components/esp_modem/examples/pppos_client/CMakeLists.txt b/components/esp_modem/examples/pppos_client/CMakeLists.txt index 43372227e..4728071e6 100644 --- a/components/esp_modem/examples/pppos_client/CMakeLists.txt +++ b/components/esp_modem/examples/pppos_client/CMakeLists.txt @@ -6,5 +6,3 @@ set(EXTRA_COMPONENT_DIRS "../..") include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(pppos_client) - - diff --git a/components/esp_modem/examples/pppos_client/README.md b/components/esp_modem/examples/pppos_client/README.md index 8c776c66e..f319a2fed 100644 --- a/components/esp_modem/examples/pppos_client/README.md +++ b/components/esp_modem/examples/pppos_client/README.md @@ -21,6 +21,6 @@ This example supports USB modem hot-plugging and reconnection. ### Supported IDF versions -This example is only supported from `v4.1`, as this is the default dependency of `esp-modem` component. +This example is only supported from `v4.1`, as this is the default dependency of `esp-modem` component. -USB example is supported from `v4.4`. \ No newline at end of file +USB example is supported from `v4.4`. diff --git a/components/esp_modem/examples/pppos_client/main/idf_component.yml b/components/esp_modem/examples/pppos_client/main/idf_component.yml index 27e4aa420..dd06b5100 100644 --- a/components/esp_modem/examples/pppos_client/main/idf_component.yml +++ b/components/esp_modem/examples/pppos_client/main/idf_component.yml @@ -9,4 +9,4 @@ dependencies: version: "^1.0.0" rules: - if: "idf_version >=4.4" - - if: "target in [esp32s2, esp32s3]" \ No newline at end of file + - if: "target in [esp32s2, esp32s3]" diff --git a/components/esp_modem/examples/pppos_client/main/pppos_client_main.c b/components/esp_modem/examples/pppos_client/main/pppos_client_main.c index ec41d61fd..a7dac04a6 100644 --- a/components/esp_modem/examples/pppos_client/main/pppos_client_main.c +++ b/components/esp_modem/examples/pppos_client/main/pppos_client_main.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ /* PPPoS Client Example This example code is in the Public Domain (or CC0 licensed, at your option.) @@ -181,7 +186,7 @@ void app_main(void) while (1) { ESP_LOGI(TAG, "Initializing esp_modem for the BG96 module..."); struct esp_modem_usb_term_config usb_config = ESP_MODEM_DEFAULT_USB_CONFIG(0x2C7C, 0x0296, 2); // VID, PID and interface num of BG96 modem - const esp_modem_dte_config_t dte_usb_config = ESP_MODEM_DTE_DEFAULT_USB_CONFIG(usb_config); + const esp_modem_dte_config_t dte_usb_config = ESP_MODEM_DTE_DEFAULT_USB_CONFIG(usb_config); ESP_LOGI(TAG, "Waiting for USB device connection..."); esp_modem_dce_t *dce = esp_modem_new_dev_usb(ESP_MODEM_DCE_BG96, &dte_usb_config, &dce_config, esp_netif); esp_modem_set_error_cb(dce, usb_terminal_error_handler); @@ -244,7 +249,7 @@ void app_main(void) }; #else esp_mqtt_client_config_t mqtt_config = { - .uri = BROKER_URL, + .uri = BROKER_URL, }; #endif esp_mqtt_client_handle_t mqtt_client = esp_mqtt_client_init(&mqtt_config); @@ -269,11 +274,11 @@ void app_main(void) ESP_LOGI(TAG, "IMSI=%s", imsi); #if defined(CONFIG_EXAMPLE_SERIAL_CONFIG_USB) - // USB example runs in a loop to demonstrate hot-plugging and sudden disconnection features. - ESP_LOGI(TAG, "USB demo finished. Disconnect and connect the modem to run it again"); - xEventGroupWaitBits(event_group, USB_DISCONNECTED_BIT, pdFALSE, pdFALSE, portMAX_DELAY); - CHECK_USB_DISCONNECTION(event_group); // dce will be destroyed here - } // while (1) + // USB example runs in a loop to demonstrate hot-plugging and sudden disconnection features. + ESP_LOGI(TAG, "USB demo finished. Disconnect and connect the modem to run it again"); + xEventGroupWaitBits(event_group, USB_DISCONNECTED_BIT, pdFALSE, pdFALSE, portMAX_DELAY); + CHECK_USB_DISCONNECTION(event_group); // dce will be destroyed here +} // while (1) #else // UART DTE clean-up esp_modem_destroy(dce); diff --git a/components/esp_modem/examples/pppos_client/sdkconfig.ci.usb b/components/esp_modem/examples/pppos_client/sdkconfig.ci.usb index 0014fb451..ae535ca26 100644 --- a/components/esp_modem/examples/pppos_client/sdkconfig.ci.usb +++ b/components/esp_modem/examples/pppos_client/sdkconfig.ci.usb @@ -1 +1 @@ -CONFIG_EXAMPLE_SERIAL_CONFIG_USB=y \ No newline at end of file +CONFIG_EXAMPLE_SERIAL_CONFIG_USB=y diff --git a/components/esp_modem/examples/simple_cmux_client/CMakeLists.txt b/components/esp_modem/examples/simple_cmux_client/CMakeLists.txt index dfe712c00..6547c1450 100644 --- a/components/esp_modem/examples/simple_cmux_client/CMakeLists.txt +++ b/components/esp_modem/examples/simple_cmux_client/CMakeLists.txt @@ -6,5 +6,3 @@ set(EXTRA_COMPONENT_DIRS "../.." $ENV{IDF_PATH}/examples/cxx/experimental/experi include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(simple_cmux_client) - - diff --git a/components/esp_modem/examples/simple_cmux_client/README.md b/components/esp_modem/examples/simple_cmux_client/README.md index 71438d512..f0242fe85 100644 --- a/components/esp_modem/examples/simple_cmux_client/README.md +++ b/components/esp_modem/examples/simple_cmux_client/README.md @@ -18,4 +18,4 @@ Please check the component [README](../../README.md) ### Supported IDF versions -This example is only supported from `v4.3`, since is uses an experimental `esp_event_cxx` component. \ No newline at end of file +This example is only supported from `v4.3`, since is uses an experimental `esp_event_cxx` component. diff --git a/components/esp_modem/examples/simple_cmux_client/main/Kconfig.projbuild b/components/esp_modem/examples/simple_cmux_client/main/Kconfig.projbuild index 73ea224f6..16c0da168 100644 --- a/components/esp_modem/examples/simple_cmux_client/main/Kconfig.projbuild +++ b/components/esp_modem/examples/simple_cmux_client/main/Kconfig.projbuild @@ -90,7 +90,7 @@ menu "Example Configuration" help Pin number of UART CTS. endmenu - + config EXAMPLE_USE_VFS_TERM bool "Use VFS terminal" default n diff --git a/components/esp_modem/examples/simple_cmux_client/main/simple_cmux_client_main.cpp b/components/esp_modem/examples/simple_cmux_client/main/simple_cmux_client_main.cpp index 9678c6313..0f3f4b760 100644 --- a/components/esp_modem/examples/simple_cmux_client/main/simple_cmux_client_main.cpp +++ b/components/esp_modem/examples/simple_cmux_client/main/simple_cmux_client_main.cpp @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ /* PPPoS Client Example This example code is in the Public Domain (or CC0 licensed, at your option.) @@ -96,8 +101,7 @@ extern "C" void app_main(void) #endif assert(dce); - if(dte_config.uart_config.flow_control == ESP_MODEM_FLOW_CONTROL_HW) - { + if (dte_config.uart_config.flow_control == ESP_MODEM_FLOW_CONTROL_HW) { if (command_result::OK != dce->set_flow_control(2, 2)) { ESP_LOGE(TAG, "Failed to set the set_flow_control mode"); return; diff --git a/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.cpp b/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.cpp index 571ce4af0..91b95519c 100644 --- a/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.cpp +++ b/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.cpp @@ -1,10 +1,11 @@ -/* PPPoS Client Example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * PPPoS Client Example */ #include diff --git a/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.hpp b/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.hpp index d3fa3d77b..971d980b9 100644 --- a/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.hpp +++ b/components/esp_modem/examples/simple_cmux_client/main/simple_mqtt_client.hpp @@ -1,10 +1,11 @@ -/* PPPoS Client Example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * PPPoS Client Example */ #pragma once diff --git a/components/esp_modem/examples/simple_cmux_client/sdkconfig.defaults b/components/esp_modem/examples/simple_cmux_client/sdkconfig.defaults index b6fa51455..8f54fe475 100644 --- a/components/esp_modem/examples/simple_cmux_client/sdkconfig.defaults +++ b/components/esp_modem/examples/simple_cmux_client/sdkconfig.defaults @@ -9,4 +9,4 @@ CONFIG_PARTITION_TABLE_TWO_OTA=y CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF=y CONFIG_NEWLIB_STDIN_LINE_ENDING_LF=y -CONFIG_MAIN_TASK_STACK_SIZE=8192 \ No newline at end of file +CONFIG_MAIN_TASK_STACK_SIZE=8192 diff --git a/components/esp_modem/include/cxx_include/esp_modem_api.hpp b/components/esp_modem/include/cxx_include/esp_modem_api.hpp index b74ea8b36..690d7b324 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_api.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_api.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/include/cxx_include/esp_modem_buffer.hpp b/components/esp_modem/include/cxx_include/esp_modem_buffer.hpp index b04903b35..a26ee8e01 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_buffer.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_buffer.hpp @@ -1,16 +1,8 @@ -// Copyright 2022 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -22,15 +14,15 @@ namespace esp_modem { */ struct unique_buffer { explicit unique_buffer(size_t size); - unique_buffer (unique_buffer const&) = delete; - unique_buffer& operator=(unique_buffer const&) = delete; - unique_buffer(unique_buffer&& other) noexcept + unique_buffer (unique_buffer const &) = delete; + unique_buffer &operator=(unique_buffer const &) = delete; + unique_buffer(unique_buffer &&other) noexcept { data = std::move(other.data); size = other.size; consumed = 0; } - unique_buffer& operator=(unique_buffer&& other) noexcept + unique_buffer &operator=(unique_buffer &&other) noexcept { if (&other == this) { return *this; @@ -40,7 +32,10 @@ struct unique_buffer { consumed = 0; return *this; } - [[nodiscard]] uint8_t *get() const { return data.get(); } + [[nodiscard]] uint8_t *get() const + { + return data.get(); + } std::unique_ptr data; size_t size{}; diff --git a/components/esp_modem/include/cxx_include/esp_modem_cmux.hpp b/components/esp_modem/include/cxx_include/esp_modem_cmux.hpp index 16c6adc87..6866ad446 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_cmux.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_cmux.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -55,7 +47,7 @@ class CMuxInstance; */ class CMux { public: - explicit CMux(std::shared_ptr t, unique_buffer&& b): + explicit CMux(std::shared_ptr t, unique_buffer &&b): term(std::move(t)), payload_start(nullptr), total_payload_size(0), buffer(std::move(b)) {} ~CMux() = default; diff --git a/components/esp_modem/include/cxx_include/esp_modem_command_library.hpp b/components/esp_modem/include/cxx_include/esp_modem_command_library.hpp index 1952d44f1..feba2febc 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_command_library.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_command_library.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -47,7 +39,7 @@ command_result get_battery_status_sim7xxx(CommandableIf *t, int &voltage, int &b command_result set_gnss_power_mode_sim76xx(CommandableIf *t, int mode); command_result power_down_sim76xx(CommandableIf *t); command_result power_down_sim70xx(CommandableIf *t); -command_result set_network_bands_sim76xx(CommandableIf *t, const std::string& mode, const int* bands, int size); +command_result set_network_bands_sim76xx(CommandableIf *t, const std::string &mode, const int *bands, int size); command_result power_down_sim8xx(CommandableIf *t); command_result set_data_mode_sim8xx(CommandableIf *t); diff --git a/components/esp_modem/include/cxx_include/esp_modem_dce.hpp b/components/esp_modem/include/cxx_include/esp_modem_dce.hpp index f909bfce8..28395e158 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_dce.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_dce.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/include/cxx_include/esp_modem_dce_factory.hpp b/components/esp_modem/include/cxx_include/esp_modem_dce_factory.hpp index 29e2e80f6..46113029a 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_dce_factory.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_dce_factory.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once #include "esp_log.h" diff --git a/components/esp_modem/include/cxx_include/esp_modem_dce_module.hpp b/components/esp_modem/include/cxx_include/esp_modem_dce_module.hpp index 516cc054e..3c6669b37 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_dce_module.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_dce_module.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -82,11 +74,13 @@ public: Task::Delay(1000); // Mandatory 1s pause before int retry = 0; while (retry++ < 3) { - if (set_command_mode() == command_result::OK) + if (set_command_mode() == command_result::OK) { return true; + } Task::Delay(1000); // Mandatory 1s pause after escape - if (sync() == command_result::OK) + if (sync() == command_result::OK) { return true; + } Task::Delay(1000); // Mandatory 1s pause before escape } return false; @@ -107,7 +101,7 @@ public: /** * @brief Simplified version of operator name (without the ACT, which is included in the command library) */ - command_result get_operator_name(std::string& name) + command_result get_operator_name(std::string &name) { int dummy_act; return get_operator_name(name, dummy_act); @@ -140,7 +134,7 @@ public: command_result get_battery_status(int &voltage, int &bcs, int &bcl) override; command_result power_down() override; command_result set_gnss_power_mode(int mode) override; - command_result set_network_bands(const std::string& mode, const int* bands, int size) override; + command_result set_network_bands(const std::string &mode, const int *bands, int size) override; }; /** diff --git a/components/esp_modem/include/cxx_include/esp_modem_dte.hpp b/components/esp_modem/include/cxx_include/esp_modem_dte.hpp index 9c220171b..eba9797f5 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_dte.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_dte.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -106,8 +98,14 @@ protected: /** * @brief Allows for locking the DTE */ - void lock() { internal_lock.lock(); } - void unlock() { internal_lock.unlock(); } + void lock() + { + internal_lock.lock(); + } + void unlock() + { + internal_lock.unlock(); + } friend class Scoped; /*!< Declaring "Scoped lock(dte)" locks this instance */ private: static const size_t GOT_LINE = SignalGroup::bit0; /*!< Bit indicating response available */ diff --git a/components/esp_modem/include/cxx_include/esp_modem_exception.hpp b/components/esp_modem/include/cxx_include/esp_modem_exception.hpp index c51e06d06..fe704d56c 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_exception.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_exception.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -51,35 +43,44 @@ private: #define ESP_MODEM_THROW(exception) do { exception; abort(); } while(0) class esp_err_exception { - void print(std::string msg) { ESP_LOGE("ESP_MODEM_THROW", "%s\n", msg.c_str()); } + void print(std::string msg) + { + ESP_LOGE("ESP_MODEM_THROW", "%s\n", msg.c_str()); + } public: - explicit esp_err_exception(std::string msg) { print(std::move(msg)); } - explicit esp_err_exception(std::string msg, esp_err_t err) { print(std::move(msg)); } + explicit esp_err_exception(std::string msg) + { + print(std::move(msg)); + } + explicit esp_err_exception(std::string msg, esp_err_t err) + { + print(std::move(msg)); + } }; #endif -static inline std::string make_message(const std::string& filename, int line, const std::string& message = "ERROR") +static inline std::string make_message(const std::string &filename, int line, const std::string &message = "ERROR") { std::string text = filename + ":" + std::to_string(line) + " " + message; return text; } -static inline void throw_if_false(const std::string& filename, int line, bool condition, const std::string& message) +static inline void throw_if_false(const std::string &filename, int line, bool condition, const std::string &message) { if (!condition) { ESP_MODEM_THROW(esp_err_exception(make_message(filename, line, message))); } } -static inline void throw_if_error(const std::string& filename, int line, esp_err_t err, const std::string& message) +static inline void throw_if_error(const std::string &filename, int line, esp_err_t err, const std::string &message) { if (err != ESP_OK) { ESP_MODEM_THROW(esp_err_exception(make_message(filename, line, message), err)); } } -static inline void throw_if_error(const std::string& filename, int line, esp_err_t err) +static inline void throw_if_error(const std::string &filename, int line, esp_err_t err) { if (err != ESP_OK) { ESP_MODEM_THROW(esp_err_exception(make_message(filename, line), err)); diff --git a/components/esp_modem/include/cxx_include/esp_modem_netif.hpp b/components/esp_modem/include/cxx_include/esp_modem_netif.hpp index 6262be5a5..8dc8fb2fd 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_netif.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_netif.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/include/cxx_include/esp_modem_primitives.hpp b/components/esp_modem/include/cxx_include/esp_modem_primitives.hpp index 2df6bf85f..843af3d7a 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_primitives.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_primitives.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/include/cxx_include/esp_modem_terminal.hpp b/components/esp_modem/include/cxx_include/esp_modem_terminal.hpp index 24bcd7d1c..07e72b415 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_terminal.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_terminal.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/include/cxx_include/esp_modem_types.hpp b/components/esp_modem/include/cxx_include/esp_modem_types.hpp index d6a3c0efd..e9be501a5 100644 --- a/components/esp_modem/include/cxx_include/esp_modem_types.hpp +++ b/components/esp_modem/include/cxx_include/esp_modem_types.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -68,10 +60,10 @@ struct PdpContext { class CommandableIf { public: CommandableIf() = default; - CommandableIf(const CommandableIf&) = delete; - CommandableIf& operator=(const CommandableIf&) = delete; - CommandableIf(CommandableIf&&) = delete; - CommandableIf& operator=(CommandableIf&&) = delete; + CommandableIf(const CommandableIf &) = delete; + CommandableIf &operator=(const CommandableIf &) = delete; + CommandableIf(CommandableIf &&) = delete; + CommandableIf &operator=(CommandableIf &&) = delete; virtual ~CommandableIf() = default; /** * @brief Sends custom AT command @@ -90,10 +82,10 @@ public: class ModuleIf { public: ModuleIf() = default; - ModuleIf(const ModuleIf&) = delete; - ModuleIf& operator=(const ModuleIf&) = delete; - ModuleIf(ModuleIf&&) = delete; - ModuleIf& operator=(ModuleIf&&) = delete; + ModuleIf(const ModuleIf &) = delete; + ModuleIf &operator=(const ModuleIf &) = delete; + ModuleIf(ModuleIf &&) = delete; + ModuleIf &operator=(ModuleIf &&) = delete; virtual ~ModuleIf() = default; /** * @brief Sets the data mode up (provides the necessary configuration to connect to the cellular network) diff --git a/components/esp_modem/include/esp_modem_api.h b/components/esp_modem/include/esp_modem_api.h index b28b57f62..fdc27ab8a 100644 --- a/components/esp_modem/include/esp_modem_api.h +++ b/components/esp_modem/include/esp_modem_api.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -26,7 +18,7 @@ extern "C" { #define ESP_MODEM_DECLARE_DCE_COMMAND(name, return_type, num, ...) \ esp_err_t esp_modem_ ## name(esp_modem_dce_t *dce, ##__VA_ARGS__); -DECLARE_ALL_COMMAND_APIS(declares esp_modem_(esp_modem_t * dce, ...);) +DECLARE_ALL_COMMAND_APIS(declares esp_modem_(esp_modem_t *dce, ...);) #undef ESP_MODEM_DECLARE_DCE_COMMAND diff --git a/components/esp_modem/include/esp_modem_c_api_types.h b/components/esp_modem/include/esp_modem_c_api_types.h index d1989330a..b0388076b 100644 --- a/components/esp_modem/include/esp_modem_c_api_types.h +++ b/components/esp_modem/include/esp_modem_c_api_types.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -40,8 +32,7 @@ typedef struct esp_modem_PdpContext_t { /** * @brief DCE mode: This enum is used to set desired operation mode of the DCE */ -typedef enum esp_modem_dce_mode -{ +typedef enum esp_modem_dce_mode { ESP_MODEM_MODE_COMMAND, /**< Default mode after modem startup, used for sending AT commands */ ESP_MODEM_MODE_DATA, /**< Used for switching to PPP mode for the modem to connect to a network */ ESP_MODEM_MODE_CMUX, /**< Multiplexed terminal mode */ @@ -50,8 +41,7 @@ typedef enum esp_modem_dce_mode /** * @brief DCE devices: Enum list of supported devices */ -typedef enum esp_modem_dce_device -{ +typedef enum esp_modem_dce_device { ESP_MODEM_DCE_GENETIC, /**< The most generic device */ ESP_MODEM_DCE_SIM7600, ESP_MODEM_DCE_SIM7070, @@ -63,8 +53,7 @@ typedef enum esp_modem_dce_device /** * @brief Terminal errors */ -typedef enum esp_modem_terminal_error -{ +typedef enum esp_modem_terminal_error { ESP_MODEM_TERMINAL_BUFFER_OVERFLOW, ESP_MODEM_TERMINAL_CHECKSUM_ERROR, ESP_MODEM_TERMINAL_UNEXPECTED_CONTROL_FLOW, @@ -105,16 +94,16 @@ esp_modem_dce_t *esp_modem_new_dev(esp_modem_dce_device_t module, const esp_mode * * @param dce DCE to destroy */ -void esp_modem_destroy(esp_modem_dce_t * dce); +void esp_modem_destroy(esp_modem_dce_t *dce); /** * @brief Set DTE's error callback - * + * * @param dce Modem DCE handle * @param[in] err_cb Error callback * @return ESP_OK on success, ESP_FAIL on failure */ -esp_err_t esp_modem_set_error_cb(esp_modem_dce_t * dce, esp_modem_terminal_error_cbt err_cb); +esp_err_t esp_modem_set_error_cb(esp_modem_dce_t *dce, esp_modem_terminal_error_cbt err_cb); /** * @brief Set operation mode for this DCE @@ -122,7 +111,7 @@ esp_err_t esp_modem_set_error_cb(esp_modem_dce_t * dce, esp_modem_terminal_error * @param mode Desired MODE * @return ESP_OK on success, ESP_FAIL on failure */ -esp_err_t esp_modem_set_mode(esp_modem_dce_t * dce, esp_modem_dce_mode_t mode); +esp_err_t esp_modem_set_mode(esp_modem_dce_t *dce, esp_modem_dce_mode_t mode); /** * @} diff --git a/components/esp_modem/include/esp_modem_config.h b/components/esp_modem/include/esp_modem_config.h index 0604142aa..123c83967 100644 --- a/components/esp_modem/include/esp_modem_config.h +++ b/components/esp_modem/include/esp_modem_config.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -70,7 +62,7 @@ struct esp_modem_vfs_resource; */ struct esp_modem_vfs_term_config { int fd; /*!< Already created file descriptor */ - void (*deleter)(int, struct esp_modem_vfs_resource*); /*!< Custom close function for the fd */ + void (*deleter)(int, struct esp_modem_vfs_resource *); /*!< Custom close function for the fd */ struct esp_modem_vfs_resource *resource; /*!< Resource attached to the VFS (need for clenaup) */ }; diff --git a/components/esp_modem/include/esp_modem_dce_config.h b/components/esp_modem/include/esp_modem_dce_config.h index aa523316e..7de716c18 100644 --- a/components/esp_modem/include/esp_modem_dce_config.h +++ b/components/esp_modem/include/esp_modem_dce_config.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -37,7 +29,7 @@ typedef struct esp_modem_dce_config esp_modem_dce_config_t; * @brief DCE configuration structure */ struct esp_modem_dce_config { - const char* apn; /*!< APN: Logical name of the Access point */ + const char *apn; /*!< APN: Logical name of the Access point */ }; /** diff --git a/components/esp_modem/include/esp_private/c_api_wrapper.hpp b/components/esp_modem/include/esp_private/c_api_wrapper.hpp index 7cf903c6b..75cbede18 100644 --- a/components/esp_modem/include/esp_private/c_api_wrapper.hpp +++ b/components/esp_modem/include/esp_private/c_api_wrapper.hpp @@ -1,87 +1,79 @@ -// Copyright 2022 Espressif Systems (Shanghai) PTE LTD -// -// 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. - -/** - * @file c_api_wrapper.hpp - * @brief Collection of C API wrappers - * - * This file is located in include/esp_private because it is not intended for users, - * but rather for esp_modem C extension developers. - * - * The C extension API must provide a 'factory function' that returns initialized pointer to esp_modem_dce_wrap. - * Helper functions provided below, can be used for conversion between C++ enum classes and standard C enums. - */ - -#pragma once - -#include "cxx_include/esp_modem_dce_factory.hpp" -#include "esp_modem_c_api_types.h" - -using namespace esp_modem; - -struct esp_modem_dce_wrap { // need to mimic the polymorphic dispatch as CPP uses templated dispatch - enum class modem_wrap_dte_type { UART, VFS, USB } dte_type; - dce_factory::ModemType modem_type; - DCE *dce; - std::shared_ptr dte; - esp_modem_dce_wrap() : dce(nullptr), dte(nullptr) {} -}; - -inline dce_factory::ModemType convert_modem_enum(esp_modem_dce_device_t module) -{ - switch (module) { - case ESP_MODEM_DCE_SIM7600: - return esp_modem::dce_factory::ModemType::SIM7600; - case ESP_MODEM_DCE_SIM7070: - return esp_modem::dce_factory::ModemType::SIM7070; - case ESP_MODEM_DCE_SIM7000: - return esp_modem::dce_factory::ModemType::SIM7000; - case ESP_MODEM_DCE_BG96: - return esp_modem::dce_factory::ModemType::BG96; - case ESP_MODEM_DCE_SIM800: - return esp_modem::dce_factory::ModemType::SIM800; - default: - case ESP_MODEM_DCE_GENETIC: - return esp_modem::dce_factory::ModemType::GenericModule; - } -} - -inline esp_modem_terminal_error_t convert_terminal_error_enum(terminal_error err) -{ - switch (err) { - case terminal_error::BUFFER_OVERFLOW: - return ESP_MODEM_TERMINAL_BUFFER_OVERFLOW; - case terminal_error::CHECKSUM_ERROR: - return ESP_MODEM_TERMINAL_CHECKSUM_ERROR; - case terminal_error::UNEXPECTED_CONTROL_FLOW: - return ESP_MODEM_TERMINAL_UNEXPECTED_CONTROL_FLOW; - case terminal_error::DEVICE_GONE: - return ESP_MODEM_TERMINAL_DEVICE_GONE; - default: - return ESP_MODEM_TERMINAL_UNKNOWN_ERROR; - } -} - -inline esp_err_t command_response_to_esp_err(command_result res) -{ - switch (res) { - case command_result::OK: - return ESP_OK; - case command_result::FAIL: - return ESP_FAIL; - case command_result::TIMEOUT: - return ESP_ERR_TIMEOUT; - } - return ESP_ERR_INVALID_ARG; -} +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file c_api_wrapper.hpp + * @brief Collection of C API wrappers + * + * This file is located in include/esp_private because it is not intended for users, + * but rather for esp_modem C extension developers. + * + * The C extension API must provide a 'factory function' that returns initialized pointer to esp_modem_dce_wrap. + * Helper functions provided below, can be used for conversion between C++ enum classes and standard C enums. + */ + +#pragma once + +#include "cxx_include/esp_modem_dce_factory.hpp" +#include "esp_modem_c_api_types.h" + +using namespace esp_modem; + +struct esp_modem_dce_wrap { // need to mimic the polymorphic dispatch as CPP uses templated dispatch + enum class modem_wrap_dte_type { UART, VFS, USB } dte_type; + dce_factory::ModemType modem_type; + DCE *dce; + std::shared_ptr dte; + esp_modem_dce_wrap() : dce(nullptr), dte(nullptr) {} +}; + +inline dce_factory::ModemType convert_modem_enum(esp_modem_dce_device_t module) +{ + switch (module) { + case ESP_MODEM_DCE_SIM7600: + return esp_modem::dce_factory::ModemType::SIM7600; + case ESP_MODEM_DCE_SIM7070: + return esp_modem::dce_factory::ModemType::SIM7070; + case ESP_MODEM_DCE_SIM7000: + return esp_modem::dce_factory::ModemType::SIM7000; + case ESP_MODEM_DCE_BG96: + return esp_modem::dce_factory::ModemType::BG96; + case ESP_MODEM_DCE_SIM800: + return esp_modem::dce_factory::ModemType::SIM800; + default: + case ESP_MODEM_DCE_GENETIC: + return esp_modem::dce_factory::ModemType::GenericModule; + } +} + +inline esp_modem_terminal_error_t convert_terminal_error_enum(terminal_error err) +{ + switch (err) { + case terminal_error::BUFFER_OVERFLOW: + return ESP_MODEM_TERMINAL_BUFFER_OVERFLOW; + case terminal_error::CHECKSUM_ERROR: + return ESP_MODEM_TERMINAL_CHECKSUM_ERROR; + case terminal_error::UNEXPECTED_CONTROL_FLOW: + return ESP_MODEM_TERMINAL_UNEXPECTED_CONTROL_FLOW; + case terminal_error::DEVICE_GONE: + return ESP_MODEM_TERMINAL_DEVICE_GONE; + default: + return ESP_MODEM_TERMINAL_UNKNOWN_ERROR; + } +} + +inline esp_err_t command_response_to_esp_err(command_result res) +{ + switch (res) { + case command_result::OK: + return ESP_OK; + case command_result::FAIL: + return ESP_FAIL; + case command_result::TIMEOUT: + return ESP_ERR_TIMEOUT; + } + return ESP_ERR_INVALID_ARG; +} diff --git a/components/esp_modem/include/generate/esp_modem_command_declare.inc b/components/esp_modem/include/generate/esp_modem_command_declare.inc index de2fd382e..0b6c343c2 100644 --- a/components/esp_modem/include/generate/esp_modem_command_declare.inc +++ b/components/esp_modem/include/generate/esp_modem_command_declare.inc @@ -324,7 +324,7 @@ public: #define ESP_MODEM_DECLARE_DCE_COMMAND(name, return_type, TEMPLATE_ARG, ...) return_type esp_modem_ ## name (__VA_ARGS__); #endif -DECLARE_ALL_COMMAND_APIS() + DECLARE_ALL_COMMAND_APIS() #ifdef __cplusplus }; diff --git a/components/esp_modem/include/vfs_resource/vfs_create.hpp b/components/esp_modem/include/vfs_resource/vfs_create.hpp index 4f266fb11..3f1a80a2c 100644 --- a/components/esp_modem/include/vfs_resource/vfs_create.hpp +++ b/components/esp_modem/include/vfs_resource/vfs_create.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/port/linux/esp_event_mock/esp_event_mock.c b/components/esp_modem/port/linux/esp_event_mock/esp_event_mock.c index cc3dfaa07..9f49a68a6 100644 --- a/components/esp_modem/port/linux/esp_event_mock/esp_event_mock.c +++ b/components/esp_modem/port/linux/esp_event_mock/esp_event_mock.c @@ -14,15 +14,15 @@ #include "esp_err.h" #include "esp_event.h" -const char * WIFI_EVENT = "WIFI_EVENT"; -const char * IP_EVENT = "IP_EVENT"; +const char *WIFI_EVENT = "WIFI_EVENT"; +const char *IP_EVENT = "IP_EVENT"; -esp_err_t esp_event_handler_register(const char * event_base, int32_t event_id, void* event_handler, void* event_handler_arg) +esp_err_t esp_event_handler_register(const char *event_base, int32_t event_id, void *event_handler, void *event_handler_arg) { return ESP_OK; } -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler) +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler) { return ESP_OK; } diff --git a/components/esp_modem/port/linux/esp_event_mock/include/esp_event.h b/components/esp_modem/port/linux/esp_event_mock/include/esp_event.h index da948935b..5681b9f38 100644 --- a/components/esp_modem/port/linux/esp_event_mock/include/esp_event.h +++ b/components/esp_modem/port/linux/esp_event_mock/include/esp_event.h @@ -18,10 +18,10 @@ #include "esp_err.h" -typedef void * system_event_t; +typedef void *system_event_t; -extern const char * WIFI_EVENT; -extern const char * IP_EVENT; +extern const char *WIFI_EVENT; +extern const char *IP_EVENT; #define ESP_EVENT_ANY_BASE NULL /**< register handler for any event base */ #define ESP_EVENT_ANY_ID -1 /**< register handler for any event id */ @@ -33,8 +33,8 @@ typedef struct { int ip_index; /*!< IPv6 address index */ } ip_event_got_ip6_t; -esp_err_t esp_event_handler_register(const char * event_base, int32_t event_id, void* event_handler, void* event_handler_arg); +esp_err_t esp_event_handler_register(const char *event_base, int32_t event_id, void *event_handler, void *event_handler_arg); -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler); +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler); -typedef void * QueueHandle_t; +typedef void *QueueHandle_t; diff --git a/components/esp_modem/port/linux/esp_event_mock/include/esp_event_base.h b/components/esp_modem/port/linux/esp_event_mock/include/esp_event_base.h index fdb58e635..761518c3a 100644 --- a/components/esp_modem/port/linux/esp_event_mock/include/esp_event_base.h +++ b/components/esp_modem/port/linux/esp_event_mock/include/esp_event_base.h @@ -22,5 +22,4 @@ typedef enum { IP_EVENT_GOT_IP6 } mdns_used_event_t; -typedef void * esp_event_base_t; - +typedef void *esp_event_base_t; diff --git a/components/esp_modem/port/linux/esp_netif_linux/CMakeLists.txt b/components/esp_modem/port/linux/esp_netif_linux/CMakeLists.txt index fc6e78f54..04bf1c07d 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/CMakeLists.txt +++ b/components/esp_modem/port/linux/esp_netif_linux/CMakeLists.txt @@ -20,4 +20,3 @@ idf_component_register(SRCS esp_netif_linux.cpp tun_io.c ip4_stub.c ip6_stub.c $ INCLUDE_DIRS include ${LWIP_INCLUDE_DIRS} PRIV_INCLUDE_DIRS . REQUIRES esp_system_protocols_linux) - diff --git a/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif.h b/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif.h index df6c0a9c4..11f9a79fc 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif.h +++ b/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif.h @@ -39,8 +39,8 @@ struct esp_netif_driver_ifconfig { }; struct esp_netif_config { - const char * dev_name; /**< Name of the file device */ - const char * if_name; /**< Network interface name */ + const char *dev_name; /**< Name of the file device */ + const char *if_name; /**< Network interface name */ }; struct esp_netif_obj { diff --git a/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif_ip_addr.h b/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif_ip_addr.h index 72b9d51a8..c1ed6015e 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif_ip_addr.h +++ b/components/esp_modem/port/linux/esp_netif_linux/include/esp_netif_ip_addr.h @@ -158,7 +158,7 @@ typedef struct { * * @return IPv6 type in form of enum esp_ip6_addr_type_t */ -esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t* ip6_addr); +esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t *ip6_addr); #ifdef __cplusplus } diff --git a/components/esp_modem/port/linux/esp_netif_linux/ip4_stub.c b/components/esp_modem/port/linux/esp_netif_linux/ip4_stub.c index 2d049c85e..e3f84ce5e 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/ip4_stub.c +++ b/components/esp_modem/port/linux/esp_netif_linux/ip4_stub.c @@ -4,14 +4,20 @@ err_t ip4_output_if(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto, struct netif *netif) -{ return ERR_OK; } +{ + return ERR_OK; +} struct netif * ip4_route(const ip4_addr_t *dest) -{ return NULL; } +{ + return NULL; +} err_t ip4_output_if_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto, struct netif *netif) -{ return ERR_OK; } +{ + return ERR_OK; +} diff --git a/components/esp_modem/port/linux/esp_netif_linux/ip6_stub.c b/components/esp_modem/port/linux/esp_netif_linux/ip6_stub.c index c98f780c5..d05bce673 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/ip6_stub.c +++ b/components/esp_modem/port/linux/esp_netif_linux/ip6_stub.c @@ -4,22 +4,32 @@ err_t ip6_output_if(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, u8_t hl, u8_t tc, u8_t nexth, struct netif *netif) -{ return ERR_OK; } +{ + return ERR_OK; +} struct netif * ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest) -{ return NULL; } +{ + return NULL; +} err_t ip6_output_if_src(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, u8_t hl, u8_t tc, u8_t nexth, struct netif *netif) -{ return ERR_OK; } +{ + return ERR_OK; +} const ip_addr_t * ip6_select_source_address(struct netif *netif, const ip6_addr_t *dest) -{ return NULL; } +{ + return NULL; +} err_t ip6_options_add_hbh_ra(struct pbuf *p, u8_t nexth, u8_t value) -{ return ERR_OK; } \ No newline at end of file +{ + return ERR_OK; +} diff --git a/components/esp_modem/port/linux/esp_netif_linux/lwipopts.h b/components/esp_modem/port/linux/esp_netif_linux/lwipopts.h index 8fdc8da1f..edeed034e 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/lwipopts.h +++ b/components/esp_modem/port/linux/esp_netif_linux/lwipopts.h @@ -77,7 +77,7 @@ #define PPP_DEBUG LWIP_DBG_ON #define LWIP_DEBUG LWIP_DBG_ON -#define PPP_IPV6_SUPPORT 0 +#define PPP_IPV6_SUPPORT 0 #define PPP_NOTIFY_PHASE 1 diff --git a/components/esp_modem/port/linux/esp_netif_linux/tun_io.c b/components/esp_modem/port/linux/esp_netif_linux/tun_io.c index 7b8c4128c..16f57e713 100644 --- a/components/esp_modem/port/linux/esp_netif_linux/tun_io.c +++ b/components/esp_modem/port/linux/esp_netif_linux/tun_io.c @@ -23,93 +23,93 @@ static void ppp_link_status_cb(ppp_pcb *pcb, int err_code, void *ctx) struct netif *pppif = ppp_netif(pcb); LWIP_UNUSED_ARG(ctx); - switch(err_code) { - case PPPERR_NONE: /* No error. */ - { + switch (err_code) { + case PPPERR_NONE: { /* No error. */ #if LWIP_DNS - const ip_addr_t *ns; + const ip_addr_t *ns; #endif /* LWIP_DNS */ - fprintf(stderr, "ppp_link_status_cb: PPPERR_NONE\n\r"); + fprintf(stderr, "ppp_link_status_cb: PPPERR_NONE\n\r"); #if LWIP_IPV4 - fprintf(stderr, " our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(pppif))); - fprintf(stderr, " his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(pppif))); - fprintf(stderr, " netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(pppif))); + fprintf(stderr, " our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(pppif))); + fprintf(stderr, " his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(pppif))); + fprintf(stderr, " netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(pppif))); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 - fprintf(stderr, " our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); + fprintf(stderr, " our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); #endif /* LWIP_IPV6 */ #if LWIP_DNS - ns = dns_getserver(0); - fprintf(stderr, " dns1 = %s\n\r", ipaddr_ntoa(ns)); - ns = dns_getserver(1); - fprintf(stderr, " dns2 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(0); + fprintf(stderr, " dns1 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(1); + fprintf(stderr, " dns2 = %s\n\r", ipaddr_ntoa(ns)); #endif /* LWIP_DNS */ #if PPP_IPV6_SUPPORT - fprintf(stderr, " our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); + fprintf(stderr, " our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); #endif /* PPP_IPV6_SUPPORT */ - } - break; + } + break; - case PPPERR_PARAM: /* Invalid parameter. */ - printf("ppp_link_status_cb: PPPERR_PARAM\n"); - break; + case PPPERR_PARAM: /* Invalid parameter. */ + printf("ppp_link_status_cb: PPPERR_PARAM\n"); + break; - case PPPERR_OPEN: /* Unable to open PPP session. */ - printf("ppp_link_status_cb: PPPERR_OPEN\n"); - break; + case PPPERR_OPEN: /* Unable to open PPP session. */ + printf("ppp_link_status_cb: PPPERR_OPEN\n"); + break; - case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ - printf("ppp_link_status_cb: PPPERR_DEVICE\n"); - break; + case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ + printf("ppp_link_status_cb: PPPERR_DEVICE\n"); + break; - case PPPERR_ALLOC: /* Unable to allocate resources. */ - printf("ppp_link_status_cb: PPPERR_ALLOC\n"); - break; + case PPPERR_ALLOC: /* Unable to allocate resources. */ + printf("ppp_link_status_cb: PPPERR_ALLOC\n"); + break; - case PPPERR_USER: /* User interrupt. */ - printf("ppp_link_status_cb: PPPERR_USER\n"); - break; + case PPPERR_USER: /* User interrupt. */ + printf("ppp_link_status_cb: PPPERR_USER\n"); + break; - case PPPERR_CONNECT: /* Connection lost. */ - printf("ppp_link_status_cb: PPPERR_CONNECT\n"); - break; + case PPPERR_CONNECT: /* Connection lost. */ + printf("ppp_link_status_cb: PPPERR_CONNECT\n"); + break; - case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ - printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); - break; + case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ + printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); + break; - case PPPERR_PROTOCOL: /* Failed to meet protocol. */ - printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); - break; + case PPPERR_PROTOCOL: /* Failed to meet protocol. */ + printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); + break; - case PPPERR_PEERDEAD: /* Connection timeout. */ - printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); - break; + case PPPERR_PEERDEAD: /* Connection timeout. */ + printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); + break; - case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ - printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); - break; + case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ + printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); + break; - case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ - printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); - break; + case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ + printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); + break; - case PPPERR_LOOPBACK: /* Connection timeout. */ - printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); - break; + case PPPERR_LOOPBACK: /* Connection timeout. */ + printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); + break; - default: - printf("ppp_link_status_cb: unknown errCode %d\n", err_code); - break; + default: + printf("ppp_link_status_cb: unknown errCode %d\n", err_code); + break; } } static u32_t ppp_output_cb(struct ppp_pcb_s *pcb, const void *data, u32_t len, void *ctx) { esp_netif_t *netif = (esp_netif_t *)ctx; - if (netif->transmit) - return netif->transmit(netif->ctx, (uint8_t*)data, len); + if (netif->transmit) { + return netif->transmit(netif->ctx, (uint8_t *)data, len); + } return 0; } @@ -131,7 +131,7 @@ int ppp_netif_init(esp_netif_t *netif) sys_timeouts_init(); // init and start connection attempts on PPP interface - ppp = pppos_create(&pppos_netif, ppp_output_cb, ppp_link_status_cb, (void*)netif); + ppp = pppos_create(&pppos_netif, ppp_output_cb, ppp_link_status_cb, (void *)netif); if (ppp == NULL) { return 0; } @@ -175,7 +175,7 @@ int tun_read(void) FD_SET(esp_netif->fd, &fds); struct timeval tv = { .tv_usec = 0, .tv_sec = 1 }; - if (select(esp_netif->fd +1, &fds, NULL, NULL, &tv) <= 0) { + if (select(esp_netif->fd + 1, &fds, NULL, NULL, &tv) <= 0) { sys_check_timeouts(); return 0; } @@ -206,4 +206,4 @@ int tun_read(void) } pbuf_free(p); return 1; -} \ No newline at end of file +} diff --git a/components/esp_modem/port/linux/esp_system_protocols_linux/include/esp_log.h b/components/esp_modem/port/linux/esp_system_protocols_linux/include/esp_log.h index 84e3700b1..21b1bf09a 100644 --- a/components/esp_modem/port/linux/esp_system_protocols_linux/include/esp_log.h +++ b/components/esp_modem/port/linux/esp_system_protocols_linux/include/esp_log.h @@ -44,4 +44,3 @@ printf(LOG_COLOR_I); printf("(%s) ", TAG); printf(__VA_ARGS__); printf(LOG_RESET printf(LOG_COLOR_D); printf("(%s) ", TAG); printf(__VA_ARGS__); printf(LOG_RESET_COLOR "\n"); } while(0) #define ESP_LOGV(TAG, ...) do { \ printf(LOG_COLOR_V); printf("(%s) ", TAG); printf(__VA_ARGS__); printf(LOG_RESET_COLOR "\n"); } while(0) - diff --git a/components/esp_modem/port/linux/esp_system_protocols_linux/include/machine/endian.h b/components/esp_modem/port/linux/esp_system_protocols_linux/include/machine/endian.h index d51201596..2228debd3 100644 --- a/components/esp_modem/port/linux/esp_system_protocols_linux/include/machine/endian.h +++ b/components/esp_modem/port/linux/esp_system_protocols_linux/include/machine/endian.h @@ -14,4 +14,3 @@ #pragma once #include_next "endian.h" - diff --git a/components/esp_modem/private_include/exception_stub.hpp b/components/esp_modem/private_include/exception_stub.hpp index 4f2700894..163241f41 100644 --- a/components/esp_modem/private_include/exception_stub.hpp +++ b/components/esp_modem/private_include/exception_stub.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/private_include/uart_compat.h b/components/esp_modem/private_include/uart_compat.h index 456763b11..9159302b0 100644 --- a/components/esp_modem/private_include/uart_compat.h +++ b/components/esp_modem/private_include/uart_compat.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -22,12 +14,12 @@ * @brief This is a compatible header, which just takes care of different data ptr type * across different IDF version in driver/uart */ -static inline int uart_write_bytes_compat(uart_port_t uart_num, const void* src, size_t size) +static inline int uart_write_bytes_compat(uart_port_t uart_num, const void *src, size_t size) { #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0) const void *data = src; #else - auto *data = reinterpret_cast(src); + auto *data = reinterpret_cast(src); #endif return uart_write_bytes(uart_num, data, size); } diff --git a/components/esp_modem/private_include/uart_resource.hpp b/components/esp_modem/private_include/uart_resource.hpp index 1e2b66acc..6d9096fba 100644 --- a/components/esp_modem/private_include/uart_resource.hpp +++ b/components/esp_modem/private_include/uart_resource.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/private_include/uart_terminal.hpp b/components/esp_modem/private_include/uart_terminal.hpp index 45478b071..4ce94859d 100644 --- a/components/esp_modem/private_include/uart_terminal.hpp +++ b/components/esp_modem/private_include/uart_terminal.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -23,4 +15,3 @@ namespace esp_modem { std::unique_ptr create_uart_terminal(const esp_modem_dte_config *config); } // namespace esp_modem - diff --git a/components/esp_modem/private_include/vfs_termial.hpp b/components/esp_modem/private_include/vfs_termial.hpp index 445907bfb..7a8ca676f 100644 --- a/components/esp_modem/private_include/vfs_termial.hpp +++ b/components/esp_modem/private_include/vfs_termial.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once diff --git a/components/esp_modem/src/esp_modem_api.cpp b/components/esp_modem/src/esp_modem_api.cpp index 116213ff9..832774d0a 100644 --- a/components/esp_modem/src/esp_modem_api.cpp +++ b/components/esp_modem/src/esp_modem_api.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "esp_log.h" diff --git a/components/esp_modem/src/esp_modem_api_target.cpp b/components/esp_modem/src/esp_modem_api_target.cpp index c72175c23..b261b1537 100644 --- a/components/esp_modem/src/esp_modem_api_target.cpp +++ b/components/esp_modem/src/esp_modem_api_target.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "esp_log.h" @@ -31,8 +23,8 @@ static const char *TAG = "modem_api_target"; std::shared_ptr create_uart_dte(const dte_config *config) { TRY_CATCH_RET_NULL( - auto term = create_uart_terminal(config); - return std::make_shared(config, std::move(term)); + auto term = create_uart_terminal(config); + return std::make_shared(config, std::move(term)); ) } diff --git a/components/esp_modem/src/esp_modem_c_api.cpp b/components/esp_modem/src/esp_modem_c_api.cpp index f1f0aa15b..d17a9c78b 100644 --- a/components/esp_modem/src/esp_modem_c_api.cpp +++ b/components/esp_modem/src/esp_modem_c_api.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "cxx_include/esp_modem_dte.hpp" @@ -72,7 +64,7 @@ extern "C" void esp_modem_destroy(esp_modem_dce_t *dce_wrap) } } -extern "C" esp_err_t esp_modem_set_error_cb(esp_modem_dce_t * dce_wrap, esp_modem_terminal_error_cbt err_cb) +extern "C" esp_err_t esp_modem_set_error_cb(esp_modem_dce_t *dce_wrap, esp_modem_terminal_error_cbt err_cb) { if (dce_wrap == nullptr || dce_wrap->dce == nullptr || dce_wrap->dte == nullptr) { return ESP_ERR_INVALID_ARG; @@ -105,7 +97,7 @@ extern "C" esp_err_t esp_modem_set_mode(esp_modem_dce_t *dce_wrap, esp_modem_dce return dce_wrap->dce->set_mode(modem_mode::DATA_MODE) ? ESP_OK : ESP_FAIL; } if (mode == ESP_MODEM_MODE_COMMAND) { - return dce_wrap->dce->set_mode(modem_mode::COMMAND_MODE) ? ESP_OK : ESP_FAIL; + return dce_wrap->dce->set_mode(modem_mode::COMMAND_MODE) ? ESP_OK : ESP_FAIL; } if (mode == ESP_MODEM_MODE_CMUX) { return dce_wrap->dce->set_mode(modem_mode::CMUX_MODE) ? ESP_OK : ESP_FAIL; @@ -274,7 +266,7 @@ extern "C" esp_err_t esp_modem_power_down(esp_modem_dce_t *dce_wrap) return command_response_to_esp_err(dce_wrap->dce->power_down()); } -extern "C" esp_err_t esp_modem_set_operator(esp_modem_dce_t *dce_wrap, int mode, int format, const char* oper) +extern "C" esp_err_t esp_modem_set_operator(esp_modem_dce_t *dce_wrap, int mode, int format, const char *oper) { if (dce_wrap == nullptr || dce_wrap->dce == nullptr) { return ESP_ERR_INVALID_ARG; @@ -341,7 +333,7 @@ extern "C" esp_err_t esp_modem_set_preferred_mode(esp_modem_dce_t *dce_wrap, int return command_response_to_esp_err(dce_wrap->dce->set_preferred_mode(mode)); } -extern "C" esp_err_t esp_modem_set_network_bands(esp_modem_dce_t *dce_wrap, const char* mode, const int* bands, int size) +extern "C" esp_err_t esp_modem_set_network_bands(esp_modem_dce_t *dce_wrap, const char *mode, const int *bands, int size) { if (dce_wrap == nullptr || dce_wrap->dce == nullptr) { return ESP_ERR_INVALID_ARG; @@ -350,7 +342,7 @@ extern "C" esp_err_t esp_modem_set_network_bands(esp_modem_dce_t *dce_wrap, cons return command_response_to_esp_err(dce_wrap->dce->set_network_bands(mode, bands, size)); } -extern "C" esp_err_t esp_modem_get_network_system_mode(esp_modem_dce_t *dce_wrap, int* p_mode) +extern "C" esp_err_t esp_modem_get_network_system_mode(esp_modem_dce_t *dce_wrap, int *p_mode) { if (dce_wrap == nullptr || dce_wrap->dce == nullptr) { return ESP_ERR_INVALID_ARG; diff --git a/components/esp_modem/src/esp_modem_cmux.cpp b/components/esp_modem/src/esp_modem_cmux.cpp index 8cb7e566f..0c480f868 100644 --- a/components/esp_modem/src/esp_modem_cmux.cpp +++ b/components/esp_modem/src/esp_modem_cmux.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -85,11 +77,13 @@ void CMux::send_disconnect(size_t i) { if (i == 0) { // control terminal uint8_t frame[] = { - SOF_MARKER, 0x3, 0xEF, 0x5, 0xC3, 0x1, 0xF2, SOF_MARKER }; + SOF_MARKER, 0x3, 0xEF, 0x5, 0xC3, 0x1, 0xF2, SOF_MARKER + }; term->write(frame, 8); } else { // separate virtual terminal uint8_t frame[] = { - SOF_MARKER, 0x3, FT_DISC | PF, 0x1, 0, SOF_MARKER }; + SOF_MARKER, 0x3, FT_DISC | PF, 0x1, 0, SOF_MARKER + }; frame[1] |= i << 2; frame[4] = 0xFF - fcs_crc(frame); term->write(frame, sizeof(frame)); @@ -121,7 +115,7 @@ struct CMux::CMuxFrame { void CMux::data_available(uint8_t *data, size_t len) { - if (data && (type&FT_UIH) == FT_UIH && len > 0 && dlci > 0) { // valid payload on a virtual term + if (data && (type & FT_UIH) == FT_UIH && len > 0 && dlci > 0) { // valid payload on a virtual term int virtual_term = dlci - 1; if (virtual_term < MAX_TERMINALS_NUM && read_cb[virtual_term]) { // Post partial data (or defragment to post on CMUX footer) @@ -145,7 +139,7 @@ void CMux::data_available(uint8_t *data, size_t len) read_cb[virtual_term](payload_start, total_payload_size); #endif } - } else if ((type&FT_UIH) == FT_UIH && dlci == 0) { // notify the internal DISC command + } else if ((type & FT_UIH) == FT_UIH && dlci == 0) { // notify the internal DISC command if (len > 0 && (data[0] & 0xE1) == 0xE1) { // Not a DISC, ignore (MSC frame) return; diff --git a/components/esp_modem/src/esp_modem_command_library.cpp b/components/esp_modem/src/esp_modem_command_library.cpp index 065483efa..18d74532f 100644 --- a/components/esp_modem/src/esp_modem_command_library.cpp +++ b/components/esp_modem/src/esp_modem_command_library.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -243,14 +235,14 @@ command_result get_operator_name(CommandableIf *t, std::string &operator_name, i if (property++ == 2) { // operator name is after second comma (as a 3rd property of COPS string) operator_name = out.substr(++pos); auto additional_comma = operator_name.find(','); // check for the optional ACT - if (additional_comma != std::string::npos && std::from_chars(operator_name.data() + additional_comma + 1,operator_name.data() + operator_name.length(), act).ec != std::errc::invalid_argument) { + if (additional_comma != std::string::npos && std::from_chars(operator_name.data() + additional_comma + 1, operator_name.data() + operator_name.length(), act).ec != std::errc::invalid_argument) { operator_name = operator_name.substr(0, additional_comma); } // and strip quotes if present auto quote1 = operator_name.find('"'); auto quote2 = operator_name.rfind('"'); if (quote1 != std::string::npos && quote2 != std::string::npos) { - operator_name = operator_name.substr(quote1+1, quote2-1); + operator_name = operator_name.substr(quote1 + 1, quote2 - 1); } return command_result::OK; } @@ -422,7 +414,7 @@ command_result get_signal_quality(CommandableIf *t, int &rssi, int &ber) return command_result::OK; } -command_result set_operator(CommandableIf *t, int mode, int format, const std::string& oper) +command_result set_operator(CommandableIf *t, int mode, int format, const std::string &oper) { ESP_LOGV(TAG, "%s", __func__ ); return generic_command_common(t, "AT+COPS=" + std::to_string(mode) + "," + std::to_string(format) + ",\"" + oper + "\"\r", 90000); @@ -494,34 +486,34 @@ command_result set_preferred_mode(CommandableIf *t, int mode) return generic_command_common(t, "AT+CMNB=" + std::to_string(mode) + "\r"); } -command_result set_network_bands(CommandableIf *t, const std::string& mode, const int* bands, int size) +command_result set_network_bands(CommandableIf *t, const std::string &mode, const int *bands, int size) { ESP_LOGV(TAG, "%s", __func__ ); std::string band_string = ""; - for (int i = 0; i0; i--){ - band_string[i-1] = hexDigits[(band_bits >> ((hex_len-i)*4)) & 0xF]; + for (int i = hex_len; i > 0; i--) { + band_string[i - 1] = hexDigits[(band_bits >> ((hex_len - i) * 4)) & 0xF]; } return generic_command_common(t, "AT+CNBP=" + mode + ",0x" + band_string + "\r"); } diff --git a/components/esp_modem/src/esp_modem_dce.cpp b/components/esp_modem/src/esp_modem_dce.cpp index 21c2abc7a..c82fed0ed 100644 --- a/components/esp_modem/src/esp_modem_dce.cpp +++ b/components/esp_modem/src/esp_modem_dce.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -44,53 +36,54 @@ bool DCE_Mode::set_unsafe(DTE *dte, ModuleIf *device, Netif &netif, modem_mode m switch (m) { case modem_mode::UNDEF: break; - case modem_mode::COMMAND_MODE: - { - if (mode == modem_mode::COMMAND_MODE) { - return false; - } - if (mode == modem_mode::CMUX_MODE) { - netif.stop(); - netif.wait_until_ppp_exits(); - if (!dte->set_mode(modem_mode::COMMAND_MODE)) { - return false; - } - mode = m; - return true; - } + case modem_mode::COMMAND_MODE: { + if (mode == modem_mode::COMMAND_MODE) { + return false; + } + if (mode == modem_mode::CMUX_MODE) { netif.stop(); - auto signal = std::make_shared(); - std::weak_ptr weak_signal = signal; - dte->set_read_cb([weak_signal](uint8_t *data, size_t len) -> bool { - if (memchr(data, '\n', len)) { - ESP_LOG_BUFFER_HEXDUMP("esp-modem: debug_data", data, len, ESP_LOG_DEBUG); - const auto pass = std::list({"NO CARRIER", "DISCONNECTED"}); - std::string_view response((char *) data, len); - for (auto &it : pass) - if (response.find(it) != std::string::npos) { - if (auto signal = weak_signal.lock()) - signal->set(1); - return true; - } - } - return false; - }); netif.wait_until_ppp_exits(); - if (!signal->wait(1, 2000)) { - if (!device->set_mode(modem_mode::COMMAND_MODE)) { - mode = modem_mode::UNDEF; - return false; - } - } - dte->set_read_cb(nullptr); if (!dte->set_mode(modem_mode::COMMAND_MODE)) { - mode = modem_mode::UNDEF; return false; } mode = m; return true; } - break; + netif.stop(); + auto signal = std::make_shared(); + std::weak_ptr weak_signal = signal; + dte->set_read_cb([weak_signal](uint8_t *data, size_t len) -> bool { + if (memchr(data, '\n', len)) + { + ESP_LOG_BUFFER_HEXDUMP("esp-modem: debug_data", data, len, ESP_LOG_DEBUG); + const auto pass = std::list({"NO CARRIER", "DISCONNECTED"}); + std::string_view response((char *) data, len); + for (auto &it : pass) + if (response.find(it) != std::string::npos) { + if (auto signal = weak_signal.lock()) { + signal->set(1); + } + return true; + } + } + return false; + }); + netif.wait_until_ppp_exits(); + if (!signal->wait(1, 2000)) { + if (!device->set_mode(modem_mode::COMMAND_MODE)) { + mode = modem_mode::UNDEF; + return false; + } + } + dte->set_read_cb(nullptr); + if (!dte->set_mode(modem_mode::COMMAND_MODE)) { + mode = modem_mode::UNDEF; + return false; + } + mode = m; + return true; + } + break; case modem_mode::DATA_MODE: if (mode == modem_mode::DATA_MODE || mode == modem_mode::CMUX_MODE) { return false; @@ -138,4 +131,4 @@ modem_mode DCE_Mode::get() return mode; } -} // esp_modem \ No newline at end of file +} // esp_modem diff --git a/components/esp_modem/src/esp_modem_dte.cpp b/components/esp_modem/src/esp_modem_dte.cpp index 48eba2ec5..142cae468 100644 --- a/components/esp_modem/src/esp_modem_dte.cpp +++ b/components/esp_modem/src/esp_modem_dte.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "esp_log.h" diff --git a/components/esp_modem/src/esp_modem_factory.cpp b/components/esp_modem/src/esp_modem_factory.cpp index c75b227dc..c7d0b9575 100644 --- a/components/esp_modem/src/esp_modem_factory.cpp +++ b/components/esp_modem/src/esp_modem_factory.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "cxx_include/esp_modem_types.hpp" @@ -47,4 +39,4 @@ std::unique_ptr FactoryHelper::create_pdp_context(std::string &apn) return std::unique_ptr(); } -} \ No newline at end of file +} diff --git a/components/esp_modem/src/esp_modem_modules.cpp b/components/esp_modem/src/esp_modem_modules.cpp index be0ed06e1..a1d0fc48c 100644 --- a/components/esp_modem/src/esp_modem_modules.cpp +++ b/components/esp_modem/src/esp_modem_modules.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "cxx_include/esp_modem_api.hpp" #include "cxx_include/esp_modem_dce_module.hpp" @@ -55,7 +47,7 @@ command_result SIM7600::get_battery_status(int &voltage, int &bcs, int &bcl) return dce_commands::get_battery_status_sim7xxx(dte.get(), voltage, bcs, bcl); } -command_result SIM7600::set_network_bands(const std::string& mode, const int* bands, int size) +command_result SIM7600::set_network_bands(const std::string &mode, const int *bands, int size) { return dce_commands::set_network_bands_sim76xx(dte.get(), mode, bands, size); } @@ -90,4 +82,4 @@ command_result SIM800::set_data_mode() return dce_commands::set_data_mode_sim8xx(dte.get()); } -} \ No newline at end of file +} diff --git a/components/esp_modem/src/esp_modem_netif.cpp b/components/esp_modem/src/esp_modem_netif.cpp index b7acf4a07..56a75f13b 100644 --- a/components/esp_modem/src/esp_modem_netif.cpp +++ b/components/esp_modem/src/esp_modem_netif.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -124,4 +116,4 @@ void Netif::wait_until_ppp_exits() signal.wait(PPP_EXIT, 30000); } -} // namespace esp_modem \ No newline at end of file +} // namespace esp_modem diff --git a/components/esp_modem/src/esp_modem_netif_linux.cpp b/components/esp_modem/src/esp_modem_netif_linux.cpp index f965d1084..9052df98d 100644 --- a/components/esp_modem/src/esp_modem_netif_linux.cpp +++ b/components/esp_modem/src/esp_modem_netif_linux.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "cxx_include/esp_modem_netif.hpp" @@ -66,4 +58,4 @@ void Netif::wait_until_ppp_exits() { } -} // namespace esp_modem \ No newline at end of file +} // namespace esp_modem diff --git a/components/esp_modem/src/esp_modem_primitives_freertos.cpp b/components/esp_modem/src/esp_modem_primitives_freertos.cpp index d500484e2..f8b4e03f9 100644 --- a/components/esp_modem/src/esp_modem_primitives_freertos.cpp +++ b/components/esp_modem/src/esp_modem_primitives_freertos.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "cxx_include/esp_modem_primitives.hpp" diff --git a/components/esp_modem/src/esp_modem_primitives_linux.cpp b/components/esp_modem/src/esp_modem_primitives_linux.cpp index dd4875b60..3f805bd1a 100644 --- a/components/esp_modem/src/esp_modem_primitives_linux.cpp +++ b/components/esp_modem/src/esp_modem_primitives_linux.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -91,7 +83,7 @@ void Task::Relinquish() void Task::Delay(uint32_t ms) { - usleep(ms*1000); + usleep(ms * 1000); } } // namespace esp_modem diff --git a/components/esp_modem/src/esp_modem_term_fs.cpp b/components/esp_modem/src/esp_modem_term_fs.cpp index f3728c331..fde9c40ce 100644 --- a/components/esp_modem/src/esp_modem_term_fs.cpp +++ b/components/esp_modem/src/esp_modem_term_fs.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -169,4 +161,3 @@ FdTerminal::~FdTerminal() } } // namespace esp_modem - diff --git a/components/esp_modem/src/esp_modem_term_uart.cpp b/components/esp_modem/src/esp_modem_term_uart.cpp index 5e97db502..a4effac20 100644 --- a/components/esp_modem/src/esp_modem_term_uart.cpp +++ b/components/esp_modem/src/esp_modem_term_uart.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. - +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "cxx_include/esp_modem_dte.hpp" #include "driver/uart.h" #include "esp_modem_config.h" diff --git a/components/esp_modem/src/esp_modem_uart.cpp b/components/esp_modem/src/esp_modem_uart.cpp index 6c78399d1..e08247398 100644 --- a/components/esp_modem/src/esp_modem_uart.cpp +++ b/components/esp_modem/src/esp_modem_uart.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -195,4 +187,3 @@ int UartTerminal::write(uint8_t *data, size_t len) } } // namespace esp_modem - diff --git a/components/esp_modem/src/esp_modem_uart_linux.cpp b/components/esp_modem/src/esp_modem_uart_linux.cpp index 15a1eb91e..e6aa222a4 100644 --- a/components/esp_modem/src/esp_modem_uart_linux.cpp +++ b/components/esp_modem/src/esp_modem_uart_linux.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -52,4 +44,4 @@ uart_resource::uart_resource(const esp_modem_uart_term_config *config, QueueHand uart_resource::~uart_resource() = default; -} // namespace esp_modem \ No newline at end of file +} // namespace esp_modem diff --git a/components/esp_modem/src/esp_modem_vfs_socket_creator.cpp b/components/esp_modem/src/esp_modem_vfs_socket_creator.cpp index 037d0f62e..7571d2dfe 100644 --- a/components/esp_modem/src/esp_modem_vfs_socket_creator.cpp +++ b/components/esp_modem/src/esp_modem_vfs_socket_creator.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include diff --git a/components/esp_modem/src/esp_modem_vfs_uart_creator.cpp b/components/esp_modem/src/esp_modem_vfs_uart_creator.cpp index 2ff487027..366e385da 100644 --- a/components/esp_modem/src/esp_modem_vfs_uart_creator.cpp +++ b/components/esp_modem/src/esp_modem_vfs_uart_creator.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include diff --git a/components/esp_modem/test/host_test/main/LoopbackTerm.cpp b/components/esp_modem/test/host_test/main/LoopbackTerm.cpp index a830b757e..2d5778964 100644 --- a/components/esp_modem/test/host_test/main/LoopbackTerm.cpp +++ b/components/esp_modem/test/host_test/main/LoopbackTerm.cpp @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include #include #include @@ -83,8 +88,9 @@ int LoopbackTerm::write(uint8_t *data, size_t len) int LoopbackTerm::read(uint8_t *data, size_t len) { size_t read_len = std::min(data_len, len); - if (inject_by && read_len > inject_by) + if (inject_by && read_len > inject_by) { read_len = inject_by; + } if (read_len) { if (loopback_data.capacity() < len) { loopback_data.reserve(len); diff --git a/components/esp_modem/test/host_test/main/LoopbackTerm.h b/components/esp_modem/test/host_test/main/LoopbackTerm.h index f4161de5e..eb24ce4e1 100644 --- a/components/esp_modem/test/host_test/main/LoopbackTerm.h +++ b/components/esp_modem/test/host_test/main/LoopbackTerm.h @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #pragma once #include "cxx_include/esp_modem_api.hpp" @@ -17,7 +22,7 @@ public: * inject_by defines batch sizes: the read callback is called multiple times * with partial data of `inject_by` size */ - int inject(uint8_t *data, size_t len, size_t inject_by,size_t delay_before=0, size_t delay_after=1); + int inject(uint8_t *data, size_t len, size_t inject_by, size_t delay_before = 0, size_t delay_after = 1); void start() override; void stop() override; diff --git a/components/esp_modem/test/host_test/main/test_modem.cpp b/components/esp_modem/test/host_test/main/test_modem.cpp index 9f30f7f8d..4a238f5bc 100644 --- a/components/esp_modem/test/host_test/main/test_modem.cpp +++ b/components/esp_modem/test/host_test/main/test_modem.cpp @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #define CATCH_CONFIG_MAIN // This tells the catch header to generate a main #include #include @@ -7,7 +12,8 @@ using namespace esp_modem; -TEST_CASE("DTE command races", "[esp_modem]") { +TEST_CASE("DTE command races", "[esp_modem]") +{ auto term = std::make_unique(true); auto loopback = term.get(); auto dte = std::make_shared(std::move(term)); @@ -19,7 +25,7 @@ TEST_CASE("DTE command races", "[esp_modem]") { uint8_t resp[] = {'O', 'K', '\n'}; // run many commands in succession with the timeout set exactly to the timespan of injected reply // (checks for potential exception, data races, recycled local variables, etc.) - for (int i=0; i<1000; ++i) { + for (int i = 0; i < 1000; ++i) { loopback->inject(&resp[0], sizeof(resp), sizeof(resp), /* 1ms before injecting reply */1, 0); auto ret = dce->command("AT\n", [&](uint8_t *data, size_t len) { return command_result::OK; @@ -229,13 +235,13 @@ TEST_CASE("Test CMUX protocol by injecting payloads", "[esp_modem]") long_payload[450] = '\n'; long_payload[451] = 0x53; // footer long_payload[452] = 0xf9; - for (int i=0; i<5; ++i) { + for (int i = 0; i < 5; ++i) { // inject the whole payload (i=0) and then per 1,2,3,4 bytes (i) - loopback->inject(&long_payload[0], sizeof(long_payload), i==0?sizeof(long_payload):i); + loopback->inject(&long_payload[0], sizeof(long_payload), i == 0 ? sizeof(long_payload) : i); auto ret = dce->command("ignore", [&](uint8_t *data, size_t len) { CHECK(data[0] == 0x7e); - CHECK(data[len-2] == 0x7e); - CHECK(data[len-1] == '\n'); + CHECK(data[len - 2] == 0x7e); + CHECK(data[len - 1] == '\n'); return command_result::OK; }, 1000); CHECK(ret == command_result::OK); diff --git a/components/esp_modem/test/target/main/NetworkDCE.cpp b/components/esp_modem/test/target/main/NetworkDCE.cpp index c14f0d17e..a321644d3 100644 --- a/components/esp_modem/test/target/main/NetworkDCE.cpp +++ b/components/esp_modem/test/target/main/NetworkDCE.cpp @@ -1,3 +1,9 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ + /* softAP to PPPoS Example (modem_board) This example code is in the Public Domain (or CC0 licensed, at your option.) diff --git a/components/esp_modem/test/target/main/component.mk b/components/esp_modem/test/target/main/component.mk index 61f8990c3..0adf45649 100644 --- a/components/esp_modem/test/target/main/component.mk +++ b/components/esp_modem/test/target/main/component.mk @@ -1,8 +1,8 @@ # # Main component makefile. # -# This Makefile can be left empty. By default, it will take the sources in the -# src/ directory, compile them and link them into lib(subdirectory_name).a +# This Makefile can be left empty. By default, it will take the sources in the +# src/ directory, compile them and link them into lib(subdirectory_name).a # in the build directory. This behaviour is entirely configurable, # please read the ESP-IDF documents if you need to do this. # diff --git a/components/esp_modem/test/target/main/pppd_test.cpp b/components/esp_modem/test/target/main/pppd_test.cpp index ace21650c..36df49159 100644 --- a/components/esp_modem/test/target/main/pppd_test.cpp +++ b/components/esp_modem/test/target/main/pppd_test.cpp @@ -1,10 +1,11 @@ -/* pppd test +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * pppd test */ #include diff --git a/components/esp_modem/test/target/sdkconfig.defaults b/components/esp_modem/test/target/sdkconfig.defaults index dcd87e48f..aa6763982 100644 --- a/components/esp_modem/test/target/sdkconfig.defaults +++ b/components/esp_modem/test/target/sdkconfig.defaults @@ -1,4 +1,3 @@ CONFIG_COMPILER_CXX_EXCEPTIONS=y CONFIG_CXX_EXCEPTIONS=y CONFIG_PPP_SUPPORT=y - diff --git a/components/esp_websocket_client/.gitignore b/components/esp_websocket_client/.gitignore index 5aa50beb2..8d681ae3e 100644 --- a/components/esp_websocket_client/.gitignore +++ b/components/esp_websocket_client/.gitignore @@ -90,4 +90,4 @@ build dependencies.lock # ignore generated docs -docs/html \ No newline at end of file +docs/html diff --git a/components/esp_websocket_client/docs/conf_common.py b/components/esp_websocket_client/docs/conf_common.py index edae5fd88..abc2b53e3 100644 --- a/components/esp_websocket_client/docs/conf_common.py +++ b/components/esp_websocket_client/docs/conf_common.py @@ -1,10 +1,12 @@ -from esp_docs.conf_docs import * # noqa: F403,F401 +# flake8: noqa +from esp_docs.conf_docs import * -extensions += ['sphinx_copybutton', - # Needed as a trigger for running doxygen - 'esp_docs.esp_extensions.dummy_build_system', - 'esp_docs.esp_extensions.run_doxygen', - ] +extensions += [ + 'sphinx_copybutton', + # Needed as a trigger for running doxygen + 'esp_docs.esp_extensions.dummy_build_system', + 'esp_docs.esp_extensions.run_doxygen', +] # link roles config github_repo = 'espressif/esp-protocols' @@ -14,7 +16,7 @@ html_context['github_user'] = 'espressif' html_context['github_repo'] = 'esp-docs' # Extra options required by sphinx_idf_theme -project_slug = 'esp-idf' # >=5.0 +project_slug = 'esp-idf' # >=5.0 versions_url = 'https://github.com/espressif/esp-protocols/docs/docs_versions.js' idf_targets = ['esp32'] diff --git a/components/esp_websocket_client/docs/en/index.rst b/components/esp_websocket_client/docs/en/index.rst index 7c3abd970..2469e1473 100644 --- a/components/esp_websocket_client/docs/en/index.rst +++ b/components/esp_websocket_client/docs/en/index.rst @@ -124,4 +124,3 @@ API Reference ------------- .. include-build-file:: inc/esp_websocket_client.inc - diff --git a/components/esp_websocket_client/docs/generate_docs b/components/esp_websocket_client/docs/generate_docs index e60c1a8f9..def507c5e 100755 --- a/components/esp_websocket_client/docs/generate_docs +++ b/components/esp_websocket_client/docs/generate_docs @@ -13,7 +13,7 @@ window.onload =(function() { mySpan.value = 'latest'; mySpan.setAttribute('disabled', true); myAnchor.parentNode.replaceChild(mySpan, myAnchor); - + var myAnchor = document.getElementById('target-select'); var mySpan = document.createElement('input'); mySpan.setAttribute('type', 'text'); @@ -24,4 +24,3 @@ window.onload =(function() { })(); " >> html/index.html - diff --git a/components/esp_websocket_client/esp_websocket_client.c b/components/esp_websocket_client/esp_websocket_client.c index 7af38927f..27e19ba9d 100644 --- a/components/esp_websocket_client/esp_websocket_client.c +++ b/components/esp_websocket_client/esp_websocket_client.c @@ -59,7 +59,7 @@ static const char *TAG = "WEBSOCKET_CLIENT"; const static int STOPPED_BIT = BIT0; const static int CLOSE_FRAME_SENT_BIT = BIT1; // Indicates that a close frame was sent by the client - // and we are waiting for the server to continue with clean close +// and we are waiting for the server to continue with clean close ESP_EVENT_DEFINE_BASE(WEBSOCKET_EVENTS); @@ -82,7 +82,7 @@ typedef struct { int pingpong_timeout_sec; size_t ping_interval_sec; const char *cert; - size_t cert_len; + size_t cert_len; const char *client_cert; size_t client_cert_len; const char *client_key; @@ -131,7 +131,7 @@ struct esp_websocket_client { static uint64_t _tick_get_ms(void) { - return esp_timer_get_time()/1000; + return esp_timer_get_time() / 1000; } static esp_err_t esp_websocket_new_buf(esp_websocket_client_handle_t client, bool is_tx) @@ -295,7 +295,7 @@ static esp_err_t esp_websocket_client_set_config(esp_websocket_client_handle_t c cfg->auto_reconnect = false; } - if (config->disable_pingpong_discon){ + if (config->disable_pingpong_discon) { cfg->pingpong_timeout_sec = 0; } else if (config->pingpong_timeout_sec) { cfg->pingpong_timeout_sec = config->pingpong_timeout_sec; @@ -348,11 +348,11 @@ static esp_err_t set_websocket_transport_optional_settings(esp_websocket_client_ esp_transport_handle_t trans = esp_transport_list_get_transport(client->transport_list, scheme); if (trans) { const esp_transport_ws_config_t config = { - .ws_path = client->config->path, - .sub_protocol = client->config->subprotocol, - .user_agent = client->config->user_agent, - .headers = client->config->headers, - .propagate_control_frames = true + .ws_path = client->config->path, + .sub_protocol = client->config->subprotocol, + .user_agent = client->config->user_agent, + .headers = client->config->headers, + .propagate_control_frames = true }; return esp_transport_ws_set_config(trans, &config); } @@ -616,12 +616,12 @@ esp_err_t esp_websocket_client_set_uri(esp_websocket_client_handle_t client, con asprintf(&client->config->path, "/?%.*s", puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off); } else { asprintf(&client->config->path, "%.*s?%.*s", puri.field_data[UF_PATH].len, uri + puri.field_data[UF_PATH].off, - puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off); + puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off); } ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->path, return ESP_ERR_NO_MEM); } if (puri.field_data[UF_PORT].off) { - client->config->port = strtol((const char*)(uri + puri.field_data[UF_PORT].off), NULL, 10); + client->config->port = strtol((const char *)(uri + puri.field_data[UF_PORT].off), NULL, 10); } if (puri.field_data[UF_USERINFO].len) { @@ -724,86 +724,86 @@ static void esp_websocket_client_task(void *pv) break; } switch ((int)client->state) { - case WEBSOCKET_STATE_INIT: - if (client->transport == NULL) { - ESP_LOGE(TAG, "There are no transport"); - client->run = false; - break; - } - int result = esp_transport_connect(client->transport, - client->config->host, - client->config->port, - client->config->network_timeout_ms); - if (result < 0) { - ESP_LOGE(TAG, "Error transport connect %i", result); - esp_websocket_client_error_connection(client); - break; - } - ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port); - - client->state = WEBSOCKET_STATE_CONNECTED; - client->wait_for_pong_resp = false; - esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CONNECTED, NULL, 0); - + case WEBSOCKET_STATE_INIT: + if (client->transport == NULL) { + ESP_LOGE(TAG, "There are no transport"); + client->run = false; break; - case WEBSOCKET_STATE_CONNECTED: - if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) { // only send and check for PING - // if closing hasn't been initiated - if (_tick_get_ms() - client->ping_tick_ms > client->config->ping_interval_sec*1000) { - client->ping_tick_ms = _tick_get_ms(); - ESP_LOGD(TAG, "Sending PING..."); - esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PING | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms); + } + int result = esp_transport_connect(client->transport, + client->config->host, + client->config->port, + client->config->network_timeout_ms); + if (result < 0) { + ESP_LOGE(TAG, "Error transport connect %i", result); + esp_websocket_client_error_connection(client); + break; + } + ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port); - if (!client->wait_for_pong_resp && client->config->pingpong_timeout_sec) { - client->pingpong_tick_ms = _tick_get_ms(); - client->wait_for_pong_resp = true; - } - } + client->state = WEBSOCKET_STATE_CONNECTED; + client->wait_for_pong_resp = false; + esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CONNECTED, NULL, 0); - if ( _tick_get_ms() - client->pingpong_tick_ms > client->config->pingpong_timeout_sec*1000 ) { - if (client->wait_for_pong_resp) { - ESP_LOGE(TAG, "Error, no PONG received for more than %d seconds after PING", client->config->pingpong_timeout_sec); - esp_websocket_client_abort_connection(client); - break; - } + break; + case WEBSOCKET_STATE_CONNECTED: + if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) { // only send and check for PING + // if closing hasn't been initiated + if (_tick_get_ms() - client->ping_tick_ms > client->config->ping_interval_sec * 1000) { + client->ping_tick_ms = _tick_get_ms(); + ESP_LOGD(TAG, "Sending PING..."); + esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PING | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms); + + if (!client->wait_for_pong_resp && client->config->pingpong_timeout_sec) { + client->pingpong_tick_ms = _tick_get_ms(); + client->wait_for_pong_resp = true; } } - if (read_select == 0) { - ESP_LOGV(TAG, "Read poll timeout: skipping esp_transport_read()..."); - break; + if ( _tick_get_ms() - client->pingpong_tick_ms > client->config->pingpong_timeout_sec * 1000 ) { + if (client->wait_for_pong_resp) { + ESP_LOGE(TAG, "Error, no PONG received for more than %d seconds after PING", client->config->pingpong_timeout_sec); + esp_websocket_client_abort_connection(client); + break; + } } - client->ping_tick_ms = _tick_get_ms(); + } - if (esp_websocket_client_recv(client) == ESP_FAIL) { - ESP_LOGE(TAG, "Error receive data"); - esp_websocket_client_abort_connection(client); - break; - } + if (read_select == 0) { + ESP_LOGV(TAG, "Read poll timeout: skipping esp_transport_read()..."); break; - case WEBSOCKET_STATE_WAIT_TIMEOUT: + } + client->ping_tick_ms = _tick_get_ms(); - if (!client->config->auto_reconnect) { - client->run = false; - break; - } - if (_tick_get_ms() - client->reconnect_tick_ms > client->wait_timeout_ms) { - client->state = WEBSOCKET_STATE_INIT; - client->reconnect_tick_ms = _tick_get_ms(); - ESP_LOGD(TAG, "Reconnecting..."); - } + if (esp_websocket_client_recv(client) == ESP_FAIL) { + ESP_LOGE(TAG, "Error receive data"); + esp_websocket_client_abort_connection(client); break; - case WEBSOCKET_STATE_CLOSING: - // if closing not initiated by the client echo the close message back - if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) { - ESP_LOGD(TAG, "Closing initiated by the server, sending close frame"); - esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_CLOSE | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms); - xEventGroupSetBits(client->status_bits, CLOSE_FRAME_SENT_BIT); - } - break; - default: - ESP_LOGD(TAG, "Client run iteration in a default state: %d", client->state); + } + break; + case WEBSOCKET_STATE_WAIT_TIMEOUT: + + if (!client->config->auto_reconnect) { + client->run = false; break; + } + if (_tick_get_ms() - client->reconnect_tick_ms > client->wait_timeout_ms) { + client->state = WEBSOCKET_STATE_INIT; + client->reconnect_tick_ms = _tick_get_ms(); + ESP_LOGD(TAG, "Reconnecting..."); + } + break; + case WEBSOCKET_STATE_CLOSING: + // if closing not initiated by the client echo the close message back + if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) { + ESP_LOGD(TAG, "Closing initiated by the server, sending close frame"); + esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_CLOSE | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms); + xEventGroupSetBits(client->status_bits, CLOSE_FRAME_SENT_BIT); + } + break; + default: + ESP_LOGD(TAG, "Client run iteration in a default state: %d", client->state); + break; } xSemaphoreGiveRecursive(client->lock); if (WEBSOCKET_STATE_CONNECTED == client->state) { @@ -816,7 +816,7 @@ static void esp_websocket_client_task(void *pv) // waiting for reconnecting... vTaskDelay(client->wait_timeout_ms / 2 / portTICK_PERIOD_MS); } else if (WEBSOCKET_STATE_CLOSING == client->state && - (CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits))) { + (CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits))) { ESP_LOGD(TAG, " Waiting for TCP connection to be closed by the server"); int ret = esp_transport_ws_poll_connection_closed(client->transport, 1000); if (ret == 0) { @@ -967,7 +967,7 @@ static int esp_websocket_client_send_with_opcode(esp_websocket_client_handle_t c int ret = ESP_FAIL; if (client == NULL || len < 0 || - (opcode != WS_TRANSPORT_OPCODES_CLOSE && (data == NULL || len <= 0))) { + (opcode != WS_TRANSPORT_OPCODES_CLOSE && (data == NULL || len <= 0))) { ESP_LOGE(TAG, "Invalid arguments"); return ESP_FAIL; } @@ -1000,7 +1000,7 @@ static int esp_websocket_client_send_with_opcode(esp_websocket_client_handle_t c memcpy(client->tx_buffer, data + widx, need_write); // send with ws specific way and specific opcode wlen = esp_transport_ws_send_raw(client->transport, current_opcode, (char *)client->tx_buffer, need_write, - (timeout==portMAX_DELAY)? -1 : timeout * portTICK_PERIOD_MS); + (timeout == portMAX_DELAY) ? -1 : timeout * portTICK_PERIOD_MS); if (wlen < 0 || (wlen == 0 && need_write != 0)) { ret = wlen; ESP_LOGE(TAG, "Network error: esp_transport_write() returned %d, errno=%d", ret, errno); diff --git a/components/esp_websocket_client/examples/README.md b/components/esp_websocket_client/examples/README.md index a14c18ab0..56870ea12 100644 --- a/components/esp_websocket_client/examples/README.md +++ b/components/esp_websocket_client/examples/README.md @@ -86,4 +86,3 @@ if __name__ == '__main__': # gunicorn -b 0.0.0.0:5000 --workers 4 --threads 100 module:app app.run(host="0.0.0.0", debug=True) ``` - diff --git a/components/esp_websocket_client/examples/main/websocket_example.c b/components/esp_websocket_client/examples/main/websocket_example.c index f138b78d8..59ce0bd0b 100644 --- a/components/esp_websocket_client/examples/main/websocket_example.c +++ b/components/esp_websocket_client/examples/main/websocket_example.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ /* ESP HTTP Client Example This example code is in the Public Domain (or CC0 licensed, at your option.) @@ -71,11 +76,11 @@ static void websocket_event_handler(void *handler_args, esp_event_base_t base, i ESP_LOGI(TAG, "WEBSOCKET_EVENT_DATA"); ESP_LOGI(TAG, "Received opcode=%d", data->op_code); if (data->op_code == 0x08 && data->data_len == 2) { - ESP_LOGW(TAG, "Received closed message with code=%d", 256*data->data_ptr[0] + data->data_ptr[1]); + ESP_LOGW(TAG, "Received closed message with code=%d", 256 * data->data_ptr[0] + data->data_ptr[1]); } else { ESP_LOGW(TAG, "Received=%.*s", data->data_len, (char *)data->data_ptr); } - + // If received data contains json structure it succeed to parse cJSON *root = cJSON_Parse(data->data_ptr); if (root) { diff --git a/components/esp_websocket_client/examples/pytest_websocket.py b/components/esp_websocket_client/examples/pytest_websocket.py index be21104db..547677455 100644 --- a/components/esp_websocket_client/examples/pytest_websocket.py +++ b/components/esp_websocket_client/examples/pytest_websocket.py @@ -1,16 +1,13 @@ -import os +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 +import json import random import re import socket import string from threading import Event, Thread -import pytest -import sys -import json -import time from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket -from pytest_embedded import Dut def get_my_ip(): @@ -64,7 +61,7 @@ class Websocket(object): self.exit_event.set() self.thread.join(10) if self.thread.is_alive(): - Utility.console_log('Thread cannot be joined', 'orange') + print('Thread cannot be joined', 'orange') def test_examples_protocol_websocket(dut): @@ -74,6 +71,7 @@ def test_examples_protocol_websocket(dut): 2. connect to uri specified in the config 3. send and receive data """ + def test_echo(dut): dut.expect('WEBSOCKET_EVENT_CONNECTED') for i in range(0, 5): @@ -81,7 +79,9 @@ def test_examples_protocol_websocket(dut): print('All echos received') def test_close(dut): - code = dut.expect(re.compile(b'WEBSOCKET: Received closed message with code=(\\d*)'))[0] + code = dut.expect( + re.compile( + b'WEBSOCKET: Received closed message with code=(\\d*)'))[0] print('Received close frame with code {}'.format(code)) def test_json(dut, websocket): @@ -100,32 +100,39 @@ def test_examples_protocol_websocket(dut): websocket.send_data(json_string) data = json.loads(json_string) - match = dut.expect(re.compile(b'Json=([a-zA-Z0-9]*).*')).group(0).decode()[5:] + match = dut.expect( + re.compile(b'Json=([a-zA-Z0-9]*).*')).group(0).decode()[5:] if match == str(data[0]): print('Sent message and received message are equal') else: - raise ValueError('DUT received string do not match sent string, \nexpected: {}\nwith length {}\ - \nreceived: {}\nwith length {}'.format(data[0], len(data[0]), match, len(match))) + raise ValueError( + 'DUT received string do not match sent string, \nexpected: {}\nwith length {}\ + \nreceived: {}\nwith length {}'.format( + data[0], len(data[0]), match, len(match))) - def test_recv_long_msg(dut, websocket, msg_len, repeats): - send_msg = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(msg_len)) + send_msg = ''.join( + random.choice(string.ascii_uppercase + string.ascii_lowercase + + string.digits) for _ in range(msg_len)) for _ in range(repeats): websocket.send_data(send_msg) - + recv_msg = '' while len(recv_msg) < msg_len: - match = dut.expect(re.compile(b'Received=([a-zA-Z0-9]*).*')).group(1).decode() + match = dut.expect(re.compile( + b'Received=([a-zA-Z0-9]*).*')).group(1).decode() recv_msg += match - + if recv_msg == send_msg: print('Sent message and received message are equal') else: - raise ValueError('DUT received string do not match sent string, \nexpected: {}\nwith length {}\ - \nreceived: {}\nwith length {}'.format(send_msg, len(send_msg), recv_msg, len(recv_msg))) - + raise ValueError( + 'DUT received string do not match sent string, \nexpected: {}\nwith length {}\ + \nreceived: {}\nwith length {}'.format( + send_msg, len(send_msg), recv_msg, len(recv_msg))) + # Starting of the test try: if dut.app.sdkconfig.get('WEBSOCKET_URI_FROM_STDIN') is True: @@ -153,4 +160,3 @@ def test_examples_protocol_websocket(dut): else: print('DUT connecting to {}'.format(uri)) test_echo(dut) - diff --git a/components/esp_websocket_client/examples/requirements.txt b/components/esp_websocket_client/examples/requirements.txt index afc47f922..e92ba8128 100644 --- a/components/esp_websocket_client/examples/requirements.txt +++ b/components/esp_websocket_client/examples/requirements.txt @@ -1,4 +1,4 @@ -pytest-embedded-serial-esp -pytest-embedded-idf -junit_xml +pytest-embedded-serial-esp +pytest-embedded-idf +junit_xml SimpleWebSocketServer diff --git a/components/esp_websocket_client/test/test_websocket_client.c b/components/esp_websocket_client/test/test_websocket_client.c index 1c9e895a3..9e0e7bd24 100644 --- a/components/esp_websocket_client/test/test_websocket_client.c +++ b/components/esp_websocket_client/test/test_websocket_client.c @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Unlicense OR CC0-1.0 * @@ -17,7 +17,7 @@ #include "unity.h" #include "memory_checks.h" -static void test_leak_setup(const char * file, long line) +static void test_leak_setup(const char *file, long line) { printf("%s:%ld\n", file, line); test_utils_record_free_mem(); @@ -27,8 +27,8 @@ TEST_CASE("websocket init and deinit", "[websocket][leaks=0]") { test_leak_setup(__FILE__, __LINE__); const esp_websocket_client_config_t websocket_cfg = { - // no connection takes place, but the uri has to be valid for init() to succeed - .uri = "ws://echo.websocket.org", + // no connection takes place, but the uri has to be valid for init() to succeed + .uri = "ws://echo.websocket.org", }; esp_websocket_client_handle_t client = esp_websocket_client_init(&websocket_cfg); TEST_ASSERT_NOT_EQUAL(NULL, client); @@ -39,7 +39,7 @@ TEST_CASE("websocket init with invalid url", "[websocket][leaks=0]") { test_leak_setup(__FILE__, __LINE__); const esp_websocket_client_config_t websocket_cfg = { - .uri = "INVALID", + .uri = "INVALID", }; esp_websocket_client_handle_t client = esp_websocket_client_init(&websocket_cfg); TEST_ASSERT_NULL(client); diff --git a/components/mdns/docs/conf_common.py b/components/mdns/docs/conf_common.py index 10d1e997e..3d34aad4c 100644 --- a/components/mdns/docs/conf_common.py +++ b/components/mdns/docs/conf_common.py @@ -1,10 +1,12 @@ -from esp_docs.conf_docs import * # noqa: F403,F401 +# flake8: noqa +from esp_docs.conf_docs import * -extensions += ['sphinx_copybutton', - # Needed as a trigger for running doxygen - 'esp_docs.esp_extensions.dummy_build_system', - 'esp_docs.esp_extensions.run_doxygen', - ] +extensions += [ + 'sphinx_copybutton', + # Needed as a trigger for running doxygen + 'esp_docs.esp_extensions.dummy_build_system', + 'esp_docs.esp_extensions.run_doxygen', +] # link roles config github_repo = 'espressif/esp-protocols' @@ -14,7 +16,7 @@ html_context['github_user'] = 'espressif' html_context['github_repo'] = 'esp-protocols' # Extra options required by sphinx_idf_theme -project_slug = 'esp-idf' # >=5.0 +project_slug = 'esp-idf' # >=5.0 versions_url = 'https://github.com/espressif/esp-protocols/docs/docs_versions.js' idf_targets = ['esp32'] diff --git a/components/mdns/docs/en/index.rst b/components/mdns/docs/en/index.rst index 007d1bd9d..b9b3a549c 100644 --- a/components/mdns/docs/en/index.rst +++ b/components/mdns/docs/en/index.rst @@ -201,5 +201,3 @@ API Reference ------------- .. include-build-file:: inc/mdns.inc - - diff --git a/components/mdns/docs/generate_docs b/components/mdns/docs/generate_docs index d822222b5..6eb01da46 100755 --- a/components/mdns/docs/generate_docs +++ b/components/mdns/docs/generate_docs @@ -15,7 +15,7 @@ window.onload =(function() { mySpan.value = 'latest'; mySpan.setAttribute('disabled', true); myAnchor.parentNode.replaceChild(mySpan, myAnchor); - + var myAnchor = document.getElementById('target-select'); var mySpan = document.createElement('input'); mySpan.setAttribute('type', 'text'); diff --git a/components/mdns/docs/zh_CN/index.rst b/components/mdns/docs/zh_CN/index.rst index 68befb637..8b8cc9ac7 100644 --- a/components/mdns/docs/zh_CN/index.rst +++ b/components/mdns/docs/zh_CN/index.rst @@ -185,5 +185,3 @@ API 参考 -------- .. include-build-file:: inc/mdns.inc - - diff --git a/components/mdns/examples/main/mdns_example_main.c b/components/mdns/examples/main/mdns_example_main.c index a3f2cb272..d0a393c9a 100644 --- a/components/mdns/examples/main/mdns_example_main.c +++ b/components/mdns/examples/main/mdns_example_main.c @@ -1,10 +1,11 @@ -/* MDNS-SD Query and advertise Example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * MDNS-SD Query and advertise Example */ #include #include "freertos/FreeRTOS.h" @@ -24,17 +25,17 @@ #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); +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); +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(); + char *hostname = generate_hostname(); //initialize mDNS ESP_ERROR_CHECK( mdns_init() ); @@ -84,7 +85,7 @@ static void initialise_mdns(void) } /* these strings match mdns_ip_protocol_t enumeration */ -static const char * ip_protocol_str[] = {"V4", "V6", "MAX"}; +static const char *ip_protocol_str[] = {"V4", "V6", "MAX"}; static void mdns_print_results(mdns_result_t *results) { @@ -120,17 +121,17 @@ static void mdns_print_results(mdns_result_t *results) } } -static void query_mdns_service(const char * service_name, const char * proto) +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; + mdns_result_t *results = NULL; esp_err_t err = mdns_query_ptr(service_name, proto, 3000, 20, &results); - if(err){ + if (err) { ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); return; } - if(!results){ + if (!results) { ESP_LOGW(TAG, "No results found!"); return; } @@ -142,7 +143,7 @@ static void query_mdns_service(const char * service_name, const char * proto) static bool check_and_print_result(mdns_search_once_t *search) { // Check if any result is available - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; if (!mdns_query_async_get_results(search, 0, &result, NULL)) { return false; } @@ -152,9 +153,9 @@ static bool check_and_print_result(mdns_search_once_t *search) } // If yes, print the result - mdns_ip_addr_t * a = result->addr; + mdns_ip_addr_t *a = result->addr; while (a) { - if(a->addr.type == ESP_IPADDR_TYPE_V6){ + 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))); @@ -166,7 +167,7 @@ static bool check_and_print_result(mdns_search_once_t *search) return true; } -static void query_mdns_hosts_async(const char * host_name) +static void query_mdns_hosts_async(const char *host_name) { ESP_LOGI(TAG, "Query both A and AAA: %s.local", host_name); @@ -187,7 +188,7 @@ static void query_mdns_hosts_async(const char * host_name) } } -static void query_mdns_host(const char * host_name) +static void query_mdns_host(const char *host_name) { ESP_LOGI(TAG, "Query A: %s.local", host_name); @@ -195,8 +196,8 @@ static void query_mdns_host(const char * host_name) addr.addr = 0; esp_err_t err = mdns_query_a(host_name, 2000, &addr); - if(err){ - if(err == ESP_ERR_NOT_FOUND){ + if (err) { + if (err == ESP_ERR_NOT_FOUND) { ESP_LOGW(TAG, "%s: Host was not found!", esp_err_to_name(err)); return; } @@ -285,7 +286,7 @@ void app_main(void) /** 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) +static char *generate_hostname(void) { #ifndef CONFIG_MDNS_ADD_MAC_TO_HOSTNAME return strdup(CONFIG_MDNS_HOSTNAME); @@ -305,7 +306,7 @@ static char* generate_hostname(void) * @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) +static void query_mdns_host_with_gethostbyname(char *host) { struct hostent *res = gethostbyname(host); if (res) { @@ -321,10 +322,10 @@ static void query_mdns_host_with_gethostbyname(char * host) * @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) +static void query_mdns_host_with_getaddrinfo(char *host) { struct addrinfo hints; - struct addrinfo * res; + struct addrinfo *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; @@ -335,8 +336,8 @@ static void query_mdns_host_with_getaddrinfo(char * host) char *resolved_addr; #if CONFIG_LWIP_IPV6 resolved_addr = res->ai_family == AF_INET ? - inet_ntoa(((struct sockaddr_in *) res->ai_addr)->sin_addr) : - inet_ntoa(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr); + inet_ntoa(((struct sockaddr_in *) res->ai_addr)->sin_addr) : + inet_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 diff --git a/components/mdns/examples/pytest_mdns.py b/components/mdns/examples/pytest_mdns.py index b9f4d1b22..fc13d8e77 100644 --- a/components/mdns/examples/pytest_mdns.py +++ b/components/mdns/examples/pytest_mdns.py @@ -1,28 +1,30 @@ -import os +# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 import re import select import socket import struct import subprocess import time -import pytest from threading import Event, Thread import dpkt import dpkt.dns -from pytest_embedded import Dut -import subprocess 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 = 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 = 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() @@ -36,9 +38,10 @@ def get_dns_answer_to_mdns(tester_host): 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 = 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') @@ -69,10 +72,13 @@ def mdns_server(esp_host, events): 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)) + 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)) + 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 @@ -81,17 +87,22 @@ def mdns_server(esp_host, events): if len(dns.qd) > 0 and dns.qd[0].type == dpkt.dns.DNS_A: if dns.qd[0].name == TESTER_NAME: print('Received query: {} '.format(dns.__repr__())) - sock.sendto(get_dns_answer_to_mdns(TESTER_NAME), (MCAST_GRP, UDP_PORT)) + sock.sendto(get_dns_answer_to_mdns(TESTER_NAME), + (MCAST_GRP, UDP_PORT)) elif dns.qd[0].name == TESTER_NAME_LWIP: print('Received query: {} '.format(dns.__repr__())) - sock.sendto(get_dns_answer_to_mdns_lwip(TESTER_NAME_LWIP, dns.id), addr) + sock.sendto( + get_dns_answer_to_mdns_lwip(TESTER_NAME_LWIP, dns.id), + addr) if len(dns.an) > 0 and dns.an[0].type == dpkt.dns.DNS_A: print('Received answer from {}'.format(dns.an[0].name)) if dns.an[0].name == esp_host + u'.local': - print('Received answer to esp32-mdns query: {}'.format(dns.__repr__())) + print('Received answer to esp32-mdns query: {}'.format( + dns.__repr__())) events['esp_answered'].set() if dns.an[0].name == esp_host + u'-delegated.local': - print('Received answer to esp32-mdns-delegate query: {}'.format(dns.__repr__())) + print('Received answer to esp32-mdns-delegate query: {}'. + format(dns.__repr__())) events['esp_delegated_answered'].set() except socket.timeout: break @@ -108,30 +119,54 @@ def test_examples_protocol_mdns(dut): 4. check DUT output if mdns advertized host is resolved """ - specific_host = dut.expect(re.compile(b'mdns hostname set to: \[(.*?)\]')).group(1).decode() + specific_host = dut.expect(re.compile( + b'mdns hostname set to: \[(.*?)\]')).group(1).decode() # noqa: W605 - 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_address = dut.expect(re.compile(b'IPv4 address:([a-zA-Z0-9]*).*')).group(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_address = dut.expect( + re.compile(b'IPv4 address:([a-zA-Z0-9]*).*')).group(1).decode() print('Connected to AP with IP: {}'.format(ip_address)) try: # 3. check the mdns name is accessible. mdns_responder.start() if not mdns_server_events['esp_answered'].wait(timeout=30): - raise ValueError('Test has failed: did not receive mdns answer within timeout') + 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') + 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'), timeout=30) - dut.expect(re.compile(b'mdns-test: gethostbyname: tinytester-lwip.local resolved to: 127.0.0.1'), timeout=30) - dut.expect(re.compile(b'mdns-test: getaddrinfo: tinytester-lwip.local resolved to: 127.0.0.1'), timeout=30) + 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 `dig` command - dig_output = subprocess.check_output(['dig', '+short', '-p', '5353', '@224.0.0.251', - '{}.local'.format(specific_host)]) - print('Resolving {} using "dig" succeeded with:\n{}'.format(specific_host, dig_output)) + dig_output = subprocess.check_output([ + 'dig', '+short', '-p', '5353', '@224.0.0.251', + '{}.local'.format(specific_host) + ]) + print('Resolving {} using "dig" succeeded with:\n{}'.format( + specific_host, dig_output)) if not ip_address.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(ip_address)) + raise ValueError( + 'Test has failed: Incorrectly resolved DUT hostname using dig' + "Output should've contained DUT's IP address:{}".format( + ip_address)) finally: mdns_server_events['stop'].set() mdns_responder.join() diff --git a/components/mdns/include/mdns.h b/components/mdns/include/mdns.h index 7f81d0af8..fd6186276 100644 --- a/components/mdns/include/mdns.h +++ b/components/mdns/include/mdns.h @@ -50,8 +50,8 @@ typedef enum { * Used in mdns_service_add() */ typedef struct { - const char * key; /*!< item key name */ - const char * value; /*!< item value string */ + const char *key; /*!< item key name */ + const char *value; /*!< item value string */ } mdns_txt_item_t; /** @@ -59,7 +59,7 @@ typedef struct { */ 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 */ + struct mdns_ip_addr_s *next; /*!< next IP, or NULL for the last IP in the list */ } mdns_ip_addr_t; /** @@ -74,25 +74,25 @@ typedef enum { * @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 */ + 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 */ + 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 */ + char *instance_name; /*!< instance name */ + char *service_type; /*!< service type */ + char *proto; /*!< srevice protocol */ // SRV - char * hostname; /*!< hostname */ + char *hostname; /*!< hostname */ uint16_t port; /*!< service port */ // TXT - mdns_txt_item_t * txt; /*!< txt record */ + 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 */ + mdns_ip_addr_t *addr; /*!< linked list of IP addresses found */ } mdns_result_t; typedef void (*mdns_query_notify_t)(mdns_search_once_t *search); @@ -125,7 +125,7 @@ void mdns_free(void); * - ESP_ERR_INVALID_ARG Parameter error * - ESP_ERR_NO_MEM memory error */ -esp_err_t mdns_hostname_set(const char * hostname); +esp_err_t mdns_hostname_set(const char *hostname); /** * @brief Adds a hostname and address to be delegated @@ -142,7 +142,7 @@ esp_err_t mdns_hostname_set(const char * hostname); * - ESP_ERR_NO_MEM memory error * */ -esp_err_t mdns_delegate_hostname_add(const char * hostname, const mdns_ip_addr_t *address_list); +esp_err_t mdns_delegate_hostname_add(const char *hostname, const mdns_ip_addr_t *address_list); /** * @brief Remove a delegated hostname @@ -157,7 +157,7 @@ esp_err_t mdns_delegate_hostname_add(const char * hostname, const mdns_ip_addr_t * - ESP_ERR_NO_MEM memory error * */ -esp_err_t mdns_delegate_hostname_remove(const char * hostname); +esp_err_t mdns_delegate_hostname_remove(const char *hostname); /** * @brief Query whether a hostname has been added @@ -169,7 +169,7 @@ esp_err_t mdns_delegate_hostname_remove(const char * hostname); * - false The hostname has not been added. * */ -bool mdns_hostname_exists(const char * hostname); +bool mdns_hostname_exists(const char *hostname); /** * @brief Set the default instance name for mDNS server @@ -181,7 +181,7 @@ bool mdns_hostname_exists(const char * hostname); * - ESP_ERR_INVALID_ARG Parameter error * - ESP_ERR_NO_MEM memory error */ -esp_err_t mdns_instance_name_set(const char * instance_name); +esp_err_t mdns_instance_name_set(const char *instance_name); /** * @brief Add service to mDNS server @@ -205,7 +205,7 @@ esp_err_t mdns_instance_name_set(const char * instance_name); * - 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); +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 @@ -230,8 +230,8 @@ esp_err_t mdns_service_add(const char * instance_name, const char * service_type * - 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); +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 Check whether a service has been added. @@ -244,7 +244,7 @@ esp_err_t mdns_service_add_for_host(const char * instance_name, const char * ser * - true Correspondding service has been added. * - false Service not found. */ -bool mdns_service_exists(const char * service_type, const char * proto, const char * hostname); +bool mdns_service_exists(const char *service_type, const char *proto, const char *hostname); /** @@ -274,7 +274,7 @@ bool mdns_service_exists_with_instance(const char *instance, const char *service * - 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); +esp_err_t mdns_service_remove(const char *service_type, const char *proto); /** * @brief Remove service from mDNS server with hostname @@ -290,7 +290,7 @@ esp_err_t mdns_service_remove(const char * service_type, const char * proto); * - 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); +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 @@ -305,7 +305,7 @@ esp_err_t mdns_service_remove_for_host(const char *instance, const char * servic * - 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); +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 @@ -322,8 +322,8 @@ esp_err_t mdns_service_instance_name_set(const char * service_type, const char * * - 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); +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 @@ -338,7 +338,7 @@ esp_err_t mdns_service_instance_name_set_for_host(const char * instance_old, con * - 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); +esp_err_t mdns_service_port_set(const char *service_type, const char *proto, uint16_t port); /** @@ -356,8 +356,8 @@ esp_err_t mdns_service_port_set(const char * service_type, const char * proto, u * - 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); +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 @@ -375,7 +375,7 @@ esp_err_t mdns_service_port_set_for_host(const char * instance, const char * ser * - 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); +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 @@ -395,7 +395,7 @@ esp_err_t mdns_service_txt_set(const char * service_type, const char * proto, md * - 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, +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); /** @@ -414,7 +414,7 @@ esp_err_t mdns_service_txt_set_for_host(const char * instance, const char * serv * - 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); +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 @@ -432,7 +432,7 @@ esp_err_t mdns_service_txt_item_set(const char * service_type, const char * prot * - 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); + const char *key, const char *value, uint8_t value_len); /** * @brief Set/Add TXT item for service TXT record with hostname @@ -452,8 +452,8 @@ esp_err_t mdns_service_txt_item_set_with_explicit_value_len(const char *service_ * - 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); +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 @@ -472,9 +472,9 @@ esp_err_t mdns_service_txt_item_set_for_host(const char * instance, const char * * - 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); +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 @@ -489,7 +489,7 @@ esp_err_t mdns_service_txt_item_set_for_host_with_explicit_value_len(const char * - 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); +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 @@ -506,8 +506,8 @@ esp_err_t mdns_service_txt_item_remove(const char * service_type, const char * p * - 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); +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 subtype for service. @@ -525,7 +525,7 @@ esp_err_t mdns_service_txt_item_remove_for_host(const char * instance, const cha * - 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); + const char *hostname, const char *subtype); /** * @brief Remove and free all services from mDNS server @@ -546,7 +546,7 @@ esp_err_t mdns_service_remove_all(void); * - 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); +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. @@ -562,7 +562,7 @@ esp_err_t mdns_query_async_delete(mdns_search_once_t* search); * 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); +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. @@ -580,7 +580,7 @@ bool mdns_query_async_get_results(mdns_search_once_t* search, uint32_t timeout, * 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); + uint32_t timeout, size_t max_results, mdns_query_notify_t notifier); /** * @brief Generic mDNS query @@ -602,8 +602,8 @@ mdns_search_once_t *mdns_query_async_new(const char *name, const char *service_t * - 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); +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 @@ -625,14 +625,14 @@ esp_err_t mdns_query_generic(const char * name, const char * service_type, const * - 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); +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); +void mdns_query_results_free(mdns_result_t *results); /** * @brief Query mDNS for service @@ -649,7 +649,7 @@ void mdns_query_results_free(mdns_result_t * results); * - 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); +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 @@ -666,7 +666,7 @@ esp_err_t mdns_query_ptr(const char * service_type, const char * proto, uint32_t * - 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); +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 @@ -683,7 +683,7 @@ esp_err_t mdns_query_srv(const char * instance_name, const char * service_type, * - 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); +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 Query mDNS for A record @@ -698,7 +698,7 @@ esp_err_t mdns_query_txt(const char * instance_name, const char * service_type, * - 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); +esp_err_t mdns_query_a(const char *host_name, uint32_t timeout, esp_ip4_addr_t *addr); #if CONFIG_LWIP_IPV6 /** @@ -716,7 +716,7 @@ esp_err_t mdns_query_a(const char * host_name, uint32_t timeout, esp_ip4_addr_t * - 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); +esp_err_t mdns_query_aaaa(const char *host_name, uint32_t timeout, esp_ip6_addr_t *addr); #endif diff --git a/components/mdns/include/mdns_console.h b/components/mdns/include/mdns_console.h index 059e03de5..cb28eca7a 100644 --- a/components/mdns/include/mdns_console.h +++ b/components/mdns/include/mdns_console.h @@ -1,16 +1,8 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #ifndef _MDNS_CONSOLE_H_ #define _MDNS_CONSOLE_H_ diff --git a/components/mdns/mdns.c b/components/mdns/mdns.c index d005ba483..f69f10ad6 100644 --- a/components/mdns/mdns.c +++ b/components/mdns/mdns.c @@ -24,7 +24,7 @@ #ifdef MDNS_ENABLE_DEBUG -void mdns_debug_packet(const uint8_t * data, size_t len); +void mdns_debug_packet(const uint8_t *data, size_t len); #endif #ifndef ARRAY_SIZE @@ -35,11 +35,11 @@ void mdns_debug_packet(const uint8_t * data, size_t len); // since the ip6_addr_t is defined in lwip and depends on using IPv6 zones #define _MDNS_SIZEOF_IP6_ADDR (MDNS_ANSWER_AAAA_SIZE) -static const char * MDNS_DEFAULT_DOMAIN = "local"; -static const char * MDNS_SUB_STR = "_sub"; +static const char *MDNS_DEFAULT_DOMAIN = "local"; +static const char *MDNS_SUB_STR = "_sub"; -mdns_server_t * _mdns_server = NULL; -static mdns_host_item_t * _mdns_host_list = NULL; +mdns_server_t *_mdns_server = NULL; +static mdns_host_item_t *_mdns_host_list = NULL; static mdns_host_item_t _mdns_self_host; static const char *TAG = "MDNS"; @@ -48,19 +48,19 @@ static volatile TaskHandle_t _mdns_service_task_handle = NULL; static SemaphoreHandle_t _mdns_service_semaphore = NULL; static void _mdns_search_finish_done(void); -static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * search, mdns_name_t * name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); -static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * hostname, esp_ip_addr_t * ip, +static mdns_search_once_t *_mdns_search_find_from(mdns_search_once_t *search, mdns_name_t *name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); +static void _mdns_search_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); static void _mdns_search_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); static void _mdns_search_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); -static mdns_result_t * _mdns_search_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); -static bool _mdns_append_host_list_in_services(mdns_out_answer_t ** destination, mdns_srv_item_t * services[], size_t services_len, bool flush, bool bye); -static bool _mdns_append_host_list(mdns_out_answer_t ** destination, bool flush, bool bye); +static mdns_result_t *_mdns_search_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); +static bool _mdns_append_host_list_in_services(mdns_out_answer_t **destination, mdns_srv_item_t *services[], size_t services_len, bool flush, bool bye); +static bool _mdns_append_host_list(mdns_out_answer_t **destination, bool flush, bool bye); static void _mdns_remap_self_service_hostname(const char *old_hostname, const char *new_hostname); static esp_err_t mdns_post_custom_action_tcpip_if(mdns_if_t mdns_if, mdns_event_actions_t event_action); @@ -74,7 +74,7 @@ typedef struct mdns_interfaces mdns_interfaces_t; struct mdns_interfaces { const bool predefined; - esp_netif_t * netif; + esp_netif_t *netif; const mdns_predef_if_t predef_if; mdns_if_t duplicate; }; @@ -104,7 +104,7 @@ static mdns_interfaces_t s_esp_netifs[MDNS_MAX_INTERFACES] = { */ static mdns_if_t mdns_if_from_preset_if(mdns_predef_if_t predef_if) { - for (int i=0; ihostname) { return false; } return !strcasecmp(srv->service, service) && !strcasecmp(srv->proto, proto) && - (_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); + (_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); } /** @@ -248,9 +251,9 @@ static bool _mdns_service_match(const mdns_service_t * srv, const char * service * * @return the service item if found or NULL on error */ -static mdns_srv_item_t * _mdns_get_service_item(const char * service, const char * proto, const char * hostname) +static mdns_srv_item_t *_mdns_get_service_item(const char *service, const char *proto, const char *hostname) { - mdns_srv_item_t * s = _mdns_server->services; + mdns_srv_item_t *s = _mdns_server->services; while (s) { if (_mdns_service_match(s->service, service, proto, hostname)) { return s; @@ -260,13 +263,13 @@ static mdns_srv_item_t * _mdns_get_service_item(const char * service, const char return NULL; } -static mdns_srv_item_t * _mdns_get_service_item_subtype(const char *subtype, const char * service, const char * proto) +static mdns_srv_item_t *_mdns_get_service_item_subtype(const char *subtype, const char *service, const char *proto) { - mdns_srv_item_t * s = _mdns_server->services; + mdns_srv_item_t *s = _mdns_server->services; while (s) { if (_mdns_service_match(s->service, service, proto, NULL)) { mdns_subtype_t *subtype_item = s->service->subtype; - while(subtype_item) { + while (subtype_item) { if (!strcasecmp(subtype_item->subtype, subtype)) { return s; } @@ -278,12 +281,12 @@ static mdns_srv_item_t * _mdns_get_service_item_subtype(const char *subtype, con return NULL; } -static mdns_host_item_t * mdns_get_host_item(const char * hostname) +static mdns_host_item_t *mdns_get_host_item(const char *hostname) { if (hostname == NULL || strcasecmp(hostname, _mdns_server->hostname) == 0) { return &_mdns_self_host; } - mdns_host_item_t * host = _mdns_host_list; + mdns_host_item_t *host = _mdns_host_list; while (host != NULL) { if (strcasecmp(host->hostname, hostname) == 0) { return host; @@ -295,7 +298,7 @@ static mdns_host_item_t * mdns_get_host_item(const char * hostname) static bool _mdns_can_add_more_services(void) { - mdns_srv_item_t * s = _mdns_server->services; + mdns_srv_item_t *s = _mdns_server->services; uint16_t service_num = 0; while (s) { service_num ++; @@ -308,9 +311,9 @@ static bool _mdns_can_add_more_services(void) return true; } -esp_err_t _mdns_send_rx_action(mdns_rx_packet_t * packet) +esp_err_t _mdns_send_rx_action(mdns_rx_packet_t *packet) { - mdns_action_t * action = NULL; + mdns_action_t *action = NULL; action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { @@ -343,7 +346,7 @@ static const char *_mdns_get_default_instance_name(void) /** * @brief Get the service name of a service */ -static const char * _mdns_get_service_instance_name(const mdns_service_t * service) +static const char *_mdns_get_service_instance_name(const mdns_service_t *service) { if (service && !_str_null_or_empty(service->instance)) { return service->instance; @@ -364,7 +367,7 @@ static bool _mdns_instance_name_match(const char *lhs, const char *rhs) } static bool _mdns_service_match_instance(const mdns_service_t *srv, const char *instance, const char *service, - const char *proto, const char *hostname) + const char *proto, const char *hostname) { // service and proto must be supplied, if not this instance won't match if (!service || !proto) { @@ -373,11 +376,11 @@ static bool _mdns_service_match_instance(const mdns_service_t *srv, const char * // instance==NULL -> _mdns_instance_name_match() will check the default instance // hostname==NULL -> matches if instance, service and proto matches return !strcasecmp(srv->service, service) && _mdns_instance_name_match(srv->instance, instance) && - !strcasecmp(srv->proto, proto) && (_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); + !strcasecmp(srv->proto, proto) && (_str_null_or_empty(hostname) || !strcasecmp(srv->hostname, hostname)); } static mdns_srv_item_t *_mdns_get_service_item_instance(const char *instance, const char *service, const char *proto, - const char *hostname) + const char *hostname) { mdns_srv_item_t *s = _mdns_server->services; while (s) { @@ -406,10 +409,10 @@ static mdns_srv_item_t *_mdns_get_service_item_instance(const char *instance, co * * @return the address after the parsed FQDN in the packet or NULL on error */ -static const uint8_t * _mdns_read_fqdn(const uint8_t * packet, const uint8_t * start, mdns_name_t * name, char * buf, size_t packet_len) +static const uint8_t *_mdns_read_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, char *buf, size_t packet_len) { size_t index = 0; - const uint8_t * packet_end = packet + packet_len; + const uint8_t *packet_end = packet + packet_len; while (start + index < packet_end && start[index]) { if (name->parts == 4) { name->invalid = true; @@ -421,7 +424,7 @@ static const uint8_t * _mdns_read_fqdn(const uint8_t * packet, const uint8_t * s return NULL; } uint8_t i; - for (i=0; i= packet_end) { return NULL; } @@ -438,8 +441,8 @@ static const uint8_t * _mdns_read_fqdn(const uint8_t * packet, const uint8_t * s } else if (strcasecmp(buf, MDNS_SUB_STR) == 0) { 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); + char *mdns_name_ptrs[] = {name->host, name->service, name->proto, name->domain}; + memcpy(mdns_name_ptrs[name->parts++], buf, len + 1); } } else { size_t address = (((uint16_t)len & 0x3F) << 8) | start[index++]; @@ -463,13 +466,13 @@ static const uint8_t * _mdns_read_fqdn(const uint8_t * packet, const uint8_t * s * @param index offset of uint16_t value * @param value the value to set */ -static inline void _mdns_set_u16(uint8_t * packet, uint16_t index, uint16_t value) +static inline void _mdns_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; + packet[index + 1] = value & 0xFF; } /** @@ -481,7 +484,7 @@ static inline void _mdns_set_u16(uint8_t * packet, uint16_t index, uint16_t valu * * @return length of added data: 0 on error or 1 on success */ -static inline uint8_t _mdns_append_u8(uint8_t * packet, uint16_t * index, uint8_t value) +static inline uint8_t _mdns_append_u8(uint8_t *packet, uint16_t *index, uint8_t value) { if (*index >= MDNS_MAX_PACKET_SIZE) { return 0; @@ -500,7 +503,7 @@ static inline uint8_t _mdns_append_u8(uint8_t * packet, uint16_t * index, uint8_ * * @return length of added data: 0 on error or 2 on success */ -static inline uint8_t _mdns_append_u16(uint8_t * packet, uint16_t * index, uint16_t value) +static inline uint8_t _mdns_append_u16(uint8_t *packet, uint16_t *index, uint16_t value) { if ((*index + 1) >= MDNS_MAX_PACKET_SIZE) { return 0; @@ -519,7 +522,7 @@ static inline uint8_t _mdns_append_u16(uint8_t * packet, uint16_t * index, uint1 * * @return length of added data: 0 on error or 4 on success */ -static inline uint8_t _mdns_append_u32(uint8_t * packet, uint16_t * index, uint32_t value) +static inline uint8_t _mdns_append_u32(uint8_t *packet, uint16_t *index, uint32_t value) { if ((*index + 3) >= MDNS_MAX_PACKET_SIZE) { return 0; @@ -541,7 +544,7 @@ static inline uint8_t _mdns_append_u32(uint8_t * packet, uint16_t * index, uint3 * * @return length of added data: 0 on error or 10 on success */ -static inline uint8_t _mdns_append_type(uint8_t * packet, uint16_t * index, uint8_t type, bool flush, uint32_t ttl) +static inline uint8_t _mdns_append_type(uint8_t *packet, uint16_t *index, uint8_t type, bool flush, uint32_t ttl) { if ((*index + 10) >= MDNS_MAX_PACKET_SIZE) { return 0; @@ -573,7 +576,7 @@ static inline uint8_t _mdns_append_type(uint8_t * packet, uint16_t * index, uint return 10; } -static inline uint8_t _mdns_append_string_with_len(uint8_t * packet, uint16_t * index, const char * string, uint8_t len) +static inline uint8_t _mdns_append_string_with_len(uint8_t *packet, uint16_t *index, const char *string, uint8_t len) { if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) { return 0; @@ -593,7 +596,7 @@ static inline uint8_t _mdns_append_string_with_len(uint8_t * packet, uint16_t * * * @return length of added data: 0 on error or length of the string + 1 on success */ -static inline uint8_t _mdns_append_string(uint8_t * packet, uint16_t * index, const char * string) +static inline uint8_t _mdns_append_string(uint8_t *packet, uint16_t *index, const char *string) { uint8_t len = strlen(string); if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) { @@ -616,7 +619,7 @@ static inline uint8_t _mdns_append_string(uint8_t * packet, uint16_t * index, co * 0 if data won't fit the packet * -1 if invalid TXT entry */ -static inline int append_one_txt_record_entry(uint8_t * packet, uint16_t * index, mdns_txt_linked_item_t * txt) +static inline int 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; @@ -647,7 +650,7 @@ static inline int append_one_txt_record_entry(uint8_t * packet, uint16_t * index * * @return length of added data: 0 on error or length on success */ -static uint16_t _mdns_append_fqdn(uint8_t * packet, uint16_t * index, const char * strings[], uint8_t count, size_t packet_len) +static uint16_t _mdns_append_fqdn(uint8_t *packet, uint16_t *index, const char *strings[], uint8_t count, size_t packet_len) { if (!count) { //empty string so terminate @@ -657,13 +660,13 @@ static uint16_t _mdns_append_fqdn(uint8_t * packet, uint16_t * index, const char 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); + uint8_t *len_location = (uint8_t *)memchr(packet, (char)len, *index); while (len_location) { //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 + 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)); + 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 @@ -674,14 +677,14 @@ search_next: name.service[0] = 0; name.proto[0] = 0; name.domain[0] = 0; - const uint8_t * content = _mdns_read_fqdn(packet, len_location, &name, buf, packet_len); + const uint8_t *content = _mdns_read_fqdn(packet, len_location, &name, buf, packet_len); if (!content) { //not a readable fqdn? return 0; } if (name.parts == count) { uint8_t i; - for (i=0; iservice; @@ -864,9 +867,9 @@ static uint16_t _mdns_append_sdptr_record(uint8_t * packet, uint16_t * index, md * * @return length of added data: 0 on error or length on success */ -static uint16_t _mdns_append_txt_record(uint8_t * packet, uint16_t * index, mdns_service_t * service, bool flush, bool bye) +static uint16_t _mdns_append_txt_record(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, bool bye) { - const char * str[4]; + const char *str[4]; uint16_t record_length = 0; uint8_t part_length; @@ -889,7 +892,7 @@ static uint16_t _mdns_append_txt_record(uint8_t * packet, uint16_t * index, mdns } record_length += part_length; - part_length = _mdns_append_type(packet, index, MDNS_ANSWER_TXT, flush, bye?0:MDNS_ANSWER_TXT_TTL); + part_length = _mdns_append_type(packet, index, MDNS_ANSWER_TXT, flush, bye ? 0 : MDNS_ANSWER_TXT_TTL); if (!part_length) { return 0; } @@ -898,7 +901,7 @@ static uint16_t _mdns_append_txt_record(uint8_t * packet, uint16_t * index, mdns uint16_t data_len_location = *index - 2; uint16_t data_len = 0; - mdns_txt_linked_item_t * txt = service->txt; + mdns_txt_linked_item_t *txt = service->txt; while (txt) { int l = append_one_txt_record_entry(packet, index, txt); if (l > 0) { @@ -928,9 +931,9 @@ static uint16_t _mdns_append_txt_record(uint8_t * packet, uint16_t * index, mdns * * @return length of added data: 0 on error or length on success */ -static uint16_t _mdns_append_srv_record(uint8_t * packet, uint16_t * index, mdns_service_t * service, bool flush, bool bye) +static uint16_t _mdns_append_srv_record(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, bool bye) { - const char * str[4]; + const char *str[4]; uint16_t record_length = 0; uint8_t part_length; @@ -953,7 +956,7 @@ static uint16_t _mdns_append_srv_record(uint8_t * packet, uint16_t * index, mdns } record_length += part_length; - part_length = _mdns_append_type(packet, index, MDNS_ANSWER_SRV, flush, bye?0:MDNS_ANSWER_SRV_TTL); + part_length = _mdns_append_type(packet, index, MDNS_ANSWER_SRV, flush, bye ? 0 : MDNS_ANSWER_SRV_TTL); if (!part_length) { return 0; } @@ -1000,9 +1003,9 @@ static uint16_t _mdns_append_srv_record(uint8_t * packet, uint16_t * index, mdns * * @return length of added data: 0 on error or length on success */ -static uint16_t _mdns_append_a_record(uint8_t * packet, uint16_t * index, const char * hostname, uint32_t ip, bool flush, bool bye) +static uint16_t _mdns_append_a_record(uint8_t *packet, uint16_t *index, const char *hostname, uint32_t ip, bool flush, bool bye) { - const char * str[2]; + const char *str[2]; uint16_t record_length = 0; uint8_t part_length; @@ -1019,7 +1022,7 @@ static uint16_t _mdns_append_a_record(uint8_t * packet, uint16_t * index, const } record_length += part_length; - part_length = _mdns_append_type(packet, index, MDNS_ANSWER_A, flush, bye?0:MDNS_ANSWER_A_TTL); + part_length = _mdns_append_type(packet, index, MDNS_ANSWER_A, flush, bye ? 0 : MDNS_ANSWER_A_TTL); if (!part_length) { return 0; } @@ -1051,9 +1054,9 @@ static uint16_t _mdns_append_a_record(uint8_t * packet, uint16_t * index, const * * @return length of added data: 0 on error or length on success */ -static uint16_t _mdns_append_aaaa_record(uint8_t * packet, uint16_t * index, const char * hostname, uint8_t * ipv6, bool flush, bool bye) +static uint16_t _mdns_append_aaaa_record(uint8_t *packet, uint16_t *index, const char *hostname, uint8_t *ipv6, bool flush, bool bye) { - const char * str[2]; + const char *str[2]; uint16_t record_length = 0; uint8_t part_length; @@ -1071,7 +1074,7 @@ static uint16_t _mdns_append_aaaa_record(uint8_t * packet, uint16_t * index, con } record_length += part_length; - part_length = _mdns_append_type(packet, index, MDNS_ANSWER_AAAA, flush, bye?0:MDNS_ANSWER_AAAA_TTL); + part_length = _mdns_append_type(packet, index, MDNS_ANSWER_AAAA, flush, bye ? 0 : MDNS_ANSWER_AAAA_TTL); if (!part_length) { return 0; } @@ -1095,9 +1098,9 @@ static uint16_t _mdns_append_aaaa_record(uint8_t * packet, uint16_t * index, con /** * @brief Append question to packet */ -static uint16_t _mdns_append_question(uint8_t * packet, uint16_t * index, mdns_out_question_t * q) +static uint16_t _mdns_append_question(uint8_t *packet, uint16_t *index, mdns_out_question_t *q) { - const char * str[4]; + const char *str[4]; uint8_t str_index = 0; uint8_t part_length; if (q->host) { @@ -1119,7 +1122,7 @@ static uint16_t _mdns_append_question(uint8_t * packet, uint16_t * index, mdns_o } part_length += _mdns_append_u16(packet, index, q->type); - part_length += _mdns_append_u16(packet, index, q->unicast?0x8001:0x0001); + part_length += _mdns_append_u16(packet, index, q->unicast ? 0x8001 : 0x0001); return part_length; } @@ -1145,10 +1148,10 @@ static bool _mdns_if_is_dup(mdns_if_t tcpip_if) return false; } if (_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].state == PCB_DUP - || _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP - || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V4].state == PCB_DUP - || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP - ) { + || _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP + || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V4].state == PCB_DUP + || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP + ) { return true; } return false; @@ -1161,8 +1164,8 @@ static bool _mdns_if_is_dup(mdns_if_t tcpip_if) static bool _ipv6_address_is_zero(esp_ip6_addr_t ip6) { uint8_t i; - uint8_t * data = (uint8_t *)ip6.addr; - for (i=0; i<_MDNS_SIZEOF_IP6_ADDR; i++) { + uint8_t *data = (uint8_t *)ip6.addr; + for (i = 0; i < _MDNS_SIZEOF_IP6_ADDR; i++) { if (data[i]) { return false; } @@ -1171,22 +1174,22 @@ static bool _ipv6_address_is_zero(esp_ip6_addr_t ip6) } #endif -static uint8_t _mdns_append_host_answer(uint8_t * packet, uint16_t * index, mdns_host_item_t * host, +static uint8_t _mdns_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; + mdns_ip_addr_t *addr = host->address_list; uint8_t num_records = 0; while (addr != NULL) { if (addr->addr.type == address_type) { if (address_type == ESP_IPADDR_TYPE_V4 && - _mdns_append_a_record(packet, index, host->hostname, addr->addr.u_addr.ip4.addr, flush, bye) <= 0) { + _mdns_append_a_record(packet, index, host->hostname, addr->addr.u_addr.ip4.addr, flush, bye) <= 0) { break; } #if CONFIG_LWIP_IPV6 if (address_type == ESP_IPADDR_TYPE_V6 && - _mdns_append_aaaa_record(packet, index, host->hostname, (uint8_t *)addr->addr.u_addr.ip6.addr, flush, - bye) <= 0) { + _mdns_append_aaaa_record(packet, index, host->hostname, (uint8_t *)addr->addr.u_addr.ip6.addr, flush, + bye) <= 0) { break; } #endif // CONFIG_LWIP_IPV6 @@ -1203,7 +1206,7 @@ static uint8_t _mdns_append_host_answer(uint8_t * packet, uint16_t * index, mdns * @return number of answers added to the packet */ static uint8_t _mdns_append_service_ptr_answers(uint8_t *packet, uint16_t *index, mdns_service_t *service, bool flush, - bool bye) + bool bye) { uint8_t appended_answers = 0; @@ -1230,15 +1233,15 @@ static uint8_t _mdns_append_service_ptr_answers(uint8_t *packet, uint16_t *index * * @return number of answers added to the packet */ -static uint8_t _mdns_append_answer(uint8_t * packet, uint16_t * index, mdns_out_answer_t * answer, mdns_if_t tcpip_if) +static uint8_t _mdns_append_answer(uint8_t *packet, uint16_t *index, mdns_out_answer_t *answer, mdns_if_t tcpip_if) { if (answer->type == MDNS_TYPE_PTR) { if (answer->service) { return _mdns_append_service_ptr_answers(packet, index, answer->service, answer->flush, answer->bye); } else { return _mdns_append_ptr_record(packet, index, - answer->custom_instance, answer->custom_service, answer->custom_proto, - answer->flush, answer->bye) > 0; + answer->custom_instance, answer->custom_service, answer->custom_proto, + answer->flush, answer->bye) > 0; } } else if (answer->type == MDNS_TYPE_SRV) { return _mdns_append_srv_record(packet, index, answer->service, answer->flush, answer->bye) > 0; @@ -1286,7 +1289,7 @@ static uint8_t _mdns_append_answer(uint8_t * packet, uint16_t * index, mdns_out_ if (_ipv6_address_is_zero(if_ip6)) { return 0; } - if (_mdns_append_aaaa_record(packet, index, _mdns_server->hostname, (uint8_t*)if_ip6.addr, answer->flush, answer->bye) <= 0) { + if (_mdns_append_aaaa_record(packet, index, _mdns_server->hostname, (uint8_t *)if_ip6.addr, answer->flush, answer->bye) <= 0) { return 0; } if (!_mdns_if_is_dup(tcpip_if)) { @@ -1296,7 +1299,7 @@ static uint8_t _mdns_append_answer(uint8_t * packet, uint16_t * index, mdns_out_ if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(other_if), &if_ip6)) { return 1; } - if (_mdns_append_aaaa_record(packet, index, _mdns_server->hostname, (uint8_t*)if_ip6.addr, answer->flush, answer->bye) > 0) { + if (_mdns_append_aaaa_record(packet, index, _mdns_server->hostname, (uint8_t *)if_ip6.addr, answer->flush, answer->bye) > 0) { return 2; } return 1; @@ -1313,13 +1316,13 @@ static uint8_t _mdns_append_answer(uint8_t * packet, uint16_t * index, mdns_out_ * * @param p the packet */ -static void _mdns_dispatch_tx_packet(mdns_tx_packet_t * p) +static void _mdns_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; + mdns_out_question_t *q; + mdns_out_answer_t *a; uint8_t count; _mdns_set_u16(packet, MDNS_HEAD_FLAGS_OFFSET, p->flags); @@ -1377,14 +1380,14 @@ static void _mdns_dispatch_tx_packet(mdns_tx_packet_t * p) * * @param packet the packet */ -static void _mdns_free_tx_packet(mdns_tx_packet_t * packet) +static void _mdns_free_tx_packet(mdns_tx_packet_t *packet) { if (!packet) { return; } - mdns_out_question_t * q = packet->questions; + mdns_out_question_t *q = packet->questions; while (q) { - mdns_out_question_t * next = q->next; + mdns_out_question_t *next = q->next; if (q->own_dynamic_memory) { free((char *)q->host); free((char *)q->service); @@ -1406,7 +1409,7 @@ static void _mdns_free_tx_packet(mdns_tx_packet_t * packet) * @param packet the packet * @param ms_after number of milliseconds after which the packet should be dispatched */ -static void _mdns_schedule_tx_packet(mdns_tx_packet_t * packet, uint32_t ms_after) +static void _mdns_schedule_tx_packet(mdns_tx_packet_t *packet, uint32_t ms_after) { if (!packet) { return; @@ -1418,7 +1421,7 @@ static void _mdns_schedule_tx_packet(mdns_tx_packet_t * packet, uint32_t ms_afte _mdns_server->tx_queue_head = packet; return; } - mdns_tx_packet_t * q = _mdns_server->tx_queue_head; + mdns_tx_packet_t *q = _mdns_server->tx_queue_head; while (q->next && q->next->send_at <= packet->send_at) { q = q->next; } @@ -1431,7 +1434,7 @@ static void _mdns_schedule_tx_packet(mdns_tx_packet_t * packet, uint32_t ms_afte */ static void _mdns_clear_tx_queue_head(void) { - mdns_tx_packet_t * q; + mdns_tx_packet_t *q; while (_mdns_server->tx_queue_head) { q = _mdns_server->tx_queue_head; _mdns_server->tx_queue_head = _mdns_server->tx_queue_head->next; @@ -1447,7 +1450,7 @@ static void _mdns_clear_tx_queue_head(void) */ static void _mdns_clear_pcb_tx_queue_head(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { - mdns_tx_packet_t * q, * p; + mdns_tx_packet_t *q, * p; while (_mdns_server->tx_queue_head && _mdns_server->tx_queue_head->tcpip_if == tcpip_if && _mdns_server->tx_queue_head->ip_protocol == ip_protocol) { q = _mdns_server->tx_queue_head; _mdns_server->tx_queue_head = _mdns_server->tx_queue_head->next; @@ -1473,9 +1476,9 @@ static void _mdns_clear_pcb_tx_queue_head(mdns_if_t tcpip_if, mdns_ip_protocol_t * @param tcpip_if the interface * @param ip_protocol pcb type V4/V6 */ -static mdns_tx_packet_t * _mdns_get_next_pcb_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +static mdns_tx_packet_t *_mdns_get_next_pcb_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { - mdns_tx_packet_t * q = _mdns_server->tx_queue_head; + mdns_tx_packet_t *q = _mdns_server->tx_queue_head; while (q) { if (q->tcpip_if == tcpip_if && q->ip_protocol == ip_protocol) { return q; @@ -1488,23 +1491,23 @@ static mdns_tx_packet_t * _mdns_get_next_pcb_packet(mdns_if_t tcpip_if, mdns_ip_ /** * @brief Find, remove and free answer from the scheduled packets */ -static void _mdns_remove_scheduled_answer(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint16_t type, mdns_srv_item_t * service) +static void _mdns_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 = _mdns_server->tx_queue_head; + mdns_tx_packet_t *q = _mdns_server->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; + mdns_out_answer_t *a = q->answers; if (a->type == type && a->service == service->service) { q->answers = q->answers->next; free(a); } else { while (a->next) { if (a->next->type == type && a->next->service == service->service) { - mdns_out_answer_t * b = a->next; + mdns_out_answer_t *b = a->next; a->next = b->next; free(b); break; @@ -1520,9 +1523,9 @@ static void _mdns_remove_scheduled_answer(mdns_if_t tcpip_if, mdns_ip_protocol_t /** * @brief Remove and free answer from answer list (destination) */ -static void _mdns_dealloc_answer(mdns_out_answer_t ** destination, uint16_t type, mdns_srv_item_t * service) +static void _mdns_dealloc_answer(mdns_out_answer_t **destination, uint16_t type, mdns_srv_item_t *service) { - mdns_out_answer_t * d = *destination; + mdns_out_answer_t *d = *destination; if (!d) { return; } @@ -1536,7 +1539,7 @@ static void _mdns_dealloc_answer(mdns_out_answer_t ** destination, uint16_t type return; } while (d->next) { - mdns_out_answer_t * a = d->next; + mdns_out_answer_t *a = d->next; if (a->type == type && a->service == service->service) { d->next = a->next; free(a); @@ -1549,10 +1552,10 @@ static void _mdns_dealloc_answer(mdns_out_answer_t ** destination, uint16_t type /** * @brief Allocate new answer and add it to answer list (destination) */ -static bool _mdns_alloc_answer(mdns_out_answer_t ** destination, uint16_t type, mdns_service_t * service, - mdns_host_item_t * host, bool flush, bool bye) +static bool _mdns_alloc_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; + mdns_out_answer_t *d = *destination; while (d) { if (d->type == type && d->service == service && d->host == host) { return true; @@ -1560,7 +1563,7 @@ static bool _mdns_alloc_answer(mdns_out_answer_t ** destination, uint16_t type, d = d->next; } - mdns_out_answer_t * a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t)); + mdns_out_answer_t *a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t)); if (!a) { HOOK_MALLOC_FAILED; return false; @@ -1579,14 +1582,14 @@ static bool _mdns_alloc_answer(mdns_out_answer_t ** destination, uint16_t type, /** * @brief Allocate new packet for sending */ -static mdns_tx_packet_t * _mdns_alloc_packet_default(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +static mdns_tx_packet_t *_mdns_alloc_packet_default(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { - mdns_tx_packet_t * packet = (mdns_tx_packet_t*)malloc(sizeof(mdns_tx_packet_t)); + mdns_tx_packet_t *packet = (mdns_tx_packet_t *)malloc(sizeof(mdns_tx_packet_t)); if (!packet) { HOOK_MALLOC_FAILED; return NULL; } - memset((uint8_t*)packet, 0, sizeof(mdns_tx_packet_t)); + 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; @@ -1603,24 +1606,24 @@ static mdns_tx_packet_t * _mdns_alloc_packet_default(mdns_if_t tcpip_if, mdns_ip return packet; } -static bool _mdns_create_answer_from_service(mdns_tx_packet_t * packet, mdns_service_t * service, - mdns_parsed_question_t * question, bool shared, bool send_flush) +static bool _mdns_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 = mdns_get_host_item(service->hostname); + mdns_host_item_t *host = mdns_get_host_item(service->hostname); if (question->type == MDNS_TYPE_PTR || question->type == MDNS_TYPE_ANY) { if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, service, NULL, false, false) || - !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, service, NULL, send_flush, false) || - !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, service, NULL, send_flush, false) || - !_mdns_alloc_answer(shared ? &packet->additional : &packet->answers, MDNS_TYPE_A, service, host, send_flush, - false) || - !_mdns_alloc_answer(shared ? &packet->additional : &packet->answers, MDNS_TYPE_AAAA, service, host, - send_flush, false)) { + !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, service, NULL, send_flush, false) || + !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, service, NULL, send_flush, false) || + !_mdns_alloc_answer(shared ? &packet->additional : &packet->answers, MDNS_TYPE_A, service, host, send_flush, + false) || + !_mdns_alloc_answer(shared ? &packet->additional : &packet->answers, MDNS_TYPE_AAAA, service, host, + send_flush, false)) { return false; } } else if (question->type == MDNS_TYPE_SRV) { if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, service, NULL, send_flush, false) || - !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_A, service, host, send_flush, false) || - !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_AAAA, service, host, send_flush, false)) { + !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_A, service, host, send_flush, false) || + !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_AAAA, service, host, send_flush, false)) { return false; } } else if (question->type == MDNS_TYPE_TXT) { @@ -1636,11 +1639,11 @@ static bool _mdns_create_answer_from_service(mdns_tx_packet_t * packet, mdns_ser return true; } -static bool _mdns_create_answer_from_hostname(mdns_tx_packet_t * packet, const char * hostname, bool send_flush) +static bool _mdns_create_answer_from_hostname(mdns_tx_packet_t *packet, const char *hostname, bool send_flush) { - mdns_host_item_t * host = mdns_get_host_item(hostname); + mdns_host_item_t *host = mdns_get_host_item(hostname); if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_A, NULL, host, send_flush, false) || - !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, host, send_flush, false)) { + !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, host, send_flush, false)) { return false; } return true; @@ -1727,8 +1730,8 @@ static void _mdns_create_answer_from_parsed_packet(mdns_parsed_packet_t *parsed_ #ifdef MDNS_REPEAT_QUERY_IN_RESPONSE 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)) { - mdns_out_question_t * out_question = malloc(sizeof(mdns_out_question_t)); + (q->type == MDNS_TYPE_ANY || q->type == MDNS_TYPE_A || q->type == MDNS_TYPE_AAAA)) { + mdns_out_question_t *out_question = malloc(sizeof(mdns_out_question_t)); if (out_question == NULL) { HOOK_MALLOC_FAILED; _mdns_free_tx_packet(packet); @@ -1772,13 +1775,13 @@ static void _mdns_create_answer_from_parsed_packet(mdns_parsed_packet_t *parsed_ /** * @brief Check if question is already in the list */ -static bool _mdns_question_exists(mdns_out_question_t * needle, mdns_out_question_t * haystack) +static bool _mdns_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) { + && haystack->host == needle->host + && haystack->service == needle->service + && haystack->proto == needle->proto) { return true; } haystack = haystack->next; @@ -1786,7 +1789,7 @@ static bool _mdns_question_exists(mdns_out_question_t * needle, mdns_out_questio return false; } -static bool _mdns_append_host(mdns_out_answer_t ** destination, mdns_host_item_t * host, bool flush, bool bye) +static bool _mdns_append_host(mdns_out_answer_t **destination, mdns_host_item_t *host, bool flush, bool bye) { if (!_mdns_alloc_answer(destination, MDNS_TYPE_A, NULL, host, flush, bye)) { return false; @@ -1797,11 +1800,11 @@ static bool _mdns_append_host(mdns_out_answer_t ** destination, mdns_host_item_t return true; } -static bool _mdns_append_host_list_in_services(mdns_out_answer_t ** destination, mdns_srv_item_t * services[], - size_t services_len, bool flush, bool bye) +static bool _mdns_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 = mdns_get_host_item(_mdns_server->hostname); + mdns_host_item_t *host = mdns_get_host_item(_mdns_server->hostname); if (host != NULL) { return _mdns_append_host(destination, host, flush, bye); } @@ -1816,15 +1819,15 @@ static bool _mdns_append_host_list_in_services(mdns_out_answer_t ** destination, return true; } -static bool _mdns_append_host_list(mdns_out_answer_t ** destination, bool flush, bool bye) +static bool _mdns_append_host_list(mdns_out_answer_t **destination, bool flush, bool bye) { if (!_str_null_or_empty(_mdns_server->hostname)) { - mdns_host_item_t * self_host = mdns_get_host_item(_mdns_server->hostname); + mdns_host_item_t *self_host = mdns_get_host_item(_mdns_server->hostname); if (!_mdns_append_host(destination, self_host, flush, bye)) { return false; } } - mdns_host_item_t * host = _mdns_host_list; + mdns_host_item_t *host = _mdns_host_list; while (host != NULL) { host = host->next; if (!_mdns_append_host(destination, host, flush, bye)) { @@ -1858,10 +1861,10 @@ static bool _mdns_append_host_question(mdns_out_question_t **questions, const ch } static bool _mdns_append_host_questions_for_services(mdns_out_question_t **questions, mdns_srv_item_t *services[], - size_t len, bool unicast) + size_t len, bool unicast) { if (!_str_null_or_empty(_mdns_server->hostname) && - !_mdns_append_host_question(questions, _mdns_server->hostname, unicast)) { + !_mdns_append_host_question(questions, _mdns_server->hostname, unicast)) { return false; } for (size_t i = 0; i < len; i++) { @@ -1875,16 +1878,16 @@ static bool _mdns_append_host_questions_for_services(mdns_out_question_t **quest /** * @brief Create probe packet for particular services on particular PCB */ -static mdns_tx_packet_t * _mdns_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) +static mdns_tx_packet_t *_mdns_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_alloc_packet_default(tcpip_if, ip_protocol); + mdns_tx_packet_t *packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol); if (!packet) { return NULL; } size_t i; - for (i=0; iflags = MDNS_FLAGS_QR_AUTHORITATIVE; uint8_t i; - for (i=0; ianswers, MDNS_TYPE_SDPTR, services[i]->service, NULL, false, false) || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, services[i]->service, NULL, false, false) || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, services[i]->service, NULL, true, false) @@ -1959,15 +1962,15 @@ static mdns_tx_packet_t * _mdns_create_announce_packet(mdns_if_t tcpip_if, mdns_ /** * @brief Convert probe packet to announce */ -static mdns_tx_packet_t * _mdns_create_announce_from_probe(mdns_tx_packet_t * probe) +static mdns_tx_packet_t *_mdns_create_announce_from_probe(mdns_tx_packet_t *probe) { - mdns_tx_packet_t * packet = _mdns_alloc_packet_default(probe->tcpip_if, probe->ip_protocol); + mdns_tx_packet_t *packet = _mdns_alloc_packet_default(probe->tcpip_if, probe->ip_protocol); if (!packet) { return NULL; } packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; - mdns_out_answer_t * s = probe->servers; + mdns_out_answer_t *s = probe->servers; while (s) { if (s->type == MDNS_TYPE_SRV) { if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SDPTR, s->service, NULL, false, false) @@ -1999,15 +2002,15 @@ static mdns_tx_packet_t * _mdns_create_announce_from_probe(mdns_tx_packet_t * pr /** * @brief Send by for particular services on particular PCB */ -static void _mdns_pcb_send_bye(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool include_ip) +static void _mdns_pcb_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_alloc_packet_default(tcpip_if, ip_protocol); + mdns_tx_packet_t *packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol); if (!packet) { return; } packet->flags = MDNS_FLAGS_QR_AUTHORITATIVE; size_t i; - for (i=0; ianswers, MDNS_TYPE_PTR, services[i]->service, NULL, true, true)) { _mdns_free_tx_packet(packet); return; @@ -2023,15 +2026,15 @@ static void _mdns_pcb_send_bye(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protoco /** * @brief Send probe for additional services on particular PCB */ -static void _mdns_init_pcb_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) +static void _mdns_init_pcb_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 = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; + mdns_pcb_t *pcb = &_mdns_server->interfaces[tcpip_if].pcbs[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 ** _services = NULL; + mdns_srv_item_t **_services = NULL; if (services_final_len) { _services = (mdns_srv_item_t **)malloc(sizeof(mdns_srv_item_t *) * services_final_len); if (!_services) { @@ -2040,12 +2043,12 @@ static void _mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protoco } size_t i; - for (i=0; iprobe_services) { - for (i=0; iprobe_services_len; i++) { - _services[len+i] = pcb->probe_services[i]; + for (i = 0; i < pcb->probe_services_len; i++) { + _services[len + i] = pcb->probe_services[i]; } free(pcb->probe_services); } @@ -2058,7 +2061,7 @@ static void _mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protoco pcb->probe_services_len = 0; pcb->probe_running = false; - mdns_tx_packet_t * packet = _mdns_create_probe_packet(tcpip_if, ip_protocol, _services, services_final_len, true, probe_ip); + mdns_tx_packet_t *packet = _mdns_create_probe_packet(tcpip_if, ip_protocol, _services, services_final_len, true, probe_ip); if (!packet) { free(_services); return; @@ -2068,7 +2071,7 @@ static void _mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protoco pcb->probe_services = _services; pcb->probe_services_len = services_final_len; pcb->probe_running = true; - _mdns_schedule_tx_packet(packet, ((pcb->failed_probes > 5)?1000:120) + (esp_random() & 0x7F)); + _mdns_schedule_tx_packet(packet, ((pcb->failed_probes > 5) ? 1000 : 120) + (esp_random() & 0x7F)); pcb->state = PCB_PROBE_1; } @@ -2079,9 +2082,9 @@ static void _mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protoco * - If pcb probing then add only non-probing services and restarts probing * - If pcb not probing, run probing for all specified services */ -static void _mdns_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) +static void _mdns_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 = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; + mdns_pcb_t *pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; _mdns_clear_pcb_tx_queue_head(tcpip_if, ip_protocol); @@ -2092,12 +2095,12 @@ static void _mdns_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_proto if (PCB_STATE_IS_PROBING(pcb)) { // Looking for already probing services to resolve duplications - mdns_srv_item_t * new_probe_services[len]; + mdns_srv_item_t *new_probe_services[len]; int new_probe_service_len = 0; bool found; - for (size_t j=0; j < len; ++j) { + for (size_t j = 0; j < len; ++j) { found = false; - for (int i=0; i < pcb->probe_services_len; ++i) { + for (int i = 0; i < pcb->probe_services_len; ++i) { if (pcb->probe_services[i] == services[j]) { found = true; break; @@ -2109,7 +2112,7 @@ static void _mdns_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_proto } // init probing for newly added services _mdns_init_pcb_probe_new_service(tcpip_if, ip_protocol, - new_probe_service_len?new_probe_services:NULL, new_probe_service_len, probe_ip); + new_probe_service_len ? new_probe_services : NULL, new_probe_service_len, probe_ip); } else { // not probing, so init for all services _mdns_init_pcb_probe_new_service(tcpip_if, ip_protocol, services, len, probe_ip); @@ -2122,12 +2125,12 @@ static void _mdns_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_proto static void _mdns_restart_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { size_t srv_count = 0; - mdns_srv_item_t * a = _mdns_server->services; + mdns_srv_item_t *a = _mdns_server->services; while (a) { srv_count++; a = a->next; } - mdns_srv_item_t * services[srv_count]; + mdns_srv_item_t *services[srv_count]; size_t i = 0; a = _mdns_server->services; while (a) { @@ -2140,15 +2143,15 @@ static void _mdns_restart_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol /** * @brief Send by for particular services */ -static void _mdns_send_bye(mdns_srv_item_t ** services, size_t len, bool include_ip) +static void _mdns_send_bye(mdns_srv_item_t **services, size_t len, bool include_ip) { uint8_t i, j; if (_str_null_or_empty(_mdns_server->hostname)) { return; } - for (i=0; iinterfaces[i].pcbs[j].pcb && _mdns_server->interfaces[i].pcbs[j].state == PCB_RUNNING) { _mdns_pcb_send_bye((mdns_if_t)i, (mdns_ip_protocol_t)j, services, len, include_ip); } @@ -2159,17 +2162,17 @@ static void _mdns_send_bye(mdns_srv_item_t ** services, size_t len, bool include /** * @brief Send announcement on particular PCB */ -static void _mdns_announce_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool include_ip) +static void _mdns_announce_pcb(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 = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; + mdns_pcb_t *_pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; size_t i; if (_pcb->pcb) { if (PCB_STATE_IS_PROBING(_pcb)) { _mdns_init_pcb_probe(tcpip_if, ip_protocol, services, len, include_ip); } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) { - mdns_tx_packet_t * p = _mdns_get_next_pcb_packet(tcpip_if, ip_protocol); + mdns_tx_packet_t *p = _mdns_get_next_pcb_packet(tcpip_if, ip_protocol); if (p) { - for (i=0; ianswers, MDNS_TYPE_SDPTR, services[i]->service, NULL, false, false) || !_mdns_alloc_answer(&p->answers, MDNS_TYPE_PTR, services[i]->service, NULL, false, false) || !_mdns_alloc_answer(&p->answers, MDNS_TYPE_SRV, services[i]->service, NULL, true, false) @@ -2191,7 +2194,7 @@ static void _mdns_announce_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protoco } _pcb->state = PCB_ANNOUNCE_1; - mdns_tx_packet_t * p = _mdns_create_announce_packet(tcpip_if, ip_protocol, services, len, include_ip); + mdns_tx_packet_t *p = _mdns_create_announce_packet(tcpip_if, ip_protocol, services, len, include_ip); if (p) { _mdns_schedule_tx_packet(p, 0); } @@ -2202,13 +2205,13 @@ static void _mdns_announce_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protoco /** * @brief Send probe on all active PCBs */ -static void _mdns_probe_all_pcbs(mdns_srv_item_t ** services, size_t len, bool probe_ip, bool clear_old_probe) +static void _mdns_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; iinterfaces[i].pcbs[j].pcb) { - mdns_pcb_t * _pcb = &_mdns_server->interfaces[i].pcbs[j]; + mdns_pcb_t *_pcb = &_mdns_server->interfaces[i].pcbs[j]; if (clear_old_probe) { free(_pcb->probe_services); _pcb->probe_services = NULL; @@ -2224,11 +2227,11 @@ static void _mdns_probe_all_pcbs(mdns_srv_item_t ** services, size_t len, bool p /** * @brief Send announcement on all active PCBs */ -static void _mdns_announce_all_pcbs(mdns_srv_item_t ** services, size_t len, bool include_ip) +static void _mdns_announce_all_pcbs(mdns_srv_item_t **services, size_t len, bool include_ip) { uint8_t i, j; - for (i=0; iservices; + mdns_srv_item_t *a = _mdns_server->services; while (a) { srv_count++; a = a->next; @@ -2249,7 +2252,7 @@ static void _mdns_send_final_bye(bool include_ip) if (!srv_count) { return; } - mdns_srv_item_t * services[srv_count]; + mdns_srv_item_t *services[srv_count]; size_t i = 0; a = _mdns_server->services; while (a) { @@ -2265,7 +2268,7 @@ static void _mdns_send_final_bye(bool include_ip) static void _mdns_send_bye_all_pcbs_no_instance(bool include_ip) { size_t srv_count = 0; - mdns_srv_item_t * a = _mdns_server->services; + mdns_srv_item_t *a = _mdns_server->services; while (a) { if (!a->service->instance) { srv_count++; @@ -2275,7 +2278,7 @@ static void _mdns_send_bye_all_pcbs_no_instance(bool include_ip) if (!srv_count) { return; } - mdns_srv_item_t * services[srv_count]; + mdns_srv_item_t *services[srv_count]; size_t i = 0; a = _mdns_server->services; while (a) { @@ -2293,7 +2296,7 @@ static void _mdns_send_bye_all_pcbs_no_instance(bool include_ip) static void _mdns_restart_all_pcbs_no_instance(void) { size_t srv_count = 0; - mdns_srv_item_t * a = _mdns_server->services; + mdns_srv_item_t *a = _mdns_server->services; while (a) { if (!a->service->instance) { srv_count++; @@ -2303,7 +2306,7 @@ static void _mdns_restart_all_pcbs_no_instance(void) if (!srv_count) { return; } - mdns_srv_item_t * services[srv_count]; + mdns_srv_item_t *services[srv_count]; size_t i = 0; a = _mdns_server->services; while (a) { @@ -2322,12 +2325,12 @@ static void _mdns_restart_all_pcbs(void) { _mdns_clear_tx_queue_head(); size_t srv_count = 0; - mdns_srv_item_t * a = _mdns_server->services; + mdns_srv_item_t *a = _mdns_server->services; while (a) { srv_count++; a = a->next; } - mdns_srv_item_t * services[srv_count]; + mdns_srv_item_t *services[srv_count]; size_t l = 0; a = _mdns_server->services; while (a) { @@ -2347,13 +2350,13 @@ static void _mdns_restart_all_pcbs(void) * * @return pointer to the linked txt item list or NULL */ -static mdns_txt_linked_item_t * _mdns_allocate_txt(size_t num_items, mdns_txt_item_t txt[]) +static mdns_txt_linked_item_t *_mdns_allocate_txt(size_t num_items, mdns_txt_item_t txt[]) { - mdns_txt_linked_item_t * new_txt = NULL; + mdns_txt_linked_item_t *new_txt = NULL; size_t i = 0; if (num_items) { - for (i=0; ipriority = 0; s->weight = 0; - s->instance = instance?strndup(instance, MDNS_NAME_BUF_LEN - 1):NULL; + s->instance = instance ? strndup(instance, MDNS_NAME_BUF_LEN - 1) : NULL; s->txt = new_txt; s->port = port; s->subtype = NULL; @@ -2461,9 +2464,9 @@ fail: /** * @brief Remove and free service answer from answer list (destination) */ -static void _mdns_dealloc_scheduled_service_answers(mdns_out_answer_t ** destination, mdns_service_t * service) +static void _mdns_dealloc_scheduled_service_answers(mdns_out_answer_t **destination, mdns_service_t *service) { - mdns_out_answer_t * d = *destination; + mdns_out_answer_t *d = *destination; if (!d) { return; } @@ -2473,7 +2476,7 @@ static void _mdns_dealloc_scheduled_service_answers(mdns_out_answer_t ** destina d = *destination; } while (d && d->next) { - mdns_out_answer_t * a = d->next; + mdns_out_answer_t *a = d->next; if (a->service == service) { d->next = a->next; free(a); @@ -2486,13 +2489,13 @@ static void _mdns_dealloc_scheduled_service_answers(mdns_out_answer_t ** destina /** * @brief Find, remove and free answers and scheduled packets for service */ -static void _mdns_remove_scheduled_service_packets(mdns_service_t * service) +static void _mdns_remove_scheduled_service_packets(mdns_service_t *service) { if (!service) { return; } - mdns_tx_packet_t * p = NULL; - mdns_tx_packet_t * q = _mdns_server->tx_queue_head; + mdns_tx_packet_t *p = NULL; + mdns_tx_packet_t *q = _mdns_server->tx_queue_head; while (q) { bool had_answers = (q->answers != NULL); @@ -2501,22 +2504,22 @@ static void _mdns_remove_scheduled_service_packets(mdns_service_t * service) _mdns_dealloc_scheduled_service_answers(&(q->servers), service); - mdns_pcb_t * _pcb = &_mdns_server->interfaces[q->tcpip_if].pcbs[q->ip_protocol]; - if(_pcb->pcb) { + mdns_pcb_t *_pcb = &_mdns_server->interfaces[q->tcpip_if].pcbs[q->ip_protocol]; + if (_pcb->pcb) { 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){ + 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]; + for (n = (i + 1); n < _pcb->probe_services_len; n++) { + _pcb->probe_services[n - 1] = _pcb->probe_services[n]; } _pcb->probe_services_len--; } else { @@ -2530,26 +2533,24 @@ static void _mdns_remove_scheduled_service_packets(mdns_service_t * service) } if (q->questions) { - mdns_out_question_t * qsn = NULL; - mdns_out_question_t * qs = 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) - { + && qs->service && strcmp(qs->service, service->service) == 0 + && qs->proto && strcmp(qs->proto, service->proto) == 0) { q->questions = q->questions->next; 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; - free(qsn); - break; + 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; + free(qsn); + break; + } + qs = qs->next; } - qs = qs->next; - } } } } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) { @@ -2562,7 +2563,7 @@ static void _mdns_remove_scheduled_service_packets(mdns_service_t * service) p = q; q = q->next; - if(!p->questions && !p->answers && !p->additional && !p->servers){ + if (!p->questions && !p->answers && !p->additional && !p->servers) { queueDetach(mdns_tx_packet_t, _mdns_server->tx_queue_head, p); _mdns_free_tx_packet(p); } @@ -2574,7 +2575,7 @@ static void _mdns_remove_scheduled_service_packets(mdns_service_t * service) * * @param service the service */ -static void _mdns_free_service(mdns_service_t * service) +static void _mdns_free_service(mdns_service_t *service) { if (!service) { return; @@ -2584,14 +2585,14 @@ static void _mdns_free_service(mdns_service_t * service) free((char *)service->proto); free((char *)service->hostname); while (service->txt) { - mdns_txt_linked_item_t * s = service->txt; + mdns_txt_linked_item_t *s = service->txt; service->txt = service->txt->next; free((char *)s->key); free((char *)s->value); free(s); } while (service->subtype) { - mdns_subtype_t * next = service->subtype->next; + mdns_subtype_t *next = service->subtype->next; free((char *)service->subtype->subtype); free(service->subtype); service->subtype = next; @@ -2607,7 +2608,7 @@ static void _mdns_free_service(mdns_service_t * service) /** * @brief Detect SRV collision */ -static int _mdns_check_srv_collision(mdns_service_t * service, uint16_t priority, uint16_t weight, uint16_t port, const char * host, const char * domain) +static int _mdns_check_srv_collision(mdns_service_t *service, uint16_t priority, uint16_t weight, uint16_t port, const char *host, const char *domain) { if (_str_null_or_empty(_mdns_server->hostname)) { return 0; @@ -2664,7 +2665,7 @@ static int _mdns_check_srv_collision(mdns_service_t * service, uint16_t priority /** * @brief Detect TXT collision */ -static int _mdns_check_txt_collision(mdns_service_t * service, const uint8_t * data, size_t len) +static int _mdns_check_txt_collision(mdns_service_t *service, const uint8_t *data, size_t len) { size_t data_len = 0; if (len == 1 && service->txt) { @@ -2675,7 +2676,7 @@ static int _mdns_check_txt_collision(mdns_service_t * service, const uint8_t * d return 0;//same } - mdns_txt_linked_item_t * txt = service->txt; + 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; @@ -2715,7 +2716,7 @@ static void _mdns_dup_interface(mdns_if_t tcpip_if) if (other_if == MDNS_MAX_INTERFACES) { return; // no other interface found } - for (i=0; iinterfaces[other_if].pcbs[i].pcb) { //stop this interface and mark as dup if (_mdns_server->interfaces[tcpip_if].pcbs[i].pcb) { @@ -2731,7 +2732,7 @@ static void _mdns_dup_interface(mdns_if_t tcpip_if) /** * @brief Detect IPv4 address collision */ -static int _mdns_check_a_collision(esp_ip4_addr_t * ip, mdns_if_t tcpip_if) +static int _mdns_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; @@ -2742,7 +2743,7 @@ static int _mdns_check_a_collision(esp_ip4_addr_t * ip, mdns_if_t tcpip_if) return 1;//they win } - int ret = memcmp((uint8_t*)&if_ip_info.ip.addr, (uint8_t*)&ip->addr, sizeof(esp_ip4_addr_t)); + 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) { @@ -2767,7 +2768,7 @@ static int _mdns_check_a_collision(esp_ip4_addr_t * ip, mdns_if_t tcpip_if) /** * @brief Detect IPv6 address collision */ -static int _mdns_check_aaaa_collision(esp_ip6_addr_t * ip, mdns_if_t tcpip_if) +static int _mdns_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; @@ -2777,7 +2778,7 @@ static int _mdns_check_aaaa_collision(esp_ip6_addr_t * ip, mdns_if_t tcpip_if) if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(tcpip_if), &if_ip6)) { return 1;//they win } - int ret = memcmp((uint8_t*)&if_ip6.addr, (uint8_t*)ip->addr, _MDNS_SIZEOF_IP6_ADDR); + int ret = memcmp((uint8_t *)&if_ip6.addr, (uint8_t *)ip->addr, _MDNS_SIZEOF_IP6_ADDR); if (ret > 0) { return -1;//we win } else if (ret < 0) { @@ -2789,7 +2790,7 @@ static int _mdns_check_aaaa_collision(esp_ip6_addr_t * ip, mdns_if_t tcpip_if) if (esp_netif_get_ip6_linklocal(_mdns_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_SIZEOF_IP6_ADDR)) { + if (memcmp((uint8_t *)&other_ip6.addr, (uint8_t *)ip->addr, _MDNS_SIZEOF_IP6_ADDR)) { return 1;//IPv6 not ours! They win } _mdns_dup_interface(tcpip_if); @@ -2799,13 +2800,13 @@ static int _mdns_check_aaaa_collision(esp_ip6_addr_t * ip, mdns_if_t tcpip_if) } #endif -static bool _hostname_is_ours(const char * hostname) +static bool _hostname_is_ours(const char *hostname) { if (!_str_null_or_empty(_mdns_server->hostname) && - strcasecmp(hostname, _mdns_server->hostname) == 0) { + strcasecmp(hostname, _mdns_server->hostname) == 0) { return true; } - mdns_host_item_t * host = _mdns_host_list; + mdns_host_item_t *host = _mdns_host_list; while (host != NULL) { if (strcasecmp(hostname, host->hostname) == 0) { return true; @@ -2822,13 +2823,13 @@ static bool _hostname_is_ours(const char * hostname) * @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 */ -static bool _mdns_delegate_hostname_add(const char * hostname, mdns_ip_addr_t * address_list) +static bool _mdns_delegate_hostname_add(const char *hostname, mdns_ip_addr_t *address_list) { if (_hostname_is_ours(hostname)) { return false; } - mdns_host_item_t * host = (mdns_host_item_t *)malloc(sizeof(mdns_host_item_t)); + mdns_host_item_t *host = (mdns_host_item_t *)malloc(sizeof(mdns_host_item_t)); if (host == NULL) { return false; @@ -2840,21 +2841,21 @@ static bool _mdns_delegate_hostname_add(const char * hostname, mdns_ip_addr_t * return true; } -static void free_address_list(mdns_ip_addr_t * address_list) +static void free_address_list(mdns_ip_addr_t *address_list) { while (address_list != NULL) { - mdns_ip_addr_t * next = address_list->next; + mdns_ip_addr_t *next = address_list->next; free(address_list); address_list = next; } } -static mdns_ip_addr_t * copy_address_list(const mdns_ip_addr_t * address_list) +static mdns_ip_addr_t *copy_address_list(const mdns_ip_addr_t *address_list) { - mdns_ip_addr_t * head = NULL; - mdns_ip_addr_t * tail = NULL; + 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 *)malloc(sizeof(mdns_ip_addr_t)); + mdns_ip_addr_t *addr = (mdns_ip_addr_t *)malloc(sizeof(mdns_ip_addr_t)); if (addr == NULL) { free_address_list(head); return NULL; @@ -2875,7 +2876,7 @@ static mdns_ip_addr_t * copy_address_list(const mdns_ip_addr_t * address_list) static void free_delegated_hostnames(void) { - mdns_host_item_t * host = _mdns_host_list; + mdns_host_item_t *host = _mdns_host_list; while (host != NULL) { free_address_list(host->address_list); free((char *)host->hostname); @@ -2885,13 +2886,13 @@ static void free_delegated_hostnames(void) } } -static bool _mdns_delegate_hostname_remove(const char * hostname) +static bool _mdns_delegate_hostname_remove(const char *hostname) { - mdns_srv_item_t * srv = _mdns_server->services; - mdns_srv_item_t * prev_srv = NULL; + mdns_srv_item_t *srv = _mdns_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_srv_item_t *to_free = srv; _mdns_send_bye(&srv, 1, false); _mdns_remove_scheduled_service_packets(srv->service); if (prev_srv == NULL) { @@ -2908,8 +2909,8 @@ static bool _mdns_delegate_hostname_remove(const char * hostname) srv = srv->next; } } - mdns_host_item_t * host = _mdns_host_list; - mdns_host_item_t * prev_host = NULL; + mdns_host_item_t *host = _mdns_host_list; + mdns_host_item_t *prev_host = NULL; while (host != NULL) { if (strcasecmp(hostname, host->hostname) == 0) { if (prev_host == NULL) { @@ -2932,7 +2933,7 @@ static bool _mdns_delegate_hostname_remove(const char * hostname) /** * @brief Check if parsed name is discovery */ -static bool _mdns_name_is_discovery(mdns_name_t * name, uint16_t type) +static bool _mdns_name_is_discovery(mdns_name_t *name, uint16_t type) { return ( (name->host && name->host[0] && !strcasecmp(name->host, "_services")) @@ -2946,7 +2947,7 @@ static bool _mdns_name_is_discovery(mdns_name_t * name, uint16_t type) /** * @brief Check if the parsed name is ours (matches service or host name) */ -static bool _mdns_name_is_ours(mdns_name_t * name) +static bool _mdns_name_is_ours(mdns_name_t *name) { //domain have to be "local" if (_str_null_or_empty(name->domain) || strcasecmp(name->domain, MDNS_DEFAULT_DOMAIN)) { @@ -2956,9 +2957,8 @@ static bool _mdns_name_is_ours(mdns_name_t * name) //if service and proto are empty, host must match out hostname if (_str_null_or_empty(name->service) && _str_null_or_empty(name->proto)) { if (!_str_null_or_empty(name->host) - && !_str_null_or_empty(_mdns_server->hostname) - && _hostname_is_ours(name->host)) - { + && !_str_null_or_empty(_mdns_server->hostname) + && _hostname_is_ours(name->host)) { return true; } return false; @@ -2971,7 +2971,7 @@ static bool _mdns_name_is_ours(mdns_name_t * name) //find the service - mdns_srv_item_t * service; + mdns_srv_item_t *service; if (name->sub) { service = _mdns_get_service_item_subtype(name->host, name->service, name->proto); } else if (_str_null_or_empty(name->host)) { @@ -2989,7 +2989,7 @@ static bool _mdns_name_is_ours(mdns_name_t * name) } //OK we have host in the name. find what is the instance of the service - const char * instance = _mdns_get_service_instance_name(service->service); + const char *instance = _mdns_get_service_instance_name(service->service); if (instance == NULL) { return false; } @@ -3009,9 +3009,9 @@ static bool _mdns_name_is_ours(mdns_name_t * name) * * @return the value */ -static inline uint16_t _mdns_read_u16(const uint8_t * packet, uint16_t index) +static inline uint16_t _mdns_read_u16(const uint8_t *packet, uint16_t index) { - return (uint16_t)(packet[index]) << 8 | packet[index+1]; + return (uint16_t)(packet[index]) << 8 | packet[index + 1]; } /** @@ -3021,9 +3021,9 @@ static inline uint16_t _mdns_read_u16(const uint8_t * packet, uint16_t index) * * @return the value */ -static inline uint32_t _mdns_read_u32(const uint8_t * packet, uint16_t index) +static inline uint32_t _mdns_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]; + return (uint32_t)(packet[index]) << 24 | (uint32_t)(packet[index + 1]) << 16 | (uint32_t)(packet[index + 2]) << 8 | packet[index + 3]; } /** @@ -3035,7 +3035,7 @@ static inline uint32_t _mdns_read_u32(const uint8_t * packet, uint16_t index) * * @return the address after the parsed FQDN in the packet or NULL on error */ -static const uint8_t * _mdns_parse_fqdn(const uint8_t * packet, const uint8_t * start, mdns_name_t * name, size_t packet_len) +static const uint8_t *_mdns_parse_fqdn(const uint8_t *packet, const uint8_t *start, mdns_name_t *name, size_t packet_len) { name->parts = 0; name->sub = 0; @@ -3047,7 +3047,7 @@ static const uint8_t * _mdns_parse_fqdn(const uint8_t * packet, const uint8_t * static char buf[MDNS_NAME_BUF_LEN]; - const uint8_t * next_data = (uint8_t*)_mdns_read_fqdn(packet, start, name, buf, packet_len); + const uint8_t *next_data = (uint8_t *)_mdns_read_fqdn(packet, start, name, buf, packet_len); if (!next_data) { return 0; } @@ -3055,10 +3055,10 @@ static const uint8_t * _mdns_parse_fqdn(const uint8_t * packet, const uint8_t * return next_data; } if (name->parts == 3) { - memmove((uint8_t*)name + (MDNS_NAME_BUF_LEN), (uint8_t*)name, 3*(MDNS_NAME_BUF_LEN)); + 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)); + memmove((uint8_t *)(name->domain), (uint8_t *)(name->service), (MDNS_NAME_BUF_LEN)); name->service[0] = 0; name->proto[0] = 0; } @@ -3072,7 +3072,7 @@ static const uint8_t * _mdns_parse_fqdn(const uint8_t * packet, const uint8_t * /** * @brief Called from parser to check if question matches particular service */ -static bool _mdns_question_matches(mdns_parsed_question_t * question, uint16_t type, mdns_srv_item_t * service) +static bool _mdns_question_matches(mdns_parsed_question_t *question, uint16_t type, mdns_srv_item_t *service) { if (question->type != type) { return false; @@ -3081,18 +3081,18 @@ static bool _mdns_question_matches(mdns_parsed_question_t * question, uint16_t t 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_DEFAULT_DOMAIN, question->domain)) { + && !strcasecmp(service->service->service, question->service) + && !strcasecmp(service->service->proto, question->proto) + && !strcasecmp(MDNS_DEFAULT_DOMAIN, question->domain)) { return true; } } else if (service && (type == MDNS_TYPE_SRV || type == MDNS_TYPE_TXT)) { - const char * name = _mdns_get_service_instance_name(service->service); + const char *name = _mdns_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_DEFAULT_DOMAIN, question->domain)) { + && !strcasecmp(name, question->host) + && !strcasecmp(service->service->service, question->service) + && !strcasecmp(service->service->proto, question->proto) + && !strcasecmp(MDNS_DEFAULT_DOMAIN, question->domain)) { return true; } } @@ -3103,9 +3103,9 @@ static bool _mdns_question_matches(mdns_parsed_question_t * question, uint16_t t /** * @brief Removes saved question from parsed data */ -static void _mdns_remove_parsed_question(mdns_parsed_packet_t * parsed_packet, uint16_t type, mdns_srv_item_t * service) +static void _mdns_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; + mdns_parsed_question_t *q = parsed_packet->questions; if (_mdns_question_matches(q, type, service)) { parsed_packet->questions = q->next; @@ -3118,7 +3118,7 @@ static void _mdns_remove_parsed_question(mdns_parsed_packet_t * parsed_packet, u } while (q->next) { - mdns_parsed_question_t * p = q->next; + mdns_parsed_question_t *p = q->next; if (_mdns_question_matches(p, type, service)) { q->next = p->next; free(p->host); @@ -3135,14 +3135,14 @@ static void _mdns_remove_parsed_question(mdns_parsed_packet_t * parsed_packet, u /** * @brief Get number of items in TXT parsed data */ -static int _mdns_txt_items_count_get(const uint8_t * data, size_t len) +static int _mdns_txt_items_count_get(const uint8_t *data, size_t len) { if (len == 1) { return 0; } int num_items = 0; - uint16_t i=0; + uint16_t i = 0; size_t partLen = 0; while (i < len) { @@ -3150,10 +3150,10 @@ static int _mdns_txt_items_count_get(const uint8_t * data, size_t len) if (!partLen) { break; } - if ((i+partLen) > len) { + if ((i + partLen) > len) { return -1;//error } - i+=partLen; + i += partLen; num_items++; } return num_items; @@ -3162,7 +3162,7 @@ static int _mdns_txt_items_count_get(const uint8_t * data, size_t len) /** * @brief Get the length of TXT item's key name */ -static int _mdns_txt_item_name_get_len(const uint8_t * data, size_t len) +static int _mdns_txt_item_name_get_len(const uint8_t *data, size_t len) { if (*data == '=') { return -1; @@ -3183,7 +3183,7 @@ static void _mdns_result_txt_create(const uint8_t *data, size_t len, mdns_txt_it { *out_txt = NULL; *out_count = 0; - uint16_t i=0, y; + uint16_t i = 0, y; size_t partLen = 0; int num_items = _mdns_txt_items_count_get(data, len); if (num_items < 0) { @@ -3194,12 +3194,12 @@ static void _mdns_result_txt_create(const uint8_t *data, size_t len, mdns_txt_it return; } - mdns_txt_item_t * txt = (mdns_txt_item_t *)malloc(sizeof(mdns_txt_item_t) * num_items); + mdns_txt_item_t *txt = (mdns_txt_item_t *)malloc(sizeof(mdns_txt_item_t) * num_items); if (!txt) { HOOK_MALLOC_FAILED; return; } - uint8_t * txt_value_len = (uint8_t *)malloc(num_items); + uint8_t *txt_value_len = (uint8_t *)malloc(num_items); if (!txt_value_len) { free(txt); HOOK_MALLOC_FAILED; @@ -3215,23 +3215,23 @@ static void _mdns_result_txt_create(const uint8_t *data, size_t len, mdns_txt_it break; } - if ((i+partLen) > len) { + if ((i + partLen) > len) { goto handle_error;//error } - int name_len = _mdns_txt_item_name_get_len(data+i, partLen); + int name_len = _mdns_txt_item_name_get_len(data + i, partLen); if (name_len < 0) {//invalid item (no name) i += partLen; continue; } - char * key = (char *)malloc(name_len + 1); + char *key = (char *)malloc(name_len + 1); if (!key) { HOOK_MALLOC_FAILED; goto handle_error;//error } - mdns_txt_item_t * t = &txt[txt_num]; - uint8_t * value_len = &txt_value_len[txt_num]; + mdns_txt_item_t *t = &txt[txt_num]; + uint8_t *value_len = &txt_value_len[txt_num]; txt_num++; memcpy(key, data + i, name_len); @@ -3241,7 +3241,7 @@ static void _mdns_result_txt_create(const uint8_t *data, size_t len, mdns_txt_it int new_value_len = partLen - name_len - 1; if (new_value_len > 0) { - char * value = (char *)malloc(new_value_len + 1); + char *value = (char *)malloc(new_value_len + 1); if (!value) { HOOK_MALLOC_FAILED; goto handle_error;//error @@ -3260,8 +3260,8 @@ static void _mdns_result_txt_create(const uint8_t *data, size_t len, mdns_txt_it return; handle_error : - for (y=0; ykey); free((char *)t->value); } @@ -3272,7 +3272,7 @@ handle_error : /** * @brief Duplicate string or return error */ -static esp_err_t _mdns_strdup_check(char ** out, char * in) +static esp_err_t _mdns_strdup_check(char **out, char *in) { if (in && in[0]) { *out = strdup(in); @@ -3290,15 +3290,15 @@ static esp_err_t _mdns_strdup_check(char ** out, char * in) * * @param packet the packet */ -void mdns_parse_packet(mdns_rx_packet_t * packet) +void mdns_parse_packet(mdns_rx_packet_t *packet) { static mdns_name_t n; mdns_header_t header; - const uint8_t * data = _mdns_get_packet_data(packet); + const uint8_t *data = _mdns_get_packet_data(packet); size_t len = _mdns_get_packet_len(packet); - const uint8_t * content = data + MDNS_HEAD_LEN; + const uint8_t *content = data + MDNS_HEAD_LEN; bool do_not_reply = false; - mdns_search_once_t * search_result = NULL; + mdns_search_once_t *search_result = NULL; #ifdef MDNS_ENABLE_DEBUG _mdns_dbg_printf("\nRX[%u][%u]: ", packet->tcpip_if, (uint32_t)packet->ip_protocol); @@ -3314,14 +3314,14 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (packet->ip_protocol == MDNS_IP_PROTOCOL_V4) { esp_netif_ip_info_t if_ip_info; if (esp_netif_get_ip_info(_mdns_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) { + memcmp(&if_ip_info.ip.addr, &packet->src.u_addr.ip4.addr, sizeof(esp_ip4_addr_t)) == 0) { return; } #if CONFIG_LWIP_IPV6 } else { struct esp_ip6_addr if_ip6; if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(packet->tcpip_if), &if_ip6) == ESP_OK && - memcmp(&if_ip6, &packet->src.u_addr.ip6, sizeof(esp_ip6_addr_t)) == 0) { + memcmp(&if_ip6, &packet->src.u_addr.ip6, sizeof(esp_ip6_addr_t)) == 0) { return; } #endif @@ -3332,14 +3332,14 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) return; } - mdns_parsed_packet_t * parsed_packet = (mdns_parsed_packet_t *)malloc(sizeof(mdns_parsed_packet_t)); + mdns_parsed_packet_t *parsed_packet = (mdns_parsed_packet_t *)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; + mdns_name_t *name = &n; memset(name, 0, sizeof(mdns_name_t)); header.id = _mdns_read_u16(data, MDNS_HEAD_ID_OFFSET); @@ -3397,9 +3397,9 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (_mdns_name_is_discovery(name, type)) { //service discovery parsed_packet->discovery = true; - mdns_srv_item_t * a = _mdns_server->services; + mdns_srv_item_t *a = _mdns_server->services; while (a) { - mdns_parsed_question_t * question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t)); + mdns_parsed_question_t *question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t)); if (!question) { HOOK_MALLOC_FAILED; goto clear_rx_packet; @@ -3428,7 +3428,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) parsed_packet->probe = true; } - mdns_parsed_question_t * question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t)); + mdns_parsed_question_t *question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t)); if (!question) { HOOK_MALLOC_FAILED; goto clear_rx_packet; @@ -3440,9 +3440,9 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) question->type = type; question->sub = name->sub; if (_mdns_strdup_check(&(question->host), name->host) - || _mdns_strdup_check(&(question->service), name->service) - || _mdns_strdup_check(&(question->proto), name->proto) - || _mdns_strdup_check(&(question->domain), name->domain)) { + || _mdns_strdup_check(&(question->service), name->service) + || _mdns_strdup_check(&(question->proto), name->proto) + || _mdns_strdup_check(&(question->domain), name->domain)) { goto clear_rx_packet; } } @@ -3467,7 +3467,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET); uint32_t ttl = _mdns_read_u32(content, MDNS_TTL_OFFSET); uint16_t data_len = _mdns_read_u16(content, MDNS_LEN_OFFSET); - const uint8_t * data_ptr = content + MDNS_DATA_OFFSET; + const uint8_t *data_ptr = content + MDNS_DATA_OFFSET; mdns_class &= 0x7FFF; content = data_ptr + data_len; @@ -3477,7 +3477,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) bool discovery = false; bool ours = false; - mdns_srv_item_t * service = NULL; + mdns_srv_item_t *service = NULL; mdns_parsed_record_type_t record_type = MDNS_ANSWER; if (recordIndex >= (header.answers + header.servers)) { @@ -3521,19 +3521,19 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) _mdns_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)) { + if (ttl > (MDNS_ANSWER_PTR_TTL / 2)) { _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); } } } } else if (type == MDNS_TYPE_SRV) { - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; if (search_result && search_result->type == MDNS_TYPE_PTR) { result = search_result->result; while (result) { if (_mdns_get_esp_netif(packet->tcpip_if) == result->esp_netif - && packet->ip_protocol == result->ip_protocol - && result->instance_name && !strcmp(name->host, result->instance_name)) { + && packet->ip_protocol == result->ip_protocol + && result->instance_name && !strcmp(name->host, result->instance_name)) { break; } result = result->next; @@ -3589,21 +3589,21 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) { _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++; if (!_str_null_or_empty(service->service->instance)) { - char * new_instance = _mdns_mangle_name((char *)service->service->instance); + char *new_instance = _mdns_mangle_name((char *)service->service->instance); if (new_instance) { free((char *)service->service->instance); service->service->instance = new_instance; } _mdns_probe_all_pcbs(&service, 1, false, false); } else if (!_str_null_or_empty(_mdns_server->instance)) { - char * new_instance = _mdns_mangle_name((char *)_mdns_server->instance); + char *new_instance = _mdns_mangle_name((char *)_mdns_server->instance); if (new_instance) { free((char *)_mdns_server->instance); _mdns_server->instance = new_instance; } _mdns_restart_all_pcbs_no_instance(); } else { - char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname); + char *new_host = _mdns_mangle_name((char *)_mdns_server->hostname); if (new_host) { _mdns_remap_self_service_hostname(_mdns_server->hostname, new_host); free((char *)_mdns_server->hostname); @@ -3623,17 +3623,17 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) } } else if (type == MDNS_TYPE_TXT) { if (search_result) { - mdns_txt_item_t * txt = NULL; + mdns_txt_item_t *txt = NULL; uint8_t *txt_value_len = NULL; size_t txt_count = 0; - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; if (search_result->type == MDNS_TYPE_PTR) { result = search_result->result; while (result) { if (_mdns_get_esp_netif(packet->tcpip_if) == result->esp_netif - && packet->ip_protocol == result->ip_protocol - && result->instance_name && !strcmp(name->host, result->instance_name)) { + && packet->ip_protocol == result->ip_protocol + && result->instance_name && !strcmp(name->host, result->instance_name)) { break; } result = result->next; @@ -3676,7 +3676,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (col && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running && service) { do_not_reply = true; _mdns_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_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) { + } else if (ttl > (MDNS_ANSWER_TXT_TTL / 2) && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) { _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service); } } @@ -3714,7 +3714,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) { if (col && (parsed_packet->probe || parsed_packet->authoritative)) { _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++; - char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname); + char *new_host = _mdns_mangle_name((char *)_mdns_server->hostname); if (new_host) { _mdns_remap_self_service_hostname(_mdns_server->hostname, new_host); free((char *)_mdns_server->hostname); @@ -3764,7 +3764,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) { if (col && (parsed_packet->probe || parsed_packet->authoritative)) { _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++; - char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname); + char *new_host = _mdns_mangle_name((char *)_mdns_server->hostname); if (new_host) { _mdns_remap_self_service_hostname(_mdns_server->hostname, new_host); free((char *)_mdns_server->hostname); @@ -3796,7 +3796,7 @@ void mdns_parse_packet(mdns_rx_packet_t * packet) clear_rx_packet: while (parsed_packet->questions) { - mdns_parsed_question_t * question = parsed_packet->questions; + mdns_parsed_question_t *question = parsed_packet->questions; parsed_packet->questions = parsed_packet->questions->next; if (question->host) { free(question->host); @@ -3902,72 +3902,71 @@ void mdns_preset_if_handle_system_event(void *arg, esp_event_base_t event_base, esp_netif_dhcp_status_t dcst; if (event_base == WIFI_EVENT) { - switch(event_id) { - case WIFI_EVENT_STA_CONNECTED: - if (!esp_netif_dhcpc_get_status(esp_netif_from_preset_if(MDNS_IF_STA), &dcst)) { - if (dcst == ESP_NETIF_DHCP_STOPPED) { - post_mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); - } + switch (event_id) { + case WIFI_EVENT_STA_CONNECTED: + if (!esp_netif_dhcpc_get_status(esp_netif_from_preset_if(MDNS_IF_STA), &dcst)) { + if (dcst == ESP_NETIF_DHCP_STOPPED) { + post_mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); } - break; - case WIFI_EVENT_STA_DISCONNECTED: - post_mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); - post_mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); - break; - case WIFI_EVENT_AP_START: - post_mdns_enable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); - break; - case WIFI_EVENT_AP_STOP: - post_mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); - post_mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V6); - break; - default: - break; + } + break; + case WIFI_EVENT_STA_DISCONNECTED: + post_mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); + post_mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); + break; + case WIFI_EVENT_AP_START: + post_mdns_enable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); + break; + case WIFI_EVENT_AP_STOP: + post_mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4); + post_mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V6); + break; + default: + break; } } #if CONFIG_ETH_ENABLED else if (event_base == ETH_EVENT) { switch (event_id) { - case ETHERNET_EVENT_CONNECTED: - if (!esp_netif_dhcpc_get_status(esp_netif_from_preset_if(MDNS_IF_ETH), &dcst)) { - if (dcst == ESP_NETIF_DHCP_STOPPED) { - post_mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); - } + case ETHERNET_EVENT_CONNECTED: + if (!esp_netif_dhcpc_get_status(esp_netif_from_preset_if(MDNS_IF_ETH), &dcst)) { + if (dcst == ESP_NETIF_DHCP_STOPPED) { + post_mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); } - break; - case ETHERNET_EVENT_DISCONNECTED: - post_mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); - post_mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V6); - break; - default: - break; + } + break; + case ETHERNET_EVENT_DISCONNECTED: + post_mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); + post_mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V6); + break; + default: + break; } } #endif else if (event_base == IP_EVENT) { switch (event_id) { - case IP_EVENT_STA_GOT_IP: - post_mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); - post_mdns_announce_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); - break; + case IP_EVENT_STA_GOT_IP: + post_mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4); + post_mdns_announce_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6); + break; #if CONFIG_ETH_ENABLED - case IP_EVENT_ETH_GOT_IP: - post_mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); - break; + case IP_EVENT_ETH_GOT_IP: + post_mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4); + 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 = _mdns_get_if_from_esp_netif(event->esp_netif); - if (mdns_if < MDNS_MAX_INTERFACES) { - post_mdns_enable_pcb(mdns_if, MDNS_IP_PROTOCOL_V6); - post_mdns_announce_pcb(mdns_if, MDNS_IP_PROTOCOL_V4); - } - + case IP_EVENT_GOT_IP6: { + ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data; + mdns_if_t mdns_if = _mdns_get_if_from_esp_netif(event->esp_netif); + if (mdns_if < MDNS_MAX_INTERFACES) { + post_mdns_enable_pcb(mdns_if, MDNS_IP_PROTOCOL_V6); + post_mdns_announce_pcb(mdns_if, MDNS_IP_PROTOCOL_V4); } - break; - default: - break; + + } + break; + default: + break; } } } @@ -3979,7 +3978,7 @@ void mdns_preset_if_handle_system_event(void *arg, esp_event_base_t event_base, /** * @brief Free search structure (except the results) */ -static void _mdns_search_free(mdns_search_once_t * search) +static void _mdns_search_free(mdns_search_once_t *search) { free(search->instance); free(search->service); @@ -3992,9 +3991,9 @@ static void _mdns_search_free(mdns_search_once_t * search) * @brief Allocate new search structure */ static mdns_search_once_t *_mdns_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) + uint32_t timeout, uint8_t max_results, mdns_query_notify_t notifier) { - mdns_search_once_t * search = (mdns_search_once_t *)malloc(sizeof(mdns_search_once_t)); + mdns_search_once_t *search = (mdns_search_once_t *)malloc(sizeof(mdns_search_once_t)); if (!search) { HOOK_MALLOC_FAILED; return NULL; @@ -4008,7 +4007,7 @@ static mdns_search_once_t *_mdns_search_init(const char *name, const char *servi } if (!_str_null_or_empty(name)) { - search->instance = strndup(name, MDNS_NAME_BUF_LEN-1); + search->instance = strndup(name, MDNS_NAME_BUF_LEN - 1); if (!search->instance) { _mdns_search_free(search); return NULL; @@ -4016,7 +4015,7 @@ static mdns_search_once_t *_mdns_search_init(const char *name, const char *servi } if (!_str_null_or_empty(service)) { - search->service = strndup(service, MDNS_NAME_BUF_LEN-1); + search->service = strndup(service, MDNS_NAME_BUF_LEN - 1); if (!search->service) { _mdns_search_free(search); return NULL; @@ -4024,7 +4023,7 @@ static mdns_search_once_t *_mdns_search_init(const char *name, const char *servi } if (!_str_null_or_empty(proto)) { - search->proto = strndup(proto, MDNS_NAME_BUF_LEN-1); + search->proto = strndup(proto, MDNS_NAME_BUF_LEN - 1); if (!search->proto) { _mdns_search_free(search); return NULL; @@ -4049,7 +4048,7 @@ static mdns_search_once_t *_mdns_search_init(const char *name, const char *servi /** * @brief Mark search as finished and remove it from search chain */ -static void _mdns_search_finish(mdns_search_once_t * search) +static void _mdns_search_finish(mdns_search_once_t *search) { search->state = SEARCH_OFF; queueDetach(mdns_search_once_t, _mdns_server->search_once, search); @@ -4062,7 +4061,7 @@ static void _mdns_search_finish(mdns_search_once_t * search) /** * @brief Add new search to the search chain */ -static void _mdns_search_add(mdns_search_once_t * search) +static void _mdns_search_add(mdns_search_once_t *search) { search->next = _mdns_server->search_once; _mdns_server->search_once = search; @@ -4073,8 +4072,8 @@ static void _mdns_search_add(mdns_search_once_t * search) */ static void _mdns_search_finish_done(void) { - mdns_search_once_t * search = _mdns_server->search_once; - mdns_search_once_t * s = NULL; + mdns_search_once_t *search = _mdns_server->search_once; + mdns_search_once_t *s = NULL; while (search) { s = search; search = search->next; @@ -4087,14 +4086,14 @@ static void _mdns_search_finish_done(void) /** * @brief Create linked IP (copy) from parsed one */ -static mdns_ip_addr_t * _mdns_result_addr_create_ip(esp_ip_addr_t * ip) +static mdns_ip_addr_t *_mdns_result_addr_create_ip(esp_ip_addr_t *ip) { - mdns_ip_addr_t * a = (mdns_ip_addr_t *)malloc(sizeof(mdns_ip_addr_t)); + mdns_ip_addr_t *a = (mdns_ip_addr_t *)malloc(sizeof(mdns_ip_addr_t)); if (!a) { HOOK_MALLOC_FAILED; return NULL; } - memset(a, 0 , sizeof(mdns_ip_addr_t)); + 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); @@ -4104,7 +4103,7 @@ static mdns_ip_addr_t * _mdns_result_addr_create_ip(esp_ip_addr_t * ip) return a; } -static inline void _mdns_result_update_ttl(mdns_result_t * r, uint32_t ttl) +static inline void _mdns_result_update_ttl(mdns_result_t *r, uint32_t ttl) { r->ttl = r->ttl < ttl ? r->ttl : ttl; } @@ -4112,9 +4111,9 @@ static inline void _mdns_result_update_ttl(mdns_result_t * r, uint32_t ttl) /** * @brief Chain new IP to search result */ -static void _mdns_result_add_ip(mdns_result_t * r, esp_ip_addr_t * ip) +static void _mdns_result_add_ip(mdns_result_t *r, esp_ip_addr_t *ip) { - mdns_ip_addr_t * a = r->addr; + mdns_ip_addr_t *a = r->addr; while (a) { if (a->addr.type == ip->type) { if (a->addr.type == ESP_IPADDR_TYPE_V4 && a->addr.u_addr.ip4.addr == ip->u_addr.ip4.addr) { @@ -4137,15 +4136,15 @@ static void _mdns_result_add_ip(mdns_result_t * r, esp_ip_addr_t * ip) /** * @brief Called from parser to add A/AAAA data to search result */ -static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * hostname, esp_ip_addr_t * ip, +static void _mdns_search_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; + 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) { + || (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_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol) { @@ -4162,7 +4161,7 @@ static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * return; } - memset(r, 0 , sizeof(mdns_result_t)); + memset(r, 0, sizeof(mdns_result_t)); a = _mdns_result_addr_create_ip(ip); if (!a) { @@ -4195,11 +4194,11 @@ static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * /** * @brief Called from parser to add PTR data to search result */ -static mdns_result_t * _mdns_search_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) +static mdns_result_t *_mdns_search_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; + mdns_result_t *r = search->result; while (r) { if (r->esp_netif == _mdns_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->instance_name) && !strcasecmp(instance, r->instance_name)) { _mdns_result_update_ttl(r, ttl); @@ -4214,7 +4213,7 @@ static mdns_result_t * _mdns_search_result_add_ptr(mdns_search_once_t * search, return NULL; } - memset(r, 0 , sizeof(mdns_result_t)); + memset(r, 0, sizeof(mdns_result_t)); r->instance_name = strdup(instance); r->service_type = strdup(service_type); r->proto = strdup(proto); @@ -4240,7 +4239,7 @@ static mdns_result_t * _mdns_search_result_add_ptr(mdns_search_once_t * search, static void _mdns_search_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; + mdns_result_t *r = search->result; while (r) { if (r->esp_netif == _mdns_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->hostname) && !strcasecmp(hostname, r->hostname)) { _mdns_result_update_ttl(r, ttl); @@ -4255,7 +4254,7 @@ static void _mdns_search_result_add_srv(mdns_search_once_t *search, const char * return; } - memset(r, 0 , sizeof(mdns_result_t)); + memset(r, 0, sizeof(mdns_result_t)); r->hostname = strdup(hostname); if (!r->hostname) { free(r); @@ -4283,7 +4282,7 @@ static void _mdns_search_result_add_txt(mdns_search_once_t *search, mdns_txt_ite size_t txt_count, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint32_t ttl) { - mdns_result_t * r = search->result; + mdns_result_t *r = search->result; while (r) { if (r->esp_netif == _mdns_get_esp_netif(tcpip_if) && r->ip_protocol == ip_protocol) { if (r->txt) { @@ -4304,7 +4303,7 @@ static void _mdns_search_result_add_txt(mdns_search_once_t *search, mdns_txt_ite goto free_txt; } - memset(r, 0 , sizeof(mdns_result_t)); + memset(r, 0, sizeof(mdns_result_t)); r->txt = txt; r->txt_value_len = txt_value_len; r->txt_count = txt_count; @@ -4318,7 +4317,7 @@ static void _mdns_search_result_add_txt(mdns_search_once_t *search, mdns_txt_ite return; free_txt: - for (size_t i=0; istate == SEARCH_OFF) { s = s->next; @@ -4339,8 +4338,7 @@ static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * s, mdns_ 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->type != MDNS_TYPE_ANY && s->type != type && s->type != MDNS_TYPE_PTR && s->type != MDNS_TYPE_SRV)) { s = s->next; continue; } @@ -4364,14 +4362,12 @@ static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * s, mdns_ 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->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)) - { + || strcasecmp(name->proto, s->proto)) { s = s->next; continue; } @@ -4398,15 +4394,15 @@ static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * s, mdns_ /** * @brief Create search packet for particular interface */ -static mdns_tx_packet_t * _mdns_create_search_packet(mdns_search_once_t * search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +static mdns_tx_packet_t *_mdns_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_alloc_packet_default(tcpip_if, ip_protocol); + mdns_result_t *r = NULL; + mdns_tx_packet_t *packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol); if (!packet) { return NULL; } - mdns_out_question_t * q = (mdns_out_question_t *)malloc(sizeof(mdns_out_question_t)); + mdns_out_question_t *q = (mdns_out_question_t *)malloc(sizeof(mdns_out_question_t)); if (!q) { HOOK_MALLOC_FAILED; _mdns_free_tx_packet(packet); @@ -4430,7 +4426,7 @@ static mdns_tx_packet_t * _mdns_create_search_packet(mdns_search_once_t * search r = r->next; continue; } - mdns_out_answer_t * a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t)); + mdns_out_answer_t *a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t)); if (!a) { HOOK_MALLOC_FAILED; _mdns_free_tx_packet(packet); @@ -4455,9 +4451,9 @@ static mdns_tx_packet_t * _mdns_create_search_packet(mdns_search_once_t * search /** * @brief Send search packet to particular interface */ -static void _mdns_search_send_pcb(mdns_search_once_t * search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +static void _mdns_search_send_pcb(mdns_search_once_t *search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { - mdns_tx_packet_t * packet = NULL; + mdns_tx_packet_t *packet = NULL; if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state > PCB_INIT) { packet = _mdns_create_search_packet(search, tcpip_if, ip_protocol); if (!packet) { @@ -4471,9 +4467,9 @@ static void _mdns_search_send_pcb(mdns_search_once_t * search, mdns_if_t tcpip_i /** * @brief Send search packet to all available interfaces */ -static void _mdns_search_send(mdns_search_once_t * search) +static void _mdns_search_send(mdns_search_once_t *search) { - mdns_search_once_t* queue = _mdns_server->search_once; + mdns_search_once_t *queue = _mdns_server->search_once; bool found = false; // looking for this search in active searches while (queue) { @@ -4490,18 +4486,18 @@ static void _mdns_search_send(mdns_search_once_t * search) } uint8_t i, j; - for (i=0; iinterfaces[p->tcpip_if].pcbs[p->ip_protocol]; + mdns_tx_packet_t *a = NULL; + mdns_out_question_t *q = NULL; + mdns_pcb_t *pcb = &_mdns_server->interfaces[p->tcpip_if].pcbs[p->ip_protocol]; uint32_t send_after = 1000; if (pcb->state == PCB_OFF) { @@ -4510,14 +4506,14 @@ static void _mdns_tx_handle_packet(mdns_tx_packet_t * p) } _mdns_dispatch_tx_packet(p); - switch(pcb->state) { + switch (pcb->state) { case PCB_PROBE_1: q = p->questions; while (q) { q->unicast = false; q = q->next; } - //fallthrough + //fallthrough case PCB_PROBE_2: _mdns_schedule_tx_packet(p, 250); pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1); @@ -4537,9 +4533,9 @@ static void _mdns_tx_handle_packet(mdns_tx_packet_t * p) _mdns_free_tx_packet(p); p = a; send_after = 250; - //fallthrough + //fallthrough case PCB_ANNOUNCE_1: - //fallthrough + //fallthrough case PCB_ANNOUNCE_2: _mdns_schedule_tx_packet(p, send_after); pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1); @@ -4554,13 +4550,13 @@ static void _mdns_tx_handle_packet(mdns_tx_packet_t * p) } } -static void _mdns_remap_self_service_hostname(const char * old_hostname, const char * new_hostname) +static void _mdns_remap_self_service_hostname(const char *old_hostname, const char *new_hostname) { - mdns_srv_item_t * service = _mdns_server->services; + mdns_srv_item_t *service = _mdns_server->services; while (service) { if (service->service->hostname && - strcmp(service->service->hostname, old_hostname) == 0) { + strcmp(service->service->hostname, old_hostname) == 0) { free((char *)service->service->hostname); service->service->hostname = strdup(new_hostname); } @@ -4571,9 +4567,9 @@ static void _mdns_remap_self_service_hostname(const char * old_hostname, const c /** * @brief Free action data */ -static void _mdns_free_action(mdns_action_t * action) +static void _mdns_free_action(mdns_action_t *action) { - switch(action->type) { + switch (action->type) { case ACTION_HOSTNAME_SET: free(action->data.hostname_set.hostname); break; @@ -4601,9 +4597,9 @@ static void _mdns_free_action(mdns_action_t * action) free(action->data.srv_subtype_add.subtype); break; case ACTION_SEARCH_ADD: - //fallthrough + //fallthrough case ACTION_SEARCH_SEND: - //fallthrough + //fallthrough case ACTION_SEARCH_END: _mdns_search_free(action->data.search_add.search); break; @@ -4629,24 +4625,24 @@ static void _mdns_free_action(mdns_action_t * action) /** * @brief Called from service thread to execute given action */ -static void _mdns_execute_action(mdns_action_t * action) +static void _mdns_execute_action(mdns_action_t *action) { - mdns_srv_item_t * a = NULL; - mdns_service_t * service; - char * key; - char * value; + mdns_srv_item_t *a = NULL; + mdns_service_t *service; + char *key; + char *value; char *subtype; mdns_subtype_t *subtype_item; - mdns_txt_linked_item_t * txt, * t; + mdns_txt_linked_item_t *txt, * t; - switch(action->type) { + switch (action->type) { case ACTION_SYSTEM_EVENT: perform_event_action(action->data.sys_event.interface, action->data.sys_event.event_action); break; case ACTION_HOSTNAME_SET: _mdns_send_bye_all_pcbs_no_instance(true); _mdns_remap_self_service_hostname(_mdns_server->hostname, action->data.hostname_set.hostname); - free((char*)_mdns_server->hostname); + free((char *)_mdns_server->hostname); _mdns_server->hostname = action->data.hostname_set.hostname; _mdns_self_host.hostname = action->data.hostname_set.hostname; _mdns_restart_all_pcbs(); @@ -4654,7 +4650,7 @@ static void _mdns_execute_action(mdns_action_t * action) break; case ACTION_INSTANCE_SET: _mdns_send_bye_all_pcbs_no_instance(false); - free((char*)_mdns_server->instance); + free((char *)_mdns_server->instance); _mdns_server->instance = action->data.instance; _mdns_restart_all_pcbs_no_instance(); @@ -4667,7 +4663,7 @@ static void _mdns_execute_action(mdns_action_t * action) case ACTION_SERVICE_INSTANCE_SET: if (action->data.srv_instance.service->service->instance) { _mdns_send_bye(&action->data.srv_instance.service, 1, false); - free((char*)action->data.srv_instance.service->service->instance); + free((char *)action->data.srv_instance.service->service->instance); } action->data.srv_instance.service->service->instance = action->data.srv_instance.instance; _mdns_probe_all_pcbs(&action->data.srv_instance.service, 1, false, false); @@ -4777,7 +4773,7 @@ static void _mdns_execute_action(mdns_action_t * action) a = a->next; } if (a->next == action->data.srv_del.service) { - mdns_srv_item_t * b = a->next; + mdns_srv_item_t *b = a->next; a->next = a->next->next; _mdns_send_bye(&b, 1, false); _mdns_remove_scheduled_service_packets(b->service); @@ -4793,7 +4789,7 @@ static void _mdns_execute_action(mdns_action_t * action) a = _mdns_server->services; _mdns_server->services = NULL; while (a) { - mdns_srv_item_t * s = a; + mdns_srv_item_t *s = a; a = a->next; _mdns_remove_scheduled_service_packets(s->service); _mdns_free_service(s->service); @@ -4810,26 +4806,25 @@ static void _mdns_execute_action(mdns_action_t * action) case ACTION_SEARCH_END: _mdns_search_finish(action->data.search_add.search); break; - case ACTION_TX_HANDLE: - { - mdns_tx_packet_t * p = _mdns_server->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==action->data.tx_handle.packet && p->queued) { - p->queued = false; // clearing, as the packet might be reused (pushed and transmitted again) - _mdns_server->tx_queue_head = p->next; - _mdns_tx_handle_packet(p); - } else { - ESP_LOGD(TAG, "Skipping transmit of an unexpected packet!"); - } + case ACTION_TX_HANDLE: { + mdns_tx_packet_t *p = _mdns_server->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 == action->data.tx_handle.packet && p->queued) { + p->queued = false; // clearing, as the packet might be reused (pushed and transmitted again) + _mdns_server->tx_queue_head = p->next; + _mdns_tx_handle_packet(p); + } else { + ESP_LOGD(TAG, "Skipping transmit of an unexpected packet!"); } - break; + } + break; case ACTION_RX_HANDLE: mdns_parse_packet(action->data.rx_handle.packet); _mdns_packet_free(action->data.rx_handle.packet); break; case ACTION_DELEGATE_HOSTNAME_ADD: if (!_mdns_delegate_hostname_add(action->data.delegate_hostname.hostname, - action->data.delegate_hostname.address_list)) { + action->data.delegate_hostname.address_list)) { free((char *)action->data.delegate_hostname.hostname); free_address_list(action->data.delegate_hostname.address_list); } @@ -4847,9 +4842,9 @@ static void _mdns_execute_action(mdns_action_t * action) /** * @brief Queue search action */ -static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_once_t * search) +static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_once_t *search) { - mdns_action_t * action = NULL; + mdns_action_t *action = NULL; action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { @@ -4876,8 +4871,8 @@ static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_o static void _mdns_scheduler_run(void) { MDNS_SERVICE_LOCK(); - mdns_tx_packet_t * p = _mdns_server->tx_queue_head; - mdns_action_t * action = NULL; + mdns_tx_packet_t *p = _mdns_server->tx_queue_head; + mdns_action_t *action = NULL; // find first unqueued packet while (p && p->queued) { @@ -4911,7 +4906,7 @@ static void _mdns_scheduler_run(void) static void _mdns_search_run(void) { MDNS_SERVICE_LOCK(); - mdns_search_once_t * s = _mdns_server->search_once; + mdns_search_once_t *s = _mdns_server->search_once; uint32_t now = xTaskGetTickCount() * portTICK_PERIOD_MS; if (!s) { MDNS_SERVICE_UNLOCK(); @@ -4942,7 +4937,7 @@ static void _mdns_search_run(void) */ static void _mdns_service_task(void *pvParameters) { - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; for (;;) { if (_mdns_server && _mdns_server->action_queue) { if (xQueueReceive(_mdns_server->action_queue, &a, portMAX_DELAY) == pdTRUE) { @@ -4961,13 +4956,14 @@ static void _mdns_service_task(void *pvParameters) vTaskDelete(NULL); } -static void _mdns_timer_cb(void * arg) +static void _mdns_timer_cb(void *arg) { _mdns_scheduler_run(); _mdns_search_run(); } -static esp_err_t _mdns_start_timer(void){ +static esp_err_t _mdns_start_timer(void) +{ esp_timer_create_args_t timer_conf = { .callback = _mdns_timer_cb, .arg = NULL, @@ -4981,7 +4977,8 @@ static esp_err_t _mdns_start_timer(void){ return esp_timer_start_periodic(_mdns_server->timer_handle, MDNS_TIMER_PERIOD_US); } -static esp_err_t _mdns_stop_timer(void){ +static esp_err_t _mdns_stop_timer(void) +{ esp_err_t err = ESP_OK; if (_mdns_server->timer_handle) { err = esp_timer_stop(_mdns_server->timer_handle); @@ -5015,7 +5012,7 @@ static esp_err_t _mdns_service_task_start(void) } if (!_mdns_service_task_handle) { xTaskCreatePinnedToCore(_mdns_service_task, "mdns", MDNS_SERVICE_STACK_DEPTH, NULL, MDNS_TASK_PRIORITY, - (TaskHandle_t * const)(&_mdns_service_task_handle), MDNS_TASK_AFFINITY); + (TaskHandle_t *const)(&_mdns_service_task_handle), MDNS_TASK_AFFINITY); if (!_mdns_service_task_handle) { _mdns_stop_timer(); MDNS_SERVICE_UNLOCK(); @@ -5039,7 +5036,7 @@ static esp_err_t _mdns_service_task_stop(void) _mdns_stop_timer(); if (_mdns_service_task_handle) { mdns_action_t action; - mdns_action_t * a = &action; + mdns_action_t *a = &action; action.type = ACTION_TASK_STOP; if (xQueueSend(_mdns_server->action_queue, &a, (TickType_t)0) != pdPASS) { vTaskDelete(_mdns_service_task_handle); @@ -5060,7 +5057,7 @@ static esp_err_t mdns_post_custom_action_tcpip_if(mdns_if_t mdns_if, mdns_event_ return ESP_ERR_INVALID_STATE; } - mdns_action_t * action = (mdns_action_t *)calloc(1, sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)calloc(1, sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5079,7 +5076,7 @@ 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; ihostname); - free((char*)_mdns_server->instance); + free((char *)_mdns_server->hostname); + free((char *)_mdns_server->instance); if (_mdns_server->action_queue) { - mdns_action_t * c; + mdns_action_t *c; while (xQueueReceive(_mdns_server->action_queue, &c, 0) == pdTRUE) { _mdns_free_action(c); } @@ -5285,7 +5282,7 @@ void mdns_free(void) } _mdns_clear_tx_queue_head(); while (_mdns_server->search_once) { - mdns_search_once_t * h = _mdns_server->search_once; + mdns_search_once_t *h = _mdns_server->search_once; _mdns_server->search_once = h->next; free(h->instance); free(h->service); @@ -5301,7 +5298,7 @@ void mdns_free(void) _mdns_server = NULL; } -esp_err_t mdns_hostname_set(const char * hostname) +esp_err_t mdns_hostname_set(const char *hostname) { if (!_mdns_server) { return ESP_ERR_INVALID_ARG; @@ -5309,12 +5306,12 @@ esp_err_t mdns_hostname_set(const char * hostname) if (_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { return ESP_ERR_INVALID_ARG; } - char * new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); + char *new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); if (!new_hostname) { return ESP_ERR_NO_MEM; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; free(new_hostname); @@ -5332,7 +5329,7 @@ esp_err_t mdns_hostname_set(const char * hostname) return ESP_OK; } -esp_err_t mdns_delegate_hostname_add(const char * hostname, const mdns_ip_addr_t * address_list) +esp_err_t mdns_delegate_hostname_add(const char *hostname, const mdns_ip_addr_t *address_list) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5340,12 +5337,12 @@ esp_err_t mdns_delegate_hostname_add(const char * hostname, const mdns_ip_addr_t if (_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1) || address_list == NULL) { return ESP_ERR_INVALID_ARG; } - char * new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); + char *new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); if (!new_hostname) { return ESP_ERR_NO_MEM; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; free(new_hostname); @@ -5362,7 +5359,7 @@ esp_err_t mdns_delegate_hostname_add(const char * hostname, const mdns_ip_addr_t return ESP_OK; } -esp_err_t mdns_delegate_hostname_remove(const char * hostname) +esp_err_t mdns_delegate_hostname_remove(const char *hostname) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5370,12 +5367,12 @@ esp_err_t mdns_delegate_hostname_remove(const char * hostname) if (_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) { return ESP_ERR_INVALID_ARG; } - char * new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); + char *new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1); if (!new_hostname) { return ESP_ERR_NO_MEM; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; free(new_hostname); @@ -5391,12 +5388,12 @@ esp_err_t mdns_delegate_hostname_remove(const char * hostname) return ESP_OK; } -bool mdns_hostname_exists(const char * hostname) +bool mdns_hostname_exists(const char *hostname) { return _hostname_is_ours(hostname); } -esp_err_t mdns_instance_name_set(const char * instance) +esp_err_t mdns_instance_name_set(const char *instance) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5404,12 +5401,12 @@ esp_err_t mdns_instance_name_set(const char * instance) if (_str_null_or_empty(instance) || strlen(instance) > (MDNS_NAME_BUF_LEN - 1)) { return ESP_ERR_INVALID_ARG; } - char * new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1); + char *new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1); if (!new_instance) { return ESP_ERR_NO_MEM; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; free(new_instance); @@ -5429,7 +5426,7 @@ esp_err_t mdns_instance_name_set(const char * instance) * MDNS SERVICES * */ -esp_err_t mdns_service_add_for_host(const char * instance, const char * service, const char * proto, const char * hostname, +esp_err_t mdns_service_add_for_host(const char *instance, const char *service, const char *proto, const char *hostname, uint16_t port, mdns_txt_item_t txt[], size_t num_items) { if (!_mdns_server || _str_null_or_empty(service) || _str_null_or_empty(proto) || !port || !hostname) { @@ -5440,12 +5437,12 @@ esp_err_t mdns_service_add_for_host(const char * instance, const char * service, return ESP_ERR_NO_MEM; } - mdns_srv_item_t * item = _mdns_get_service_item_instance(instance, service, proto, hostname); + mdns_srv_item_t *item = _mdns_get_service_item_instance(instance, service, proto, hostname); if (item) { return ESP_ERR_INVALID_ARG; } - mdns_service_t * s = _mdns_create_service(service, proto, hostname, port, instance, num_items, txt); + mdns_service_t *s = _mdns_create_service(service, proto, hostname, port, instance, num_items, txt); if (!s) { return ESP_ERR_NO_MEM; } @@ -5460,7 +5457,7 @@ esp_err_t mdns_service_add_for_host(const char * instance, const char * service, item->service = s; item->next = NULL; - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; _mdns_free_service(s); @@ -5489,7 +5486,7 @@ esp_err_t mdns_service_add_for_host(const char * instance, const char * service, return ESP_OK; } -esp_err_t mdns_service_add(const char * instance, const char * service, const char * proto, uint16_t port, +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 (!_mdns_server) { @@ -5498,7 +5495,7 @@ esp_err_t mdns_service_add(const char * instance, const char * service, const ch return mdns_service_add_for_host(instance, service, proto, _mdns_server->hostname, port, txt, num_items); } -bool mdns_service_exists(const char * service_type, const char * proto, const char * hostname) +bool mdns_service_exists(const char *service_type, const char *proto, const char *hostname) { return _mdns_get_service_item(service_type, proto, hostname) != NULL; } @@ -5509,17 +5506,17 @@ bool mdns_service_exists_with_instance(const char *instance, const char *service return _mdns_get_service_item_instance(instance, service_type, proto, hostname) != NULL; } -esp_err_t mdns_service_port_set_for_host(const char *instance, const char * service, const char * proto, const char * hostname, uint16_t port) +esp_err_t mdns_service_port_set_for_host(const char *instance, const char *service, const char *proto, const char *hostname, uint16_t port) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || !port) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5534,7 +5531,7 @@ esp_err_t mdns_service_port_set_for_host(const char *instance, const char * serv return ESP_OK; } -esp_err_t mdns_service_port_set(const char * service, const char * proto, uint16_t port) +esp_err_t mdns_service_port_set(const char *service, const char *proto, uint16_t port) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5542,26 +5539,26 @@ esp_err_t mdns_service_port_set(const char * service, const char * proto, uint16 return mdns_service_port_set_for_host(NULL, service, proto, _mdns_server->hostname, port); } -esp_err_t mdns_service_txt_set_for_host(const char * instance, const char * service, const char * proto, const char * hostname, +esp_err_t mdns_service_txt_set_for_host(const char *instance, const char *service, const char *proto, const char *hostname, mdns_txt_item_t txt[], uint8_t num_items) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || (num_items && txt == NULL)) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - mdns_txt_linked_item_t * new_txt = NULL; - if (num_items){ + mdns_txt_linked_item_t *new_txt = NULL; + if (num_items) { new_txt = _mdns_allocate_txt(num_items, txt); if (!new_txt) { return ESP_ERR_NO_MEM; } } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; _mdns_free_linked_txt(new_txt); @@ -5579,7 +5576,7 @@ esp_err_t mdns_service_txt_set_for_host(const char * instance, const char * serv return ESP_OK; } -esp_err_t mdns_service_txt_set(const char * service, const char * proto, mdns_txt_item_t txt[], uint8_t num_items) +esp_err_t mdns_service_txt_set(const char *service, const char *proto, mdns_txt_item_t txt[], uint8_t num_items) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5587,12 +5584,12 @@ esp_err_t mdns_service_txt_set(const char * service, const char * proto, mdns_tx return mdns_service_txt_set_for_host(NULL, service, proto, _mdns_server->hostname, 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 *hostname, const char *key, - const char *value, uint8_t value_len) +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 *hostname, const char *key, + const char *value, uint8_t value_len) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || - _str_null_or_empty(key) || (!value && value_len)) { + _str_null_or_empty(key) || (!value && value_len)) { return ESP_ERR_INVALID_ARG; } mdns_srv_item_t *s = _mdns_get_service_item_instance(instance, service, proto, hostname); @@ -5634,11 +5631,11 @@ esp_err_t mdns_service_txt_item_set_for_host_with_explicit_value_len(const char return ESP_OK; } -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) +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)); + strlen(value)); } @@ -5648,30 +5645,30 @@ esp_err_t mdns_service_txt_item_set(const char *service, const char *proto, cons return ESP_ERR_INVALID_STATE; } return mdns_service_txt_item_set_for_host_with_explicit_value_len(NULL, service, proto, _mdns_server->hostname, key, - value, strlen(value)); + 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) + const char *value, uint8_t value_len) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; } return mdns_service_txt_item_set_for_host_with_explicit_value_len(NULL, service, proto, _mdns_server->hostname, key, - value, value_len); + value, value_len); } -esp_err_t mdns_service_txt_item_remove_for_host(const char * instance, const char * service, const char * proto, const char * hostname, - const char * key) +esp_err_t mdns_service_txt_item_remove_for_host(const char *instance, const char *service, const char *proto, const char *hostname, + const char *key) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || _str_null_or_empty(key)) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5692,7 +5689,7 @@ esp_err_t mdns_service_txt_item_remove_for_host(const char * instance, const cha return ESP_OK; } -esp_err_t mdns_service_txt_item_remove(const char * service, const char * proto, const char * key) +esp_err_t mdns_service_txt_item_remove(const char *service, const char *proto, const char *key) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5701,17 +5698,17 @@ esp_err_t mdns_service_txt_item_remove(const char * service, const char * proto, } esp_err_t mdns_service_subtype_add_for_host(const char *instance_name, const char *service, const char *proto, - const char *hostname, const char *subtype) + const char *hostname, const char *subtype) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || - _str_null_or_empty(subtype)) { + _str_null_or_empty(subtype)) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance_name, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance_name, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5733,8 +5730,8 @@ esp_err_t mdns_service_subtype_add_for_host(const char *instance_name, const cha return ESP_OK; } -esp_err_t mdns_service_instance_name_set_for_host(const char * instance_old, const char * service, const char * proto, const char * hostname, - const char * instance) +esp_err_t mdns_service_instance_name_set_for_host(const char *instance_old, const char *service, const char *proto, const char *hostname, + const char *instance) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto)) { return ESP_ERR_INVALID_ARG; @@ -5742,16 +5739,16 @@ esp_err_t mdns_service_instance_name_set_for_host(const char * instance_old, con if (_str_null_or_empty(instance) || strlen(instance) > (MDNS_NAME_BUF_LEN - 1)) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance_old, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance_old, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - char * new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1); + char *new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1); if (!new_instance) { return ESP_ERR_NO_MEM; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; free(new_instance); @@ -5768,7 +5765,7 @@ esp_err_t mdns_service_instance_name_set_for_host(const char * instance_old, con return ESP_OK; } -esp_err_t mdns_service_instance_name_set(const char * service, const char * proto, const char * instance) +esp_err_t mdns_service_instance_name_set(const char *service, const char *proto, const char *instance) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5776,17 +5773,17 @@ esp_err_t mdns_service_instance_name_set(const char * service, const char * prot return mdns_service_instance_name_set_for_host(NULL, service, proto, _mdns_server->hostname, instance); } -esp_err_t mdns_service_remove_for_host(const char * instance, const char * service, const char * proto, const char * hostname) +esp_err_t mdns_service_remove_for_host(const char *instance, const char *service, const char *proto, const char *hostname) { if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto)) { return ESP_ERR_INVALID_ARG; } - mdns_srv_item_t * s = _mdns_get_service_item_instance(instance, service, proto, hostname); + mdns_srv_item_t *s = _mdns_get_service_item_instance(instance, service, proto, hostname); if (!s) { return ESP_ERR_NOT_FOUND; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5800,7 +5797,7 @@ esp_err_t mdns_service_remove_for_host(const char * instance, const char * servi return ESP_OK; } -esp_err_t mdns_service_remove(const char * service_type, const char * proto) +esp_err_t mdns_service_remove(const char *service_type, const char *proto) { if (!_mdns_server) { return ESP_ERR_INVALID_STATE; @@ -5817,7 +5814,7 @@ esp_err_t mdns_service_remove_all(void) return ESP_OK; } - mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); + mdns_action_t *action = (mdns_action_t *)malloc(sizeof(mdns_action_t)); if (!action) { HOOK_MALLOC_FAILED; return ESP_ERR_NO_MEM; @@ -5834,10 +5831,10 @@ esp_err_t mdns_service_remove_all(void) * MDNS QUERY * */ -void mdns_query_results_free(mdns_result_t * results) +void mdns_query_results_free(mdns_result_t *results) { - mdns_result_t * r; - mdns_ip_addr_t * a; + mdns_result_t *r; + mdns_ip_addr_t *a; while (results) { r = results; @@ -5847,7 +5844,7 @@ void mdns_query_results_free(mdns_result_t * results) free((char *)(r->service_type)); free((char *)(r->proto)); - for (size_t i=0; itxt_count; i++) { + for (size_t i = 0; i < r->txt_count; i++) { free((char *)(r->txt[i].key)); free((char *)(r->txt[i].value)); } @@ -5865,7 +5862,7 @@ void mdns_query_results_free(mdns_result_t * results) } } -esp_err_t mdns_query_async_delete(mdns_search_once_t* search) +esp_err_t mdns_query_async_delete(mdns_search_once_t *search) { if (!search) { return ESP_ERR_INVALID_ARG; @@ -5881,7 +5878,7 @@ esp_err_t mdns_query_async_delete(mdns_search_once_t* search) 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) +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) { @@ -5896,7 +5893,7 @@ bool mdns_query_async_get_results(mdns_search_once_t* search, uint32_t timeout, } 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) + uint32_t timeout, size_t max_results, mdns_query_notify_t notifier) { mdns_search_once_t *search = NULL; @@ -5917,9 +5914,9 @@ mdns_search_once_t *mdns_query_async_new(const char *name, const char *service, 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) +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; + mdns_search_once_t *search = NULL; *results = NULL; @@ -5948,12 +5945,12 @@ esp_err_t mdns_query_generic(const char * name, const char * service, const char 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) +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) { return mdns_query_generic(name, service_type, proto, type, type != MDNS_TYPE_PTR, 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) +esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout, size_t max_results, mdns_result_t **results) { if (_str_null_or_empty(service) || _str_null_or_empty(proto)) { return ESP_ERR_INVALID_ARG; @@ -5962,7 +5959,7 @@ esp_err_t mdns_query_ptr(const char * service, const char * proto, uint32_t time 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) +esp_err_t mdns_query_srv(const char *instance, const char *service, const char *proto, uint32_t timeout, mdns_result_t **result) { if (_str_null_or_empty(instance) || _str_null_or_empty(service) || _str_null_or_empty(proto)) { return ESP_ERR_INVALID_ARG; @@ -5971,7 +5968,7 @@ esp_err_t mdns_query_srv(const char * instance, const char * service, const char 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) +esp_err_t mdns_query_txt(const char *instance, const char *service, const char *proto, uint32_t timeout, mdns_result_t **result) { if (_str_null_or_empty(instance) || _str_null_or_empty(service) || _str_null_or_empty(proto)) { return ESP_ERR_INVALID_ARG; @@ -5980,9 +5977,9 @@ esp_err_t mdns_query_txt(const char * instance, const char * service, const char return mdns_query(instance, service, proto, MDNS_TYPE_TXT, timeout, 1, result); } -esp_err_t mdns_query_a(const char * name, uint32_t timeout, esp_ip4_addr_t * addr) +esp_err_t mdns_query_a(const char *name, uint32_t timeout, esp_ip4_addr_t *addr) { - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; esp_err_t err; if (_str_null_or_empty(name)) { @@ -6003,7 +6000,7 @@ esp_err_t mdns_query_a(const char * name, uint32_t timeout, esp_ip4_addr_t * add return ESP_ERR_NOT_FOUND; } - mdns_ip_addr_t * a = result->addr; + 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; @@ -6018,9 +6015,9 @@ esp_err_t mdns_query_a(const char * name, uint32_t timeout, esp_ip4_addr_t * add } #if CONFIG_LWIP_IPV6 -esp_err_t mdns_query_aaaa(const char * name, uint32_t timeout, esp_ip6_addr_t * addr) +esp_err_t mdns_query_aaaa(const char *name, uint32_t timeout, esp_ip6_addr_t *addr) { - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; esp_err_t err; if (_str_null_or_empty(name)) { @@ -6041,7 +6038,7 @@ esp_err_t mdns_query_aaaa(const char * name, uint32_t timeout, esp_ip6_addr_t * return ESP_ERR_NOT_FOUND; } - mdns_ip_addr_t * a = result->addr; + 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); @@ -6058,13 +6055,13 @@ esp_err_t mdns_query_aaaa(const char * name, uint32_t timeout, esp_ip6_addr_t * #ifdef MDNS_ENABLE_DEBUG -void mdns_debug_packet(const uint8_t * data, size_t len) +void mdns_debug_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; + const uint8_t *content = data + MDNS_HEAD_LEN; uint32_t t = xTaskGetTickCount() * portTICK_PERIOD_MS; - mdns_name_t * name = &n; + mdns_name_t *name = &n; memset(name, 0, sizeof(mdns_name_t)); _mdns_dbg_printf("Packet[%u]: ", t); @@ -6077,10 +6074,10 @@ void mdns_debug_packet(const uint8_t * data, size_t len) header.additional = _mdns_read_u16(data, MDNS_HEAD_ADDITIONAL_OFFSET); _mdns_dbg_printf("%s", - (header.flags.value == MDNS_FLAGS_QR_AUTHORITATIVE)?"AUTHORITATIVE\n": - (header.flags.value == MDNS_FLAGS_DISTRIBUTED)?"DISTRIBUTED\n": - (header.flags.value == 0)?"\n":" " - ); + (header.flags.value == MDNS_FLAGS_QR_AUTHORITATIVE) ? "AUTHORITATIVE\n" : + (header.flags.value == MDNS_FLAGS_DISTRIBUTED) ? "DISTRIBUTED\n" : + (header.flags.value == 0) ? "\n" : " " + ); if (header.flags.value && header.flags.value != MDNS_FLAGS_QR_AUTHORITATIVE) { _mdns_dbg_printf("0x%04X\n", header.flags.value); } @@ -6109,21 +6106,21 @@ void mdns_debug_packet(const uint8_t * data, size_t len) _mdns_dbg_printf("*U* "); } if (type == MDNS_TYPE_PTR) { - _mdns_dbg_printf("%s.%s%s.%s.%s. PTR ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain); + _mdns_dbg_printf("%s.%s%s.%s.%s. PTR ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_SRV) { - _mdns_dbg_printf("%s.%s%s.%s.%s. SRV ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain); + _mdns_dbg_printf("%s.%s%s.%s.%s. SRV ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_TXT) { - _mdns_dbg_printf("%s.%s%s.%s.%s. TXT ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain); + _mdns_dbg_printf("%s.%s%s.%s.%s. TXT ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_A) { _mdns_dbg_printf("%s.%s. A ", name->host, name->domain); } else if (type == MDNS_TYPE_AAAA) { _mdns_dbg_printf("%s.%s. AAAA ", name->host, name->domain); } else if (type == MDNS_TYPE_NSEC) { - _mdns_dbg_printf("%s.%s%s.%s.%s. NSEC ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain); + _mdns_dbg_printf("%s.%s%s.%s.%s. NSEC ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_ANY) { - _mdns_dbg_printf("%s.%s%s.%s.%s. ANY ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain); + _mdns_dbg_printf("%s.%s%s.%s.%s. ANY ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain); } else { - _mdns_dbg_printf("%s.%s%s.%s.%s. %04X ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain, type); + _mdns_dbg_printf("%s.%s%s.%s.%s. %04X ", name->host, name->sub ? "_sub." : "", name->service, name->proto, name->domain, type); } if (mdns_class == 0x0001) { @@ -6150,7 +6147,7 @@ void mdns_debug_packet(const uint8_t * data, size_t len) uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET); uint32_t ttl = _mdns_read_u32(content, MDNS_TTL_OFFSET); uint16_t data_len = _mdns_read_u16(content, MDNS_LEN_OFFSET); - const uint8_t * data_ptr = content + MDNS_DATA_OFFSET; + const uint8_t *data_ptr = content + MDNS_DATA_OFFSET; bool flush = !!(mdns_class & 0x8000); mdns_class &= 0x7FFF; @@ -6178,7 +6175,7 @@ void mdns_debug_packet(const uint8_t * data, size_t len) } if (type == MDNS_TYPE_PTR) { - _mdns_dbg_printf(": %s%s%s.%s.%s. PTR ", name->host, name->host[0]?".":"", name->service, name->proto, name->domain); + _mdns_dbg_printf(": %s%s%s.%s.%s. PTR ", name->host, name->host[0] ? "." : "", name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_SRV) { _mdns_dbg_printf(": %s.%s.%s.%s. SRV ", name->host, name->service, name->proto, name->domain); } else if (type == MDNS_TYPE_TXT) { @@ -6223,21 +6220,21 @@ void mdns_debug_packet(const uint8_t * data, size_t len) uint16_t port = _mdns_read_u16(data_ptr, MDNS_SRV_PORT_OFFSET); _mdns_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; + uint16_t i = 0, y; while (i < data_len) { uint8_t partLen = data_ptr[i++]; - if ((i+partLen) > data_len) { + if ((i + partLen) > data_len) { _mdns_dbg_printf("ERROR: parse TXT\n"); break; } - char txt[partLen+1]; - for (y=0; yhost, name->service, name->proto, name->domain); size_t diff = new_ptr - old_ptr; @@ -6260,7 +6257,7 @@ void mdns_debug_packet(const uint8_t * data, size_t len) data_ptr = new_ptr; } size_t i; - for (i=0; iesp_netif), ip_protocol_str[r->ip_protocol]); @@ -26,7 +26,7 @@ static void mdns_print_results(mdns_result_t * results) } if (r->txt_count) { printf(" TXT : [%u] ", r->txt_count); - for (size_t t=0; ttxt_count; t++) { + for (size_t t = 0; t < r->txt_count; t++) { printf("%s=%s; ", r->txt[t].key, r->txt[t].value); } printf("\n"); @@ -50,15 +50,15 @@ static struct { struct arg_end *end; } mdns_query_a_args; -static int cmd_mdns_query_a(int argc, char** argv) +static int cmd_mdns_query_a(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_a_args); + 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]; + const char *hostname = mdns_query_a_args.hostname->sval[0]; int timeout = mdns_query_a_args.timeout->ival[0]; if (!hostname || !hostname[0]) { @@ -108,15 +108,15 @@ static void register_mdns_query_a(void) } #if CONFIG_LWIP_IPV6 -static int cmd_mdns_query_aaaa(int argc, char** argv) +static int cmd_mdns_query_aaaa(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_a_args); + 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]; + const char *hostname = mdns_query_a_args.hostname->sval[0]; int timeout = mdns_query_a_args.timeout->ival[0]; if (!hostname || !hostname[0]) { @@ -174,17 +174,17 @@ static struct { struct arg_end *end; } mdns_query_srv_args; -static int cmd_mdns_query_srv(int argc, char** argv) +static int cmd_mdns_query_srv(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_srv_args); + 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]; + 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) { @@ -193,7 +193,7 @@ static int cmd_mdns_query_srv(int argc, char** argv) printf("Query SRV: %s.%s.%s.local, Timeout: %d\n", instance, service, proto, timeout); - mdns_result_t * results = NULL; + mdns_result_t *results = NULL; esp_err_t err = mdns_query_srv(instance, service, proto, timeout, &results); if (err) { printf("ERROR: Query Failed\n"); @@ -235,17 +235,17 @@ static struct { struct arg_end *end; } mdns_query_txt_args; -static int cmd_mdns_query_txt(int argc, char** argv) +static int cmd_mdns_query_txt(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_txt_args); + 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]; + 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); @@ -254,7 +254,7 @@ static int cmd_mdns_query_txt(int argc, char** argv) timeout = 5000; } - mdns_result_t * results = NULL; + mdns_result_t *results = NULL; esp_err_t err = mdns_query_txt(instance, service, proto, timeout, &results); if (err) { printf("ERROR: Query Failed\n"); @@ -297,16 +297,16 @@ static struct { struct arg_end *end; } mdns_query_ptr_args; -static int cmd_mdns_query_ptr(int argc, char** argv) +static int cmd_mdns_query_ptr(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_ptr_args); + 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]; + 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]; @@ -320,7 +320,7 @@ static int cmd_mdns_query_ptr(int argc, char** argv) printf("Query PTR: %s.%s.local, Timeout: %d, Max Results: %d\n", service, proto, timeout, max_results); - mdns_result_t * results = NULL; + 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"); @@ -362,15 +362,15 @@ static struct { struct arg_end *end; } mdns_query_ip_args; -static int cmd_mdns_query_ip(int argc, char** argv) +static int cmd_mdns_query_ip(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_ip_args); + 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]; + 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]; @@ -389,7 +389,7 @@ static int cmd_mdns_query_ip(int argc, char** argv) printf("Query IP: %s.local, Timeout: %d, Max Results: %d\n", hostname, timeout, max_results); - mdns_result_t * results = NULL; + 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"); @@ -432,17 +432,17 @@ static struct { struct arg_end *end; } mdns_query_svc_args; -static int cmd_mdns_query_svc(int argc, char** argv) +static int cmd_mdns_query_svc(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_query_svc_args); + 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]; + 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]; @@ -456,7 +456,7 @@ static int cmd_mdns_query_svc(int argc, char** argv) printf("Query SVC: %s.%s.%s.local, Timeout: %d, Max Results: %d\n", instance, service, proto, timeout, max_results); - mdns_result_t * results = NULL; + 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"); @@ -498,9 +498,9 @@ static struct { struct arg_end *end; } mdns_init_args; -static int cmd_mdns_init(int argc, char** argv) +static int cmd_mdns_init(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_init_args); + 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; @@ -538,7 +538,7 @@ static void register_mdns_init(void) ESP_ERROR_CHECK( esp_console_cmd_register(&cmd_init) ); } -static int cmd_mdns_free(int argc, char** argv) +static int cmd_mdns_free(int argc, char **argv) { mdns_free(); return 0; @@ -562,9 +562,9 @@ static struct { struct arg_end *end; } mdns_set_hostname_args; -static int cmd_mdns_set_hostname(int argc, char** argv) +static int cmd_mdns_set_hostname(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_set_hostname_args); + 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; @@ -600,9 +600,9 @@ static struct { struct arg_end *end; } mdns_set_instance_args; -static int cmd_mdns_set_instance(int argc, char** argv) +static int cmd_mdns_set_instance(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_set_instance_args); + 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; @@ -633,11 +633,11 @@ static void register_mdns_set_instance(void) ESP_ERROR_CHECK( esp_console_cmd_register(&cmd_set_instance) ); } -static mdns_txt_item_t * _convert_items(const char **values, int count) +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*) malloc(sizeof(mdns_txt_item_t) * count); + int i = 0, e; + const char *value = NULL; + mdns_txt_item_t *items = (mdns_txt_item_t *) malloc(sizeof(mdns_txt_item_t) * count); if (!items) { printf("ERROR: No Memory!\n"); goto fail; @@ -645,21 +645,21 @@ static mdns_txt_item_t * _convert_items(const char **values, int count) } memset(items, 0, sizeof(mdns_txt_item_t) * count); - for (i=0; isval[0] && mdns_add_args.instance->sval[0][0]) { instance = mdns_add_args.instance->sval[0]; printf("MDNS: Service Instance: %s\n", instance); } - mdns_txt_item_t * items = NULL; + 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) { @@ -752,9 +752,9 @@ static struct { struct arg_end *end; } mdns_remove_args; -static int cmd_mdns_service_remove(int argc, char** argv) +static int cmd_mdns_service_remove(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_remove_args); + 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; @@ -793,9 +793,9 @@ static struct { struct arg_end *end; } mdns_service_instance_set_args; -static int cmd_mdns_service_instance_set(int argc, char** argv) +static int cmd_mdns_service_instance_set(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_service_instance_set_args); + 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; @@ -835,8 +835,9 @@ static struct { 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); +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; @@ -876,10 +877,10 @@ static struct { struct arg_end *end; } mdns_txt_replace_args; -static int cmd_mdns_service_txt_replace(int argc, char** argv) +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); + 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; @@ -929,9 +930,9 @@ static struct { struct arg_end *end; } mdns_txt_set_args; -static int cmd_mdns_service_txt_set(int argc, char** argv) +static int cmd_mdns_service_txt_set(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_txt_set_args); + 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; @@ -972,9 +973,9 @@ static struct { struct arg_end *end; } mdns_txt_remove_args; -static int cmd_mdns_service_txt_remove(int argc, char** argv) +static int cmd_mdns_service_txt_remove(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void**) &mdns_txt_remove_args); + 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; @@ -1007,7 +1008,7 @@ static void register_mdns_service_txt_remove(void) ESP_ERROR_CHECK( esp_console_cmd_register(&cmd_txt_remove) ); } -static int cmd_mdns_service_remove_all(int argc, char** argv) +static int cmd_mdns_service_remove_all(int argc, char **argv) { mdns_service_remove_all(); return 0; diff --git a/components/mdns/mdns_networking_lwip.c b/components/mdns/mdns_networking_lwip.c index dbbc11bb9..05ddb4621 100644 --- a/components/mdns/mdns_networking_lwip.c +++ b/components/mdns/mdns_networking_lwip.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ /* * MDNS Server Networking @@ -16,7 +21,7 @@ #include "mdns_networking.h" #include "esp_netif_net_stack.h" -extern mdns_server_t * _mdns_server; +extern mdns_server_t *_mdns_server; /* * MDNS Server Networking @@ -24,7 +29,7 @@ extern mdns_server_t * _mdns_server; */ static const char *TAG = "MDNS_Networking"; -static struct udp_pcb * _pcb_main = NULL; +static struct udp_pcb *_pcb_main = NULL; static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip_addr_t *raddr, uint16_t rport); @@ -33,7 +38,7 @@ static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip */ static esp_err_t _udp_pcb_main_init(void) { - if(_pcb_main) { + if (_pcb_main) { return ESP_OK; } _pcb_main = udp_new(); @@ -57,7 +62,7 @@ static esp_err_t _udp_pcb_main_init(void) */ static void _udp_pcb_main_deinit(void) { - if(_pcb_main){ + if (_pcb_main) { udp_recv(_pcb_main, NULL, NULL); udp_disconnect(_pcb_main); udp_remove(_pcb_main); @@ -70,7 +75,7 @@ static void _udp_pcb_main_deinit(void) */ static esp_err_t _udp_join_group(mdns_if_t if_inx, mdns_ip_protocol_t ip_protocol, bool join) { - struct netif * netif = NULL; + struct netif *netif = NULL; esp_netif_t *tcpip_if = _mdns_get_esp_netif(if_inx); if (!esp_netif_is_netif_up(tcpip_if)) { @@ -85,7 +90,7 @@ static esp_err_t _udp_join_group(mdns_if_t if_inx, mdns_ip_protocol_t ip_protoco ip4_addr_t multicast_addr; IP4_ADDR(&multicast_addr, 224, 0, 0, 251); - if(join){ + if (join) { if (igmp_joingroup_netif(netif, &multicast_addr)) { return ESP_ERR_INVALID_STATE; } @@ -99,7 +104,7 @@ static esp_err_t _udp_join_group(mdns_if_t if_inx, mdns_ip_protocol_t ip_protoco else { ip_addr_t multicast_addr = IPADDR6_INIT(0x000002ff, 0, 0, 0xfb000000); - if(join){ + if (join) { if (mld6_joingroup_netif(netif, &(multicast_addr.u_addr.ip6))) { return ESP_ERR_INVALID_STATE; } @@ -122,11 +127,11 @@ static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip uint8_t i; while (pb != NULL) { - struct pbuf * this_pb = pb; + struct pbuf *this_pb = pb; pb = pb->next; this_pb->next = NULL; - mdns_rx_packet_t * packet = (mdns_rx_packet_t *)malloc(sizeof(mdns_rx_packet_t)); + mdns_rx_packet_t *packet = (mdns_rx_packet_t *)malloc(sizeof(mdns_rx_packet_t)); if (!packet) { HOOK_MALLOC_FAILED; //missed packet - no memory @@ -148,23 +153,23 @@ static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip 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); + 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)); } #if CONFIG_LWIP_IPV6 else { packet->ip_protocol = MDNS_IP_PROTOCOL_V6; - struct ip6_hdr * ip6hdr = (struct ip6_hdr *)(((uint8_t *)(packet->pb->payload)) - UDP_HLEN - IP6_HLEN); + 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 does not return the proper pcb if you have more than one for the same multicast address (but different interfaces) - struct netif * netif = NULL; - struct udp_pcb * pcb = NULL; - for (i=0; iinterfaces[i].pcbs[packet->ip_protocol].pcb; netif = esp_netif_get_netif_impl(_mdns_get_esp_netif(i)); if (pcb && netif && netif == ip_current_input_netif ()) { @@ -185,7 +190,7 @@ static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip } if (!pcb || !_mdns_server || !_mdns_server->action_queue - || _mdns_send_rx_action(packet) != ESP_OK) { + || _mdns_send_rx_action(packet) != ESP_OK) { pbuf_free(this_pb); free(packet); } @@ -196,11 +201,12 @@ static void _udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *pb, const ip /** * @brief Check if any of the interfaces is up */ -static bool _udp_pcb_is_in_use(void){ +static bool _udp_pcb_is_in_use(void) +{ int i, p; - for (i=0; iinterfaces[i].pcbs[p].pcb){ + for (i = 0; i < MDNS_MAX_INTERFACES; i++) { + for (p = 0; p < MDNS_IP_PROTOCOL_MAX; p++) { + if (_mdns_server->interfaces[i].pcbs[p].pcb) { return true; } } @@ -216,7 +222,7 @@ static void _udp_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) if (!_mdns_server) { return; } - mdns_pcb_t * _pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; + mdns_pcb_t *_pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol]; if (_pcb->pcb) { free(_pcb->probe_services); _pcb->state = PCB_OFF; @@ -227,7 +233,7 @@ static void _udp_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) _pcb->probe_running = false; _pcb->failed_probes = 0; _udp_join_group(tcpip_if, ip_protocol, false); - if(!_udp_pcb_is_in_use()) { + if (!_udp_pcb_is_in_use()) { _udp_pcb_main_deinit(); } } @@ -243,12 +249,12 @@ static esp_err_t _udp_pcb_init(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protoco } esp_err_t err = _udp_join_group(tcpip_if, ip_protocol, true); - if(err){ + if (err) { return err; } err = _udp_pcb_main_init(); - if(err){ + if (err) { return err; } @@ -272,7 +278,7 @@ typedef struct { */ static err_t _mdns_pcb_init_api(struct tcpip_api_call_data *api_call_msg) { - mdns_api_call_t * msg = (mdns_api_call_t *)api_call_msg; + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; msg->err = _udp_pcb_init(msg->tcpip_if, msg->ip_protocol); return msg->err; } @@ -282,7 +288,7 @@ static err_t _mdns_pcb_init_api(struct tcpip_api_call_data *api_call_msg) */ static err_t _mdns_pcb_deinit_api(struct tcpip_api_call_data *api_call_msg) { - mdns_api_call_t * msg = (mdns_api_call_t *)api_call_msg; + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; _udp_pcb_deinit(msg->tcpip_if, msg->ip_protocol); msg->err = ESP_OK; return ESP_OK; @@ -315,9 +321,9 @@ esp_err_t _mdns_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) static err_t _mdns_udp_pcb_write_api(struct tcpip_api_call_data *api_call_msg) { - void * nif = NULL; - mdns_api_call_t * msg = (mdns_api_call_t *)api_call_msg; - mdns_pcb_t * _pcb = &_mdns_server->interfaces[msg->tcpip_if].pcbs[msg->ip_protocol]; + void *nif = NULL; + mdns_api_call_t *msg = (mdns_api_call_t *)api_call_msg; + mdns_pcb_t *_pcb = &_mdns_server->interfaces[msg->tcpip_if].pcbs[msg->ip_protocol]; nif = esp_netif_get_netif_impl(_mdns_get_esp_netif(msg->tcpip_if)); if (!nif) { pbuf_free(msg->pbt); @@ -330,9 +336,9 @@ static err_t _mdns_udp_pcb_write_api(struct tcpip_api_call_data *api_call_msg) return err; } -size_t _mdns_udp_pcb_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) +size_t _mdns_udp_pcb_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); + struct pbuf *pbt = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); if (pbt == NULL) { return 0; } @@ -361,7 +367,7 @@ size_t _mdns_udp_pcb_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, c return len; } -void* _mdns_get_packet_data(mdns_rx_packet_t *packet) +void *_mdns_get_packet_data(mdns_rx_packet_t *packet) { return packet->pb->payload; } diff --git a/components/mdns/mdns_networking_socket.c b/components/mdns/mdns_networking_socket.c index 0f393cbc0..66a38845b 100644 --- a/components/mdns/mdns_networking_socket.c +++ b/components/mdns/mdns_networking_socket.c @@ -27,7 +27,7 @@ #include #endif -extern mdns_server_t * _mdns_server; +extern mdns_server_t *_mdns_server; static const char *TAG = "MDNS_Networking"; static bool s_run_sock_recv_task = false; @@ -37,8 +37,8 @@ static int join_mdns_multicast_group(int sock, esp_netif_t *netif, mdns_ip_proto #if defined(CONFIG_IDF_TARGET_LINUX) // Need to define packet buffer struct on linux struct pbuf { - struct pbuf * next; - void * payload; + struct pbuf *next; + void *payload; size_t tot_len; size_t len; }; @@ -52,17 +52,17 @@ static void delete_socket(int sock) close(sock); } -static struct udp_pcb* sock_to_pcb(int sock) +static struct udp_pcb *sock_to_pcb(int sock) { if (sock < 0) { return NULL; } // Note: sock=0 is a valid descriptor, so save it as +1 ("1" is a valid pointer) intptr_t sock_plus_one = sock + 1; - return (struct udp_pcb*)sock_plus_one; + return (struct udp_pcb *)sock_plus_one; } -static int pcb_to_sock(struct udp_pcb* pcb) +static int pcb_to_sock(struct udp_pcb *pcb) { if (pcb == NULL) { return -1; @@ -71,7 +71,7 @@ static int pcb_to_sock(struct udp_pcb* pcb) return sock_plus_one - 1; } -void* _mdns_get_packet_data(mdns_rx_packet_t *packet) +void *_mdns_get_packet_data(mdns_rx_packet_t *packet) { return packet->pb->payload; } @@ -90,10 +90,10 @@ void _mdns_packet_free(mdns_rx_packet_t *packet) esp_err_t _mdns_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { - struct udp_pcb * pcb = _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb; + struct udp_pcb *pcb = _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb; _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb = NULL; if (_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].pcb == NULL && - _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].pcb == NULL) { + _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].pcb == NULL) { // if the interface for both protocol uninitialized, close the interface socket int sock = pcb_to_sock(pcb); if (sock >= 0) { @@ -101,11 +101,13 @@ esp_err_t _mdns_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) } } - for (int i=0; iinterfaces[i].pcbs[j].pcb) // If any of the interfaces/protocol initialized + { return ESP_OK; + } } } @@ -117,15 +119,15 @@ esp_err_t _mdns_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) #if defined(CONFIG_IDF_TARGET_LINUX) #ifdef CONFIG_LWIP_IPV6 -static char* inet6_ntoa_r(struct in6_addr addr, char* ptr, size_t size) +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) +static char *inet_ntoa_r(struct in_addr addr, char *ptr, size_t size) { - char * res = inet_ntoa(addr); + char *res = inet_ntoa(addr); if (res && strlen(res) < size) { strcpy(ptr, res); } @@ -133,7 +135,7 @@ static char* inet_ntoa_r(struct in_addr addr, char* ptr, size_t size) } #endif // CONFIG_IDF_TARGET_LINUX -static inline char* get_string_address(struct sockaddr_storage *source_addr) +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; @@ -175,7 +177,7 @@ static inline size_t espaddr_to_inet(const esp_ip_addr_t *addr, const uint16_t p 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; + 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]; @@ -187,7 +189,7 @@ static inline size_t espaddr_to_inet(const esp_ip_addr_t *addr, const uint16_t p return ss_addr_len; } -size_t _mdns_udp_pcb_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) +size_t _mdns_udp_pcb_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) { int sock = pcb_to_sock(_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb); if (sock < 0) { @@ -210,7 +212,7 @@ size_t _mdns_udp_pcb_write(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, c static inline void inet_to_espaddr(const struct sockaddr_storage *in_addr, esp_ip_addr_t *addr, uint16_t *port) { if (in_addr->ss_family == PF_INET) { - struct sockaddr_in * in_addr_ip4 = (struct sockaddr_in *)in_addr; + 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; @@ -218,7 +220,7 @@ static inline void inet_to_espaddr(const struct sockaddr_storage *in_addr, esp_i } #if CONFIG_LWIP_IPV6 else if (in_addr->ss_family == PF_INET6) { - struct sockaddr_in6 * in_addr_ip6 = (struct sockaddr_in6 *)in_addr; + 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; @@ -237,7 +239,7 @@ static inline void inet_to_espaddr(const struct sockaddr_storage *in_addr, esp_i #endif // CONFIG_LWIP_IPV6 } -void sock_recv_task(void* arg) +void sock_recv_task(void *arg) { while (s_run_sock_recv_task) { struct timeval tv = { @@ -247,8 +249,8 @@ void sock_recv_task(void* arg) fd_set rfds; FD_ZERO(&rfds); int max_sock = -1; - for (int i=0; iinterfaces[i].pcbs[j].pcb); if (sock >= 0) { FD_SET(sock, &rfds); @@ -267,7 +269,7 @@ void sock_recv_task(void* arg) ESP_LOGE(TAG, "Select failed. errno=%d: %s", errno, strerror(errno)); break; } else if (s > 0) { - for (int tcpip_if=0; tcpip_ifinterfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].pcb); if (sock < 0) { @@ -320,7 +322,7 @@ void sock_recv_task(void* arg) 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; + packet->src.type == ESP_IPADDR_TYPE_V4 ? MDNS_IP_PROTOCOL_V4 : MDNS_IP_PROTOCOL_V6; if (!_mdns_server || !_mdns_server->action_queue || _mdns_send_rx_action(packet) != ESP_OK) { ESP_LOGE(TAG, "_mdns_send_rx_action failed!"); free(packet->pb->payload); @@ -338,19 +340,19 @@ static void mdns_networking_init(void) { if (s_run_sock_recv_task == false) { s_run_sock_recv_task = true; - xTaskCreate( sock_recv_task, "mdns recv task", 3*1024, NULL, 5, NULL ); + xTaskCreate( sock_recv_task, "mdns recv task", 3 * 1024, NULL, 5, NULL ); } } -static struct udp_pcb* create_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) +static struct udp_pcb *create_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol) { if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb) { return _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb; } - mdns_ip_protocol_t other_ip_proto = ip_protocol==MDNS_IP_PROTOCOL_V4?MDNS_IP_PROTOCOL_V6:MDNS_IP_PROTOCOL_V4; + mdns_ip_protocol_t other_ip_proto = ip_protocol == MDNS_IP_PROTOCOL_V4 ? MDNS_IP_PROTOCOL_V6 : MDNS_IP_PROTOCOL_V4; esp_netif_t *netif = _mdns_get_esp_netif(tcpip_if); if (_mdns_server->interfaces[tcpip_if].pcbs[other_ip_proto].pcb) { - struct udp_pcb* other_pcb = _mdns_server->interfaces[tcpip_if].pcbs[other_ip_proto].pcb; + struct udp_pcb *other_pcb = _mdns_server->interfaces[tcpip_if].pcbs[other_ip_proto].pcb; int err = join_mdns_multicast_group(pcb_to_sock(other_pcb), netif, ip_protocol); if (err < 0) { ESP_LOGE(TAG, "Failed to add ipv6 multicast group for protocol %d", ip_protocol); @@ -420,7 +422,7 @@ static int create_socket(esp_netif_t *netif) #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)); + 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; @@ -477,7 +479,7 @@ static int socket_add_ipv4_multicast_group(int sock, esp_netif_t *netif) goto err; } - err: +err: return err; } diff --git a/components/mdns/private_include/mdns_networking.h b/components/mdns/private_include/mdns_networking.h index 53772c835..3ab8dc757 100644 --- a/components/mdns/private_include/mdns_networking.h +++ b/components/mdns/private_include/mdns_networking.h @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #ifndef ESP_MDNS_NETWORKING_H_ #define ESP_MDNS_NETWORKING_H_ @@ -12,7 +17,7 @@ /** * @brief Queue RX packet action */ -esp_err_t _mdns_send_rx_action(mdns_rx_packet_t * packet); +esp_err_t _mdns_send_rx_action(mdns_rx_packet_t *packet); /** * @brief Start PCB @@ -33,12 +38,12 @@ esp_err_t _mdns_pcb_deinit(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol); * * @return length of sent packet or 0 on error */ -size_t _mdns_udp_pcb_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); +size_t _mdns_udp_pcb_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_get_packet_data(mdns_rx_packet_t *packet); +void *_mdns_get_packet_data(mdns_rx_packet_t *packet); /** * @brief Gets data length of c diff --git a/components/mdns/private_include/mdns_private.h b/components/mdns/private_include/mdns_private.h index 7b0673c8f..d4fef5f13 100644 --- a/components/mdns/private_include/mdns_private.h +++ b/components/mdns/private_include/mdns_private.h @@ -231,27 +231,27 @@ typedef struct { } mdns_name_t; typedef struct mdns_parsed_question_s { - struct mdns_parsed_question_s * next; + struct mdns_parsed_question_s *next; uint16_t type; bool sub; bool unicast; - char * host; - char * service; - char * proto; - char * domain; + char *host; + char *service; + char *proto; + char *domain; } mdns_parsed_question_t; typedef struct mdns_parsed_record_s { - struct mdns_parsed_record_s * next; + 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; + char *host; + char *service; + char *proto; + char *domain; uint16_t data_len; uint8_t *data; } mdns_parsed_record_t; @@ -266,8 +266,8 @@ typedef struct { uint8_t probe; uint8_t discovery; uint8_t distributed; - mdns_parsed_question_t * questions; - mdns_parsed_record_t * records; + mdns_parsed_question_t *questions; + mdns_parsed_record_t *records; uint16_t id; } mdns_parsed_packet_t; @@ -282,65 +282,65 @@ typedef struct { } mdns_rx_packet_t; typedef struct mdns_txt_linked_item_s { - const char * key; /*!< item key name */ - char * value; /*!< item value string */ + 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 */ + 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 */ + 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; + 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_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; + 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; + 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 *host; + const char *service; + const char *proto; + const char *domain; bool own_dynamic_memory; } mdns_out_question_t; typedef struct mdns_host_item_t { - const char * hostname; + 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; + 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_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; + struct mdns_tx_packet_s *next; uint32_t send_at; mdns_if_t tcpip_if; mdns_ip_protocol_t ip_protocol; @@ -348,18 +348,18 @@ typedef struct mdns_tx_packet_s { 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; + 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 struct { mdns_pcb_state_t state; - struct udp_pcb * pcb; - mdns_srv_item_t ** probe_services; + struct udp_pcb *pcb; + mdns_srv_item_t **probe_services; uint8_t probe_services_len; uint8_t probe_ip; uint8_t probe_running; @@ -374,7 +374,7 @@ typedef enum { } mdns_search_once_state_t; typedef struct mdns_search_once_s { - struct mdns_search_once_s * next; + struct mdns_search_once_s *next; mdns_search_once_state_t state; uint32_t started_at; @@ -386,23 +386,23 @@ typedef struct mdns_search_once_s { bool unicast; uint8_t max_results; uint8_t num_results; - char * instance; - char * service; - char * proto; - mdns_result_t * result; + char *instance; + char *service; + char *proto; + mdns_result_t *result; } mdns_search_once_t; typedef struct mdns_server_s { struct { mdns_pcb_t pcbs[MDNS_IP_PROTOCOL_MAX]; } interfaces[MDNS_MAX_INTERFACES]; - const char * hostname; - const char * instance; - mdns_srv_item_t * services; + const char *hostname; + const char *instance; + mdns_srv_item_t *services; SemaphoreHandle_t lock; QueueHandle_t action_queue; - mdns_tx_packet_t * tx_queue_head; - mdns_search_once_t * search_once; + mdns_tx_packet_t *tx_queue_head; + mdns_search_once_t *search_once; esp_timer_handle_t timer_handle; } mdns_server_t; @@ -410,57 +410,57 @@ typedef struct { mdns_action_type_t type; union { struct { - char * hostname; + char *hostname; TaskHandle_t calling_task; } hostname_set; - char * instance; + char *instance; struct { mdns_if_t interface; mdns_event_actions_t event_action; } sys_event; struct { - mdns_srv_item_t * service; + mdns_srv_item_t *service; } srv_add; struct { - mdns_srv_item_t * service; + mdns_srv_item_t *service; } srv_del; struct { - mdns_srv_item_t * service; - char * instance; + mdns_srv_item_t *service; + char *instance; } srv_instance; struct { - mdns_srv_item_t * service; + mdns_srv_item_t *service; uint16_t port; } srv_port; struct { - mdns_srv_item_t * service; - mdns_txt_linked_item_t * txt; + mdns_srv_item_t *service; + mdns_txt_linked_item_t *txt; } srv_txt_replace; struct { - mdns_srv_item_t * service; - char * key; - char * value; + mdns_srv_item_t *service; + char *key; + char *value; uint8_t value_len; } srv_txt_set; struct { - mdns_srv_item_t * service; - char * key; + mdns_srv_item_t *service; + char *key; } srv_txt_del; struct { - mdns_srv_item_t * service; - char * subtype; + mdns_srv_item_t *service; + char *subtype; } srv_subtype_add; struct { - mdns_search_once_t * search; + mdns_search_once_t *search; } search_add; struct { - mdns_tx_packet_t * packet; + mdns_tx_packet_t *packet; } tx_handle; struct { - mdns_rx_packet_t * packet; + mdns_rx_packet_t *packet; } rx_handle; struct { - const char * hostname; + const char *hostname; mdns_ip_addr_t *address_list; } delegate_hostname; } data; diff --git a/components/mdns/tests/host_test/components/esp_event_mock/esp_event_mock.c b/components/mdns/tests/host_test/components/esp_event_mock/esp_event_mock.c index cd6b079b3..42e159375 100644 --- a/components/mdns/tests/host_test/components/esp_event_mock/esp_event_mock.c +++ b/components/mdns/tests/host_test/components/esp_event_mock/esp_event_mock.c @@ -1,29 +1,21 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "esp_err.h" #include "esp_event.h" -const char * WIFI_EVENT = "WIFI_EVENT"; -const char * IP_EVENT = "IP_EVENT"; +const char *WIFI_EVENT = "WIFI_EVENT"; +const char *IP_EVENT = "IP_EVENT"; -esp_err_t esp_event_handler_register(const char * event_base, int32_t event_id, void* event_handler, void* event_handler_arg) +esp_err_t esp_event_handler_register(const char *event_base, int32_t event_id, void *event_handler, void *event_handler_arg) { return ESP_OK; } -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler) +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler) { return ESP_OK; } diff --git a/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event.h b/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event.h index 18801e4b9..872eba49e 100644 --- a/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event.h +++ b/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once #include "stdbool.h" @@ -21,12 +13,12 @@ #define ESP_EVENT_DECLARE_BASE(x) #define ESP_EVENT_ANY_ID (-1) -typedef void * esp_event_base_t; -typedef void * system_event_t; +typedef void *esp_event_base_t; +typedef void *system_event_t; -const char* WIFI_EVENT; -const char* IP_EVENT; +const char *WIFI_EVENT; +const char *IP_EVENT; -esp_err_t esp_event_handler_register(const char * event_base, int32_t event_id, void* event_handler, void* event_handler_arg); +esp_err_t esp_event_handler_register(const char *event_base, int32_t event_id, void *event_handler, void *event_handler_arg); -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler); +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler); diff --git a/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event_base.h b/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event_base.h index 740b71270..a9e117bcd 100644 --- a/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event_base.h +++ b/components/mdns/tests/host_test/components/esp_event_mock/include/esp_event_base.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once typedef enum { diff --git a/components/mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c b/components/mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c index bbde59073..e595ee03a 100644 --- a/components/mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c +++ b/components/mdns/tests/host_test/components/esp_netif_linux/esp_netif_linux.c @@ -1,24 +1,16 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include #include "esp_netif.h" #include "esp_err.h" -#include //strlen +#include //strlen #include -#include //inet_addr +#include //inet_addr #include #include #include @@ -26,17 +18,16 @@ #define MAX_NETIFS 4 -static esp_netif_t* s_netif_list[MAX_NETIFS] = { 0 }; +static esp_netif_t *s_netif_list[MAX_NETIFS] = { 0 }; -struct esp_netif_obj -{ +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; iif_key, if_key) == 0) { return s_netif_list[i]; } @@ -84,15 +75,14 @@ esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if getifaddrs(&addrs); tmp = addrs; - while (tmp) - { + 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) { printf("AF_INET6: %s: %s\n", tmp->ifa_name, addr); - memcpy(if_ip6->addr, &pAddr->sin6_addr, 4*4); + memcpy(if_ip6->addr, &pAddr->sin6_addr, 4 * 4); break; } } @@ -113,7 +103,7 @@ int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif) return interfaceIndex; } -esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char* name) +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; @@ -135,13 +125,13 @@ 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)); + 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 @@ -27,8 +19,8 @@ void esp_log_buffer_hexdump_internal(const char *tag, const void *buffer, uint16 { if ( LOG_LOCAL_LEVEL >= log_level ) { ESP_LOG_LEVEL(log_level, tag, "Buffer:%p length:%d", buffer, buff_len); - for (int i=0; i @@ -38,9 +38,9 @@ */ size_t strlcat(dst, src, siz) - char *dst; - const char *src; - size_t siz; +char *dst; +const char *src; +size_t siz; { char *d = dst; const char *s = src; @@ -48,13 +48,15 @@ strlcat(dst, src, siz) size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ - while (n-- != 0 && *d != '\0') + while (n-- != 0 && *d != '\0') { d++; + } dlen = d - dst; n = siz - dlen; - if (n == 0) - return(dlen + strlen(s)); + if (n == 0) { + return (dlen + strlen(s)); + } while (*s != '\0') { if (n != 1) { *d++ = *s; @@ -64,5 +66,5 @@ strlcat(dst, src, siz) } *d = '\0'; - return(dlen + (s - src)); /* count does not include NUL */ + return (dlen + (s - src)); /* count does not include NUL */ } diff --git a/components/mdns/tests/host_test/components/esp_timer_linux/esp_timer_linux.c b/components/mdns/tests/host_test/components/esp_timer_linux/esp_timer_linux.c index bb2326985..2131e4141 100644 --- a/components/mdns/tests/host_test/components/esp_timer_linux/esp_timer_linux.c +++ b/components/mdns/tests/host_test/components/esp_timer_linux/esp_timer_linux.c @@ -1,29 +1,21 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "esp_err.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" -void * create_tt(esp_timer_cb_t cb); +void *create_tt(esp_timer_cb_t cb); -void destroy_tt(void* tt); +void destroy_tt(void *tt); -void set_tout(void* tt, uint32_t ms); +void set_tout(void *tt, uint32_t ms); -esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args, - esp_timer_handle_t* out_handle) +esp_err_t esp_timer_create(const esp_timer_create_args_t *create_args, + esp_timer_handle_t *out_handle) { *out_handle = (esp_timer_handle_t)create_tt(create_args->callback); return ESP_OK; @@ -31,7 +23,7 @@ esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args, esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period) { - set_tout(timer, period/1000); + set_tout(timer, period / 1000); return ESP_OK; } diff --git a/components/mdns/tests/host_test/components/esp_timer_linux/include/esp_timer.h b/components/mdns/tests/host_test/components/esp_timer_linux/include/esp_timer.h index 669163049..24782a4bf 100644 --- a/components/mdns/tests/host_test/components/esp_timer_linux/include/esp_timer.h +++ b/components/mdns/tests/host_test/components/esp_timer_linux/include/esp_timer.h @@ -1,24 +1,16 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once #include #include -typedef struct esp_timer* esp_timer_handle_t; +typedef struct esp_timer *esp_timer_handle_t; -typedef void (*esp_timer_cb_t)(void* arg); +typedef void (*esp_timer_cb_t)(void *arg); typedef enum { ESP_TIMER_TASK, @@ -26,14 +18,14 @@ typedef enum { typedef struct { esp_timer_cb_t callback; //!< Function to call when timer expires - void* arg; //!< Argument to pass to the callback + void *arg; //!< Argument to pass to the callback esp_timer_dispatch_t dispatch_method; //!< Call the callback from task or from ISR - const char* name; //!< Timer name, used in esp_timer_dump function + const char *name; //!< Timer name, used in esp_timer_dump function bool skip_unhandled_events; //!< Skip unhandled events for periodic timers } esp_timer_create_args_t; -esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args, - esp_timer_handle_t* out_handle); +esp_err_t esp_timer_create(const esp_timer_create_args_t *create_args, + esp_timer_handle_t *out_handle); esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period); esp_err_t esp_timer_stop(esp_timer_handle_t timer); diff --git a/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.cpp b/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.cpp index bd971b3f0..b86506184 100644 --- a/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.cpp +++ b/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "timer_task.hpp" #include @@ -18,21 +10,21 @@ #include #include -extern "C" void * create_tt(cb_t cb) +extern "C" void *create_tt(cb_t cb) { - auto * tt = new TimerTaskMock(cb); + auto *tt = new TimerTaskMock(cb); return tt; } -extern "C" void destroy_tt(void* tt) +extern "C" void destroy_tt(void *tt) { - auto * timer_task = static_cast(tt); - delete(timer_task); + auto *timer_task = static_cast(tt); + delete (timer_task); } -extern "C" void set_tout(void* tt, uint32_t ms) +extern "C" void set_tout(void *tt, uint32_t ms) { - auto * timer_task = static_cast(tt); + auto *timer_task = static_cast(tt); timer_task->SetTimeout(ms); } diff --git a/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.hpp b/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.hpp index 8d32a6bd0..be8bec5f5 100644 --- a/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.hpp +++ b/components/mdns/tests/host_test/components/esp_timer_linux/timer_task.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once #include @@ -20,13 +12,16 @@ #include #include -typedef void (*cb_t)(void* arg); +typedef void (*cb_t)(void *arg); -class TimerTaskMock -{ +class TimerTaskMock { public: TimerTaskMock(cb_t cb): cb(cb), t(run_static, this), active(false), ms(INT32_MAX) {} - ~TimerTaskMock(void) { active = false; t.join(); } + ~TimerTaskMock(void) + { + active = false; + t.join(); + } void SetTimeout(uint32_t m) { @@ -36,7 +31,7 @@ public: private: - static void run_static(TimerTaskMock* timer) + static void run_static(TimerTaskMock *timer) { timer->run(); } diff --git a/components/mdns/tests/host_test/components/freertos_linux/freertos_linux.c b/components/mdns/tests/host_test/components/freertos_linux/freertos_linux.c index 763364504..c34cf5cbd 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/freertos_linux.c +++ b/components/mdns/tests/host_test/components/freertos_linux/freertos_linux.c @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include "freertos/FreeRTOS.h" @@ -20,39 +12,39 @@ #include #include -void * create_q(void); +void *create_q(void); -void destroy_q(void* q); +void destroy_q(void *q); -bool send_q(void* q, uint8_t *data, size_t len); +bool send_q(void *q, uint8_t *data, size_t len); -bool recv_q(void* q, uint8_t *data, size_t len, uint32_t ms); +bool recv_q(void *q, uint8_t *data, size_t len, uint32_t ms); static uint64_t s_semaphore_data = 0; struct queue_handle { size_t item_size; - void * q; + void *q; }; QueueHandle_t xQueueCreate( uint32_t uxQueueLength, uint32_t uxItemSize ) { - struct queue_handle * h = calloc(1, sizeof(struct queue_handle)); + struct queue_handle *h = calloc(1, sizeof(struct queue_handle)); h->item_size = uxItemSize; h->q = create_q(); return (QueueHandle_t)h; } -uint32_t xQueueSend(QueueHandle_t xQueue, const void * pvItemToQueue, TickType_t xTicksToWait) +uint32_t xQueueSend(QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait) { - struct queue_handle * h = xQueue; - return send_q(h->q, (uint8_t*)pvItemToQueue, h->item_size) ? pdTRUE : pdFAIL; + struct queue_handle *h = xQueue; + return send_q(h->q, (uint8_t *)pvItemToQueue, h->item_size) ? pdTRUE : pdFAIL; } uint32_t xQueueReceive(QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait) { - struct queue_handle * h = xQueue; - return recv_q(h->q, (uint8_t*)pvBuffer, h->item_size, xTicksToWait) ? pdTRUE : pdFAIL; + struct queue_handle *h = xQueue; + return recv_q(h->q, (uint8_t *)pvBuffer, h->item_size, xTicksToWait) ? pdTRUE : pdFAIL; } BaseType_t xSemaphoreGive( QueueHandle_t xQueue) @@ -67,7 +59,7 @@ BaseType_t xSemaphoreTake( QueueHandle_t xQueue, TickType_t pvTask ) void vQueueDelete( QueueHandle_t xQueue ) { - struct queue_handle * h = xQueue; + struct queue_handle *h = xQueue; if (h->q) { destroy_q(h->q); } @@ -107,18 +99,18 @@ TickType_t xTaskGetTickCount( void ) void vTaskDelay( const TickType_t xTicksToDelay ) { - usleep(xTicksToDelay*1000); + usleep(xTicksToDelay * 1000); } -void * pthread_task(void * params) +void *pthread_task(void *params) { struct { - void * const param; + void *const param; TaskFunction_t task; bool started; } *pthread_params = params; - void * const param = pthread_params->param; + void *const param = pthread_params->param; TaskFunction_t task = pthread_params->task; pthread_params->started = true; @@ -127,25 +119,25 @@ void * pthread_task(void * params) return NULL; } -BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, - const char * const pcName, - const uint32_t usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pvCreatedTask, - const BaseType_t xCoreID) +BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, + const char *const pcName, + const uint32_t usStackDepth, + void *const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t *const pvCreatedTask, + const BaseType_t xCoreID) { xTaskCreate(pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pvCreatedTask); return pdTRUE; } -void xTaskCreate(TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask) +void xTaskCreate(TaskFunction_t pvTaskCode, const char *const pcName, const uint32_t usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pvCreatedTask) { pthread_t new_thread = (pthread_t)NULL; pthread_attr_t attr; struct { - void * const param; + void *const param; TaskFunction_t task; bool started; } pthread_params = { .param = pvParameters, .task = pvTaskCode}; @@ -157,7 +149,7 @@ void xTaskCreate(TaskFunction_t pvTaskCode, const char * const pcName, const uin assert(res == 0); if (pvCreatedTask) { - *pvCreatedTask = (void*)new_thread; + *pvCreatedTask = (void *)new_thread; } // just wait till the task started so we can unwind params from the stack diff --git a/components/mdns/tests/host_test/components/freertos_linux/include/esp_task.h b/components/mdns/tests/host_test/components/freertos_linux/include/esp_task.h index 797b416b6..f43cb4ceb 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/include/esp_task.h +++ b/components/mdns/tests/host_test/components/freertos_linux/include/esp_task.h @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once #include "freertos/FreeRTOS.h" diff --git a/components/mdns/tests/host_test/components/freertos_linux/include/freertos/FreeRTOS.h b/components/mdns/tests/host_test/components/freertos_linux/include/freertos/FreeRTOS.h index 2c4bcbfca..e087f8b3c 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/include/freertos/FreeRTOS.h +++ b/components/mdns/tests/host_test/components/freertos_linux/include/freertos/FreeRTOS.h @@ -13,20 +13,20 @@ #define portTICK_PERIOD_MS 1 #define portMAX_DELAY ( TickType_t ) 0xffffffffUL -typedef void * SemaphoreHandle_t; -typedef void * QueueHandle_t; -typedef void * TaskHandle_t; +typedef void *SemaphoreHandle_t; +typedef void *QueueHandle_t; +typedef void *TaskHandle_t; typedef uint32_t TickType_t; typedef void (*TaskFunction_t)( void * ); -typedef unsigned int UBaseType_t; -typedef int BaseType_t; +typedef unsigned int UBaseType_t; +typedef int BaseType_t; -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) #define pdMS_TO_TICKS(tick) (tick) diff --git a/components/mdns/tests/host_test/components/freertos_linux/include/freertos/task.h b/components/mdns/tests/host_test/components/freertos_linux/include/freertos/task.h index 39b7e19c4..91010f465 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/include/freertos/task.h +++ b/components/mdns/tests/host_test/components/freertos_linux/include/freertos/task.h @@ -18,15 +18,15 @@ TaskHandle_t xTaskGetCurrentTaskHandle(void); BaseType_t xTaskNotifyWait(uint32_t bits_entry_clear, uint32_t bits_exit_clear, uint32_t *value, TickType_t wait_time ); -BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, - const char * const pcName, - const uint32_t usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pvCreatedTask, - const BaseType_t xCoreID); +BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, + const char *const pcName, + const uint32_t usStackDepth, + void *const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t *const pvCreatedTask, + const BaseType_t xCoreID); -void xTaskCreate(TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask); +void xTaskCreate(TaskFunction_t pvTaskCode, const char *const pcName, const uint32_t usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pvCreatedTask); TickType_t xTaskGetTickCount( void ); @@ -45,6 +45,6 @@ void vTaskDelete(TaskHandle_t *task); QueueHandle_t xQueueCreate( uint32_t uxQueueLength, uint32_t uxItemSize ); -uint32_t xQueueSend(QueueHandle_t xQueue, const void * pvItemToQueue, TickType_t xTicksToWait); +uint32_t xQueueSend(QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait); uint32_t xQueueReceive(QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait); diff --git a/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.cpp b/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.cpp index 60c4a8a28..56eef6d17 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.cpp +++ b/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.cpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include "queue_unique_ptr.hpp" #include @@ -18,28 +10,28 @@ #include #include -extern "C" void * create_q(void) +extern "C" void *create_q(void) { - auto * q = new QueueMock>(); + auto *q = new QueueMock>(); return q; } -extern "C" void destroy_q(void* q) +extern "C" void destroy_q(void *q) { - auto * queue = static_cast> *>(q); - delete(queue); + auto *queue = static_cast> *>(q); + delete (queue); } -extern "C" bool send_q(void* q, uint8_t *data, size_t len) +extern "C" bool send_q(void *q, uint8_t *data, size_t len) { auto v = std::make_unique>(len); - v->assign(data, data+len); + v->assign(data, data + len); auto queue = static_cast> *>(q); queue->send(std::move(v)); return true; } -extern "C" bool recv_q(void* q, uint8_t *data, size_t len, uint32_t ms) +extern "C" bool recv_q(void *q, uint8_t *data, size_t len, uint32_t ms) { auto queue = static_cast> *>(q); auto v = queue->receive(ms); diff --git a/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.hpp b/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.hpp index fe722b97f..67fb02b99 100644 --- a/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.hpp +++ b/components/mdns/tests/host_test/components/freertos_linux/queue_unique_ptr.hpp @@ -1,16 +1,8 @@ -// Copyright 2021 Espressif Systems (Shanghai) PTE LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #pragma once @@ -22,31 +14,30 @@ #include template -class QueueMock -{ +class QueueMock { public: QueueMock(void): q(), m(), c() {} ~QueueMock(void) {} -void send(std::unique_ptr t) -{ - std::lock_guard lock(m); - q.push(std::move(t)); - c.notify_one(); -} - -std::unique_ptr receive(uint32_t ms) -{ - std::unique_lock lock(m); - while(q.empty()) { - if (c.wait_for(lock, std::chrono::milliseconds(ms)) == std::cv_status::timeout) { - return nullptr; - } + void send(std::unique_ptr t) + { + std::lock_guard lock(m); + q.push(std::move(t)); + c.notify_one(); + } + + std::unique_ptr receive(uint32_t ms) + { + std::unique_lock lock(m); + while (q.empty()) { + if (c.wait_for(lock, std::chrono::milliseconds(ms)) == std::cv_status::timeout) { + return nullptr; + } + } + std::unique_ptr val = std::move(q.front()); + q.pop(); + return val; } - std::unique_ptr val = std::move(q.front()); - q.pop(); - return val; -} private: std::queue> q; diff --git a/components/mdns/tests/host_test/main/main.c b/components/mdns/tests/host_test/main/main.c index f3883b8c3..51ca92a52 100644 --- a/components/mdns/tests/host_test/main/main.c +++ b/components/mdns/tests/host_test/main/main.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include #include "mdns.h" #include "esp_log.h" @@ -6,7 +11,7 @@ static const char *TAG = "mdns-test"; -static void query_mdns_host(const char * host_name) +static void query_mdns_host(const char *host_name) { ESP_LOGI(TAG, "Query A: %s.local", host_name); @@ -14,8 +19,8 @@ static void query_mdns_host(const char * host_name) addr.addr = 0; esp_err_t err = mdns_query_a(host_name, 2000, &addr); - if(err){ - if(err == ESP_ERR_NOT_FOUND){ + if (err) { + if (err == ESP_ERR_NOT_FOUND) { ESP_LOGW(TAG, "%x: Host was not found!", (err)); return; } @@ -26,7 +31,7 @@ static void query_mdns_host(const char * host_name) ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr)); } -int main(int argc , char *argv[]) +int main(int argc, char *argv[]) { setvbuf(stdout, NULL, _IONBF, 0); @@ -42,9 +47,9 @@ int main(int argc , char *argv[]) mdns_instance_name_set("myesp-inst"); //structure with TXT records mdns_txt_item_t serviceTxtData[3] = { - {"board","esp32"}, - {"u","user"}, - {"p","password"} + {"board", "esp32"}, + {"u", "user"}, + {"p", "password"} }; vTaskDelay(1000); ESP_ERROR_CHECK(mdns_service_add("myesp-service2", "_http", "_tcp", 80, serviceTxtData, 3)); diff --git a/components/mdns/tests/test_afl_fuzz_host/README.md b/components/mdns/tests/test_afl_fuzz_host/README.md index 11f9c5e6d..e22a89606 100644 --- a/components/mdns/tests/test_afl_fuzz_host/README.md +++ b/components/mdns/tests/test_afl_fuzz_host/README.md @@ -39,7 +39,7 @@ The rest of the document will refer to that folder as ```PATH_TO_AFL```. ``` - On Ubuntu you need the following packages: - + ```bash sudo apt-get install make clang-4.0(or <=4.0) llvm-4.0(or <=4.0) libbsd-dev ``` diff --git a/components/mdns/tests/test_afl_fuzz_host/esp32_mock.c b/components/mdns/tests/test_afl_fuzz_host/esp32_mock.c index 08ac305c5..1f74c7833 100644 --- a/components/mdns/tests/test_afl_fuzz_host/esp32_mock.c +++ b/components/mdns/tests/test_afl_fuzz_host/esp32_mock.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include #include #include @@ -5,22 +10,22 @@ #include #include "esp32_mock.h" -void* g_queue; +void *g_queue; int g_queue_send_shall_fail = 0; int g_size = 0; -const char * WIFI_EVENT = "wifi_event"; -const char * ETH_EVENT = "eth_event"; +const char *WIFI_EVENT = "wifi_event"; +const char *ETH_EVENT = "eth_event"; -esp_err_t esp_event_handler_register(const char * event_base, - int32_t event_id, - void* event_handler, - void* event_handler_arg) +esp_err_t esp_event_handler_register(const char *event_base, + int32_t event_id, + void *event_handler, + void *event_handler_arg) { return ESP_OK; } -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler) +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler) { return ESP_OK; } @@ -40,8 +45,8 @@ esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period) return ESP_OK; } -esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args, - esp_timer_handle_t* out_handle) +esp_err_t esp_timer_create(const esp_timer_create_args_t *create_args, + esp_timer_handle_t *out_handle) { return ESP_OK; } @@ -53,12 +58,12 @@ uint32_t xTaskGetTickCount(void) } /// Queue mock - QueueHandle_t xQueueCreate( uint32_t uxQueueLength, uint32_t uxItemSize ) - { - g_size = uxItemSize; - g_queue = malloc((uxQueueLength)*(uxItemSize)); - return g_queue; - } +QueueHandle_t xQueueCreate( uint32_t uxQueueLength, uint32_t uxItemSize ) +{ + g_size = uxItemSize; + g_queue = malloc((uxQueueLength) * (uxItemSize)); + return g_queue; +} void vQueueDelete( QueueHandle_t xQueue ) @@ -66,14 +71,11 @@ void vQueueDelete( QueueHandle_t xQueue ) free(xQueue); } -uint32_t xQueueSend(QueueHandle_t xQueue, const void * pvItemToQueue, TickType_t xTicksToWait) +uint32_t xQueueSend(QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait) { - if (g_queue_send_shall_fail) - { + if (g_queue_send_shall_fail) { return pdFALSE; - } - else - { + } else { memcpy(xQueue, pvItemToQueue, g_size); return pdPASS; } @@ -105,7 +107,7 @@ void xTaskNotifyGive(TaskHandle_t task) return; } -BaseType_t xTaskNotifyWait(uint32_t bits_entry_clear, uint32_t bits_exit_clear, uint32_t * value, TickType_t wait_time) +BaseType_t xTaskNotifyWait(uint32_t bits_entry_clear, uint32_t bits_exit_clear, uint32_t *value, TickType_t wait_time) { return pdTRUE; } diff --git a/components/mdns/tests/test_afl_fuzz_host/esp32_mock.h b/components/mdns/tests/test_afl_fuzz_host/esp32_mock.h index e76a17ab6..23c0b7fc4 100644 --- a/components/mdns/tests/test_afl_fuzz_host/esp32_mock.h +++ b/components/mdns/tests/test_afl_fuzz_host/esp32_mock.h @@ -40,8 +40,8 @@ #define pdTRUE true #define pdFALSE false -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) #define portMAX_DELAY 0xFFFFFFFF #define portTICK_PERIOD_MS 1 @@ -80,45 +80,45 @@ typedef int32_t esp_err_t; -typedef void * SemaphoreHandle_t; -typedef void * QueueHandle_t; -typedef void * TaskHandle_t; +typedef void *SemaphoreHandle_t; +typedef void *QueueHandle_t; +typedef void *TaskHandle_t; typedef int BaseType_t; typedef uint32_t TickType_t; -extern const char * WIFI_EVENT; -extern const char * IP_EVENT; -extern const char * ETH_EVENT; +extern const char *WIFI_EVENT; +extern const char *IP_EVENT; +extern const char *ETH_EVENT; struct udp_pcb { uint8_t dummy; }; struct ip4_addr { - uint32_t addr; + uint32_t addr; }; typedef struct ip4_addr ip4_addr_t; struct ip6_addr { - uint32_t addr[4]; + uint32_t addr[4]; }; typedef struct ip6_addr ip6_addr_t; -typedef void* system_event_t; +typedef void *system_event_t; struct pbuf { - struct pbuf *next; - void *payload; - uint16_t tot_len; - uint16_t len; - uint8_t /*pbuf_type*/ type; - uint8_t flags; - uint16_t ref; + struct pbuf *next; + void *payload; + uint16_t tot_len; + uint16_t len; + uint8_t /*pbuf_type*/ type; + uint8_t flags; + uint16_t ref; }; uint32_t xTaskGetTickCount(void); -typedef void (*esp_timer_cb_t)(void* arg); +typedef void (*esp_timer_cb_t)(void *arg); // Queue mock QueueHandle_t xQueueCreate( uint32_t uxQueueLength, @@ -126,7 +126,7 @@ QueueHandle_t xQueueCreate( uint32_t uxQueueLength, void vQueueDelete( QueueHandle_t xQueue ); -uint32_t xQueueSend(QueueHandle_t xQueue, const void * pvItemToQueue, TickType_t xTicksToWait); +uint32_t xQueueSend(QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait); uint32_t xQueueReceive(QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait); @@ -134,9 +134,9 @@ void GetLastItem(void *pvBuffer); void ForceTaskDelete(void); -esp_err_t esp_event_handler_register(const char * event_base, int32_t event_id, void* event_handler, void* event_handler_arg); +esp_err_t esp_event_handler_register(const char *event_base, int32_t event_id, void *event_handler, void *event_handler_arg); -esp_err_t esp_event_handler_unregister(const char * event_base, int32_t event_id, void* event_handler); +esp_err_t esp_event_handler_unregister(const char *event_base, int32_t event_id, void *event_handler); TaskHandle_t xTaskGetCurrentTaskHandle(void); diff --git a/components/mdns/tests/test_afl_fuzz_host/esp_attr.h b/components/mdns/tests/test_afl_fuzz_host/esp_attr.h index 49bb7515d..75b66786a 100644 --- a/components/mdns/tests/test_afl_fuzz_host/esp_attr.h +++ b/components/mdns/tests/test_afl_fuzz_host/esp_attr.h @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #pragma once #define IRAM_ATTR #define FLAG_ATTR(TYPE) diff --git a/components/mdns/tests/test_afl_fuzz_host/esp_netif_mock.c b/components/mdns/tests/test_afl_fuzz_host/esp_netif_mock.c index 36118199b..80629ad63 100644 --- a/components/mdns/tests/test_afl_fuzz_host/esp_netif_mock.c +++ b/components/mdns/tests/test_afl_fuzz_host/esp_netif_mock.c @@ -1,16 +1,8 @@ -// Copyright 2020 Espressif Systems (Shanghai) CO LTD -// -// 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. +/* + * SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ #include #include @@ -24,7 +16,7 @@ typedef struct esp_netif_ip_info esp_netif_ip_info_t; typedef struct esp_netif_dhcp_status esp_netif_dhcp_status_t; -const char * IP_EVENT = "IP_EVENT"; +const char *IP_EVENT = "IP_EVENT"; esp_err_t esp_netif_add_to_list(esp_netif_t *netif) @@ -37,12 +29,12 @@ esp_err_t esp_netif_remove_from_list(esp_netif_t *netif) return ESP_ERR_NOT_FOUND; } -esp_netif_t* esp_netif_next(esp_netif_t* netif) +esp_netif_t *esp_netif_next(esp_netif_t *netif) { return NULL; } -esp_netif_t* esp_netif_next_unsafe(esp_netif_t* netif) +esp_netif_t *esp_netif_next_unsafe(esp_netif_t *netif) { return NULL; } diff --git a/components/mdns/tests/test_afl_fuzz_host/mdns_di.h b/components/mdns/tests/test_afl_fuzz_host/mdns_di.h index 79dc00f33..ed56960f4 100644 --- a/components/mdns/tests/test_afl_fuzz_host/mdns_di.h +++ b/components/mdns/tests/test_afl_fuzz_host/mdns_di.h @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ /* * MDNS Dependecy injection -- preincluded to inject interface test functions into static variables * @@ -7,19 +12,19 @@ #include "mdns_private.h" void (*mdns_test_static_execute_action)(mdns_action_t *) = NULL; -mdns_srv_item_t * (*mdns_test_static_mdns_get_service_item)(const char * service, const char * proto, const char *hostname) = NULL; +mdns_srv_item_t *(*mdns_test_static_mdns_get_service_item)(const char *service, const char *proto, const char *hostname) = NULL; mdns_search_once_t *(*mdns_test_static_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) = NULL; -esp_err_t (*mdns_test_static_send_search_action)(mdns_action_type_t type, mdns_search_once_t * search) = NULL; -void (*mdns_test_static_search_free)(mdns_search_once_t * search) = NULL; + uint32_t timeout, uint8_t max_results, + mdns_query_notify_t notifier) = NULL; +esp_err_t (*mdns_test_static_send_search_action)(mdns_action_type_t type, mdns_search_once_t *search) = NULL; +void (*mdns_test_static_search_free)(mdns_search_once_t *search) = NULL; -static void _mdns_execute_action(mdns_action_t * action); -static mdns_srv_item_t * _mdns_get_service_item(const char * service, const char * proto, const char *hostname); +static void _mdns_execute_action(mdns_action_t *action); +static mdns_srv_item_t *_mdns_get_service_item(const char *service, const char *proto, const char *hostname); static mdns_search_once_t *_mdns_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); -static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_once_t * search); -static void _mdns_search_free(mdns_search_once_t * search); + uint32_t timeout, uint8_t max_results, mdns_query_notify_t notifier); +static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_once_t *search); +static void _mdns_search_free(mdns_search_once_t *search); void mdns_test_init_di(void) { @@ -30,27 +35,27 @@ void mdns_test_init_di(void) mdns_test_static_search_free = _mdns_search_free; } -void mdns_test_execute_action(void * action) +void mdns_test_execute_action(void *action) { mdns_test_static_execute_action((mdns_action_t *)action); } -void mdns_test_search_free(mdns_search_once_t * search) +void mdns_test_search_free(mdns_search_once_t *search) { return mdns_test_static_search_free(search); } -esp_err_t mdns_test_send_search_action(mdns_action_type_t type, mdns_search_once_t * search) +esp_err_t mdns_test_send_search_action(mdns_action_type_t type, mdns_search_once_t *search) { return mdns_test_static_send_search_action(type, search); } -mdns_search_once_t * mdns_test_search_init(const char * name, const char * service, const char * proto, uint16_t type, uint32_t timeout, uint8_t max_results) +mdns_search_once_t *mdns_test_search_init(const char *name, const char *service, const char *proto, uint16_t type, uint32_t timeout, uint8_t max_results) { return mdns_test_static_search_init(name, service, proto, type, timeout, type != MDNS_TYPE_PTR, max_results, NULL); } -mdns_srv_item_t * mdns_test_mdns_get_service_item(const char * service, const char * proto) +mdns_srv_item_t *mdns_test_mdns_get_service_item(const char *service, const char *proto) { return mdns_test_static_mdns_get_service_item(service, proto, NULL); } diff --git a/components/mdns/tests/test_afl_fuzz_host/mdns_mock.h b/components/mdns/tests/test_afl_fuzz_host/mdns_mock.h index 1898de2c0..e5cb3df78 100644 --- a/components/mdns/tests/test_afl_fuzz_host/mdns_mock.h +++ b/components/mdns/tests/test_afl_fuzz_host/mdns_mock.h @@ -1,10 +1,15 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #pragma once #include "esp32_mock.h" #include "mdns.h" #include "mdns_private.h" -static inline void* _mdns_get_packet_data(mdns_rx_packet_t *packet) +static inline void *_mdns_get_packet_data(mdns_rx_packet_t *packet) { return packet->pb->payload; } diff --git a/components/mdns/tests/test_afl_fuzz_host/sdkconfig.h b/components/mdns/tests/test_afl_fuzz_host/sdkconfig.h index bcb1b9d13..c5fb91460 100644 --- a/components/mdns/tests/test_afl_fuzz_host/sdkconfig.h +++ b/components/mdns/tests/test_afl_fuzz_host/sdkconfig.h @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ /* * This config file commited in order to not run `idf.py reconfigure` each time when running fuzzer test. You can modify it manually or run `idf.py reconfigure` to generate new one if needed. * Espressif IoT Development Framework (ESP-IDF) Configuration Header diff --git a/components/mdns/tests/test_afl_fuzz_host/test.c b/components/mdns/tests/test_afl_fuzz_host/test.c index 568c7eee1..5556c563d 100644 --- a/components/mdns/tests/test_afl_fuzz_host/test.c +++ b/components/mdns/tests/test_afl_fuzz_host/test.c @@ -18,73 +18,73 @@ // Global stuctures containing packet payload, search mdns_rx_packet_t g_packet; struct pbuf mypbuf; -mdns_search_once_t * search = NULL; +mdns_search_once_t *search = NULL; // // Dependency injected test functions -void mdns_test_execute_action(void * action); -mdns_srv_item_t * mdns_test_mdns_get_service_item(const char * service, const char * proto); -mdns_search_once_t * mdns_test_search_init(const char * name, const char * service, const char * proto, uint16_t type, uint32_t timeout, uint8_t max_results); -esp_err_t mdns_test_send_search_action(mdns_action_type_t type, mdns_search_once_t * search); -void mdns_test_search_free(mdns_search_once_t * search); +void mdns_test_execute_action(void *action); +mdns_srv_item_t *mdns_test_mdns_get_service_item(const char *service, const char *proto); +mdns_search_once_t *mdns_test_search_init(const char *name, const char *service, const char *proto, uint16_t type, uint32_t timeout, uint8_t max_results); +esp_err_t mdns_test_send_search_action(mdns_action_type_t type, mdns_search_once_t *search); +void mdns_test_search_free(mdns_search_once_t *search); void mdns_test_init_di(void); -extern mdns_server_t * _mdns_server; +extern mdns_server_t *_mdns_server; // // mdns function wrappers for mdns setup in test mode -static int mdns_test_hostname_set(const char * mdns_hostname) +static int mdns_test_hostname_set(const char *mdns_hostname) { - for (int i=0; iinterfaces[i].pcbs[MDNS_IP_PROTOCOL_V4].state = PCB_RUNNING; // mark the PCB running to exercise mdns in fully operational mode _mdns_server->interfaces[i].pcbs[MDNS_IP_PROTOCOL_V6].state = PCB_RUNNING; } int ret = mdns_hostname_set(mdns_hostname); - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); return ret; } -static int mdns_test_add_delegated_host(const char * mdns_hostname) +static int mdns_test_add_delegated_host(const char *mdns_hostname) { mdns_ip_addr_t addr = { .addr = { .u_addr = ESP_IPADDR_TYPE_V4 } }; addr.addr.u_addr.ip4.addr = 0x11111111; int ret = mdns_delegate_hostname_add(mdns_hostname, &addr); - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); return ret; } -static int mdns_test_service_instance_name_set(const char * service, const char * proto, const char * instance) +static int mdns_test_service_instance_name_set(const char *service, const char *proto, const char *instance) { int ret = mdns_service_instance_name_set(service, proto, instance); - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); return ret; } -static int mdns_test_service_txt_set(const char * service, const char * proto, uint8_t num_items, mdns_txt_item_t txt[]) +static int mdns_test_service_txt_set(const char *service, const char *proto, uint8_t num_items, mdns_txt_item_t txt[]) { int ret = mdns_service_txt_set(service, proto, txt, num_items); - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); return ret; } -static int mdns_test_sub_service_add(const char * sub_name, const char * service_name, const char * proto, uint32_t port) +static int mdns_test_sub_service_add(const char *sub_name, const char *service_name, const char *proto, uint32_t port) { if (mdns_service_add(NULL, service_name, proto, port, NULL, 0)) { // This is expected failure as the service thread is not running } - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); - if (mdns_test_mdns_get_service_item(service_name, proto)==NULL) { + if (mdns_test_mdns_get_service_item(service_name, proto) == NULL) { return ESP_FAIL; } int ret = mdns_service_subtype_add_for_host(NULL, service_name, proto, NULL, sub_name); @@ -94,22 +94,22 @@ static int mdns_test_sub_service_add(const char * sub_name, const char * service return ret; } -static int mdns_test_service_add(const char * service_name, const char * proto, uint32_t port) +static int mdns_test_service_add(const char *service_name, const char *proto, uint32_t port) { if (mdns_service_add(NULL, service_name, proto, port, NULL, 0)) { // This is expected failure as the service thread is not running } - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); - if (mdns_test_mdns_get_service_item(service_name, proto)==NULL) { + if (mdns_test_mdns_get_service_item(service_name, proto) == NULL) { return ESP_FAIL; } return ESP_OK; } -static mdns_result_t* mdns_test_query(const char * name, const char * service, const char * proto, uint16_t type) +static mdns_result_t *mdns_test_query(const char *name, const char *service, const char *proto, uint16_t type) { search = mdns_test_search_init(name, service, proto, type, 3000, 20); if (!search) { @@ -121,7 +121,7 @@ static mdns_result_t* mdns_test_query(const char * name, const char * service, c abort(); } - mdns_action_t * a = NULL; + mdns_action_t *a = NULL; GetLastItem(&a); mdns_test_execute_action(a); return NULL; @@ -135,27 +135,27 @@ static void mdns_test_query_free(void) // // function "under test" where afl-mangled packets passed // -void mdns_parse_packet(mdns_rx_packet_t * packet); +void mdns_parse_packet(mdns_rx_packet_t *packet); // // Test starts here // -int main(int argc, char** argv) +int main(int argc, char **argv) { int i; - const char * mdns_hostname = "minifritz"; - const char * mdns_instance = "Hristo's Time Capsule"; + const char *mdns_hostname = "minifritz"; + const char *mdns_instance = "Hristo's Time Capsule"; mdns_txt_item_t arduTxtData[4] = { - {"board","esp32"}, - {"tcp_check","no"}, - {"ssh_upload","no"}, - {"auth_upload","no"} + {"board", "esp32"}, + {"tcp_check", "no"}, + {"ssh_upload", "no"}, + {"auth_upload", "no"} }; const uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x32}; uint8_t buf[1460]; - char winstance[21+strlen(mdns_hostname)]; + char winstance[21 + strlen(mdns_hostname)]; sprintf(winstance, "%s [%02x:%02x:%02x:%02x:%02x:%02x]", mdns_hostname, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); @@ -208,7 +208,7 @@ int main(int argc, char** argv) } if ( - mdns_test_service_add("_afpovertcp", "_tcp", 548) + mdns_test_service_add("_afpovertcp", "_tcp", 548) || mdns_test_service_add("_rfb", "_tcp", 885) || mdns_test_service_add("_smb", "_tcp", 885) || mdns_test_service_add("_adisk", "_tcp", 885) @@ -224,12 +224,11 @@ int main(int argc, char** argv) || mdns_test_service_add("_ipps", "_tcp", 885) || mdns_test_service_add("_pdl-datastream", "_tcp", 885) || mdns_test_service_add("_ptp", "_tcp", 885) - || mdns_test_service_add("_sleep-proxy", "_udp", 885)) - { + || mdns_test_service_add("_sleep-proxy", "_udp", 885)) { abort(); } #endif - mdns_result_t * results = NULL; + mdns_result_t *results = NULL; FILE *file; size_t nread; @@ -237,13 +236,10 @@ int main(int argc, char** argv) size_t len = 1460; memset(buf, 0, 1460); - if (argc != 2) - { + if (argc != 2) { printf("Non-instrumentation mode: please supply a file name created by AFL to reproduce crash\n"); return 1; - } - else - { + } else { // // Note: parameter1 is a file (mangled packet) which caused the crash file = fopen(argv[1], "r"); @@ -252,7 +248,7 @@ int main(int argc, char** argv) fclose(file); } - for (i=0; i<1; i++) { + for (i = 0; i < 1; i++) { #else while (__AFL_LOOP(1000)) { memset(buf, 0, 1460); diff --git a/components/mdns/tests/test_apps/app_test.py b/components/mdns/tests/test_apps/app_test.py index efd98feda..643182cf6 100644 --- a/components/mdns/tests/test_apps/app_test.py +++ b/components/mdns/tests/test_apps/app_test.py @@ -65,7 +65,8 @@ def get_mdns_sub_service_query(sub_service): # type:(str) -> dpkt.dns.Msg arr.target = socket.inet_aton('127.0.0.1') arr.ptrname = sub_service dns.qd.append(arr) - console_log('Created mdns subtype service query: {} '.format(dns.__repr__())) + console_log('Created mdns subtype service query: {} '.format( + dns.__repr__())) return dns.pack() @@ -90,13 +91,14 @@ def get_dns_answer_to_mdns(tester_host): # type:(str) -> dpkt.dns.Msg arr.type = dpkt.dns.DNS_A arr.name = tester_host arr.ip = socket.inet_aton('127.0.0.1') - dns. an.append(arr) + dns.an.append(arr) console_log('Created answer to mdns query: {} '.format(dns.__repr__())) return dns.pack() # Get mdns answer for service query -def get_dns_answer_to_service_query(mdns_service): # type:(str) -> dpkt.dns.Msg +def get_dns_answer_to_service_query( + mdns_service): # type:(str) -> dpkt.dns.Msg dns = dpkt.dns.DNS() dns.op = dpkt.dns.DNS_QR | dpkt.dns.DNS_AA dns.rcode = dpkt.dns.DNS_RCODE_NOERR @@ -109,7 +111,7 @@ def get_dns_answer_to_service_query(mdns_service): # type:(str) -> dpkt.dns.Msg arr.port = 100 arr.srvname = mdns_service arr.ip = socket.inet_aton('127.0.0.1') - dns. an.append(arr) + dns.an.append(arr) console_log('Created answer to mdns query: {} '.format(dns.__repr__())) return dns.pack() @@ -122,7 +124,7 @@ def mdns_listener(esp_host): # type:(str) -> None 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)) + 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() @@ -133,7 +135,8 @@ def mdns_listener(esp_host): # type:(str) -> None current_time = time.time() if current_time - last_query_timepoint > QUERY_TIMEOUT: last_query_timepoint = current_time - timeout = max(0, QUERY_TIMEOUT - (current_time - last_query_timepoint)) + timeout = max( + 0, QUERY_TIMEOUT - (current_time - last_query_timepoint)) read_socks, _, _ = select.select([sock], [], [], timeout) if not read_socks: continue @@ -143,29 +146,40 @@ def mdns_listener(esp_host): # type:(str) -> None if len(dns.qd) > 0: if dns.qd[0].name == HOST_NAME: console_log('Received query: {} '.format(dns.__repr__())) - sock.sendto(get_dns_answer_to_mdns(HOST_NAME), (MCAST_GRP,UDP_PORT)) + sock.sendto(get_dns_answer_to_mdns(HOST_NAME), + (MCAST_GRP, UDP_PORT)) if dns.qd[0].name == HOST_NAME: console_log('Received query: {} '.format(dns.__repr__())) - sock.sendto(get_dns_answer_to_mdns(HOST_NAME), (MCAST_GRP,UDP_PORT)) + sock.sendto(get_dns_answer_to_mdns(HOST_NAME), + (MCAST_GRP, UDP_PORT)) if dns.qd[0].name == MDNS_HOST_SERVICE: print(dns.qd[0].name) console_log('Received query: {} '.format(dns.__repr__())) - sock.sendto(get_dns_answer_to_service_query(MDNS_HOST_SERVICE), (MCAST_GRP,UDP_PORT)) + sock.sendto( + get_dns_answer_to_service_query(MDNS_HOST_SERVICE), + (MCAST_GRP, UDP_PORT)) # Receives answers from esp board and sets event flags for python test cases if len(dns.an) == 1: if dns.an[0].name.startswith(SERVICE_NAME): - console_log('Received answer to service query: {}'.format(dns.__repr__())) + console_log('Received answer to service query: {}'.format( + dns.__repr__())) esp_service_answered.set() if len(dns.an) > 1: if dns.an[1].name.startswith(SUB_SERVICE_NAME): - console_log('Received answer for sub service query: {}'.format(dns.__repr__())) + console_log( + 'Received answer for sub service query: {}'.format( + dns.__repr__())) esp_sub_service_answered.set() if len(dns.an) > 0 and dns.an[0].type == dpkt.dns.DNS_A: if dns.an[0].name == esp_host + u'.local': - console_log('Received answer to esp32-mdns query: {}'.format(dns.__repr__())) + console_log( + 'Received answer to esp32-mdns query: {}'.format( + dns.__repr__())) esp_host_answered.set() if dns.an[0].name == esp_host + u'-delegated.local': - console_log('Received answer to esp32-mdns-delegate query: {}'.format(dns.__repr__())) + console_log( + 'Received answer to esp32-mdns-delegate query: {}'. + format(dns.__repr__())) esp_delegated_host_answered.set() except socket.timeout: break @@ -179,7 +193,7 @@ def create_socket(): # type:() -> socket.socket 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)) + 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) return sock @@ -192,9 +206,10 @@ def test_query_dns_http_service(service): # type: (str) -> None for _ in range(RETRY_COUNT): if esp_service_answered.wait(timeout=25): break - sock.sendto(packet, (MCAST_GRP,UDP_PORT)) + sock.sendto(packet, (MCAST_GRP, UDP_PORT)) else: - raise RuntimeError('Test has failed: did not receive mdns answer within timeout') + raise RuntimeError( + 'Test has failed: did not receive mdns answer within timeout') def test_query_dns_sub_service(sub_service): # type: (str) -> None @@ -204,9 +219,10 @@ def test_query_dns_sub_service(sub_service): # type: (str) -> None for _ in range(RETRY_COUNT): if esp_sub_service_answered.wait(timeout=25): break - sock.sendto(packet, (MCAST_GRP,UDP_PORT)) + sock.sendto(packet, (MCAST_GRP, UDP_PORT)) else: - raise RuntimeError('Test has failed: did not receive mdns answer within timeout') + raise RuntimeError( + 'Test has failed: did not receive mdns answer within timeout') def test_query_dns_host(esp_host): # type: (str) -> None @@ -216,9 +232,10 @@ def test_query_dns_host(esp_host): # type: (str) -> None for _ in range(RETRY_COUNT): if esp_host_answered.wait(timeout=25): break - sock.sendto(packet, (MCAST_GRP,UDP_PORT)) + sock.sendto(packet, (MCAST_GRP, UDP_PORT)) else: - raise RuntimeError('Test has failed: did not receive mdns answer within timeout') + raise RuntimeError( + 'Test has failed: did not receive mdns answer within timeout') def test_query_dns_host_delegated(esp_host): # type: (str) -> None @@ -228,24 +245,30 @@ def test_query_dns_host_delegated(esp_host): # type: (str) -> None for _ in range(RETRY_COUNT): if esp_delegated_host_answered.wait(timeout=25): break - sock.sendto(packet, (MCAST_GRP,UDP_PORT)) + sock.sendto(packet, (MCAST_GRP, UDP_PORT)) else: - raise RuntimeError('Test has failed: did not receive mdns answer within timeout') + raise RuntimeError( + 'Test has failed: did not receive mdns answer within timeout') @ttfw_idf.idf_custom_test(env_tag='Example_WIFI', group='test-apps') def test_app_esp_mdns(env, _): # type: (ttfw_idf.TinyFW.Env, None) -> None - dut1 = env.get_dut('mdns', 'tools/test_apps/protocols/mdns', dut_class=ttfw_idf.ESP32DUT) + dut1 = env.get_dut('mdns', + 'tools/test_apps/protocols/mdns', + dut_class=ttfw_idf.ESP32DUT) # 1. start mdns application dut1.start_app() # 2. get the dut host name (and IP address) - specific_host = dut1.expect(re.compile(r'mdns hostname set to: \[([^\]]+)\]'), timeout=30)[0] + specific_host = dut1.expect( + re.compile(r'mdns hostname set to: \[([^\]]+)\]'), timeout=30)[0] - esp_ip = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30) + esp_ip = dut1.expect( + re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), + timeout=30) print('Got IP={}'.format(esp_ip[0])) - mdns_responder = Thread(target=mdns_listener, args=(str(specific_host),)) + mdns_responder = Thread(target=mdns_listener, args=(str(specific_host), )) def start_case(case, desc, result): # type: (str, str, str) -> None print('Starting {}: {}'.format(case, desc)) @@ -258,7 +281,8 @@ def test_app_esp_mdns(env, _): # type: (ttfw_idf.TinyFW.Env, None) -> None # wait untill mdns listener thred started if not start_mdns_listener.wait(timeout=5): - raise ValueError('Test has failed: mdns listener thread did not start') + raise ValueError( + 'Test has failed: mdns listener thread did not start') # query dns service from host, answer should be received from esp board test_query_dns_http_service(SERVICE_NAME) @@ -273,13 +297,17 @@ def test_app_esp_mdns(env, _): # type: (ttfw_idf.TinyFW.Env, None) -> None test_query_dns_host_delegated(specific_host) # query service from esp board, answer should be received from host - start_case('CONFIG_TEST_QUERY_SERVICE', 'Query SRV ESP32._http._tcp.local', 'SRV:ESP32') + start_case('CONFIG_TEST_QUERY_SERVICE', + 'Query SRV ESP32._http._tcp.local', 'SRV:ESP32') # query dns-host from esp board, answer should be received from host - start_case('CONFIG_TEST_QUERY_HOST', 'Query tinytester.local', 'tinytester.local resolved to: 127.0.0.1') + start_case('CONFIG_TEST_QUERY_HOST', 'Query tinytester.local', + 'tinytester.local resolved to: 127.0.0.1') # query dns-host aynchrounusely from esp board, answer should be received from host - start_case('CONFIG_TEST_QUERY_HOST_ASYNC', 'Query tinytester.local async', 'Async query resolved to A:127.0.0.1') + start_case('CONFIG_TEST_QUERY_HOST_ASYNC', + 'Query tinytester.local async', + 'Async query resolved to A:127.0.0.1') finally: stop_mdns_listener.set() diff --git a/components/mdns/tests/test_apps/main/main.c b/components/mdns/tests/test_apps/main/main.c index 0a160aee2..afda341e4 100644 --- a/components/mdns/tests/test_apps/main/main.c +++ b/components/mdns/tests/test_apps/main/main.c @@ -35,7 +35,7 @@ static void get_string(char *line, size_t size) /** 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) +static char *generate_hostname(void) { #ifndef CONFIG_TEST_MDNS_ADD_MAC_TO_HOSTNAME return strdup(CONFIG_TEST_MDNS_HOSTNAME); @@ -52,7 +52,7 @@ static char* generate_hostname(void) static void initialise_mdns(void) { - char * hostname = generate_hostname(); + char *hostname = generate_hostname(); //initialize mDNS ESP_ERROR_CHECK( mdns_init() ); diff --git a/components/mdns/tests/test_apps/main/mdns_test.c b/components/mdns/tests/test_apps/main/mdns_test.c index d82229f1d..45137f328 100644 --- a/components/mdns/tests/test_apps/main/mdns_test.c +++ b/components/mdns/tests/test_apps/main/mdns_test.c @@ -10,7 +10,7 @@ #include "esp_log.h" #include "esp_netif.h" -static const char * TAG = "MDNS_TEST_APP"; +static const char *TAG = "MDNS_TEST_APP"; static const int RETRY_COUNT = 10; static void mdns_print_results(mdns_result_t *results) @@ -48,7 +48,7 @@ static void mdns_print_results(mdns_result_t *results) static bool check_and_print_result(mdns_search_once_t *search) { // Check if any result is available - mdns_result_t * result = NULL; + mdns_result_t *result = NULL; if (!mdns_query_async_get_results(search, 0, &result, NULL)) { return false; } @@ -58,9 +58,9 @@ static bool check_and_print_result(mdns_search_once_t *search) } // If yes, print the result - mdns_ip_addr_t * a = result->addr; + mdns_ip_addr_t *a = result->addr; while (a) { - if(a->addr.type == ESP_IPADDR_TYPE_V6){ + if (a->addr.type == ESP_IPADDR_TYPE_V6) { printf("Async query resolved to AAAA:" IPV6STR "\n", IPV62STR(a->addr.u_addr.ip6)); } else { printf("Async query resolved to A:" IPSTR "\n", IP2STR(&(a->addr.u_addr.ip4))); @@ -72,7 +72,7 @@ static bool check_and_print_result(mdns_search_once_t *search) return true; } -static bool query_mdns_hosts_async(const char * host_name) +static bool query_mdns_hosts_async(const char *host_name) { ESP_LOGI(TAG, "Query both A and AAA: %s.local", host_name); bool res = false; @@ -97,7 +97,7 @@ static bool query_mdns_hosts_async(const char * host_name) return res; } -static esp_err_t query_mdns_host(const char * host_name) +static esp_err_t query_mdns_host(const char *host_name) { ESP_LOGI(TAG, "Query A: %s.local", host_name); @@ -105,8 +105,8 @@ static esp_err_t query_mdns_host(const char * host_name) addr.addr = 0; esp_err_t err = mdns_query_a(host_name, 2000, &addr); - if(err){ - if(err == ESP_ERR_NOT_FOUND){ + if (err) { + if (err == ESP_ERR_NOT_FOUND) { ESP_LOGW(TAG, "%s: Host was not found!", esp_err_to_name(err)); } ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); @@ -117,17 +117,17 @@ static esp_err_t query_mdns_host(const char * host_name) return ESP_OK; } -static esp_err_t query_mdns_service(const char * instance, const char * service_name, const char * proto) +static esp_err_t query_mdns_service(const char *instance, const char *service_name, const char *proto) { ESP_LOGI(TAG, "Query SRV: %s.%s.local", service_name, proto); - mdns_result_t * results = NULL; + mdns_result_t *results = NULL; esp_err_t err = mdns_query_srv(instance, service_name, proto, 3000, &results); - if(err){ + if (err) { ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); return err; } - if(!results){ + if (!results) { ESP_LOGW(TAG, "No results found!"); } @@ -136,15 +136,16 @@ static esp_err_t query_mdns_service(const char * instance, const char * service_ return ESP_OK; } -void query_mdns_service_sub_type(const char * subtype, const char * service_name, const char * proto) { +void query_mdns_service_sub_type(const char *subtype, const char *service_name, const char *proto) +{ ESP_LOGI(TAG, "Query PTR: %s.%s.local", service_name, proto); - mdns_result_t * results = NULL; + mdns_result_t *results = NULL; esp_err_t err = mdns_query_ptr(service_name, proto, 3000, 20, &results); - if(err){ + if (err) { ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err)); } - if(!results){ + if (!results) { ESP_LOGW(TAG, "No results found!"); } diff --git a/components/mdns/tests/unit_test/test_mdns.c b/components/mdns/tests/unit_test/test_mdns.c index 88bc49dbc..fbdbce3ad 100644 --- a/components/mdns/tests/unit_test/test_mdns.c +++ b/components/mdns/tests/unit_test/test_mdns.c @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ #include "test_utils.h" #include "mdns.h" #include "esp_event.h" @@ -48,7 +53,7 @@ TEST_CASE("mdns api return expected err-code and do not leak memory", "[mdns][le 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 max_batch ? max_batch : (len - sent); - slipif_received_bytes(netif, buffer+sent, batch); + slipif_received_bytes(netif, buffer + sent, batch); sent += batch; } @@ -105,7 +105,7 @@ void slip_modem_netif_raw_write(esp_netif_t *netif, void *buffer, size_t len) /** @brief Get esp-netif object corresponding to registration index */ -static esp_netif_t * get_netif_with_esp_index(int index) +static esp_netif_t *get_netif_with_esp_index(int index) { esp_netif_t *netif = NULL; int counter = 0; @@ -120,7 +120,7 @@ static esp_netif_t * get_netif_with_esp_index(int index) /** @brief Return list registration index of the supplied netif ptr */ -static int get_esp_netif_index(esp_netif_t * esp_netif) +static int get_esp_netif_index(esp_netif_t *esp_netif) { esp_netif_t *netif = NULL; int counter = 0; @@ -151,10 +151,10 @@ static err_t esp_slipif_init(struct netif *netif) } const struct esp_netif_netstack_config s_netif_config_slip = { - .lwip = { - .init_fn = esp_slipif_init, - .input_fn = esp_netif_lwip_slip_input, - } + .lwip = { + .init_fn = esp_slipif_init, + .input_fn = esp_netif_lwip_slip_input, + } }; const esp_netif_netstack_config_t *netstack_default_slip = &s_netif_config_slip; diff --git a/examples/esp_netif/slip_custom_netif/main/slip_client_main.c b/examples/esp_netif/slip_custom_netif/main/slip_client_main.c index 82188556c..cdfa37fdf 100644 --- a/examples/esp_netif/slip_custom_netif/main/slip_client_main.c +++ b/examples/esp_netif/slip_custom_netif/main/slip_client_main.c @@ -1,10 +1,11 @@ -/* SLIP Client Example +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. +/* + * SLIP Client Example */ #include #include @@ -168,7 +169,7 @@ static bool slip_rx_filter(slip_modem_handle slip, uint8_t *data, uint32_t len) #if CONFIG_EXAMPLE_IPV4 static const esp_netif_ip_info_t s_slip_ip4 = { - .ip = { .addr = ESP_IP4TOADDR( 10, 0, 0, 2) }, + .ip = { .addr = ESP_IP4TOADDR( 10, 0, 0, 2) }, }; #endif @@ -179,11 +180,12 @@ esp_netif_t *slip_if_init(void) esp_netif_inherent_config_t base_cfg = ESP_NETIF_INHERENT_DEFAULT_SLIP() #if CONFIG_EXAMPLE_IPV4 - base_cfg.ip_info = &s_slip_ip4; + base_cfg.ip_info = &s_slip_ip4; #endif esp_netif_config_t cfg = { .base = &base_cfg, .driver = NULL, - .stack = netstack_default_slip }; + .stack = netstack_default_slip + }; esp_netif_t *slip_netif = esp_netif_new(&cfg); @@ -229,7 +231,7 @@ void app_main(void) ESP_ERROR_CHECK(esp_event_loop_create_default()); // Setup slip interface - esp_netif_t* esp_netif = slip_if_init(); + esp_netif_t *esp_netif = slip_if_init(); assert(esp_netif); // Start the UDP user application