Skip to content

UDP Unicast for Meshtasticd#10656

Open
jp-bennett wants to merge 10 commits into
developfrom
udp-unicast
Open

UDP Unicast for Meshtasticd#10656
jp-bennett wants to merge 10 commits into
developfrom
udp-unicast

Conversation

@jp-bennett

@jp-bennett jp-bennett commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Retreads our UDP multicast support for a unicast endpoint.

Summary by CodeRabbit

  • New Features

    • Added optional UDP unicast connectivity for Portduino devices.
    • Devices can send and receive encrypted mesh packets through a configured unicast peer.
    • Added configuration support for specifying the UDP unicast peer.
    • Made channel cryptography configuration available for broader integration.
  • Bug Fixes

    • Improved decryption of encrypted packets received through UDP unicast connections.

@jp-bennett
jp-bennett requested a review from Copilot June 8, 2026 21:49
@github-actions github-actions Bot added needs-review Needs human review enhancement New feature or request labels Jun 8, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a Portduino/meshtasticd-specific unicast UDP connector intended to forward MeshPackets to a single configured peer (e.g., a meshswitch routing daemon), reusing concepts from the existing UDP multicast pathway.

Changes:

  • Adds General.UDPUnicastPeer Portduino config and YAML serialization/loading.
  • Introduces UdpUnicastConnector (POSIX-socket-based) to send/receive MeshPackets over connected UDP.
  • Updates Router decrypt flow to optionally bypass channel-hash checks for UNICAST_UDP-origin packets.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
src/platform/portduino/PortduinoGlue.h Adds udp_unicast_peer config field and YAML output.
src/platform/portduino/PortduinoGlue.cpp Loads General.UDPUnicastPeer from YAML.
src/mesh/udp/UdpUnicastConnector.h New unicast UDP connector implementation for meshtasticd.
src/mesh/Router.cpp Mirrors outbound packets to the unicast connector; refactors AES decrypt attempt and adds UDP bypass path.
src/mesh/Channels.h Makes setCrypto() callable from Router for UDP bypass decrypt attempts.
src/main.h Exposes global udpUnicastConnector on Portduino builds.
src/main.cpp Starts the unicast connector during setup when configured.

Comment thread src/mesh/udp/UdpUnicastConnector.h
Comment thread src/mesh/udp/UdpUnicastConnector.h
Comment on lines +42 to +48
std::string host = peer;
uint16_t port = UDP_UNICAST_DEFAULT_PORT;
auto colon = peer.rfind(':');
if (colon != std::string::npos) {
host = peer.substr(0, colon);
port = (uint16_t)atoi(peer.substr(colon + 1).c_str());
}
Comment thread src/main.cpp
Comment thread src/mesh/Router.cpp
Comment thread src/mesh/Router.cpp
Comment thread src/mesh/Router.cpp
Comment thread src/platform/portduino/PortduinoGlue.h
Comment thread src/mesh/udp/UdpUnicastConnector.h
@vidplace7
vidplace7 requested a review from Jorropo June 8, 2026 22:02
jp-bennett and others added 7 commits June 8, 2026 18:34
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

@Jorropo Jorropo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. please use dtls or some other authenticated encryption, don't be part of the problem of poorly secured iot devices, it's not too hard here.
    Imo something like making the connection key: 1.2.3.4:4403@327d6a5dafc9ac5e5459f93225ee3996a66c9a4749e64e61c6ab4ff51df4104d with raw Ed25519 or ECC keys.
    Ping me if you want me to claude it up and review it.

  2. It's kinda weird that you are implementing this only on meshtasticd.
    An ESP32 is way good enough to also do this. I think it would make more sense if you implement the AsyncUDP unicast API in portduino, then write this code to use AsyncUDP, thus it would also work on ESP32s.

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Firmware Size Report

21 targets | no baseline available yet

Target Size
elecrow-adv-35-tft 3,359,856
heltec-ht62-esp32c3-sx1262 2,081,856
heltec-v3 2,203,808
heltec-vision-master-e213-inkhud 2,167,808
pico 735,680
Show 16 more target(s)
Target Size
pico2 728,528
pico2w 1,176,916
picow 1,195,480
rak11200 1,800,416
rak11310 758,272
rak3172 179,628
rak3312 2,210,848
seeed-xiao-s3 2,214,144
seeed_xiao_rp2040 733,896
seeed_xiao_rp2350 726,696
station-g2 2,214,544
station-g3 2,205,232
t-deck-tft 3,750,432
t-eth-elite 2,431,504
tlora-c6 2,313,632
wio-e5 231,100

Updated for d8e488e

@jp-bennett

Copy link
Copy Markdown
Collaborator Author
  1. please use dtls or some other authenticated encryption,

How about AES-256 and AES-CCM based on x25519? trollface
Seriously, I question the usefulness of adding yet another encryption layer. We're pushing this data over the network with the same encryption as over the airwaves.

2. It's kinda weird that you are implementing this only on meshtasticd.

Somehow I didn't think AsyncUDP had a unicast option. If we test this out and find it useful, moving it to that library makes sense, as a future PR.

@Jorropo

Jorropo commented Jun 10, 2026

Copy link
Copy Markdown
Member

The point isn't to encrypt the data again,
it's that UDP is trivial to forge.

I want there to be some authentication that means someone random who finds an open meshtastic UDP port can't easily forge a couple packets to spam the mesh with garbage.
Imo using DTLS is the easiest way to achieve this but you could come up with something else.

@jp-bennett

Copy link
Copy Markdown
Collaborator Author

The meshtasticd instance is the sender, and filters the UDP port for the connect address. While this isn't bulletproof security, it does mean that you can't just do a portscan for listening meshtasticd nodes.

