diff --git a/.github/workflows/lws_build.yml b/.github/workflows/lws_build.yml new file mode 100644 index 0000000000..87be76073a --- /dev/null +++ b/.github/workflows/lws_build.yml @@ -0,0 +1,42 @@ +name: "lws: build-tests" + +on: + push: + branches: + - master + pull_request: + types: [opened, synchronize, reopened, labeled] + +jobs: + build_lws: + if: contains(github.event.pull_request.labels.*.name, 'libwebsockets') || github.event_name == 'push' + name: Libwebsockets build + strategy: + matrix: + idf_ver: ["latest", "release-v5.3"] + runs-on: ubuntu-22.04 + container: espressif/idf:${{ matrix.idf_ver }} + env: + TEST_DIR: components/libwebsockets/examples/client-echo + TARGET_TEST_DIR: build_esp32_default + steps: + - name: Checkout esp-protocols + uses: actions/checkout@v4 + with: + submodules: recursive + - name: Build with IDF-${{ matrix.idf_ver }} + shell: bash + run: | + . ${IDF_PATH}/export.sh + pip install idf-component-manager idf-build-apps --upgrade + python ci/build_apps.py ${TEST_DIR} + cd ${TEST_DIR} + ${GITHUB_WORKSPACE}/ci/clean_build_artifacts.sh `pwd`/${TARGET_TEST_DIR} + zip -qur artifacts.zip ${TARGET_TEST_DIR} + - uses: actions/upload-artifact@v4 + with: + name: lws_target_esp32_${{ matrix.idf_ver }} + path: ${{ env.TEST_DIR }}/artifacts.zip + if-no-files-found: error + + #TODO: add test_lws diff --git a/.github/workflows/publish-docs-component.yml b/.github/workflows/publish-docs-component.yml index c364a0bf0d..601c3700d5 100644 --- a/.github/workflows/publish-docs-component.yml +++ b/.github/workflows/publish-docs-component.yml @@ -102,5 +102,6 @@ jobs: components/mbedtls_cxx; components/mosquitto; components/sock_utils; + components/libwebsockets; namespace: "espressif" api_token: ${{ secrets.IDF_COMPONENT_API_TOKEN }} diff --git a/.gitmodules b/.gitmodules index 60b3730713..c6c9187ddc 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "components/mosquitto/mosquitto"] path = components/mosquitto/mosquitto url = https://github.com/eclipse/mosquitto +[submodule "components/libwebsockets/libwebsockets"] + path = components/libwebsockets/libwebsockets + url = https://github.com/warmcat/libwebsockets.git diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2b7af80bff..cd1b0ceb7e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -61,8 +61,8 @@ repos: - repo: local hooks: - id: commit message scopes - name: "commit message must be scoped with: mdns, modem, websocket, asio, mqtt_cxx, console, common, eppp, tls_cxx, mosq, sockutls" - entry: '\A(?!(feat|fix|ci|bump|test|docs|chore)\((mdns|modem|common|console|websocket|asio|mqtt_cxx|examples|eppp|tls_cxx|mosq|sockutls)\)\:)' + name: "commit message must be scoped with: mdns, modem, websocket, asio, mqtt_cxx, console, common, eppp, tls_cxx, mosq, sockutls, lws" + entry: '\A(?!(feat|fix|ci|bump|test|docs|chore)\((mdns|modem|common|console|websocket|asio|mqtt_cxx|examples|eppp|tls_cxx|mosq|sockutls|lws)\)\:)' language: pygrep args: [--multiline] stages: [commit-msg] diff --git a/README.md b/README.md index 3962546f0b..e8e6ec398d 100644 --- a/README.md +++ b/README.md @@ -66,3 +66,7 @@ Please refer to instructions in [ESP-IDF](https://github.com/espressif/esp-idf) ### Socket helpers (sock-utils) * Brief introduction [README](components/sock_utils/README.md) + +### libwebsockets + +* Brief introduction [README](components/libwebsockets/README.md) diff --git a/components/libwebsockets/CHANGELOG.md b/components/libwebsockets/CHANGELOG.md new file mode 100644 index 0000000000..bc4f19c4bb --- /dev/null +++ b/components/libwebsockets/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## [0.1.0](https://github.com/espressif/esp-protocols/commits/libwebsockets-v0.1.0) + +### Features + +- Add initial support for libwebsockets ([8be3c11]((https://github.com/espressif/esp-protocols/commit/8be3c11)) diff --git a/components/libwebsockets/CMakeLists.txt b/components/libwebsockets/CMakeLists.txt new file mode 100644 index 0000000000..5ea32420ae --- /dev/null +++ b/components/libwebsockets/CMakeLists.txt @@ -0,0 +1,24 @@ +idf_component_register() + +option(LWS_WITH_EXPORT_LWSTARGETS "Export libwebsockets CMake targets. Disable if they conflict with an outer cmake project." OFF) +set(LWS_WITH_EXPORT_LWSTARGETS OFF) + +option(LWS_PLAT_FREERTOS "Build for FreeRTOS" ON) +set(LWS_PLAT_FREERTOS ON) + +option(LWS_WITH_MBEDTLS "Build for FreeRTOS" ON) +set(LWS_WITH_MBEDTLS ON) + +set(WRAP_FUNCTIONS mbedtls_ssl_handshake_step + lws_adopt_descriptor_vhost) + +foreach(wrap ${WRAP_FUNCTIONS}) + target_link_libraries(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=${wrap}") +endforeach() + +target_link_libraries(${COMPONENT_LIB} INTERFACE websockets) + +target_sources(${COMPONENT_LIB} INTERFACE "port/lws_port.c") + + +add_subdirectory(libwebsockets) diff --git a/components/libwebsockets/LICENSE b/components/libwebsockets/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/components/libwebsockets/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/components/libwebsockets/README.md b/components/libwebsockets/README.md new file mode 100644 index 0000000000..108e4e8be0 --- /dev/null +++ b/components/libwebsockets/README.md @@ -0,0 +1,35 @@ +# ESP32 libwebsockets Port + +This is a lightweight port of the libwebsockets library designed to run on the ESP32. It provides WebSocket client and server functionalities. + +## Supported Options + +The ESP32 port of libwebsockets supports a set of common WebSocket configurations, including both server and client modes. These options can be configured through a structure passed to the `lws_create_context()` function. + +Key features supported: +- WebSocket server with optional SSL/TLS +- WebSocket client support +- HTTP/1.1 server and client support + +## Mandatory Use of mbedTLS + +For secure WebSocket communication (WSS) and SSL/TLS support, **mbedTLS** is mandatory. mbedTLS provides the cryptographic functions required for establishing secure connections and is included as part of the ESP32 toolchain. + +- **mbedTLS** is required for all encrypted WebSocket (WSS) and HTTPS connections. +- Ensure that mbedTLS is properly configured in your ESP32 project, as it is essential for enabling SSL/TLS functionality. + +## Memory Footprint Considerations + +libwebsockets on the ESP32 has been optimized for minimal memory usage. The memory consumption primarily depends on the number of concurrent connections and the selected options for WebSocket frames, protocol handling, and SSL/TLS features. + +- **Initial Memory Usage**: TBD +- **Per Client Memory Usage**: TBD +- **Per Server Memory Usage**: TBD + +### Memory Management Tips: +- When configuring a WebSocket server, ensure that you have enough heap space to handle the desired number of concurrent client connections. +- SSL/TLS configurations may require additional memory overhead, depending on the certificate size and cryptographic settings. + +## Testing + +TBD diff --git a/components/libwebsockets/examples/client-echo/CMakeLists.txt b/components/libwebsockets/examples/client-echo/CMakeLists.txt new file mode 100644 index 0000000000..c4af04bfde --- /dev/null +++ b/components/libwebsockets/examples/client-echo/CMakeLists.txt @@ -0,0 +1,6 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(client_echo_example) diff --git a/components/libwebsockets/examples/client-echo/README.md b/components/libwebsockets/examples/client-echo/README.md new file mode 100644 index 0000000000..4d475bebaa --- /dev/null +++ b/components/libwebsockets/examples/client-echo/README.md @@ -0,0 +1,67 @@ +# Websocket LWS client example + +This example will shows how to set up and communicate over a websocket. + +## How to Use Example + +### Hardware Required + +This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet or a local server. + +### Configure the project + +* Open the project configuration menu (`idf.py menuconfig`) +* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. +* Configure the websocket endpoint URI under "Example Configuration" + +### Server Certificate Verification + + +### Generating a self signed Certificates with OpenSSL + + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +idf.py -p PORT flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output + + +## Python Flask echo server + +By default, the `ws://echo.websocket.events` endpoint is used. You can setup a Python websocket echo server locally and try the `ws://:5000` endpoint. To do this, install Flask-sock Python package + +``` +pip install flask-sock +``` + +and start a Flask websocket echo server locally by executing the following Python code: + +```python +from flask import Flask +from flask_sock import Sock + +app = Flask(__name__) +sock = Sock(app) + + +@sock.route('/') +def echo(ws): + while True: + data = ws.receive() + ws.send(data) + + +if __name__ == '__main__': + # To run your Flask + WebSocket server in production you can use Gunicorn: + # 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/libwebsockets/examples/client-echo/main/CMakeLists.txt b/components/libwebsockets/examples/client-echo/main/CMakeLists.txt new file mode 100644 index 0000000000..a0ada8f0dd --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/CMakeLists.txt @@ -0,0 +1,12 @@ +set(SRC_FILES "lws-client-echo.c") # Define source files +set(INCLUDE_DIRS ".") # Define include directories +set(EMBED_FILES "") # Initialize an empty list for files to embed + +list(APPEND EMBED_FILES + "certs/client_cert.pem" + "certs/ca_cert.pem" + "certs/client_key.pem") + +idf_component_register(SRCS "${SRC_FILES}" + INCLUDE_DIRS "${INCLUDE_DIRS}" + EMBED_TXTFILES "${EMBED_FILES}") diff --git a/components/libwebsockets/examples/client-echo/main/Kconfig.projbuild b/components/libwebsockets/examples/client-echo/main/Kconfig.projbuild new file mode 100644 index 0000000000..0f4c451bee --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/Kconfig.projbuild @@ -0,0 +1,33 @@ +menu "Example Configuration" + + config WEBSOCKET_URI + string "Websocket endpoint URI" + default "" + help + URL or IP of websocket endpoint this example connects to and sends echo + config WEBSOCKET_PORT + int "Websocket endpoint PORT" + default 80 + help + Port of websocket endpoint this example connects to and sends echo + + config WS_OVER_TLS_SERVER_AUTH + bool "Enable WebSocket over TLS with Server Certificate Verification Only" + default y + help + Enables WebSocket connections over TLS (WSS) with server certificate verification. + This setting mandates the client to verify the servers certificate, while the server + does not require client certificate verification. + + config WS_OVER_TLS_MUTUAL_AUTH + bool "Enable WebSocket over TLS with Server Client Mutual Authentification" + default n + help + Enables WebSocket connections over TLS (WSS) with server and client mutual certificate verification. + + config WS_OVER_TLS_SKIP_COMMON_NAME_CHECK + bool "Skip common name(CN) check during TLS authentification" + default y + help + Skipping Common Name(CN) check during TLS(WSS) authentification +endmenu diff --git a/components/libwebsockets/examples/client-echo/main/certs/ca_cert.pem b/components/libwebsockets/examples/client-echo/main/certs/ca_cert.pem new file mode 100644 index 0000000000..e9a27099b9 --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/certs/ca_cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIUL04QhbSEt5oNbV4f7CeLLqTCw2gwDQYJKoZIhvcNAQEL +BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAyMjMwODA2MjVaFw0zNDAy +MjAwODA2MjVaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw +HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDjc78SuXAmJeBc0el2/m+2lwtk3J/VrNxHYkhjHa8K +/ybU89VvKGuv9+L3IP67WMguFTaMgivJYUePjfMchtNJLJ+4cR9BkBKH4JnyXDae +s0a5181LxRo8rqcaOw9hmJTgt9R4dIRTR3GN2/VLhlR+L9OTYA54RUtMyMMpyk5M +YIJbcOwiwkVLsIYnexXDfgz9vQGl/2vBQ/RBtDBvbSyBiWox9SuzOrya1HUBzJkM +Iu5L0bSa0LAeXHT3i3P1Y4WPt9ub70OhUNfJtHC+XbGFSEkkQG+lfbXU75XLoMWa +iATMREOcb3Mq+pn1G8o1ZHVc6lBHUkfrNfxs5P/GQcSvAgMBAAGjUzBRMB0GA1Ud +DgQWBBQGkdK2gR2HrQTnZnbuWO7I1+wdxDAfBgNVHSMEGDAWgBQGkdK2gR2HrQTn +ZnbuWO7I1+wdxDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBx +G0hFtMwV/agIwC3ZaYC36ZWiijFzWkJSZG+fqAy32mSoVL2uQvOT8vEfF0ZnAcPc +JI4oI059dBhAVlwqv6uLHyD4Gf2bF4oSLljdTz3X23llF+/wrTC2LLqMrm09aUC0 +ac74Q0FVwVJJcqH1HgemCMVjna5MkwNA6B+q7uR3eQ692VqXk6vjd4fRLBg1bBO1 +hXjasfNxA8A9quORF5+rjYrwyUZHuzcs0FfSClckIt4tHKtt4moLufOW6/PM4fRe +AgdDfiTupxYLJFz4hFPhfgCh4TjQ+f9+uP4IAjW42dJmTVZjLEku/hm5lxCFObAq +RgfaNwH8Ug1r1xswjSZG +-----END CERTIFICATE----- diff --git a/components/libwebsockets/examples/client-echo/main/certs/client_cert.pem b/components/libwebsockets/examples/client-echo/main/certs/client_cert.pem new file mode 100644 index 0000000000..e99921a3c4 --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/certs/client_cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDWjCCAkKgAwIBAgIUUPCOgMA2v09E29fCkogx3RUBRtEwDQYJKoZIhvcNAQEL +BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAyMjMwODA3MzFaFw0zNDAy +MjAwODA3MzFaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw +HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCrNeomxI2aoP+4iUy5SiA+41oHUDZDFeJOBjv5JCsK +mlvFqxE9zynmPOVpuABErOJwzerPTa4NYKvuvs5CxVJUV5CXtWANuu9majioZNzj +f877MDNX/GnZHK2gnkxVrZCPaDmx9yiMsFMXgmfdrDhwoUpXbdgSyeU/al9Ds2kF +0hrHOH2LBWt/mVeLbONU5CC1HOdVVw+uRlhVlxnfhTPd/Nru3rJx7R0sN7qXcZpJ +PL87WvrszLVOux24DeaOz9oiD2b7egFyUuq1BM25iCwi8s/Ths8xd0Ca1d8mEcHW +FVd4w2+nUMXFE+IbP+wo6FXuiSaOBNri3rztpvCCMaWjAgMBAAGjQjBAMB0GA1Ud +DgQWBBSOlA+9Vfbcfy8iS4HSd4V0KPtm4jAfBgNVHSMEGDAWgBQGkdK2gR2HrQTn +ZnbuWO7I1+wdxDANBgkqhkiG9w0BAQsFAAOCAQEAOmzm/MwowKTrSpMSrmfA3MmW +ULzsfa25WyAoTl90ATlg4653Y7pRaNfdvVvyi2V2LlPcmc7E0rfD53t1NxjDH1uM +LgFMTNEaZ9nMRSW0kMiwaRpvmXS8Eb9PXfvIM/Mw0co/aMOtAQnfTGIqsgkQwKyk +1GG7QKQq3p4QGu5ZaTnjnaoa79hODt+0xQDD1wp6C9xwBY0M4gndAi3wkOeFkGv+ +OmGPtaCBu5V9tJCZ9dfZvjkaK44NGwDw0urAcYRK2h7asnlflu7cnlGMBB0qY4kQ +BX5WI8UjN6rECBHbtNRvEh06ogDdHbxYV+TibrqkkeDRw6HX1qqiEJ+iCgWEDQ== +-----END CERTIFICATE----- diff --git a/components/libwebsockets/examples/client-echo/main/certs/client_key.pem b/components/libwebsockets/examples/client-echo/main/certs/client_key.pem new file mode 100644 index 0000000000..68dcc7af61 --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/certs/client_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCrNeomxI2aoP+4 +iUy5SiA+41oHUDZDFeJOBjv5JCsKmlvFqxE9zynmPOVpuABErOJwzerPTa4NYKvu +vs5CxVJUV5CXtWANuu9majioZNzjf877MDNX/GnZHK2gnkxVrZCPaDmx9yiMsFMX +gmfdrDhwoUpXbdgSyeU/al9Ds2kF0hrHOH2LBWt/mVeLbONU5CC1HOdVVw+uRlhV +lxnfhTPd/Nru3rJx7R0sN7qXcZpJPL87WvrszLVOux24DeaOz9oiD2b7egFyUuq1 +BM25iCwi8s/Ths8xd0Ca1d8mEcHWFVd4w2+nUMXFE+IbP+wo6FXuiSaOBNri3rzt +pvCCMaWjAgMBAAECggEAOTWjz16AXroLmRMv8v5E9h6sN6Ni7lnCrAXDRoYCZ+Ga +Ztu5wCiYPJn+oqvcUxZd+Ammu6yeS1QRP468h20+DHbSFw+BUDU1x8gYtJQ3h0Fu +3VqG3ZC3odfGYNRkd4CuvGy8Uq5e+1vz9/gYUuc4WNJccAiBWg3ir6UQviOWJV46 +LGfdEd9hVvIGl5pmArMBVYdpj9+JHunDtG4uQxiWla5pdLjlkC2mGexD18T9d718 +6I+o3YHv1Y9RPT1d4rNhYQWx6YdTTD2rmS7nTrzroj/4fXsblpXzR+/l7crlNERY +67RMPwgDR1NiAbCAJKsSbMS66lRCNlhTM4YffGAN6QKBgQDkIdcNm9j49SK5Wbl5 +j8U6UbcVYPzPG+2ea+fDfUIafA0VQHIuX6FgA17Kp7BDX9ldKtSBpr0Z8vetVswr +agmXVMR/7QdvnZ9NpL66YA/BRs67CvsryVu4AVAzThFGySmlcXGlPq47doWDQ3B9 +0BOEnVoeDXR3SabaNsEbhDYn1wKBgQDAIAUyhJcgz+LcgaAtBwdnEN57y66JlRVZ +bsb6cEG/MNmnLjQYsplJjNbz4yrB5ukTChPTGRF/JQRqHoXh6DGQFHvobukwwA6x +RAIIq0NLJ5HUipfOi+VpCbWUHdoUNhwjAB2qVtD4LXE2Lyn46C8ET5eRtRjUKpzV +lpsq63KHFQKBgFB+cDbpCoGtXPcxZXQy+lA9jPAKLKmXHRyMzlX32F8n7iXVe3RJ +YdNS3Rt8V4EuTK/G8PxeLNL/G80ZlyiqXX/79Ol+ZOVJJHBs9K8mPejgZwkwMrec +cLRYIkg3/3iOehdaE9NOboOkqi9KmGKMDJb6PlXkQXflkO3l6/UdjU45AoGAen0v +sxiTncjMU1eVfn+nuY8ouXaPbYoOFXmqBItDb5i+e3baohBj6F+Rv+ZKIVuNp6Ta +JNErtYstOFcDdpbp2nkk0ni71WftNhkszsgZ3DV7JS3DQV0xwvj8ulUZ757b63is +cShujHu0XR5OvTGSoEX6VVxHWyVb3lTp0sBPwU0CgYBe2Ieuya0X8mAbputFN64S +Kv++dqktTUT8i+tp07sIrpDeYwO3D89x9kVSJj4ImlmhiBVGkxFWPkpGyBLotdse +Ai/E6f5I7CDSZZC0ZucgcItNd4Yy459QY+dFwFtT3kIaD9ml8fnqQ83J9W8DWtv9 +6mY9FnUUufbJcpHxN58RTw== +-----END PRIVATE KEY----- diff --git a/components/libwebsockets/examples/client-echo/main/idf_component.yml b/components/libwebsockets/examples/client-echo/main/idf_component.yml new file mode 100644 index 0000000000..959a1dfb33 --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/idf_component.yml @@ -0,0 +1,6 @@ +dependencies: + espressif/libwebsockets: + version: "*" + override_path: "../../../" + protocol_examples_common: + path: ${IDF_PATH}/examples/common_components/protocol_examples_common diff --git a/components/libwebsockets/examples/client-echo/main/lws-client-echo.c b/components/libwebsockets/examples/client-echo/main/lws-client-echo.c new file mode 100644 index 0000000000..41913bd63a --- /dev/null +++ b/components/libwebsockets/examples/client-echo/main/lws-client-echo.c @@ -0,0 +1,213 @@ +/* + * SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +/* ESP libwebsockets client 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. +*/ + +#include +#include +#include + +#include "esp_wifi.h" +#include "esp_system.h" +#include "nvs_flash.h" +#include "protocol_examples_common.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include "esp_log.h" +#include "esp_task_wdt.h" + +static uint32_t message_delay = 2000000; // microseconds +static uint8_t message_count = 0; +static const char *TAG = "lws-client-echo"; + +static struct lws_context *context; +static struct lws *client_wsi; + +static lws_sorted_usec_list_t sul; +static unsigned char msg[LWS_PRE + 128]; + +static const lws_retry_bo_t retry = { + .secs_since_valid_ping = 3, + .secs_since_valid_hangup = 10, +}; + +static void connect_cb(lws_sorted_usec_list_t *_sul) +{ + struct lws_client_connect_info i; + + ESP_LOGI(TAG, "%s: connecting\n", __func__); + + memset(&i, 0, sizeof(i)); + + i.context = context; + i.port = CONFIG_WEBSOCKET_PORT; + i.address = CONFIG_WEBSOCKET_URI; + i.host = i.address; + i.origin = i.address; + i.local_protocol_name = "lws-echo"; + i.pwsi = &client_wsi; + i.retry_and_idle_policy = &retry; + +#if defined(CONFIG_WS_OVER_TLS_MUTUAL_AUTH) || defined(CONFIG_WS_OVER_TLS_SERVER_AUTH) + i.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED; +#if CONFIG_WS_OVER_TLS_SKIP_COMMON_NAME_CHECK + i.ssl_connection |= LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK; +#endif +#else + i.ssl_connection = LCCSCF_ALLOW_INSECURE; +#endif + + if (!lws_client_connect_via_info(&i)) { + lws_sul_schedule(context, 0, _sul, connect_cb, 5 * LWS_USEC_PER_SEC); + } +} + +static int callback_minimal_echo(struct lws *wsi, enum lws_callback_reasons reason, + void *user, void *in, size_t len) +{ + switch (reason) { + + case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: + ESP_LOGE(TAG, "CLIENT_CONNECTION_ERROR: %s\n", + in ? (char *)in : "(null)"); + lws_sul_schedule(context, 0, &sul, connect_cb, 5 * LWS_USEC_PER_SEC); + break; + + case LWS_CALLBACK_CLIENT_ESTABLISHED: + lws_callback_on_writable(wsi); + ESP_LOGI(TAG, "%s: established connection, wsi = %p\n", + __func__, wsi); + break; + case LWS_CALLBACK_CLIENT_WRITEABLE: + + if (message_count >= 9) { + message_count = 0; + } else { + message_count++; + } + + itoa(message_count, (char *)&msg[LWS_PRE], 10); + ESP_LOGI(TAG, "TX -> %u", message_count); + + (void)lws_write(wsi, msg + LWS_PRE, 3, LWS_WRITE_TEXT); + + break; + case LWS_CALLBACK_CLIENT_RECEIVE: + ESP_LOGI(TAG, "RX <- %c", *(char *)in); + + /* Schedule the timer after minimum message delay */ + lws_set_timer_usecs(wsi, message_delay); + break; + case LWS_CALLBACK_TIMER: + // Let the main loop know we want to send another message to the + // server + lws_callback_on_writable(wsi); + break; + default: + break; + } + + return lws_callback_http_dummy(wsi, reason, user, in, len); +} + +static const struct lws_protocols protocols[] = { + { + "lws-echo", + callback_minimal_echo, + 4096, 4096, 0, NULL, 0 + }, + LWS_PROTOCOL_LIST_TERM +}; + +int app_main(int argc, const char **argv) +{ + ESP_LOGI(TAG, "[APP] Startup.."); + ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size()); + ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); + esp_log_level_set("*", ESP_LOG_INFO); + + ESP_ERROR_CHECK(nvs_flash_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. + * Read "Establishing Wi-Fi or Ethernet Connection" section in + * examples/protocols/README.md for more information about this function. + */ + ESP_ERROR_CHECK(example_connect()); + + /* Configure WDT. */ + esp_task_wdt_config_t esp_task_wdt_config = { + .idle_core_mask = 0, + .timeout_ms = portMAX_DELAY, + .trigger_panic = false + }; + esp_task_wdt_reconfigure(&esp_task_wdt_config); + + TaskHandle_t handle = xTaskGetCurrentTaskHandle(); + esp_task_wdt_add(handle); + + /* Create LWS Context - Client. */ + struct lws_context_creation_info info; + int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE; + + memset(msg, 'x', sizeof(msg)); + + lws_set_log_level(logs, NULL); + ESP_LOGI(TAG, "LWS minimal ws client echo\n"); + + memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */ + info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */ + info.protocols = protocols; + info.fd_limit_per_thread = 1 + 1 + 1; + +#if CONFIG_WS_OVER_TLS_MUTUAL_AUTH + info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; + + /* Configuring client certificates for mutual authentification */ + extern const char cert_start[] asm("_binary_client_cert_pem_start"); // Client certificate + extern const char cert_end[] asm("_binary_client_cert_pem_end"); + extern const char key_start[] asm("_binary_client_key_pem_start"); // Client private key + extern const char key_end[] asm("_binary_client_key_pem_end"); + + info.client_ssl_cert_mem = cert_start; + info.client_ssl_cert_mem_len = cert_end - cert_start; + info.client_ssl_key_mem = key_start; + info.client_ssl_key_mem_len = key_end - key_start; +#elif CONFIG_WS_OVER_TLS_SERVER_AUTH + info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; + + extern const char cacert_start[] asm("_binary_ca_cert_pem_start"); // CA certificate + extern const char cacert_end[] asm("_binary_ca_cert_pem_end"); + + info.client_ssl_ca_mem = cacert_start; + info.client_ssl_ca_mem_len = cacert_end - cacert_start; +#endif + + context = lws_create_context(&info); + if (!context) { + ESP_LOGE(TAG, "lws init failed\n"); + return 1; + } + + lws_sul_schedule(context, 0, &sul, connect_cb, 100); + + while (n >= 0) { + n = lws_service(context, 0); + } + + lws_context_destroy(context); + + return 0; +} diff --git a/components/libwebsockets/examples/client-echo/partitions.csv b/components/libwebsockets/examples/client-echo/partitions.csv new file mode 100644 index 0000000000..20532cfaa2 --- /dev/null +++ b/components/libwebsockets/examples/client-echo/partitions.csv @@ -0,0 +1,8 @@ +# ESP-IDF Partition Table +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x4000, +otadata, data, ota, 0xd000, 0x2000, +phy_init, data, phy, 0xf000, 0x1000, +ota_0, app, ota_0, 0x10000, 0x1f0000 +ota_1, app, ota_1, , 0x1f0000 +nvs_key, data, nvs_keys, , 0x1000 diff --git a/components/libwebsockets/examples/server-echo/CMakeLists.txt b/components/libwebsockets/examples/server-echo/CMakeLists.txt new file mode 100644 index 0000000000..d0895e11af --- /dev/null +++ b/components/libwebsockets/examples/server-echo/CMakeLists.txt @@ -0,0 +1,7 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) +set(requirements 1) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(server_echo_example) diff --git a/components/libwebsockets/examples/server-echo/README.md b/components/libwebsockets/examples/server-echo/README.md new file mode 100644 index 0000000000..5655d82b41 --- /dev/null +++ b/components/libwebsockets/examples/server-echo/README.md @@ -0,0 +1,66 @@ +# Websocket LWS server example + +This example will shows how to set up and communicate over a websocket. + +## How to Use Example + +### Hardware Required + +This example can be executed on any ESP32 board, the only required interface is WiFi and connection to internet or a local server. + +### Configure the project + +* Open the project configuration menu (`idf.py menuconfig`) +* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. + +### Server Certificate Verification + + +### Generating a self signed Certificates with OpenSSL + + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +idf.py -p PORT flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output + + +## Python Flask echo server + +By default, the `ws://echo.websocket.events` endpoint is used. You can setup a Python websocket echo server locally and try the `ws://:5000` endpoint. To do this, install Flask-sock Python package + +``` +pip install flask-sock +``` + +and start a Flask websocket echo server locally by executing the following Python code: + +```python +from flask import Flask +from flask_sock import Sock + +app = Flask(__name__) +sock = Sock(app) + + +@sock.route('/') +def echo(ws): + while True: + data = ws.receive() + ws.send(data) + + +if __name__ == '__main__': + # To run your Flask + WebSocket server in production you can use Gunicorn: + # 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/libwebsockets/examples/server-echo/main/CMakeLists.txt b/components/libwebsockets/examples/server-echo/main/CMakeLists.txt new file mode 100644 index 0000000000..fb34250123 --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/CMakeLists.txt @@ -0,0 +1,12 @@ +set(SRC_FILES "lws-server-echo.c") # Initialize SRC_FILES as an empty list +set(INCLUDE_DIRS ".") # Define include directories +set(EMBED_FILES) # Initialize EMBED_FILES as an empty list + +list(APPEND EMBED_FILES + "certs/server_cert.pem" + "certs/ca_cert.pem" + "certs/server_key.pem") + +idf_component_register(SRCS "${SRC_FILES}" + INCLUDE_DIRS "${INCLUDE_DIRS}" + EMBED_TXTFILES "${EMBED_FILES}") diff --git a/components/libwebsockets/examples/server-echo/main/Kconfig.projbuild b/components/libwebsockets/examples/server-echo/main/Kconfig.projbuild new file mode 100644 index 0000000000..decb720bfc --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/Kconfig.projbuild @@ -0,0 +1,12 @@ +menu "Example Configuration" + config WEBSOCKET_PORT + int "Websocket endpoint PORT" + default 80 + help + Port of websocket endpoint this example connects to and sends echo + config WS_OVER_TLS + bool "Enable WebSocket over TLS with Server Certificate" + default y + help + Enables WebSocket connections over TLS (WSS) +endmenu diff --git a/components/libwebsockets/examples/server-echo/main/certs/ca_cert.pem b/components/libwebsockets/examples/server-echo/main/certs/ca_cert.pem new file mode 100644 index 0000000000..e9a27099b9 --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/certs/ca_cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIUL04QhbSEt5oNbV4f7CeLLqTCw2gwDQYJKoZIhvcNAQEL +BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAyMjMwODA2MjVaFw0zNDAy +MjAwODA2MjVaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw +HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDjc78SuXAmJeBc0el2/m+2lwtk3J/VrNxHYkhjHa8K +/ybU89VvKGuv9+L3IP67WMguFTaMgivJYUePjfMchtNJLJ+4cR9BkBKH4JnyXDae +s0a5181LxRo8rqcaOw9hmJTgt9R4dIRTR3GN2/VLhlR+L9OTYA54RUtMyMMpyk5M +YIJbcOwiwkVLsIYnexXDfgz9vQGl/2vBQ/RBtDBvbSyBiWox9SuzOrya1HUBzJkM +Iu5L0bSa0LAeXHT3i3P1Y4WPt9ub70OhUNfJtHC+XbGFSEkkQG+lfbXU75XLoMWa +iATMREOcb3Mq+pn1G8o1ZHVc6lBHUkfrNfxs5P/GQcSvAgMBAAGjUzBRMB0GA1Ud +DgQWBBQGkdK2gR2HrQTnZnbuWO7I1+wdxDAfBgNVHSMEGDAWgBQGkdK2gR2HrQTn +ZnbuWO7I1+wdxDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBx +G0hFtMwV/agIwC3ZaYC36ZWiijFzWkJSZG+fqAy32mSoVL2uQvOT8vEfF0ZnAcPc +JI4oI059dBhAVlwqv6uLHyD4Gf2bF4oSLljdTz3X23llF+/wrTC2LLqMrm09aUC0 +ac74Q0FVwVJJcqH1HgemCMVjna5MkwNA6B+q7uR3eQ692VqXk6vjd4fRLBg1bBO1 +hXjasfNxA8A9quORF5+rjYrwyUZHuzcs0FfSClckIt4tHKtt4moLufOW6/PM4fRe +AgdDfiTupxYLJFz4hFPhfgCh4TjQ+f9+uP4IAjW42dJmTVZjLEku/hm5lxCFObAq +RgfaNwH8Ug1r1xswjSZG +-----END CERTIFICATE----- diff --git a/components/libwebsockets/examples/server-echo/main/certs/server_cert.pem b/components/libwebsockets/examples/server-echo/main/certs/server_cert.pem new file mode 100644 index 0000000000..cb1e9dfe74 --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/certs/server_cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDWjCCAkKgAwIBAgIUUPCOgMA2v09E29fCkogx3RUBRtAwDQYJKoZIhvcNAQEL +BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAyMjMwODA2NTlaFw0zNDAy +MjAwODA2NTlaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw +HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQC8WWbDxnLzTSfuQaO+kQnnzbwjhUHWn58s+BIEaO8M +GG6bX+8r/SH9XjMfFS36qAN3qxgRun3YoRTaHc2QByiGjf5IL4EAPDnLN+NzUIL5 +7Gi2QPQP/GksAsOGKWk/nMRPk1vcMptkFVIWSp474SQ0A92Z9z0dUIqBpjRa34kr +HsAIcT59/EG7YBBadMk0fQIxQVLh3Vosky85q+0waFihe47Ef5U2UftexoUx4Vcz +6EtP60Wx+4qN+FLsr+n2B7Oz2ITqfwgqLzjNLZwm9bMjcLZ0fWm1A/W1C989MXwI +w6DAPEZv7pbgp8r9phyrNieSDuuRaCvFsaXh6troAjLxAgMBAAGjQjBAMB0GA1Ud +DgQWBBRJCYAQG2+1FN5P/wyAR1AsrAyb4DAfBgNVHSMEGDAWgBQGkdK2gR2HrQTn +ZnbuWO7I1+wdxDANBgkqhkiG9w0BAQsFAAOCAQEAmllul/GIH7RVq85mM/SxP47J +M7Z7T032KuR3n/Psyv2iq/uEV2CUje3XrKNwR2PaJL4Q6CtoWy7xgIP+9CBbjddR +M7sdNQab8P2crAUtBKnkNOl/na/5KnXnjwi/PmWJJ9i2Cqt0PPkaykTWp/MLfYIw +RPkY2Yo8f8gEiqXQd+0qTuMgumbgkPq3V8Lk1ocy62F5/qUhXxH+ifAXEoUQS6EG +8DlgwdZlfUY+jeM6N56WzYmxD1syjNW7faPio+qXINfpYatROhqphaMQ5SA6TRj6 +jcnLa31TdDdWmWYDcYgZntAv6yGi3rh0MdYqeNS0FKlMKmaH81VHs7V1UUXwUQ== +-----END CERTIFICATE----- diff --git a/components/libwebsockets/examples/server-echo/main/certs/server_key.pem b/components/libwebsockets/examples/server-echo/main/certs/server_key.pem new file mode 100644 index 0000000000..cf2fdadb7a --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/certs/server_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8WWbDxnLzTSfu +QaO+kQnnzbwjhUHWn58s+BIEaO8MGG6bX+8r/SH9XjMfFS36qAN3qxgRun3YoRTa +Hc2QByiGjf5IL4EAPDnLN+NzUIL57Gi2QPQP/GksAsOGKWk/nMRPk1vcMptkFVIW +Sp474SQ0A92Z9z0dUIqBpjRa34krHsAIcT59/EG7YBBadMk0fQIxQVLh3Vosky85 +q+0waFihe47Ef5U2UftexoUx4Vcz6EtP60Wx+4qN+FLsr+n2B7Oz2ITqfwgqLzjN +LZwm9bMjcLZ0fWm1A/W1C989MXwIw6DAPEZv7pbgp8r9phyrNieSDuuRaCvFsaXh +6troAjLxAgMBAAECggEACNVCggTxCCMCr+RJKxs/NS1LWPkbZNbYjrHVmnpXV6Bf +s460t0HoUasUx6zlGp+9heOyvcYat8maIj6KkOodBu5q0fTUXm/0n+ivlI1ejxz8 +ritupr9GKWe5xrVzd6XA+SBmivWenvt2/Y+jSxica4oQ3vMe3RyVWk4yn15jXu+9 +7B9lNyNeZtOBr6OozHGLYw4dwWcBNv2S6wevRKfHPwn/Ch5yTH1uAskgoMxUuyK2 +ynNVHWUhyS4pFU7Tex5ENDel15VYdbxV/2lQ2W6fHMLtC5GWKJXXbigCX7pfOpzC +BFJEfZl7ze/qptE9AR7DkLFYyMtrS7OlebYbLDOM9wKBgQD+rTdwULZibpKwlI3a +9Y22d4N/EDFvuu8LnuEiVQnXgwg9M+tlaa2liP18j1a7y/FCfoXf5sjUWCsdYR6d +C0TuiOGI59hYGI94NvVLAmOutR+vJ/3jhbv5wyqEQLhJ42Yz9kWBrDCI+V3q3TdO +H7wcH6suUIZpeLEJF4qHzY/1dwKBgQC9U/Pvswiww8sfysmd5shUNo4ofAZnTM1A +ak6pWE3lSyiOkSm+3B2GqxYWLRoo1v+pTyhhXDtRRmxGtMNrKCsmlHef/o3c6kkG +cuC2h/DiSmoITHy3BYKJoDeE54E8ubXUUKqHo41LYUs+D7M/IGxeiO13MUoIrEtF +AwzVWPBU1wKBgH8barD2x6Bm+XWCHy6qIZlxGsMfDN1r2gTdvhWJhcj3D/Sj5heO +X+lfbsxtKee+yOHcDesK3y8D9jjKkSHmTvgSfyX6OML3NxvTqidOwPugUHj2J8QX +qhLk8mJhftj50reacWRf0TV76ADhecnXEuaic6hA7mTTpOAZzL0svm3PAoGBALWF +r6VLX3KzVqZVtLb7FWmAoQ35093pCgXPpznAW3cTd4Axd/fxbTG4CUYb2i/760X2 +ij3Gw2yqe5fTKmYsLisgQA2bb4K28msHa6I2dmNQe5cXVp/X3Y98mJ6JpCSH3ekB +qm7ABfGXCCApx28n9B8zY5JbJKNqJgS15vELA+ojAoGAAkaV2w46+3iQ6gJtQepr +zGNybiYBx/Wo5fDdTS5u0xN+ZdC9fl2Zs0n7sMmUT8bWdDLcMnntHHO+oDIKyRHs +TQh1n68vQ4JoegQv3Z9Z/TLEKqr9gyJC1Ao6M4bZpPhUWQwupfHColtsr2TskcnJ +Nf2FpJZ7z6fQEShGlK1yTXM= +-----END PRIVATE KEY----- diff --git a/components/libwebsockets/examples/server-echo/main/idf_component.yml b/components/libwebsockets/examples/server-echo/main/idf_component.yml new file mode 100644 index 0000000000..959a1dfb33 --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/idf_component.yml @@ -0,0 +1,6 @@ +dependencies: + espressif/libwebsockets: + version: "*" + override_path: "../../../" + protocol_examples_common: + path: ${IDF_PATH}/examples/common_components/protocol_examples_common diff --git a/components/libwebsockets/examples/server-echo/main/lws-server-echo.c b/components/libwebsockets/examples/server-echo/main/lws-server-echo.c new file mode 100644 index 0000000000..657f45794f --- /dev/null +++ b/components/libwebsockets/examples/server-echo/main/lws-server-echo.c @@ -0,0 +1,274 @@ +/* + * SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +/* ESP libwebsockets server 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. +*/ + + +#include +#include + +#include "esp_wifi.h" +#include "esp_system.h" +#include "nvs_flash.h" +#include "protocol_examples_common.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include "esp_log.h" +#include "esp_task_wdt.h" + +#define RING_DEPTH 4096 + +static int callback_minimal_server_echo(struct lws *wsi, enum lws_callback_reasons reason, + void *user, void *in, size_t len); +/* one of these created for each message */ + +struct msg { + void *payload; /* is malloc'd */ + size_t len; +}; + +/* one of these is created for each client connecting to us */ + +struct per_session_data__minimal { + struct per_session_data__minimal *pss_list; + struct lws *wsi; + int last; /* the last message number we sent */ +}; + +/* one of these is created for each vhost our protocol is used with */ + +struct per_vhost_data__minimal { + struct lws_context *context; + struct lws_vhost *vhost; + const struct lws_protocols *protocol; + + struct per_session_data__minimal *pss_list; /* linked-list of live pss*/ + + struct msg amsg; /* the one pending message... */ + int current; /* the current message number we are caching */ +}; + +static struct lws_protocols protocols[] = { + { + .name = "lws-minimal-server-echo", + .callback = callback_minimal_server_echo, + .per_session_data_size = sizeof(struct per_session_data__minimal), + .rx_buffer_size = 128, + .id = 0, + .user = NULL, + .tx_packet_size = 0 + }, + LWS_PROTOCOL_LIST_TERM +}; + +static int options; +static const char *TAG = "lws-server-echo", *iface = ""; + +/* pass pointers to shared vars to the protocol */ +static const struct lws_protocol_vhost_options pvo_options = { + NULL, + NULL, + "options", /* pvo name */ + (void *) &options /* pvo value */ +}; + +static const struct lws_protocol_vhost_options pvo_interrupted = { + &pvo_options, + NULL, + "interrupted", /* pvo name */ + NULL /* pvo value */ +}; + +static const struct lws_protocol_vhost_options pvo = { + NULL, /* "next" pvo linked-list */ + &pvo_interrupted, /* "child" pvo linked-list */ + "lws-minimal-server-echo", /* protocol name we belong to on this vhost */ + "" /* ignored */ +}; + +int app_main(int argc, const char **argv) +{ + ESP_LOGI(TAG, "[APP] Startup.."); + ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size()); + ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); + esp_log_level_set("*", ESP_LOG_INFO); + + ESP_ERROR_CHECK(nvs_flash_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. + * Read "Establishing Wi-Fi or Ethernet Connection" section in + * examples/protocols/README.md for more information about this function. + */ + ESP_ERROR_CHECK(example_connect()); + + /* Configure WDT. */ + esp_task_wdt_config_t esp_task_wdt_config = { + .idle_core_mask = 0, + .timeout_ms = portMAX_DELAY, + .trigger_panic = false + }; + esp_task_wdt_reconfigure(&esp_task_wdt_config); + + TaskHandle_t handle = xTaskGetCurrentTaskHandle(); + esp_task_wdt_add(handle); + + /* Create LWS Context - Server. */ + struct lws_context_creation_info info; + struct lws_context *context; + int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE; + + lws_set_log_level(logs, NULL); + ESP_LOGI(TAG, "LWS minimal ws server echo\n"); + + memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */ + info.port = CONFIG_WEBSOCKET_PORT; + info.iface = iface; + info.protocols = protocols; + info.pvo = &pvo; + info.pt_serv_buf_size = 64 * 1024; + +#ifdef CONFIG_WS_OVER_TLS + info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE; + + /* Configuring server certificates for mutual authentification */ + extern const char cert_start[] asm("_binary_server_cert_pem_start"); // Server certificate + extern const char cert_end[] asm("_binary_server_cert_pem_end"); + extern const char key_start[] asm("_binary_server_key_pem_start"); // Server private key + extern const char key_end[] asm("_binary_server_key_pem_end"); + extern const char cacert_start[] asm("_binary_ca_cert_pem_start"); // CA certificate + extern const char cacert_end[] asm("_binary_ca_cert_pem_end"); + + info.server_ssl_cert_mem = cert_start; + info.server_ssl_cert_mem_len = cert_end - cert_start - 1; + info.server_ssl_private_key_mem = key_start; + info.server_ssl_private_key_mem_len = key_end - key_start - 1; + info.server_ssl_ca_mem = cacert_start; + info.server_ssl_ca_mem_len = cacert_end - cacert_start; +#endif + + context = lws_create_context(&info); + if (!context) { + ESP_LOGE(TAG, "lws init failed\n"); + return 1; + } + + while (n >= 0) { + n = lws_service(context, 0); + } + + lws_context_destroy(context); + + return 1; +} + +static void __minimal_destroy_message(void *_msg) +{ + struct msg *msg = _msg; + + free(msg->payload); + msg->payload = NULL; + msg->len = 0; +} + +static int callback_minimal_server_echo(struct lws *wsi, enum lws_callback_reasons reason, + void *user, void *in, size_t len) +{ + { + struct per_session_data__minimal *pss = + (struct per_session_data__minimal *)user; + struct per_vhost_data__minimal *vhd = + (struct per_vhost_data__minimal *) + lws_protocol_vh_priv_get(lws_get_vhost(wsi), + lws_get_protocol(wsi)); + int m; + + switch (reason) { + case LWS_CALLBACK_PROTOCOL_INIT: + vhd = lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), + lws_get_protocol(wsi), + sizeof(struct per_vhost_data__minimal)); + vhd->context = lws_get_context(wsi); + vhd->protocol = lws_get_protocol(wsi); + vhd->vhost = lws_get_vhost(wsi); + break; + + case LWS_CALLBACK_ESTABLISHED: + /* add ourselves to the list of live pss held in the vhd */ + lws_ll_fwd_insert(pss, pss_list, vhd->pss_list); + pss->wsi = wsi; + pss->last = vhd->current; + break; + + case LWS_CALLBACK_CLOSED: + /* remove our closing pss from the list of live pss */ + lws_ll_fwd_remove(struct per_session_data__minimal, pss_list, + pss, vhd->pss_list); + break; + + case LWS_CALLBACK_SERVER_WRITEABLE: + if (!vhd->amsg.payload) { + break; + } + + if (pss->last == vhd->current) { + break; + } + + /* notice we allowed for LWS_PRE in the payload already */ + m = lws_write(wsi, ((unsigned char *)vhd->amsg.payload) + + LWS_PRE, vhd->amsg.len, LWS_WRITE_TEXT); + if (m < (int)vhd->amsg.len) { + lwsl_err("ERROR %d writing to ws\n", m); + return -1; + } + + pss->last = vhd->current; + break; + + case LWS_CALLBACK_RECEIVE: + if (vhd->amsg.payload) { + __minimal_destroy_message(&vhd->amsg); + } + + vhd->amsg.len = len; + /* notice we over-allocate by LWS_PRE */ + vhd->amsg.payload = malloc(LWS_PRE + len); + if (!vhd->amsg.payload) { + lwsl_user("OOM: dropping\n"); + break; + } + + memcpy((char *)vhd->amsg.payload + LWS_PRE, in, len); + vhd->current++; + + /* + * let everybody know we want to write something on them + * as soon as they are ready + */ + lws_start_foreach_llp(struct per_session_data__minimal **, + ppss, vhd->pss_list) { + lws_callback_on_writable((*ppss)->wsi); + } lws_end_foreach_llp(ppss, pss_list); + break; + + default: + break; + } + + return 0; + } + +} diff --git a/components/libwebsockets/idf_component.yml b/components/libwebsockets/idf_component.yml new file mode 100644 index 0000000000..c6e0bef73d --- /dev/null +++ b/components/libwebsockets/idf_component.yml @@ -0,0 +1,5 @@ +version: "0.1.0" +url: https://github.com/espressif/esp-protocols/tree/master/components/libwebsockets +description: The component provides a simple ESP32 port of libwebsockets server and client. +dependencies: + idf: '>=5.1' diff --git a/components/libwebsockets/libwebsockets b/components/libwebsockets/libwebsockets new file mode 160000 index 0000000000..a74362ffdd --- /dev/null +++ b/components/libwebsockets/libwebsockets @@ -0,0 +1 @@ +Subproject commit a74362ffdd17b7f6293f675edef6d602096a1e29 diff --git a/components/libwebsockets/port/lws_port.c b/components/libwebsockets/port/lws_port.c new file mode 100644 index 0000000000..73ab62a13b --- /dev/null +++ b/components/libwebsockets/port/lws_port.c @@ -0,0 +1,49 @@ +/* + * SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "stdio.h" +#include + +extern int __real_mbedtls_ssl_handshake_step(mbedtls_ssl_context *ssl); +extern int __wrap_mbedtls_ssl_handshake_step(mbedtls_ssl_context *ssl); + +int __wrap_mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) +{ + int ret = 0; + + while (ssl->MBEDTLS_PRIVATE(state) != MBEDTLS_SSL_HANDSHAKE_OVER) { + ret = __real_mbedtls_ssl_handshake_step(ssl); + + if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + continue; + } + + if (ret != 0) { + break; + } + } + + return ret; +} + +extern struct lws *__real_lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, lws_sock_file_fd_type fd, const char *vh_prot_name, struct lws *parent); +extern struct lws *__wrap_lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, lws_sock_file_fd_type fd, const char *vh_prot_name, struct lws *parent); + +struct lws *__wrap_lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, lws_sock_file_fd_type fd, const char *vh_prot_name, struct lws *parent) +{ + lws_adopt_desc_t info; + char nullstr[] = "(null)"; + memset(&info, 0, sizeof(info)); + + info.vh = vh; + info.type = type; + info.fd = fd; + info.vh_prot_name = vh_prot_name; + info.parent = parent; + info.fi_wsi_name = nullstr; + + return lws_adopt_descriptor_vhost_via_info(&info); +} diff --git a/test_app/CMakeLists.txt b/test_app/CMakeLists.txt index bda7a057a9..f2cf76d4be 100644 --- a/test_app/CMakeLists.txt +++ b/test_app/CMakeLists.txt @@ -15,6 +15,7 @@ set(EXTRA_COMPONENT_DIRS ../components/console_simple_init ../components/mbedtls_cxx ../components/sock_utils + ../components/libwebsockets ../components/mdns)