Some authentication would eventually be handy. There's no published client yet, this is still a WIP. It's just a pain to juggle a bunch of patches to try to test things out.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Portduino gains configurable UDP unicast transport. Startup initializes the connector, Router forwards outbound packets, received encrypted packets are enqueued, and channel decryption supports UDP-unicast hash bypasses.

Changes

Portduino UDP unicast transport

Layer / File(s) Summary
Configuration and connector startup
src/platform/portduino/PortduinoGlue.*, src/main.*
Adds the udp_unicast_peer configuration field, YAML loading/emission, exported connector state, and conditional startup handling.
UDP unicast socket connector
src/mesh/udp/UdpUnicastConnector.h
Adds connected UDP socket setup, threaded receiving, protobuf encoding/decoding, packet filtering, forwarding, and shutdown.
Router forwarding and channel decryption
src/mesh/Channels.h, src/mesh/Router.cpp
Makes Channels::setCrypto() accessible, mirrors outbound packets to UDP unicast, centralizes AES decoding, and retries decryption for UDP-unicast packets across channels.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Router
  participant UdpUnicastConnector
  participant UDP_Peer
  Router->>UdpUnicastConnector: Forward outbound mesh packet
  UdpUnicastConnector->>UDP_Peer: Send protobuf datagram
  UDP_Peer->>UdpUnicastConnector: Return encrypted datagram
  UdpUnicastConnector->>Router: Enqueue received packet
Loading

Possibly related PRs

Suggested reviewers: caveman99, thebentern

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is far too brief and does not follow the required template, missing the attestation checklist and testing details. Replace it with the repository template, remove the placeholder tips, and fill in the attestations plus any relevant issue and testing notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding UDP unicast support for meshtasticd.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch udp-unicast

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/platform/portduino/PortduinoGlue.h (1)

645-646: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer empty() for string emptiness checks.

♻️ Proposed refactor
-        if (udp_unicast_peer != "")
+        if (!udp_unicast_peer.empty())
             out << YAML::Key << "UDPUnicastPeer" << YAML::Value << udp_unicast_peer;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platform/portduino/PortduinoGlue.h` around lines 645 - 646, Update the
UDP unicast peer check in the surrounding YAML serialization logic to use
udp_unicast_peer.empty() instead of comparing it with an empty string, while
preserving the existing conditional output behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/mesh/udp/UdpUnicastConnector.h`:
- Around line 45-48: Replace the unchecked atoi conversion in the peer parsing
logic with std::stoi inside a try-catch block, validating malformed port input
and handling conversion errors explicitly before assigning the result to port.
Preserve the existing host extraction and valid port parsing behavior in the
colon branch.

---

Nitpick comments:
In `@src/platform/portduino/PortduinoGlue.h`:
- Around line 645-646: Update the UDP unicast peer check in the surrounding YAML
serialization logic to use udp_unicast_peer.empty() instead of comparing it with
an empty string, while preserving the existing conditional output behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 25e016fd-e420-4029-a009-7efc405cff7a

📥 Commits

Reviewing files that changed from the base of the PR and between cf0cb90 and 459828a.

📒 Files selected for processing (7)
  • src/main.cpp
  • src/main.h
  • src/mesh/Channels.h
  • src/mesh/Router.cpp
  • src/mesh/udp/UdpUnicastConnector.h
  • src/platform/portduino/PortduinoGlue.cpp
  • src/platform/portduino/PortduinoGlue.h

Comment on lines +45 to +48
if (colon != std::string::npos) {
host = peer.substr(0, colon);
port = (uint16_t)atoi(peer.substr(colon + 1).c_str());
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate string-to-integer conversion.

The atoi function performs no error detection and returns 0 on non-numeric input, which evaluates to an invalid port. Use std::stoi in a try-catch block to properly handle malformed input.

🛠️ Proposed fix
         auto colon = peer.rfind(':');
         if (colon != std::string::npos) {
             host = peer.substr(0, colon);
-            port = (uint16_t)atoi(peer.substr(colon + 1).c_str());
+            try {
+                port = (uint16_t)std::stoi(peer.substr(colon + 1));
+            } catch (...) {
+                LOG_ERROR("UDP unicast: bad port in peer address '%s'", peer.c_str());
+                return false;
+            }
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (colon != std::string::npos) {
host = peer.substr(0, colon);
port = (uint16_t)atoi(peer.substr(colon + 1).c_str());
}
auto colon = peer.rfind(':');
if (colon != std::string::npos) {
host = peer.substr(0, colon);
try {
port = (uint16_t)std::stoi(peer.substr(colon + 1));
} catch (...) {
LOG_ERROR("UDP unicast: bad port in peer address '%s'", peer.c_str());
return false;
}
}
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 46-46: Avoid atoi/atol/atoll/atof: they perform no error detection, returning 0 on non-numeric input and invoking undefined behavior on out-of-range values. This rule flags every use of these functions regardless of data provenance. Convert strings with strtol/strtoul/strtod and check errno (and the endptr) so malformed or overflowing input is rejected.
Context: atoi(peer.substr(colon + 1).c_str())
Note: [CWE-20] Improper Input Validation.

(atoi-no-error-detection-c)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/mesh/udp/UdpUnicastConnector.h` around lines 45 - 48, Replace the
unchecked atoi conversion in the peer parsing logic with std::stoi inside a
try-catch block, validating malformed port input and handling conversion errors
explicitly before assigning the result to port. Preserve the existing host
extraction and valid port parsing behavior in the colon branch.

Source: Linters/SAST tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request needs-review Needs human review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants