From 43499e39d225b4ca63ef84cf5246595eed9cd003 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:12:27 +0200 Subject: [PATCH 01/13] loopback: IPv4 127/8 and own addresses take an IP-layer queue, not the wire A datagram to 127.0.0.0/8 or to one of the stack's own addresses is built as for the wire and queued (bounded, 1024; overflow counts loopback_drops) instead of routed, ARPed and transmitted. poll() delivers the queue before the channels, capped at half the frame budget and only what was queued at the start, so replies wait for the next call and no send re-enters a receive path. ms_until_next_timer() is 0 while the queue is non-empty and poll() returns false until it is empty. Source address is the destination (Linux's rule), so a reply matches its connection. MSS on a local route comes from LOOPBACK_MTU (65535). A 127/8 source or destination arriving on a real interface is dropped and counted (RFC 1122 3.2.1.3), which also keeps forwarding away from loopback. The IPv6 half is stubbed here and lands next. Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 54 +++++ src/network_stack.cpp | 238 +++++++++++++++++++--- src/network_stack_ipv6.cpp | 9 + tests/include/guard_channel.h | 50 +++++ tests/src/test_loopback.cpp | 362 ++++++++++++++++++++++++++++++++++ 5 files changed, 686 insertions(+), 27 deletions(-) create mode 100644 tests/include/guard_channel.h create mode 100644 tests/src/test_loopback.cpp diff --git a/include/network_stack.h b/include/network_stack.h index b913e6c..99c2005 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -355,6 +355,29 @@ class NetworkStack // where it shows instead. Fatal channel errors are not counted here: they // propagate out of poll()/on_time_passed()/send(). uint64_t transmit_drops() const { return _transmit_drops; } + + // ---- Loopback ---------------------------------------------------------- + // + // A datagram to 127.0.0.0/8, to ::1, or to one of this stack's own + // addresses is local: it never reaches routing, ARP or a channel. It is + // queued at the IP layer and delivered by the next poll(), so no send + // path ever re-enters a receive path. + // + // The queue is bounded; a datagram that finds it full is dropped and + // counted, which TCP treats as loss and retransmits. Delivery is deferred + // (never from inside send()), and ms_until_next_timer() reads 0 while + // anything is queued, so a driver that sleeps on it never sleeps on + // pending loopback traffic. + static constexpr size_t LOOPBACK_QUEUE_LIMIT = 1024; + // The largest value both IP total-length (16 bits, IPv4 header included) + // and the IPv6 payload length (16 bits, header excluded) can carry: a + // loopback segment is never fragmented, and TCP's MSS on a loopback route + // is derived from it (MTU less 40 for v4, less 60 for v6). + static constexpr uint16_t LOOPBACK_MTU = 65535; + uint64_t loopback_drops() const { return _loopback_drops; } + // Packets that arrived on a real interface with a loopback source or + // destination and were dropped (RFC 1122 3.2.1.3; RFC 4291 2.5.3). + uint64_t loopback_martian_drops() const { return _loopback_martian_drops; } uint64_t challenge_acks_sent() const { return _challenge_acks_sent; } uint64_t challenge_acks_suppressed() const { return _challenge_acks_suppressed; } // SYNs that ended a TIME_WAIT early to open a new connection on the same @@ -995,6 +1018,37 @@ class NetworkStack uint64_t _time_wait_reuses = 0; uint64_t _transmit_drops = 0; + // ---- Loopback internals ---- + // + // Whole IP packets, built and checksummed, waiting for the next poll(). + // `v6` says which receive path takes it. No Ethernet header: there is no + // link, so nothing in a packet depends on one. + struct LoopbackDatagram + { + bool v6; + Bytes packet; + }; + std::deque _loopback_queue; + uint64_t _loopback_drops = 0; + uint64_t _loopback_martian_drops = 0; + // The "ingress interface" of a datagram taken off the loopback queue. Not + // an index into _interfaces on purpose: there is no pseudo-interface (code + // that iterates interfaces or assumes interface 0 must not see one), and a + // value that cannot be mistaken for an index makes any at() on it throw + // rather than quietly use the wrong link. + static constexpr size_t LOOPBACK_INGRESS = static_cast(-1); + // 127.0.0.0/8 or an address configured on an interface. + bool _is_local_ipv4(const IPv4Address& address) const; + bool _is_local_address(const IpAddress& address) const; + bool _is_local_ipv6(const IPv6Address& address) const; + // The v6 receive path for a datagram off the loopback queue. + void _handle_loopback_ipv6(const Bytes& packet); + // Queues a built packet, or drops and counts it when the queue is full. + void _enqueue_loopback(bool v6, const Bytes& packet); + // Delivers up to `limit` of the datagrams queued now - not those queued + // by delivering them - and returns how many it took. + size_t _drain_loopback(size_t limit); + // Null until start_dhcp(). Owned here rather than by the application // because it reconfigures the interface, which is this class's state. std::unique_ptr _dhcp_client; diff --git a/src/network_stack.cpp b/src/network_stack.cpp index 4846724..169bb4a 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -42,6 +42,13 @@ namespace // 224.0.0.0/4. Class E (240.0.0.0/4) is not multicast, but is no more a // single host's address, so callers asking "is this one host" test both. + // 127.0.0.0/8 (RFC 1122 3.2.1.3): the whole block is this host, not just + // 127.0.0.1. + bool is_loopback_v4(const IPv4Address& address) + { + return address.get_address()[0] == 127; + } + bool is_multicast(const IPv4Address& address) { return (address.get_address()[0] & 0xF0) == 0xE0; @@ -521,18 +528,31 @@ TcpConnection* NetworkStack::_open_connection(const IpAddress& remote_address, u const IPv4Address& remote_ip = remote_address.v4(); ConnectionKey key{remote_ip, remote_port, local_port}; + // A local peer is reached from the address it was named by (127.0.0.1 to + // 127.0.0.1, an own address to itself): the same rule that picks a + // datagram's source, so the connection's idea of its address and the one + // on its segments cannot disagree. + const bool local_peer = this->_is_local_ipv4(remote_ip); + const IPv4Address local_ip = local_peer ? remote_ip : this->_primary().config.ip; auto connection = std::make_unique( - local_port, remote_ip, remote_port, - this->_next_isn(this->_primary().config.ip, local_port, remote_ip, remote_port), - this->_segment_sender(remote_ip, this->_primary().config.ip), this->_primary().config.local_mss()); + local_port, remote_ip, remote_port, this->_next_isn(local_ip, local_port, remote_ip, remote_port), + this->_segment_sender(remote_ip, local_ip), this->_local_mss_for(remote_ip)); connection->set_ecn_mode(this->_tcp_ecn); connection->set_timestamps_enabled(this->_tcp_timestamps); - connection->set_local_ip(this->_primary().config.ip); - this->_set_timestamp_clock(*connection, this->_primary().config.ip, remote_ip); + connection->set_local_ip(local_ip); + this->_set_timestamp_clock(*connection, local_ip, remote_ip); TcpConnection* connection_ptr = connection.get(); this->_register_connection(key, std::move(connection)); + // Nothing to resolve: there is no next hop, so no ARP and no waiting. The + // SYN is queued for the next poll() like any loopback datagram. + if (local_peer) + { + connection_ptr->initiate_connect(); + return connection_ptr; + } + // Resolve and queue against the NEXT HOP, not the peer. For an off-link // peer the ARP reply that unblocks this connection comes from the gateway // and carries the gateway's address, so keying any of this on the peer's @@ -902,6 +922,15 @@ bool NetworkStack::poll() { bool fully_drained = true; + // Loopback first, and capped at half the budget. First because it is work + // this host generated itself: a local peer's reply is waiting on nothing + // but this call, whereas the wire can wait one more round. Capped because a + // loopback conversation can feed itself without end, and the cap is what + // leaves the channels (and the caller's timers) their half. Only the + // datagrams queued at this point are taken - their replies wait for the + // next call - so a ping-pong cannot hold poll() here forever. + const int loopback_processed = static_cast(this->_drain_loopback(POLL_FRAME_BUDGET / 2)); + // ONE budget for the whole call, spent round-robin across the interfaces. // // The budget exists to stop a fast sender starving the caller's timer work, @@ -913,7 +942,7 @@ bool NetworkStack::poll() std::vector drained(this->_interfaces.size(), false); size_t still_draining = this->_interfaces.size(); - for (int processed = 0; processed < POLL_FRAME_BUDGET && still_draining > 0;) + for (int processed = loopback_processed; processed < POLL_FRAME_BUDGET && still_draining > 0;) { for (size_t ingress = 0; ingress < this->_interfaces.size(); ingress++) { @@ -946,12 +975,82 @@ bool NetworkStack::poll() // so the caller can service its timer and completion work before coming // back - and it must come back, since an edge-triggered fd will not notify // again for what is already waiting. - fully_drained = (still_draining == 0); + // Loopback datagrams left queued - over the cap, or sent by what this call + // just delivered - are "more to do" exactly as frames left on a channel + // are: the caller must come back, because nothing will wake it for them. + fully_drained = (still_draining == 0) && this->_loopback_queue.empty(); this->_reap_closed_connections(); return fully_drained; } +bool NetworkStack::_is_local_ipv4(const IPv4Address& address) const +{ + if (is_loopback_v4(address)) + { + return true; + } + for (const auto& interface : this->_interfaces) + { + if (interface->config.has_address() && address == interface->config.ip) + { + return true; + } + } + return false; +} + +bool NetworkStack::_is_local_address(const IpAddress& address) const +{ + return address.is_v4() ? this->_is_local_ipv4(address.v4()) : this->_is_local_ipv6(address.v6()); +} + +void NetworkStack::_enqueue_loopback(bool v6, const Bytes& packet) +{ + if (this->_loopback_queue.size() >= LOOPBACK_QUEUE_LIMIT) + { + // Loss, as on a full transmit queue: TCP retransmits, and UDP never + // promised. Counted, since a loop that drops is otherwise invisible. + this->_loopback_drops++; + LOG_DEBUG("NetworkStack: loopback queue full - dropping a datagram"); + return; + } + this->_loopback_queue.push_back({v6, packet}); +} + +size_t NetworkStack::_drain_loopback(size_t limit) +{ + // Counted up front: what delivering one of these sends joins the queue + // behind them and waits for the next call. + const size_t take = std::min(limit, this->_loopback_queue.size()); + for (size_t taken = 0; taken < take; taken++) + { + LoopbackDatagram datagram = std::move(this->_loopback_queue.front()); + this->_loopback_queue.pop_front(); + try + { + if (datagram.v6) + { + this->_handle_loopback_ipv6(datagram.packet); + } + else + { + Ip ip(datagram.packet, false); + this->_handle_ip(LOOPBACK_INGRESS, ip, datagram.packet, false); + } + } + catch (const FatalChannelError&) + { + throw; + } + catch (const BaseException& e) + { + LOG_WARNING("NetworkStack: dropped a loopback datagram while handling it: " << e.what()); + } + } + return take; +} + void NetworkStack::on_time_passed(uint32_t elapsed_ms) { this->_now_ms += elapsed_ms; @@ -1121,6 +1220,13 @@ NextTimer NetworkStack::ms_until_next_timer() const { NextTimer next; + // Queued loopback traffic is due now. No driver is woken by it (there is + // no fd), so the only way it is not left waiting is a wait of zero. + if (!this->_loopback_queue.empty()) + { + fold_next_timer(next, 0); + } + this->_tidy_timer_queue(); if (!this->_timer_queue.empty()) { @@ -1407,6 +1513,24 @@ void NetworkStack::_handle_arp(size_t ingress, const Arp& arp) void NetworkStack::_handle_ip(size_t ingress, const Ip& ip, const Bytes& ip_bytes, bool link_layer_group) { + // A datagram off the loopback queue is marked by its ingress, and is the + // one way a 127/8 address is accepted. On a real interface it never is + // (RFC 1122 3.2.1.3: a host must not send 127/8 on a network, and a router + // must not forward it): a spoofed 127.0.0.1 source would otherwise pass + // every "is this local" check made further down, and a loopback + // destination reaching the forwarding branch would be relayed. Dropping + // here, before anything is parsed or forwarded, covers both. + const bool from_loopback = ingress == LOOPBACK_INGRESS; + if (!from_loopback + && (is_loopback_v4(IPv4Address(ip.get_src_address())) || is_loopback_v4(IPv4Address(ip.get_dest_address())))) + { + this->_loopback_martian_drops++; + LOG_DEBUG("NetworkStack: dropping an IPv4 packet from " + << IPv4Address(ip.get_src_address()).to_string() << " to " + << IPv4Address(ip.get_dest_address()).to_string() << " - a loopback address on a real interface"); + return; + } + // RFC 1122 3.3.6: a datagram that arrived as a link-layer broadcast or // multicast but names a unicast IP destination is silently discarded. // Answering it would draw an error from every host that heard it, and @@ -1432,7 +1556,9 @@ void NetworkStack::_handle_ip(size_t ingress, const Ip& ip, const Bytes& ip_byte // which link the answer should come back on. The strong model - accept only // the arrival interface's own address - is more defensible on a firewall and // is not what this is. - bool addressed_to_us = false; + // Whatever is on the loopback queue was addressed to this host by the send + // path that put it there, so the interface search is skipped for it. + bool addressed_to_us = from_loopback; for (const auto& candidate : this->_interfaces) { if (candidate->config.has_address() && destination == candidate->config.ip) @@ -1470,7 +1596,10 @@ void NetworkStack::_handle_ip(size_t ingress, const Ip& ip, const Bytes& ip_byte // hearing from a peer proves it's still alive at its cached MAC - keep that // mapping fresh so an actively-talking peer never ages out mid-conversation // (its data/acks arrive as IP frames, not ARP, so nothing else would) - this->_interfaces.at(ingress)->arp_table.refresh(IPv4Address(ip.get_src_address())); + if (!from_loopback) + { + this->_interfaces.at(ingress)->arp_table.refresh(IPv4Address(ip.get_src_address())); + } if (!ip.verify_checksum()) { @@ -1832,7 +1961,10 @@ void NetworkStack::_handle_tcp(const IpAddress& source, const IpAddress& destina << " on port " << key.local_port); // The local address in the ISN tuple: the primary interface's for v4, as // it has always been, and the address the SYN was sent to for v6. - const IpAddress local_ip = source.is_v4() ? IpAddress(this->_primary().config.ip) : destination; + // A local peer's SYN came to the address it named, which is also the one + // this side answers from (see _open_connection). + const IpAddress local_ip = + source.is_v4() && !this->_is_local_address(source) ? IpAddress(this->_primary().config.ip) : destination; uint32_t isn = this->_next_isn(local_ip, key.local_port, remote_ip, key.remote_port); if (old_send_next) { @@ -2672,6 +2804,15 @@ IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip) const // another produces a packet that is correct in a local capture and rejected // by every peer that verifies it - the hardest kind of bug to see, because // tcpdump on the sending host shows nothing wrong. + // + // For a local destination it is the destination itself (127.0.0.1 for + // 127.0.0.1, an own address for that address), as on Linux: the peer that + // answers then replies from the address it was sent to, and a reply + // matches the connection it belongs to. + if (this->_is_local_ipv4(dest_ip)) + { + return dest_ip; + } IPv4Address next_hop; size_t egress = 0; if (!this->_route_for(dest_ip, next_hop, egress)) @@ -2684,6 +2825,29 @@ IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip) const void NetworkStack::_send_ip_packet(const IPv4Address& dest_ip, uint8_t protocol, const Bytes& payload, bool dont_fragment, Ecn ecn) { + // Local: no route, no ARP, no frame. The packet is built exactly as it + // would be for the wire - header, checksum - because the receive side + // treats it as any other arriving datagram; the source is the destination + // (see _source_address_for). Never fragmented: the loopback MTU is the + // most an IPv4 total-length field can say, so anything that fits an IP + // packet at all fits here. + if (this->_is_local_ipv4(dest_ip)) + { + if (20 + payload.size() > LOOPBACK_MTU) + { + LOG_WARNING("NetworkStack: dropping a " << payload.size() << "-byte loopback payload - it exceeds the " + << LOOPBACK_MTU << "-byte loopback MTU"); + return; + } + Ip header(4, 5, static_cast(ecn), static_cast(20 + payload.size()), 0, + dont_fragment ? IP_FLAG_DONT_FRAGMENT : 0, 0, 64, protocol, 0, dest_ip.get_address(), + dest_ip.get_address()); + header /= std::make_unique(payload); + header.compute_checksum(); + this->_enqueue_loopback(false, header.to_bytes()); + return; + } + // The IP header keeps naming the final destination; the frame goes to // whoever will carry it onward, out of the link the route names. IPv4Address next_hop; @@ -2847,7 +3011,7 @@ void NetworkStack::_send_tcp_segment(const IpAddress& destination, const Tcp& he // queue is needed here (unlike UDP, which has no retransmission). IPv4Address next_hop; size_t egress = 0; - if (this->_route_for(dest_ip, next_hop, egress)) + if (!this->_is_local_ipv4(dest_ip) && this->_route_for(dest_ip, next_hop, egress)) { const Interface& interface = *this->_interfaces.at(egress); if (!is_broadcast_address(next_hop, interface.config) && !interface.arp_table.contains(next_hop)) @@ -2906,6 +3070,12 @@ void NetworkStack::_send_rst(const IpAddress& source, const IpAddress& destinati uint16_t NetworkStack::_local_mss_for(const IpAddress& peer) const { + // A local peer is not behind any interface, so the interface MTU says + // nothing about it: the loopback MTU does (see LOOPBACK_MTU). + if (this->_is_local_address(peer)) + { + return static_cast(LOOPBACK_MTU - (peer.is_v4() ? 40 : 60)); + } if (peer.is_v4()) { return this->_primary().config.local_mss(); @@ -2945,6 +3115,12 @@ void NetworkStack::_send_or_queue_udp(const IpAddress& destination, const Udp& h this->_send_udp_datagram(dest_ip, header, payload); return; } + // Local needs no resolution either: there is no neighbour to ask. + if (this->_is_local_ipv4(dest_ip)) + { + this->_send_udp_datagram(dest_ip, header, payload); + return; + } // Queue against the next hop for the same reason connect() does: an // off-link destination is unblocked by the gateway's ARP reply, not the @@ -3049,21 +3225,26 @@ void NetworkStack::_send_icmp_message(const IPv4Address& dest_ip, const Icmp& he // it with the broadcast MAC without consulting the table at all. Note // _next_hop_for() already reports an on-link destination as its own next // hop, so this one check covers both the neighbour and the via-gateway case. - IPv4Address next_hop; - size_t egress = 0; - if (!this->_route_for(dest_ip, next_hop, egress)) - { - LOG_DEBUG("NetworkStack: dropping an ICMP message to " << dest_ip.to_string() << " - no route to it"); - return; - } - Interface& egress_interface = *this->_interfaces.at(egress); - if (!is_broadcast_address(next_hop, egress_interface.config) && !egress_interface.arp_table.contains(next_hop)) + // + // A local destination has no next hop, so none of this applies to it. + if (!this->_is_local_ipv4(dest_ip)) { - LOG_DEBUG("NetworkStack: dropping an ICMP message to " << dest_ip.to_string() << " - no ARP entry for next hop " - << next_hop.to_string() - << "; resolving it for next time"); - this->_ensure_arp_resolution(egress, next_hop); - return; + IPv4Address next_hop; + size_t egress = 0; + if (!this->_route_for(dest_ip, next_hop, egress)) + { + LOG_DEBUG("NetworkStack: dropping an ICMP message to " << dest_ip.to_string() << " - no route to it"); + return; + } + Interface& egress_interface = *this->_interfaces.at(egress); + if (!is_broadcast_address(next_hop, egress_interface.config) && !egress_interface.arp_table.contains(next_hop)) + { + LOG_DEBUG("NetworkStack: dropping an ICMP message to " + << dest_ip.to_string() << " - no ARP entry for next hop " << next_hop.to_string() + << "; resolving it for next time"); + this->_ensure_arp_resolution(egress, next_hop); + return; + } } // Icmp can't be copied (same ProtocolLayer reason as Tcp/Udp) - rebuild @@ -3082,8 +3263,11 @@ bool NetworkStack::_may_report_error_for(const IPv4Address& source, const IPv4Ad // checked first so they do not spend that budget either. // Not to a single host: there is nobody, or everybody, to send it to. - if (source == IPv4Address("0.0.0.0") || (source.get_address()[0] == 127) || is_multicast(source) - || is_class_e(source) || this->_is_broadcast_for_any_interface(source)) + // (A 127/8 source is not refused here: one can only have got this far by + // the loopback queue, since _handle_ip drops it from a real interface, and + // an error about local traffic is answered locally.) + if (source == IPv4Address("0.0.0.0") || is_multicast(source) || is_class_e(source) + || this->_is_broadcast_for_any_interface(source)) { return false; } diff --git a/src/network_stack_ipv6.cpp b/src/network_stack_ipv6.cpp index 3878079..cab510d 100644 --- a/src/network_stack_ipv6.cpp +++ b/src/network_stack_ipv6.cpp @@ -1061,3 +1061,12 @@ void NetworkStack::_fold_ipv6_timers(NextTimer& next) const fold_deadline(router.expires_ms); } } + +// ---- loopback -------------------------------------------------------------- + +bool NetworkStack::_is_local_ipv6(const IPv6Address&) const +{ + return false; +} + +void NetworkStack::_handle_loopback_ipv6(const Bytes&) {} diff --git a/tests/include/guard_channel.h b/tests/include/guard_channel.h new file mode 100644 index 0000000..41a301e --- /dev/null +++ b/tests/include/guard_channel.h @@ -0,0 +1,50 @@ +#pragma once + +#include + +#include + +#include "bytes.h" +#include "packet_channel.h" + +// A channel that fails the test on ANY write. For traffic that must never +// reach a wire - loopback above all - where "the test passed" is worthless if +// the packets quietly went out of the real interface and were answered by +// nobody: a guard makes the accidental pass impossible. +// +// The failure is recorded with ADD_FAILURE() before the throw, so a catch in +// the stack between the write and the test cannot hide it. FatalChannelError +// is what the stack rethrows rather than absorbing. +// +// Frames pushed with push_inbound() are read back like a real channel's, which +// is how a test injects what a peer on the wire would send. +class GuardChannel : public PacketChannel +{ +public: + Bytes read(unsigned int /*max_length*/) override + { + if (_inbound.empty()) + { + return Bytes(); + } + Bytes frame = _inbound.front(); + _inbound.pop_front(); + return frame; + } + + void write(const Bytes& buffer) override + { + _writes++; + ADD_FAILURE() << "a " << buffer.size() << "-byte frame was written to a channel that must stay silent"; + throw FatalChannelError("GuardChannel: unexpected write"); + } + + int get_fd() const override { return -1; } + + void push_inbound(const Bytes& frame) { _inbound.push_back(frame); } + size_t writes() const { return _writes; } + +private: + std::deque _inbound; + size_t _writes = 0; +}; diff --git a/tests/src/test_loopback.cpp b/tests/src/test_loopback.cpp new file mode 100644 index 0000000..f747bb3 --- /dev/null +++ b/tests/src/test_loopback.cpp @@ -0,0 +1,362 @@ +#include "test_support.h" +#include "guard_channel.h" +#include "network_stack.h" +#include "ethernet.h" +#include "ip.h" +#include "raw.h" +#include "udp.h" +#include "utils.h" + +#include +#include +#include +#include +#include + +// Local traffic: a datagram to 127.0.0.0/8 or to one of the stack's own +// addresses never touches an interface. Every stack here sits on a GuardChannel +// that fails the test on any write, so a pass cannot be the packets having gone +// out of the real interface and been answered by nobody. +namespace +{ + const MacAddress MAC("02:00:00:00:00:01"); + const MacAddress PEER_MAC("02:00:00:00:00:99"); + const IPv4Address OWN("10.0.0.2"); + const IPv4Address LOOPBACK("127.0.0.1"); + constexpr uint16_t PORT = 7000; + + struct Host + { + Host() + { + auto guard_channel = std::make_unique(); + guard = guard_channel.get(); + InterfaceConfig config; + config.mac = MAC; + config.ip = OWN; + config.prefix_length = 24; + stack = std::make_unique(std::move(guard_channel), config); + } + + // Runs the stack the way a driver does: time, then poll() until drained. + void pump(uint32_t ms) + { + for (uint32_t i = 0; i < ms; i++) + { + stack->on_time_passed(1); + while (!stack->poll()) + { + } + } + } + + bool pump_until(const std::function& done, uint32_t max_ms) + { + for (uint32_t i = 0; i < max_ms; i++) + { + if (done()) + { + return true; + } + pump(1); + } + return done(); + } + + GuardChannel* guard = nullptr; + std::unique_ptr stack; + }; + + // An Ethernet/IPv4/UDP frame as a peer on the wire would send it. The UDP + // checksum is 0, which is "none" over IPv4 (RFC 768): everything these + // tests check is about addresses. + Bytes udp_frame(const IPv4Address& source, const IPv4Address& destination, uint16_t sport, uint16_t dport, + const Bytes& data) + { + auto ip = std::make_unique(4, 5, 0, static_cast(20 + 8 + data.size()), 0, 0, 0, 64, + IpProtocol::UDP, 0, source.get_address(), destination.get_address()); + *ip /= std::make_unique(sport, dport, static_cast(8 + data.size()), 0, data); + ip->compute_checksum(); + Ethernet frame(PEER_MAC, MAC, EtherType::IPv4); + frame /= std::move(ip); + return frame.to_bytes(); + } + + std::string text_of(const Bytes& bytes) + { + return std::string(bytes.begin(), bytes.end()); + } + + // A connected client/server pair inside one stack, over `address`. + struct Pair + { + TcpConnection* client = nullptr; + TcpConnection* server = nullptr; + }; + + Pair connect_over(Host& host, const IPv4Address& address) + { + Pair pair; + host.stack->listen(PORT); + pair.client = host.stack->connect(address, PORT); + REQUIRE_TRUE(pair.client != nullptr, "connect() returned no connection"); + REQUIRE_TRUE(host.pump_until([&] { return host.stack->has_pending_accept(PORT); }, 5000), + "the handshake never reached the accept queue"); + pair.server = host.stack->accept(PORT); + REQUIRE_TRUE(pair.server != nullptr, "accept() returned nothing"); + REQUIRE_TRUE(host.pump_until([&] { return pair.client->get_state() == TcpState::ESTABLISHED; }, 5000), + "the client never reached ESTABLISHED"); + return pair; + } + + void echo_round_trip(Host& host, const IPv4Address& address) + { + Pair pair = connect_over(host, address); + pair.client->send(Bytes::from_hex("68656c6c6f")); // "hello" + REQUIRE_TRUE(host.pump_until([&] { return pair.server->bytes_available() >= 5; }, 1000), + "the request never arrived"); + REQUIRE_TRUE(text_of(pair.server->read()) == "hello", "the request arrived garbled"); + pair.server->send(Bytes::from_hex("68656c6c6f")); + REQUIRE_TRUE(host.pump_until([&] { return pair.client->bytes_available() >= 5; }, 1000), + "the echo never arrived"); + REQUIRE_TRUE(text_of(pair.client->read()) == "hello", "the echo arrived garbled"); + } +} + +TEST(Loopback, TcpEchoToLoopbackNeverTouchesTheChannel) +{ + Host host; + echo_round_trip(host, LOOPBACK); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, TcpEchoToTheStacksOwnAddressNeverTouchesTheChannel) +{ + Host host; + echo_round_trip(host, OWN); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, AnyAddressIn127SlashEightIsLocal) +{ + Host host; + echo_round_trip(host, IPv4Address("127.9.8.7")); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, TheMssComesFromTheLoopbackMtuNotTheInterfaces) +{ + Host host; + Pair pair = connect_over(host, LOOPBACK); + ASSERT_EQ(pair.client->get_effective_mss(), NetworkStack::LOOPBACK_MTU - 40); + ASSERT_EQ(pair.server->get_effective_mss(), NetworkStack::LOOPBACK_MTU - 40); +} + +TEST(Loopback, UdpOverLoopbackCarriesTheLoopbackSource) +{ + Host host; + std::optional from; + std::string got; + host.stack->bind_udp(5000)->set_datagram_received_callback( + [&](const IpAddress& source, uint16_t, const Bytes& data) + { + from = source; + got = text_of(data); + }); + host.stack->bind_udp(5001)->send_to(LOOPBACK, 5000, Bytes::from_hex("70696e67")); + host.pump(5); + ASSERT_EQ(got, "ping"); + ASSERT_TRUE(from.has_value() && from->v4() == LOOPBACK) << "source should be 127.0.0.1"; + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, UdpToAnOwnAddressUsesThatAddressAsSource) +{ + Host host; + std::optional from; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress& source, uint16_t, const Bytes&) + { from = source; }); + host.stack->bind_udp(5001)->send_to(OWN, 5000, Bytes::from_hex("01")); + host.pump(5); + ASSERT_TRUE(from.has_value() && from->v4() == OWN); +} + +TEST(Loopback, PingToLoopbackIsAnswered) +{ + Host host; + std::optional from; + std::optional sequence; + Bytes payload; + host.stack->set_echo_reply_callback( + [&](const IpAddress& source, uint16_t, uint16_t seq, const Bytes& data) + { + from = source; + sequence = seq; + payload = data; + }); + host.stack->send_echo_request(LOOPBACK, 0x1234, 7, Bytes::from_hex("abcd")); + host.pump(5); + ASSERT_TRUE(sequence.has_value()) << "no echo reply came back"; + ASSERT_EQ(*sequence, 7); + ASSERT_TRUE(from->v4() == LOOPBACK); + ASSERT_EQ(payload.to_hex(), "abcd"); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, ADatagramToAClosedLoopbackPortIsRefusedWithoutAFrame) +{ + // The ICMP error about loopback traffic is itself loopback traffic: it + // stays local like the datagram it is about. + Host host; + host.stack->bind_udp(5001)->send_to(LOOPBACK, 9, Bytes::from_hex("01")); + host.pump(5); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, DeliveryIsDeferredToPollAndKeepsTheTimerAtZero) +{ + Host host; + ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()) << "nothing pending on a fresh stack"; + std::string got; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes& data) + { got = text_of(data); }); + host.stack->bind_udp(5001)->send_to(LOOPBACK, 5000, Bytes::from_hex("78")); + ASSERT_TRUE(got.empty()) << "send() must not deliver re-entrantly"; + ASSERT_EQ(host.stack->ms_until_next_timer(), std::optional(0)) << "a driver must not sleep"; + ASSERT_TRUE(host.stack->poll()); + ASSERT_EQ(got, "x"); + ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()); +} + +TEST(Loopback, ABurstBeyondTheQueueBoundIsDroppedAndCounted) +{ + Host host; + size_t delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + UdpSocket* sender = host.stack->bind_udp(5001); + const size_t burst = NetworkStack::LOOPBACK_QUEUE_LIMIT + 100; + for (size_t i = 0; i < burst; i++) + { + sender->send_to(LOOPBACK, 5000, Bytes::from_hex("01")); + } + ASSERT_EQ(host.stack->loopback_drops(), 100u); + host.pump(5); + ASSERT_EQ(delivered, NetworkStack::LOOPBACK_QUEUE_LIMIT); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, PollReportsMoreToDoWhileTheQueueExceedsItsBudget) +{ + Host host; + host.stack->bind_udp(5000); + UdpSocket* sender = host.stack->bind_udp(5001); + for (int i = 0; i < NetworkStack::POLL_FRAME_BUDGET * 3; i++) + { + sender->send_to(LOOPBACK, 5000, Bytes::from_hex("01")); + } + ASSERT_FALSE(host.stack->poll()) << "the budget ran out with datagrams still queued"; + int polls = 1; + while (!host.stack->poll()) + { + ASSERT_LT(++polls, 100); + } + ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()); +} + +TEST(Loopback, TcpRecoversWhenTheQueueDropsItsHandshake) +{ + Host host; + host.stack->bind_udp(5000); + UdpSocket* sender = host.stack->bind_udp(5001); + for (size_t i = 0; i < NetworkStack::LOOPBACK_QUEUE_LIMIT; i++) + { + sender->send_to(LOOPBACK, 5000, Bytes::from_hex("01")); + } + // The queue is full: the SYN is lost, and only retransmission can finish + // the handshake. + echo_round_trip(host, LOOPBACK); + ASSERT_GE(host.stack->loopback_drops(), 1u); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, ALoopbackSourceArrivingOnARealInterfaceIsDropped) +{ + Host host; + int delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + host.guard->push_inbound(udp_frame(LOOPBACK, OWN, 1234, 5000, Bytes::from_hex("01"))); + host.guard->push_inbound(udp_frame(IPv4Address("127.200.0.1"), OWN, 1234, 5000, Bytes::from_hex("01"))); + host.pump(2); + ASSERT_EQ(delivered, 0); + ASSERT_EQ(host.stack->loopback_martian_drops(), 2u); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, ALoopbackDestinationArrivingOnARealInterfaceIsDropped) +{ + Host host; + int delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + host.guard->push_inbound(udp_frame(IPv4Address("10.0.0.9"), LOOPBACK, 1234, 5000, Bytes::from_hex("01"))); + host.pump(2); + ASSERT_EQ(delivered, 0); + ASSERT_EQ(host.stack->loopback_martian_drops(), 1u); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, AForwardingStackNeverRelaysLoopbackAddresses) +{ + Host host; + host.stack->set_forwarding(true); + host.guard->push_inbound(udp_frame(IPv4Address("10.0.0.9"), LOOPBACK, 1234, 5000, Bytes::from_hex("01"))); + host.guard->push_inbound(udp_frame(LOOPBACK, IPv4Address("10.0.0.77"), 1234, 5000, Bytes::from_hex("01"))); + host.pump(2); + ASSERT_EQ(host.stack->loopback_martian_drops(), 2u); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(Loopback, ABulkTransferUsesFullSizedSegmentsAndArrivesIntact) +{ + // 64 KiB segments are the point of the large MTU, and the case where an + // IPv4 total-length or a window computation would overflow if it were + // going to. + Host host; + Pair pair = connect_over(host, LOOPBACK); + constexpr size_t TOTAL = 1 << 20; + auto pattern = [](size_t offset) + { + return static_cast((offset * 7) ^ (offset >> 9)); + }; + size_t sent = 0; + size_t received = 0; + bool intact = true; + host.pump_until( + [&] + { + if (sent < TOTAL) + { + // send() may take less than offered; the stream continues + // from what it took. + Bytes chunk(static_cast(std::min(40000, TOTAL - sent))); + for (size_t i = 0; i < chunk.size(); i++) + { + chunk[i] = pattern(sent + i); + } + sent += pair.client->send(chunk); + } + Bytes in = pair.server->read(); + for (size_t i = 0; i < in.size(); i++) + { + intact = intact && in[i] == pattern(received + i); + } + received += in.size(); + return received >= TOTAL; + }, + 5000); + ASSERT_EQ(received, TOTAL); + ASSERT_TRUE(intact) << "the stream was corrupted"; + ASSERT_EQ(host.guard->writes(), 0u); +} From 4961d03d543d734266a9d68dac9d56611b96253a Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:14:05 +0200 Subject: [PATCH 02/13] loopback: IPv6 ::1 and own v6 addresses take the same queue _send_ipv6_packet queues a local destination instead of resolving a neighbour; the source for a local destination is the destination itself (so ::1 needs no configured address); a connection to a local peer needs no route. _handle_ipv6 is split so the loopback queue reaches the same address checks and transport demux as a frame from the wire, and ::1 as source or destination on a real interface is dropped and counted (RFC 4291 2.5.3). MSS on a local v6 route is LOOPBACK_MTU less 60. Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 4 + src/network_stack_ipv6.cpp | 67 +++++++++- tests/src/test_loopback_ipv6.cpp | 222 +++++++++++++++++++++++++++++++ 3 files changed, 286 insertions(+), 7 deletions(-) create mode 100644 tests/src/test_loopback_ipv6.cpp diff --git a/include/network_stack.h b/include/network_stack.h index 99c2005..116892b 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -1043,6 +1043,10 @@ class NetworkStack bool _is_local_ipv6(const IPv6Address& address) const; // The v6 receive path for a datagram off the loopback queue. void _handle_loopback_ipv6(const Bytes& packet); + // Everything _handle_ipv6 does once the link layer is out of the picture: + // address checks and transport demux. Shared with the loopback path so a + // local datagram is handled by the code that handles any other. + void _deliver_ipv6(const Ipv6& ip, const Bytes& packet, bool link_layer_group, bool from_loopback); // Queues a built packet, or drops and counts it when the queue is full. void _enqueue_loopback(bool v6, const Bytes& packet); // Delivers up to `limit` of the datagrams queued now - not those queued diff --git a/src/network_stack_ipv6.cpp b/src/network_stack_ipv6.cpp index cab510d..9f8d2b0 100644 --- a/src/network_stack_ipv6.cpp +++ b/src/network_stack_ipv6.cpp @@ -14,6 +14,13 @@ namespace { + // ::1 (RFC 4291 2.5.3), the one v6 loopback address. + const IPv6Address& loopback_v6() + { + static const IPv6Address loopback("::1"); + return loopback; + } + constexpr uint8_t DEFAULT_HOP_LIMIT = 64; constexpr size_t UDP_HEADER_SIZE = 8; constexpr size_t TCP_MIN_HEADER_SIZE = 20; @@ -237,6 +244,13 @@ bool NetworkStack::_ipv6_group_joined(const IPv6Address& group) const std::optional NetworkStack::_ipv6_source_for(const IPv6Address& destination) const { + // A local destination is its own source: ::1 from ::1, an own address from + // itself (as for v4 - see _source_address_for). Needs no configured + // address, which is what lets ::1 work on a stack that has none usable. + if (this->_is_local_ipv6(destination)) + { + return destination; + } const bool link_scope = destination.is_link_local() || is_link_scope_multicast(destination); std::optional link_local; std::optional global; @@ -325,7 +339,7 @@ TcpConnection* NetworkStack::_open_ipv6_connection(const IPv6Address& remote_ip, this->_register_connection(key, std::move(connection)); IPv6Address next_hop; - if (!local || !this->_ipv6_route_for(remote_ip, next_hop)) + if (!local || (!this->_is_local_ipv6(remote_ip) && !this->_ipv6_route_for(remote_ip, next_hop))) { LOG_WARNING("NetworkStack: no IPv6 " << (local ? "route" : "source address") << " for " << remote_ip.to_string() << " - failing the connection"); @@ -361,7 +375,36 @@ void NetworkStack::_handle_ipv6(size_t ingress, const Bytes& packet, const MacAd return; } - if (destination.is_multicast() ? !this->_ipv6_group_joined(destination) : !this->_is_our_ipv6(destination)) + // ::1 on a real interface, as source or destination, is a martian (RFC + // 4291 2.5.3: it must never leave the host). Both ends are refused: a + // spoofed ::1 source would pass every "is this local" test made above + // the transport, exactly as 127.0.0.1 would for v4. Only the loopback + // queue delivers it, through _handle_loopback_ipv6(). + if (source == loopback_v6() || destination == loopback_v6()) + { + this->_loopback_martian_drops++; + LOG_DEBUG("NetworkStack: dropping an IPv6 packet from " + << source.to_string() << " to " << destination.to_string() << " - ::1 on a real interface"); + return; + } + + this->_deliver_ipv6(ip, packet, link_layer_group, false); +} + +void NetworkStack::_handle_loopback_ipv6(const Bytes& packet) +{ + Ipv6 ip(packet); + this->_deliver_ipv6(ip, packet, false, true); +} + +void NetworkStack::_deliver_ipv6(const Ipv6& ip, const Bytes& packet, bool link_layer_group, bool from_loopback) +{ + const IPv6Address& source = ip.get_source(); + const IPv6Address& destination = ip.get_destination(); + // What the loopback queue holds was addressed to this host by the send + // path that queued it, and ::1 is in no address list. + if (!from_loopback + && (destination.is_multicast() ? !this->_ipv6_group_joined(destination) : !this->_is_our_ipv6(destination))) { // Not for us; there is no v6 forwarding. return; @@ -767,7 +810,11 @@ void NetworkStack::_send_ipv6_packet(const IPv6Address& source, const IPv6Addres { return; } - const size_t mtu = this->_primary().config.mtu; + // Local: no route, no neighbour, no frame. Built whole, as for the wire, + // and queued for the next poll(). The MTU is the loopback one, which is + // the largest the 16-bit payload length can describe. + const bool local = this->_is_local_ipv6(destination); + const size_t mtu = local ? LOOPBACK_MTU : this->_primary().config.mtu; if (Ipv6::HEADER_SIZE + payload.size() > mtu) { // RFC 8200 5: a source may fragment, but this one does not - TCP sizes @@ -783,6 +830,12 @@ void NetworkStack::_send_ipv6_packet(const IPv6Address& source, const IPv6Addres payload); Bytes packet = header.to_bytes(); + if (local) + { + this->_enqueue_loopback(true, packet); + return; + } + if (destination.is_multicast()) { this->_transmit_ipv6(destination.multicast_mac(), packet); @@ -1064,9 +1117,9 @@ void NetworkStack::_fold_ipv6_timers(NextTimer& next) const // ---- loopback -------------------------------------------------------------- -bool NetworkStack::_is_local_ipv6(const IPv6Address&) const +bool NetworkStack::_is_local_ipv6(const IPv6Address& address) const { - return false; + // Only once v6 is on: before that the stack has no v6 identity at all, and + // a datagram to ::1 is as undeliverable as any other v6 send. + return this->_v6.enabled && (address == loopback_v6() || this->_is_our_ipv6(address)); } - -void NetworkStack::_handle_loopback_ipv6(const Bytes&) {} diff --git a/tests/src/test_loopback_ipv6.cpp b/tests/src/test_loopback_ipv6.cpp new file mode 100644 index 0000000..82fb841 --- /dev/null +++ b/tests/src/test_loopback_ipv6.cpp @@ -0,0 +1,222 @@ +#include "test_support.h" +#include "guard_channel.h" +#include "network_stack.h" +#include "ethernet.h" +#include "ipv6.h" +#include "raw.h" + +#include +#include +#include +#include + +// The IPv6 half of local traffic: ::1 and the stack's own v6 addresses never +// touch the interface either. As in test_loopback.cpp the channel is a +// GuardChannel, which fails the test on any write. Addresses are configured +// statically: enable_ipv6() would start DAD and router solicitation, which +// are (rightly) frames on the wire. +namespace +{ + const MacAddress MAC("02:00:00:00:00:01"); + const MacAddress PEER_MAC("02:00:00:00:00:99"); + const IPv6Address LOOPBACK6("::1"); + const IPv6Address OWN6("fd00::1"); + const IPv6Address PEER6("fd00::2"); + constexpr uint16_t PORT = 7000; + + struct Host + { + Host() + { + auto guard_channel = std::make_unique(); + guard = guard_channel.get(); + InterfaceConfig config; + config.mac = MAC; + config.ip = IPv4Address("10.0.0.2"); + config.prefix_length = 24; + stack = std::make_unique(std::move(guard_channel), config); + stack->add_ipv6_address(OWN6, 64); + } + + void pump(uint32_t ms) + { + for (uint32_t i = 0; i < ms; i++) + { + stack->on_time_passed(1); + while (!stack->poll()) + { + } + } + } + + bool pump_until(const std::function& done, uint32_t max_ms) + { + for (uint32_t i = 0; i < max_ms; i++) + { + if (done()) + { + return true; + } + pump(1); + } + return done(); + } + + GuardChannel* guard = nullptr; + std::unique_ptr stack; + }; + + // An Ethernet/IPv6/UDP frame as a peer on the wire would send it. + Bytes udp6_frame(const IPv6Address& source, const IPv6Address& destination, const std::string& text) + { + Bytes udp; + udp.append_int(1234); + udp.append_int(5000); + udp.append_int(static_cast(8 + text.size())); + udp.append_int(0); + for (char c : text) + { + udp.append_int(static_cast(c)); + } + uint16_t checksum = ipv6_transport_checksum(source, destination, IPV6_NEXT_UDP, udp); + udp[6] = static_cast(checksum >> 8); + udp[7] = static_cast(checksum & 0xff); + Ipv6 ip(0, 0, static_cast(udp.size()), IPV6_NEXT_UDP, 64, source, destination, udp); + Bytes frame; + frame |= MAC.get_address(); + frame |= PEER_MAC.get_address(); + frame.append_int(EtherType::IPv6); + frame |= ip.to_bytes(); + return frame; + } + + std::string text_of(const Bytes& bytes) + { + return std::string(bytes.begin(), bytes.end()); + } + + void echo_round_trip(Host& host, const IPv6Address& address) + { + host.stack->listen(PORT); + TcpConnection* client = host.stack->connect(address, PORT); + REQUIRE_TRUE(client != nullptr, "connect() returned no connection"); + REQUIRE_TRUE(host.pump_until([&] { return host.stack->has_pending_accept(PORT); }, 5000), + "the handshake never reached the accept queue"); + TcpConnection* server = host.stack->accept(PORT); + REQUIRE_TRUE(server != nullptr, "accept() returned nothing"); + REQUIRE_TRUE(host.pump_until([&] { return client->get_state() == TcpState::ESTABLISHED; }, 5000), + "the client never reached ESTABLISHED"); + REQUIRE_TRUE(client->get_effective_mss() == NetworkStack::LOOPBACK_MTU - 60, + "the MSS should come from the loopback MTU less 60"); + + client->send(Bytes::from_hex("68656c6c6f")); + REQUIRE_TRUE(host.pump_until([&] { return server->bytes_available() >= 5; }, 1000), + "the request never arrived"); + REQUIRE_TRUE(text_of(server->read()) == "hello", "the request arrived garbled"); + server->send(Bytes::from_hex("68656c6c6f")); + REQUIRE_TRUE(host.pump_until([&] { return client->bytes_available() >= 5; }, 1000), "the echo never arrived"); + REQUIRE_TRUE(text_of(client->read()) == "hello", "the echo arrived garbled"); + } +} + +TEST(LoopbackIpv6, TcpEchoToColonColonOneNeverTouchesTheChannel) +{ + Host host; + echo_round_trip(host, LOOPBACK6); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(LoopbackIpv6, TcpEchoToTheStacksOwnV6AddressNeverTouchesTheChannel) +{ + Host host; + echo_round_trip(host, OWN6); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(LoopbackIpv6, UdpOverColonColonOneCarriesItAsSource) +{ + Host host; + std::optional from; + std::string got; + host.stack->bind_udp(5000)->set_datagram_received_callback( + [&](const IpAddress& source, uint16_t, const Bytes& data) + { + from = source; + got = text_of(data); + }); + host.stack->bind_udp(5001)->send_to(LOOPBACK6, 5000, Bytes::from_hex("70696e67")); + host.pump(5); + ASSERT_EQ(got, "ping"); + ASSERT_TRUE(from.has_value() && from->is_v6() && from->v6() == LOOPBACK6) << "source should be ::1"; + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(LoopbackIpv6, PingToColonColonOneIsAnswered) +{ + Host host; + std::optional sequence; + Bytes payload; + host.stack->set_echo_reply_callback( + [&](const IpAddress&, uint16_t, uint16_t seq, const Bytes& data) + { + sequence = seq; + payload = data; + }); + host.stack->send_echo_request(LOOPBACK6, 0x1234, 9, Bytes::from_hex("abcd")); + host.pump(5); + ASSERT_TRUE(sequence.has_value()) << "no echo reply came back"; + ASSERT_EQ(*sequence, 9); + ASSERT_EQ(payload.to_hex(), "abcd"); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(LoopbackIpv6, ColonColonOneNeedsNoRouteOrAddressOfItsOwn) +{ + // A stack with v6 switched on but no address at all still has a loopback. + auto guard_channel = std::make_unique(); + GuardChannel* guard = guard_channel.get(); + InterfaceConfig config; + config.mac = MAC; + config.ip = IPv4Address("10.0.0.2"); + NetworkStack stack(std::move(guard_channel), config); + std::string got; + stack.bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes& data) + { got = text_of(data); }); + // add_ipv6_address() is what turns v6 on without starting DAD (a frame); + // the address it adds is unrelated to ::1, which must work regardless. + stack.add_ipv6_address(IPv6Address("2001:db8::1"), 64); + stack.bind_udp(5001)->send_to(LOOPBACK6, 5000, Bytes::from_hex("01")); + while (!stack.poll()) + { + } + ASSERT_EQ(got, "\x01"); + ASSERT_EQ(guard->writes(), 0u); +} + +TEST(LoopbackIpv6, ColonColonOneArrivingOnARealInterfaceIsDropped) +{ + Host host; + int delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + host.guard->push_inbound(udp6_frame(LOOPBACK6, OWN6, "spoof")); // source ::1 + host.guard->push_inbound(udp6_frame(PEER6, LOOPBACK6, "spoof")); // destination ::1 + host.pump(2); + ASSERT_EQ(delivered, 0); + ASSERT_EQ(host.stack->loopback_martian_drops(), 2u); + ASSERT_EQ(host.guard->writes(), 0u); +} + +TEST(LoopbackIpv6, ASourceThatIsTheStacksOwnAddressStillCountsAsNothingSpecial) +{ + // Only ::1 is a martian on the wire: an ordinary peer's datagram to an own + // address is delivered as ever. + Host host; + int delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + host.guard->push_inbound(udp6_frame(PEER6, OWN6, "hi")); + host.pump(2); + ASSERT_EQ(delivered, 1); + ASSERT_EQ(host.stack->loopback_martian_drops(), 0u); +} From 940ed90a7f1a3cb52d3b1c4234c6a107d62b4a24 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:15:10 +0200 Subject: [PATCH 03/13] loopback: a real interface's own-address source is a martian A packet arriving on a real interface whose source is one of this stack's own addresses (Linux's fib_validate_source rule) is dropped and counted, v4 and v6. Accepted, its replies would be addressed to a local address and land in the loopback queue, so a spoofed SYN with source == destination and equal ports (LAND) made the stack talk to itself. The unspecified v6 source used by DAD and router solicitation is not an own address and still passes. Also makes is_local_address() public for the socket layer. Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 2 +- src/network_stack.cpp | 15 ++++++++++---- src/network_stack_ipv6.cpp | 5 ++++- tests/src/test_loopback.cpp | 35 ++++++++++++++++++++++++++++++++ tests/src/test_loopback_ipv6.cpp | 15 ++++++++++++++ 5 files changed, 66 insertions(+), 6 deletions(-) diff --git a/include/network_stack.h b/include/network_stack.h index 116892b..c1dba6e 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -1039,7 +1039,7 @@ class NetworkStack static constexpr size_t LOOPBACK_INGRESS = static_cast(-1); // 127.0.0.0/8 or an address configured on an interface. bool _is_local_ipv4(const IPv4Address& address) const; - bool _is_local_address(const IpAddress& address) const; + bool is_local_address(const IpAddress& address) const; bool _is_local_ipv6(const IPv6Address& address) const; // The v6 receive path for a datagram off the loopback queue. void _handle_loopback_ipv6(const Bytes& packet); diff --git a/src/network_stack.cpp b/src/network_stack.cpp index 169bb4a..e755581 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -1000,7 +1000,7 @@ bool NetworkStack::_is_local_ipv4(const IPv4Address& address) const return false; } -bool NetworkStack::_is_local_address(const IpAddress& address) const +bool NetworkStack::is_local_address(const IpAddress& address) const { return address.is_v4() ? this->_is_local_ipv4(address.v4()) : this->_is_local_ipv6(address.v6()); } @@ -1521,8 +1521,15 @@ void NetworkStack::_handle_ip(size_t ingress, const Ip& ip, const Bytes& ip_byte // destination reaching the forwarding branch would be relayed. Dropping // here, before anything is parsed or forwarded, covers both. const bool from_loopback = ingress == LOOPBACK_INGRESS; + // + // The same goes for a source that is one of this host's own addresses + // (Linux's martian-source rule, fib_validate_source): nothing on the wire + // is us. Accepted, its replies would be addressed to a local address and + // so land in the loopback queue - a spoofed SYN with source == destination + // and equal ports (LAND) would make the stack talk to itself. if (!from_loopback - && (is_loopback_v4(IPv4Address(ip.get_src_address())) || is_loopback_v4(IPv4Address(ip.get_dest_address())))) + && (this->_is_local_ipv4(IPv4Address(ip.get_src_address())) + || is_loopback_v4(IPv4Address(ip.get_dest_address())))) { this->_loopback_martian_drops++; LOG_DEBUG("NetworkStack: dropping an IPv4 packet from " @@ -1964,7 +1971,7 @@ void NetworkStack::_handle_tcp(const IpAddress& source, const IpAddress& destina // A local peer's SYN came to the address it named, which is also the one // this side answers from (see _open_connection). const IpAddress local_ip = - source.is_v4() && !this->_is_local_address(source) ? IpAddress(this->_primary().config.ip) : destination; + source.is_v4() && !this->is_local_address(source) ? IpAddress(this->_primary().config.ip) : destination; uint32_t isn = this->_next_isn(local_ip, key.local_port, remote_ip, key.remote_port); if (old_send_next) { @@ -3072,7 +3079,7 @@ uint16_t NetworkStack::_local_mss_for(const IpAddress& peer) const { // A local peer is not behind any interface, so the interface MTU says // nothing about it: the loopback MTU does (see LOOPBACK_MTU). - if (this->_is_local_address(peer)) + if (this->is_local_address(peer)) { return static_cast(LOOPBACK_MTU - (peer.is_v4() ? 40 : 60)); } diff --git a/src/network_stack_ipv6.cpp b/src/network_stack_ipv6.cpp index 9f8d2b0..d95f967 100644 --- a/src/network_stack_ipv6.cpp +++ b/src/network_stack_ipv6.cpp @@ -380,7 +380,10 @@ void NetworkStack::_handle_ipv6(size_t ingress, const Bytes& packet, const MacAd // spoofed ::1 source would pass every "is this local" test made above // the transport, exactly as 127.0.0.1 would for v4. Only the loopback // queue delivers it, through _handle_loopback_ipv6(). - if (source == loopback_v6() || destination == loopback_v6()) + // An own unicast address as the source is a martian too (see _handle_ip); + // the unspecified source, which DAD and router solicitation use, is not + // an own address and passes. + if (source == loopback_v6() || destination == loopback_v6() || this->_is_our_ipv6(source)) { this->_loopback_martian_drops++; LOG_DEBUG("NetworkStack: dropping an IPv6 packet from " diff --git a/tests/src/test_loopback.cpp b/tests/src/test_loopback.cpp index f747bb3..ea997f3 100644 --- a/tests/src/test_loopback.cpp +++ b/tests/src/test_loopback.cpp @@ -360,3 +360,38 @@ TEST(Loopback, ABulkTransferUsesFullSizedSegmentsAndArrivesIntact) ASSERT_TRUE(intact) << "the stream was corrupted"; ASSERT_EQ(host.guard->writes(), 0u); } + +namespace +{ + // A TCP SYN as a peer on the wire would send it, built by hand: the + // checksum is valid, so only the address rules can reject it. + Bytes syn_frame(const IPv4Address& source, const IPv4Address& destination, uint16_t sport, uint16_t dport) + { + Tcp syn(sport, dport, 1000, 0, 5, 0x02, 65535, 0, 0); + syn.set_checksum(transport_checksum(source, destination, IpProtocol::TCP, syn.to_bytes())); + auto ip = std::make_unique(4, 5, 0, static_cast(20 + syn.to_bytes().size()), 0, 0, 0, 64, + IpProtocol::TCP, 0, source.get_address(), destination.get_address()); + *ip /= std::make_unique(syn.to_bytes()); + ip->compute_checksum(); + Ethernet frame(PEER_MAC, MAC, EtherType::IPv4); + frame /= std::move(ip); + return frame.to_bytes(); + } +} + +TEST(Loopback, ASpoofedOwnSourceSynOnARealInterfaceIsDroppedAndStartsNothing) +{ + // Linux's martian-source rule: nothing on the wire is us. Accepting it + // would send every reply into the loopback queue - and src == dst with the + // same port (LAND) would make the stack talk to itself. + Host host; + host.stack->listen(PORT); + host.guard->push_inbound(syn_frame(OWN, OWN, PORT, PORT)); // LAND + host.guard->push_inbound(syn_frame(OWN, OWN, 1234, PORT)); + host.guard->push_inbound(syn_frame(OWN, IPv4Address("10.0.0.9"), 1234, PORT)); + host.pump(5); + ASSERT_EQ(host.stack->loopback_martian_drops(), 3u); + ASSERT_FALSE(host.stack->has_pending_accept(PORT)); + ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()) << "no loopback traffic, no connection, no timers"; + ASSERT_EQ(host.guard->writes(), 0u); +} diff --git a/tests/src/test_loopback_ipv6.cpp b/tests/src/test_loopback_ipv6.cpp index 82fb841..9cafc10 100644 --- a/tests/src/test_loopback_ipv6.cpp +++ b/tests/src/test_loopback_ipv6.cpp @@ -220,3 +220,18 @@ TEST(LoopbackIpv6, ASourceThatIsTheStacksOwnAddressStillCountsAsNothingSpecial) ASSERT_EQ(delivered, 1); ASSERT_EQ(host.stack->loopback_martian_drops(), 0u); } + +TEST(LoopbackIpv6, ASpoofedOwnSourceOnARealInterfaceIsDropped) +{ + Host host; + int delivered = 0; + host.stack->bind_udp(5000)->set_datagram_received_callback([&](const IpAddress&, uint16_t, const Bytes&) + { delivered++; }); + host.guard->push_inbound(udp6_frame(OWN6, OWN6, "land")); + host.guard->push_inbound(udp6_frame(OWN6, PEER6, "spoof")); + host.pump(2); + ASSERT_EQ(delivered, 0); + ASSERT_EQ(host.stack->loopback_martian_drops(), 2u); + ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()); + ASSERT_EQ(host.guard->writes(), 0u); +} From 6f24127b77e8a221fba7d96d6f12f56e02f62e67 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:16:12 +0200 Subject: [PATCH 04/13] ustack: bind and sendto accept loopback; tests over the sim and the real driver bind() accepts any 127/8 address and ::1 (previously only the interface's own address), and a UDP datagram to a local address is sized by the loopback MTU rather than the interface's. Tests drive socket/bind/listen/connect/ accept/send/recv over 127.0.0.1, an own address and ::1 through the sim driver on a channel that fails on any write, and a connect over the real driver, which only completes because ms_until_next_timer() is 0. Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 5 +- src/ustack_stack.cpp | 10 +- tests/src/test_ustack_loopback.cpp | 182 ++++++++++++++++++++++++++ tests/src/test_ustack_real_driver.cpp | 33 +++++ 4 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 tests/src/test_ustack_loopback.cpp diff --git a/include/network_stack.h b/include/network_stack.h index c1dba6e..397de4b 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -378,6 +378,10 @@ class NetworkStack // Packets that arrived on a real interface with a loopback source or // destination and were dropped (RFC 1122 3.2.1.3; RFC 4291 2.5.3). uint64_t loopback_martian_drops() const { return _loopback_martian_drops; } + // Whether a datagram to this address stays in the host: 127.0.0.0/8, ::1, or + // an address configured on this stack. What the socket layer asks to accept + // a bind() and to size a datagram by the loopback MTU. + bool is_local_address(const IpAddress& address) const; uint64_t challenge_acks_sent() const { return _challenge_acks_sent; } uint64_t challenge_acks_suppressed() const { return _challenge_acks_suppressed; } // SYNs that ended a TIME_WAIT early to open a new connection on the same @@ -1039,7 +1043,6 @@ class NetworkStack static constexpr size_t LOOPBACK_INGRESS = static_cast(-1); // 127.0.0.0/8 or an address configured on an interface. bool _is_local_ipv4(const IPv4Address& address) const; - bool is_local_address(const IpAddress& address) const; bool _is_local_ipv6(const IPv6Address& address) const; // The v6 receive path for a datagram off the loopback queue. void _handle_loopback_ipv6(const Bytes& packet); diff --git a/src/ustack_stack.cpp b/src/ustack_stack.cpp index 0bb3cc4..4a7bd1a 100644 --- a/src/ustack_stack.cpp +++ b/src/ustack_stack.cpp @@ -523,8 +523,10 @@ namespace ustack return fail(EINVAL); // a v4-mapped address on an IPv6-only socket } const std::vector v6_addresses = _stack.ipv6_addresses(); - bool local = ip.is_v4() ? ip.v4() == IPv4Address() || ip.v4() == _stack.interface_config().ip - : ip.v6().is_unspecified() + // Loopback is always this host's: any 127/8 address and ::1 (what the + // stack's own loopback queue serves), besides the configured ones. + bool local = ip.is_v4() ? ip.v4() == IPv4Address() || _stack.is_local_address(ip) + : ip.v6().is_unspecified() || _stack.is_local_address(ip) || std::any_of(v6_addresses.begin(), v6_addresses.end(), [&ip](const Ipv6ConfiguredAddress& configured) { return configured.address == ip.v6(); }); @@ -777,7 +779,9 @@ namespace ustack { return fail(ENETUNREACH); } - if (len + (ip.is_v4() ? IP_UDP_HEADER_BYTES : IPV6_UDP_HEADER_BYTES) > _stack.interface_config().mtu) + // A datagram to this host never meets the interface's MTU. + const size_t mtu = _stack.is_local_address(ip) ? NetworkStack::LOOPBACK_MTU : _stack.interface_config().mtu; + if (len + (ip.is_v4() ? IP_UDP_HEADER_BYTES : IPV6_UDP_HEADER_BYTES) > mtu) { return fail(EMSGSIZE); } diff --git a/tests/src/test_ustack_loopback.cpp b/tests/src/test_ustack_loopback.cpp new file mode 100644 index 0000000..f7d76b7 --- /dev/null +++ b/tests/src/test_ustack_loopback.cpp @@ -0,0 +1,182 @@ +#include "test_support.h" +#include "guard_channel.h" +#include "sim/sim_network.h" +#include "sim/ustack_sim_driver.h" +#include "ustack/stack.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +// The socket API over loopback: one ustack::Stack, driven by the simulator's +// virtual time, on a GuardChannel that fails the test on any write. Everything +// below must work with the wire untouched. +class UstackLoopback : public ::testing::Test +{ +protected: + UstackLoopback() + { + auto channel = std::make_unique(); + guard = channel.get(); + NetworkStack& net_stack = net.add_stack(std::move(channel), MacAddress("02:00:00:00:00:01"), own_ip); + net_stack.add_ipv6_address(IPv6Address("fd00::1"), 64); + stack = std::make_unique(net_stack, std::make_unique(net)); + } + + static sockaddr_in addr4(const char* text, uint16_t port) + { + sockaddr_in in{}; + in.sin_family = AF_INET; + in.sin_port = htons(port); + inet_pton(AF_INET, text, &in.sin_addr); + return in; + } + + static sockaddr_in6 addr6(const char* text, uint16_t port) + { + sockaddr_in6 in{}; + in.sin6_family = AF_INET6; + in.sin6_port = htons(port); + inet_pton(AF_INET6, text, &in.sin6_addr); + return in; + } + + static const sockaddr* sa(const sockaddr_in& in) { return reinterpret_cast(&in); } + static const sockaddr* sa(const sockaddr_in6& in) { return reinterpret_cast(&in); } + + // Waits on `fd` for `events` through the stack's own epoll, in virtual time. + bool wait_for(int fd, uint32_t events, int timeout_ms = 5000) + { + int epfd = stack->epoll_create1(0); + epoll_event event{}; + event.events = events; + event.data.fd = fd; + EXPECT_EQ(stack->epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event), 0) << std::strerror(errno); + epoll_event out[4]; + int n = stack->epoll_wait(epfd, out, 4, timeout_ms); + stack->close(epfd); + return n > 0 && (out[0].events & events) != 0; + } + + // listen on `listen_addr`, connect to `connect_addr`, echo "hello" both ways. + template + void echo(int family, const Sockaddr& listen_addr, const Sockaddr& connect_addr) + { + int listener = stack->socket(family, SOCK_STREAM | SOCK_NONBLOCK, 0); + ASSERT_GE(listener, 0); + ASSERT_EQ(stack->bind(listener, sa(listen_addr), sizeof(listen_addr)), 0) << std::strerror(errno); + ASSERT_EQ(stack->listen(listener, 8), 0); + + int client = stack->socket(family, SOCK_STREAM | SOCK_NONBLOCK, 0); + ASSERT_EQ(stack->connect(client, sa(connect_addr), sizeof(connect_addr)), -1); + ASSERT_EQ(errno, EINPROGRESS); + ASSERT_TRUE(wait_for(listener, EPOLLIN)) << "nothing to accept"; + int server = stack->accept4(listener, nullptr, nullptr, SOCK_NONBLOCK); + ASSERT_GE(server, 0) << std::strerror(errno); + ASSERT_TRUE(wait_for(client, EPOLLOUT)) << "connect never completed"; + int error = -1; + socklen_t length = sizeof(error); + ASSERT_EQ(stack->getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &length), 0); + ASSERT_EQ(error, 0); + + ASSERT_EQ(stack->send(client, "hello", 5, 0), 5); + ASSERT_TRUE(wait_for(server, EPOLLIN)); + char buffer[16] = {}; + ASSERT_EQ(stack->recv(server, buffer, sizeof(buffer), 0), 5); + ASSERT_EQ(std::string(buffer, 5), "hello"); + ASSERT_EQ(stack->send(server, buffer, 5, 0), 5); + ASSERT_TRUE(wait_for(client, EPOLLIN)); + std::memset(buffer, 0, sizeof(buffer)); + ASSERT_EQ(stack->recv(client, buffer, sizeof(buffer), 0), 5); + ASSERT_EQ(std::string(buffer, 5), "hello"); + ASSERT_EQ(guard->writes(), 0u); + } + + SimNetwork net{7}; + const IPv4Address own_ip{"10.0.0.2"}; + GuardChannel* guard = nullptr; + std::unique_ptr stack; +}; + +TEST_F(UstackLoopback, TcpOver127001) +{ + echo(AF_INET, addr4("127.0.0.1", 7000), addr4("127.0.0.1", 7000)); +} + +TEST_F(UstackLoopback, AWildcardListenerAcceptsALoopbackConnect) +{ + echo(AF_INET, addr4("0.0.0.0", 7000), addr4("127.0.0.1", 7000)); +} + +TEST_F(UstackLoopback, TcpOverTheStacksOwnAddress) +{ + echo(AF_INET, addr4("10.0.0.2", 7000), addr4("10.0.0.2", 7000)); +} + +TEST_F(UstackLoopback, TcpOverColonColonOne) +{ + echo(AF_INET6, addr6("::1", 7000), addr6("::1", 7000)); +} + +TEST_F(UstackLoopback, AnyAddressIn127SlashEightCanBeBound) +{ + int fd = stack->socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); + sockaddr_in in = addr4("127.5.6.7", 5000); + ASSERT_EQ(stack->bind(fd, sa(in), sizeof(in)), 0) << std::strerror(errno); + int other = stack->socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); + sockaddr_in foreign = addr4("10.9.9.9", 5001); + ASSERT_EQ(stack->bind(other, sa(foreign), sizeof(foreign)), -1); + ASSERT_EQ(errno, EADDRNOTAVAIL) << "an address that is not this host's is still refused"; +} + +TEST_F(UstackLoopback, AConnectToAClosedLoopbackPortIsRefused) +{ + int client = stack->socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); + sockaddr_in to = addr4("127.0.0.1", 9); + ASSERT_EQ(stack->connect(client, sa(to), sizeof(to)), -1); + ASSERT_EQ(errno, EINPROGRESS); + ASSERT_TRUE(wait_for(client, EPOLLERR | EPOLLHUP | EPOLLOUT)); + int error = 0; + socklen_t length = sizeof(error); + ASSERT_EQ(stack->getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &length), 0); + ASSERT_EQ(error, ECONNREFUSED); + ASSERT_EQ(guard->writes(), 0u); +} + +TEST_F(UstackLoopback, UdpOver127001AndColonColonOneCarriesBigDatagrams) +{ + int receiver = stack->socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); + sockaddr_in bound = addr4("127.0.0.1", 5000); + ASSERT_EQ(stack->bind(receiver, sa(bound), sizeof(bound)), 0); + int sender = stack->socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); + // Larger than the interface MTU: a datagram to this host never meets it. + std::string big(8000, 'x'); + ASSERT_EQ(stack->sendto(sender, big.data(), big.size(), 0, sa(bound), sizeof(bound)), + static_cast(big.size())) + << std::strerror(errno); + ASSERT_TRUE(wait_for(receiver, EPOLLIN)); + std::string got(9000, '\0'); + sockaddr_in from{}; + socklen_t from_length = sizeof(from); + ssize_t n = stack->recvfrom(receiver, got.data(), got.size(), 0, reinterpret_cast(&from), &from_length); + ASSERT_EQ(n, static_cast(big.size())); + char text[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, &from.sin_addr, text, sizeof(text)); + ASSERT_EQ(std::string(text), "127.0.0.1"); + + int receiver6 = stack->socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0); + sockaddr_in6 bound6 = addr6("::1", 5002); + ASSERT_EQ(stack->bind(receiver6, sa(bound6), sizeof(bound6)), 0) << std::strerror(errno); + int sender6 = stack->socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, 0); + ASSERT_EQ(stack->sendto(sender6, "v6", 2, 0, sa(bound6), sizeof(bound6)), 2) << std::strerror(errno); + ASSERT_TRUE(wait_for(receiver6, EPOLLIN)); + char small[8]; + ASSERT_EQ(stack->recvfrom(receiver6, small, sizeof(small), 0, nullptr, nullptr), 2); + ASSERT_EQ(guard->writes(), 0u); +} diff --git a/tests/src/test_ustack_real_driver.cpp b/tests/src/test_ustack_real_driver.cpp index 4ee71fe..d5317f7 100644 --- a/tests/src/test_ustack_real_driver.cpp +++ b/tests/src/test_ustack_real_driver.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -226,3 +227,35 @@ TEST_F(UstackRealDriver, ExternalFdMixesWithStackSocketsAndRejectsBadRequests) ASSERT_EQ(client->close(ep), 0); ::close(efd); } + +// Loopback traffic has no fd, so only ms_until_next_timer() reading 0 keeps the +// real driver from sleeping through it: a connect to 127.0.0.1 completes with +// no timer armed and no frame on the link. +TEST(UstackRealDriverLoopback, AConnectTo127001CompletesWithoutTheWire) +{ + int fds[2] = {-1, -1}; + ASSERT_EQ(::socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds), 0) << std::strerror(errno); + ustack::Stack stack(std::make_unique(std::make_unique(fds[0]), + MacAddress("02:00:00:00:00:01"), CLIENT_IP)); + sockaddr_in loopback = address(IPv4Address("127.0.0.1"), PORT); + int listener = stack.socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); + ASSERT_EQ(stack.bind(listener, reinterpret_cast(&loopback), sizeof(loopback)), 0); + ASSERT_EQ(stack.listen(listener, 4), 0); + int client = stack.socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); + ASSERT_EQ(stack.connect(client, reinterpret_cast(&loopback), sizeof(loopback)), -1); + ASSERT_EQ(errno, EINPROGRESS); + + int epfd = stack.epoll_create1(0); + epoll_event event{}; + event.events = EPOLLIN; + event.data.fd = listener; + ASSERT_EQ(stack.epoll_ctl(epfd, EPOLL_CTL_ADD, listener, &event), 0); + epoll_event out[2]; + ASSERT_EQ(stack.epoll_wait(epfd, out, 2, 2000), 1) << "the handshake stalled"; + ASSERT_GE(stack.accept4(listener, nullptr, nullptr, SOCK_NONBLOCK), 0); + + char byte = 0; + ASSERT_EQ(::recv(fds[1], &byte, 1, MSG_DONTWAIT), -1) << "something reached the link"; + ASSERT_EQ(errno, EAGAIN); + ::close(fds[1]); +} From b669b3ee4c2a215697b8753e5a8078ad316b6910 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:17:23 +0200 Subject: [PATCH 05/13] tcp: an ephemeral port never equals a local listener's port Found by the loopback differential: a ustack socket layer binds port 0 from its own counter and connect() from the stack's, both starting at 49152, so a connect to a local listener came from the listener's own port - source == destination, equal ports - and was a connection to itself. Harmless between two hosts, fatal on loopback. The allocator now steps over listening ports. Co-Authored-By: Claude Opus 5.5 --- src/network_stack.cpp | 6 ++++++ tests/src/test_loopback.cpp | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/network_stack.cpp b/src/network_stack.cpp index e755581..61c5c86 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -508,6 +508,12 @@ TcpConnection* NetworkStack::connect(const IpAddress& remote_ip, uint16_t remote { ephemeral_port = this->_allocate_ephemeral_port(); found_free_port = this->_connections.count(ConnectionKey{remote_ip, remote_port, ephemeral_port}) == 0; + // Never a port this stack listens on, as Linux's allocator. Harmless + // between two hosts; to a local peer it is a connection to itself, + // source and destination equal, which is what a listener sharing the + // ephemeral range (a socket layer that binds port 0) would otherwise + // meet on its first loopback connect. + found_free_port = found_free_port && this->_listening_ports.count(ephemeral_port) == 0; } if (!found_free_port) { diff --git a/tests/src/test_loopback.cpp b/tests/src/test_loopback.cpp index ea997f3..d312fe7 100644 --- a/tests/src/test_loopback.cpp +++ b/tests/src/test_loopback.cpp @@ -395,3 +395,20 @@ TEST(Loopback, ASpoofedOwnSourceSynOnARealInterfaceIsDroppedAndStartsNothing) ASSERT_FALSE(host.stack->ms_until_next_timer().has_value()) << "no loopback traffic, no connection, no timers"; ASSERT_EQ(host.guard->writes(), 0u); } + +TEST(Loopback, AnEphemeralPortNeverEqualsALocalListenersPort) +{ + // Connecting to a listener of this same stack from the very port it + // listens on would be a connection to itself (source == destination, + // equal ports): the allocator has to step over it. 49152 is the first + // ephemeral port the stack hands out. + Host host; + host.stack->listen(49152); + TcpConnection* client = host.stack->connect(LOOPBACK, 49152); + ASSERT_TRUE(client != nullptr); + ASSERT_TRUE(host.pump_until([&] { return host.stack->has_pending_accept(49152); }, 3000)); + TcpConnection* server = host.stack->accept(49152); + ASSERT_TRUE(server != nullptr); + ASSERT_NE(client->get_local_port(), 49152); + ASSERT_NE(client->get_id(), server->get_id()); +} From 2fcaea6679319f5b1bce6ed5a1a0c59a8728e14a Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:17:23 +0200 Subject: [PATCH 06/13] tests: loopback cases in the ustack-vs-kernel differential (v4 and v6) The same scenarios run with ustack talking to itself over 127.0.0.1 / ::1 on a channel that fails on any write, compared line by line with the kernel's own loopback. Both stacks agree. Co-Authored-By: Claude Opus 5.5 --- tests/include/stack_harness.h | 35 ++++++++++++ tests/src/test_stack_differential.cpp | 13 +++++ tests/src/test_stack_differential_ipv6.cpp | 62 ++++++++++++++++++++++ 3 files changed, 110 insertions(+) diff --git a/tests/include/stack_harness.h b/tests/include/stack_harness.h index 72d97a4..188fed2 100644 --- a/tests/include/stack_harness.h +++ b/tests/include/stack_harness.h @@ -8,6 +8,7 @@ #include #include +#include "guard_channel.h" #include "sim/sim_network.h" #include "sim/ustack_sim_driver.h" #include "ustack/kernel_stack.h" @@ -61,6 +62,40 @@ namespace stack_harness std::unique_ptr _server; }; + // Client and server are the SAME ustack::Stack, talking over 127.0.0.1 - the + // counterpart of KernelHarness, which is how the kernel sees the scenario. + // The one interface sits on a channel that fails the test on any write, so + // the scenario passing means it never left the host. + class SimLoopbackHarness + { + public: + using StackT = ustack::Stack; + static constexpr const char* NAME = "ustack over its loopback"; + + SimLoopbackHarness() + { + NetworkStack& net_stack = _net.add_stack(std::make_unique(), MacAddress("02:00:00:00:00:01"), + IPv4Address("10.0.0.1")); + _stack = std::make_unique(net_stack, std::make_unique(_net)); + } + + StackT& server_stack() { return *_stack; } + StackT& client_stack() { return *_stack; } + static sockaddr_in server_address(uint16_t port) + { + sockaddr_in in{}; + in.sin_family = AF_INET; + in.sin_port = htons(port); + in.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + return in; + } + void settle(int ms) { _net.step(static_cast(ms)); } + + private: + SimNetwork _net{42}; + std::unique_ptr _stack; + }; + class KernelHarness { public: diff --git a/tests/src/test_stack_differential.cpp b/tests/src/test_stack_differential.cpp index 32a168d..0f550e6 100644 --- a/tests/src/test_stack_differential.cpp +++ b/tests/src/test_stack_differential.cpp @@ -407,3 +407,16 @@ TEST(StackDifferential, BufferOptionsReadBackDoubledLikeTheKernel) ASSERT_TRUE(ustack.size() == 4 && ustack[2] == "SO_RCVBUF: 131072" && ustack[3] == "SO_SNDBUF: 65536") << "doubling is the contract being compared, not just agreement"; } + +// The same scenarios with ustack talking to ITSELF over 127.0.0.1, against the +// kernel doing the same: the loopback path must be indistinguishable to an +// application from the kernel's. +TEST(StackDifferential, LoopbackUserVisibleBehaviourMatchesTheKernel) +{ + compare_traces(run_scenario(), run_scenario()); +} + +TEST(StackDifferential, LoopbackReconnectIntoAServerTimeWaitMatchesTheKernel) +{ + compare_traces(run_reconnect_scenario(), run_reconnect_scenario()); +} diff --git a/tests/src/test_stack_differential_ipv6.cpp b/tests/src/test_stack_differential_ipv6.cpp index 00f2b9a..776f22f 100644 --- a/tests/src/test_stack_differential_ipv6.cpp +++ b/tests/src/test_stack_differential_ipv6.cpp @@ -12,6 +12,7 @@ #include #include +#include "guard_channel.h" #include "sim/sim_network.h" #include "sim/ustack_sim_driver.h" #include "test_support.h" @@ -57,6 +58,29 @@ namespace std::unique_ptr _server; }; + // One ustack::Stack as both ends, over ::1 - the kernel's own view. + class SimLoopbackHarness6 + { + public: + using StackT = ustack::Stack; + SimLoopbackHarness6() + { + NetworkStack& net_stack = _net.add_stack(std::make_unique(), MacAddress("02:00:00:00:00:01"), + IPv4Address("10.0.0.1")); + net_stack.add_ipv6_address(IPv6Address("fd00::1")); + _stack = std::make_unique(net_stack, std::make_unique(_net)); + } + StackT& server_stack() { return *_stack; } + StackT& client_stack() { return *_stack; } + static const char* server_text() { return "::1"; } + static const char* server_mapped_text() { return "::ffff:127.0.0.1"; } + void settle(int ms) { _net.step(static_cast(ms)); } + + private: + SimNetwork _net{7}; + std::unique_ptr _stack; + }; + class KernelHarness6 { public: @@ -262,3 +286,41 @@ TEST(StackDifferentialIpv6, SocketBehaviourMatchesTheKernel) } } } + +// ustack to itself over ::1 against the kernel over ::1. +TEST(StackDifferentialIpv6, LoopbackSocketBehaviourMatchesTheKernel) +{ + { + int probe = ::socket(AF_INET6, SOCK_STREAM, 0); + if (probe < 0) + { + GTEST_SKIP() << "no IPv6 in this environment"; + } + sockaddr_in6 loopback = address6("::1", 0); + int rc = ::bind(probe, reinterpret_cast(&loopback), sizeof(loopback)); + ::close(probe); + if (rc != 0) + { + GTEST_SKIP() << "::1 is not configured here"; + } + } + std::vector ustack = run_scenario(); + std::vector kernel = run_scenario(); + ASSERT_EQ(ustack.size(), kernel.size()) << "the scenario took a different path"; + std::string report; + for (size_t i = 0; i < ustack.size(); i++) + { + if (ustack[i] != kernel[i]) + { + report += " ustack: " + ustack[i] + "\n kernel: " + kernel[i] + "\n\n"; + } + } + EXPECT_TRUE(report.empty()) << "unexplained differences:\n" << report; + if (!report.empty()) + { + for (const std::string& line : kernel) + { + std::cerr << "kernel: " << line << "\n"; + } + } +} From b1454e875a0a145d05a14100abbedf4dc847b17a Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:21:02 +0200 Subject: [PATCH 07/13] fuzz, docs: loopback seeds, loopback traffic in the stack harness, README section The stateful harness now sends datagrams and one connection to 127.0.0.1 and ::1 whenever its application runs, and seven new seeds put loopback and own-address sources and destinations on the wire (the martian paths, incl. LAND). README gains a Loopback section. Co-Authored-By: Claude Opus 5.5 --- README.md | 17 ++++++++++ fuzz/corpus/stack/loopback_app_traffic | Bin 0 -> 6 bytes fuzz/corpus/stack/loopback_destination_syn | Bin 0 -> 57 bytes fuzz/corpus/stack/loopback_destination_udp | Bin 0 -> 61 bytes fuzz/corpus/stack/loopback_source_udp | Bin 0 -> 61 bytes fuzz/corpus/stack/own_source_land_syn | Bin 0 -> 118 bytes fuzz/corpus/stack/own_source_ping | Bin 0 -> 55 bytes fuzz/gen_corpus.cpp | 37 +++++++++++++++++++-- fuzz/stack.cpp | 17 ++++++++++ 9 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 fuzz/corpus/stack/loopback_app_traffic create mode 100644 fuzz/corpus/stack/loopback_destination_syn create mode 100644 fuzz/corpus/stack/loopback_destination_udp create mode 100644 fuzz/corpus/stack/loopback_source_udp create mode 100644 fuzz/corpus/stack/own_source_land_syn create mode 100644 fuzz/corpus/stack/own_source_ping diff --git a/README.md b/README.md index f4db72f..7edd2ee 100644 --- a/README.md +++ b/README.md @@ -453,6 +453,23 @@ segment cannot advance it and make PAWS drop the real ones. `send()` is bounded accepted, and `listen()` takes a backlog so the accept queue cannot be grown without limit by a peer. +**Loopback.** A datagram to `127.0.0.0/8`, to `::1`, or to one of the stack's own addresses never +reaches routing, ARP or a channel. It is built as for the wire and put on a bounded queue +(1024 datagrams; one that finds it full is dropped and counted in `loopback_drops()`, which TCP +recovers by retransmitting). `poll()` delivers the queue - before the channels, at most half +its frame budget per call, and only what was queued when it started, so a send never +re-enters a receive path and a local ping-pong cannot hold `poll()` - and returns `false` +until the queue is empty. `ms_until_next_timer()` reads 0 while it is not, because there is +no fd to wake a driver that sleeps. There is no pseudo-interface: nothing that iterates +interfaces sees one, and DHCP, ARP and the neighbour caches are untouched. The source of a +local datagram is its destination (as on Linux), the loopback MTU is 65535 (the most a 16-bit +IPv4 total length or IPv6 payload length can say, so loopback never fragments) and a local +connection's MSS comes from it (65495 for v4, 65475 for v6). On a real interface a `127/8` or +`::1` source or destination, or one of the stack's own addresses as a source, is dropped and +counted in `loopback_martian_drops()` (RFC 1122 3.2.1.3; Linux's martian-source rule, which +also stops a spoofed own-address SYN from making the stack talk to itself) - so forwarding +can never route to or from loopback. ustack's `bind()` accepts any `127/8` address and `::1`. + ## Deliberately out of scope These are documented decisions, not gaps that were missed: diff --git a/fuzz/corpus/stack/loopback_app_traffic b/fuzz/corpus/stack/loopback_app_traffic new file mode 100644 index 0000000000000000000000000000000000000000..b888f1e72f0684136702e48185738a00ca107f69 GIT binary patch literal 6 NcmZQzaAaVp2LJ(y0KotN literal 0 HcmV?d00001 diff --git a/fuzz/corpus/stack/loopback_destination_syn b/fuzz/corpus/stack/loopback_destination_syn new file mode 100644 index 0000000000000000000000000000000000000000..a30925b203d6179972486d4790bc9841d09837b9 GIT binary patch literal 57 zcmZQDV`O3g0tm^(!QjfkpaBwaVEcHMi-Ccu9w;}*fgyl_f%yeUJb>x{|F(1n1^}Dw B2$%o> literal 0 HcmV?d00001 diff --git a/fuzz/corpus/stack/loopback_destination_udp b/fuzz/corpus/stack/loopback_destination_udp new file mode 100644 index 0000000000000000000000000000000000000000..5cf98f262f19316f8abd10ef71f284f0dff71f67 GIT binary patch literal 61 wcmZRuVq{_f0wyrY$id*sz@Q^!!oc7lc)yDaC|=LNz{qlm!IVJ)qzn}R0Fo*MYXATM literal 0 HcmV?d00001 diff --git a/fuzz/corpus/stack/loopback_source_udp b/fuzz/corpus/stack/loopback_source_udp new file mode 100644 index 0000000000000000000000000000000000000000..37c7c0d9343514fd8f4544f5f9080bb788497251 GIT binary patch literal 61 vcmZRuVq{_f0wyrY$id*sz@Q^!!oc7lc)z=zfq{_=h*>T%m@-I!l%WCulmY~6 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/stack/own_source_land_syn b/fuzz/corpus/stack/own_source_land_syn new file mode 100644 index 0000000000000000000000000000000000000000..592be5c823e85ac849885424f5701aa1a720000d GIT binary patch literal 118 zcmZQDV`O3g0tm^(!QjfkpaBwaU`spC1r!Hih5#UBV15A-4`BNLe|jX4VFlF!(GJ$A YBV+>9C>YWM)5vm(!IVJ)qzx4S0GFf+djJ3c literal 0 HcmV?d00001 diff --git a/fuzz/corpus/stack/own_source_ping b/fuzz/corpus/stack/own_source_ping new file mode 100644 index 0000000000000000000000000000000000000000..ca34e88622cc4907837f289cd2bbe6aaa2b149d8 GIT binary patch literal 55 vcmZQDVPawc0tm^-!QjfkpeAI(z~I0bvWSa;ff0l`7{2deaAIHtDTDw3X#xa7 literal 0 HcmV?d00001 diff --git a/fuzz/gen_corpus.cpp b/fuzz/gen_corpus.cpp index ff9cf0b..df648f6 100644 --- a/fuzz/gen_corpus.cpp +++ b/fuzz/gen_corpus.cpp @@ -72,7 +72,8 @@ namespace } // An Ethernet frame carrying `payload` as IPv4 with protocol `protocol`. - Bytes ip_frame(uint8_t protocol, const Bytes& payload, uint16_t flags_and_offset = 0) + Bytes ip_frame(uint8_t protocol, const Bytes& payload, uint16_t flags_and_offset = 0, + const IPv4Address& source = IP_B, const IPv4Address& destination = IP_A) { Bytes ip; ip.push_back(0x45); @@ -83,8 +84,8 @@ namespace ip.push_back(64); ip.push_back(protocol); ip.append_int(0); - ip |= IP_B.get_address(); - ip |= IP_A.get_address(); + ip |= source.get_address(); + ip |= destination.get_address(); uint16_t sum = internet_checksum(ip); ip[10] = static_cast(sum >> 8); ip[11] = static_cast(sum); @@ -392,6 +393,36 @@ int main(int argc, char** argv) save("stack", "fragments", stack_item(frag, 0x00) | stack_item(last, 0x1f)); } save("stack", "idle_then_close", stack_item(Bytes(), 0x7f) | stack_item(data, 0x7f)); + { + // Local addresses on the wire: loopback sources and destinations, and + // the stack's own address as a source (LAND: source == destination, equal + // ports). All are martians the stack must drop without a trace; the + // harness's own loopback sends (see World::application) share the queue. + const IPv4Address loopback("127.0.0.1"); + Bytes udp_to_dns = udp_datagram(1234, 53, Bytes(16)); + Bytes land = tcp_frame::build( + [&] + { + tcp_frame::Segment s = segment(1000, 0, tcp_frame::SYN); + s.src_ip = IP_A; + s.src_port = 80; + return s; + }()); + Bytes loopback_syn = tcp_frame::build( + [&] + { + tcp_frame::Segment s = segment(1000, 0, tcp_frame::SYN); + s.dst_ip = loopback; + return s; + }()); + save("stack", "loopback_source_udp", stack_item(ip_frame(17, udp_to_dns, 0, loopback, IP_A), 0x01)); + save("stack", "loopback_destination_udp", stack_item(ip_frame(17, udp_to_dns, 0, IP_B, loopback), 0x01)); + save("stack", "loopback_destination_syn", stack_item(loopback_syn, 0x01)); + save("stack", "own_source_land_syn", + stack_item(land, 0x01) | stack_item(ip_frame(17, udp_to_dns, 0, IP_A, IP_A), 0x01)); + save("stack", "own_source_ping", stack_item(ip_frame(1, icmp_echo(8, Bytes(10)), 0, IP_A, IP_A), 0x02)); + save("stack", "loopback_app_traffic", stack_item(Bytes(), 0x41) | stack_item(Bytes(), 0x7f)); + } { // A lying receiver's D-SACKs (RFC 2883), against a connection with a // timed-out segment: the application writes 200 bytes, 1.25 s pass diff --git a/fuzz/stack.cpp b/fuzz/stack.cpp index d43bf52..c178ecb 100644 --- a/fuzz/stack.cpp +++ b/fuzz/stack.cpp @@ -137,6 +137,7 @@ namespace std::unique_ptr stack; uint64_t connection_id = 0; bool have_connection = false; + bool loopback_connected = false; World() { @@ -203,8 +204,24 @@ namespace channel->clear_outbound(); } + // The stack talking to itself: datagrams and one connection over + // 127.0.0.1 and ::1, through the loopback queue the frames above + // share it with. poll() between frames delivers them. + void loopback_traffic() + { + UdpSocket* socket = stack->bind_udp(54); + socket->send_to(IPv4Address("127.0.0.1"), 53, Bytes(8)); + socket->send_to(IPv6Address("::1"), 53, Bytes(8)); + if (!loopback_connected) + { + loopback_connected = true; + stack->connect(IPv4Address("127.0.0.1"), LOCAL_PORT); + } + } + void application(bool closing) { + loopback_traffic(); if (!have_connection) return; TcpConnection* c = stack->find_connection(connection_id); From 895a28b770d9c13f39390949bfaae879db96cb28 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:21:46 +0200 Subject: [PATCH 08/13] loopback: initialise LoopbackDatagram::v6 (cppcheck) Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/network_stack.h b/include/network_stack.h index 397de4b..c6a5323 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -1029,7 +1029,7 @@ class NetworkStack // link, so nothing in a packet depends on one. struct LoopbackDatagram { - bool v6; + bool v6 = false; Bytes packet; }; std::deque _loopback_queue; From d46a64fb912b1ee7d336ae20a3ab69171d8b5403 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:29:39 +0200 Subject: [PATCH 09/13] loopback: bound the queue in bytes too, and move packets through it Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 7 ++++++- src/network_stack.cpp | 10 +++++++--- src/network_stack_ipv6.cpp | 2 +- tests/src/test_loopback.cpp | 21 +++++++++++++++++++++ 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/include/network_stack.h b/include/network_stack.h index c6a5323..cc6c4e0 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -373,8 +373,12 @@ class NetworkStack // and the IPv6 payload length (16 bits, header excluded) can carry: a // loopback segment is never fragmented, and TCP's MSS on a loopback route // is derived from it (MTU less 40 for v4, less 60 for v6). + // And in bytes: 1024 datagrams of 64 KiB would otherwise be 64 MiB held + // for a loop that can be fed faster than it is drained. Either limit drops. + static constexpr size_t LOOPBACK_QUEUE_BYTE_LIMIT = 4 * 1024 * 1024; static constexpr uint16_t LOOPBACK_MTU = 65535; uint64_t loopback_drops() const { return _loopback_drops; } + size_t loopback_queued_bytes() const { return _loopback_queued_bytes; } // Packets that arrived on a real interface with a loopback source or // destination and were dropped (RFC 1122 3.2.1.3; RFC 4291 2.5.3). uint64_t loopback_martian_drops() const { return _loopback_martian_drops; } @@ -1034,6 +1038,7 @@ class NetworkStack }; std::deque _loopback_queue; uint64_t _loopback_drops = 0; + size_t _loopback_queued_bytes = 0; uint64_t _loopback_martian_drops = 0; // The "ingress interface" of a datagram taken off the loopback queue. Not // an index into _interfaces on purpose: there is no pseudo-interface (code @@ -1051,7 +1056,7 @@ class NetworkStack // local datagram is handled by the code that handles any other. void _deliver_ipv6(const Ipv6& ip, const Bytes& packet, bool link_layer_group, bool from_loopback); // Queues a built packet, or drops and counts it when the queue is full. - void _enqueue_loopback(bool v6, const Bytes& packet); + void _enqueue_loopback(bool v6, Bytes&& packet); // Delivers up to `limit` of the datagrams queued now - not those queued // by delivering them - and returns how many it took. size_t _drain_loopback(size_t limit); diff --git a/src/network_stack.cpp b/src/network_stack.cpp index 61c5c86..4385b38 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -1011,9 +1011,10 @@ bool NetworkStack::is_local_address(const IpAddress& address) const return address.is_v4() ? this->_is_local_ipv4(address.v4()) : this->_is_local_ipv6(address.v6()); } -void NetworkStack::_enqueue_loopback(bool v6, const Bytes& packet) +void NetworkStack::_enqueue_loopback(bool v6, Bytes&& packet) { - if (this->_loopback_queue.size() >= LOOPBACK_QUEUE_LIMIT) + if (this->_loopback_queue.size() >= LOOPBACK_QUEUE_LIMIT + || this->_loopback_queued_bytes + packet.size() > LOOPBACK_QUEUE_BYTE_LIMIT) { // Loss, as on a full transmit queue: TCP retransmits, and UDP never // promised. Counted, since a loop that drops is otherwise invisible. @@ -1021,7 +1022,9 @@ void NetworkStack::_enqueue_loopback(bool v6, const Bytes& packet) LOG_DEBUG("NetworkStack: loopback queue full - dropping a datagram"); return; } - this->_loopback_queue.push_back({v6, packet}); + this->_loopback_queued_bytes += packet.size(); + // Moved all the way in: the packet is built once and never copied. + this->_loopback_queue.push_back({v6, std::move(packet)}); } size_t NetworkStack::_drain_loopback(size_t limit) @@ -1033,6 +1036,7 @@ size_t NetworkStack::_drain_loopback(size_t limit) { LoopbackDatagram datagram = std::move(this->_loopback_queue.front()); this->_loopback_queue.pop_front(); + this->_loopback_queued_bytes -= datagram.packet.size(); try { if (datagram.v6) diff --git a/src/network_stack_ipv6.cpp b/src/network_stack_ipv6.cpp index d95f967..3006e53 100644 --- a/src/network_stack_ipv6.cpp +++ b/src/network_stack_ipv6.cpp @@ -835,7 +835,7 @@ void NetworkStack::_send_ipv6_packet(const IPv6Address& source, const IPv6Addres if (local) { - this->_enqueue_loopback(true, packet); + this->_enqueue_loopback(true, std::move(packet)); return; } diff --git a/tests/src/test_loopback.cpp b/tests/src/test_loopback.cpp index d312fe7..969dd85 100644 --- a/tests/src/test_loopback.cpp +++ b/tests/src/test_loopback.cpp @@ -412,3 +412,24 @@ TEST(Loopback, AnEphemeralPortNeverEqualsALocalListenersPort) ASSERT_NE(client->get_local_port(), 49152); ASSERT_NE(client->get_id(), server->get_id()); } + +TEST(Loopback, TheQueueIsBoundedInBytesAsWellAsInDatagrams) +{ + // 1024 datagrams of 64 KiB would be 64 MiB: the count alone is no bound on + // memory. + Host host; + host.stack->bind_udp(5000); + UdpSocket* sender = host.stack->bind_udp(5001); + Bytes big(60000); + for (int i = 0; i < 100; i++) + { + sender->send_to(LOOPBACK, 5000, big); + } + ASSERT_LE(host.stack->loopback_queued_bytes(), NetworkStack::LOOPBACK_QUEUE_BYTE_LIMIT); + ASSERT_GT(host.stack->loopback_drops(), 0u); + ASSERT_GT(host.stack->loopback_queued_bytes(), NetworkStack::LOOPBACK_QUEUE_BYTE_LIMIT / 2) + << "it should still fill"; + host.pump(5); + ASSERT_EQ(host.stack->loopback_queued_bytes(), 0u); + ASSERT_EQ(host.guard->writes(), 0u); +} From 10e810ef8c02c4cb14ca3a89b4dd590584f53e88 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:29:53 +0200 Subject: [PATCH 10/13] tcp: a local connect never uses its destination port as its source port Co-Authored-By: Claude Opus 5.5 --- src/network_stack.cpp | 6 ++++++ tests/src/test_loopback.cpp | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/network_stack.cpp b/src/network_stack.cpp index 4385b38..fd0793b 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -502,6 +502,7 @@ TcpConnection* NetworkStack::connect(const IpAddress& remote_ip, uint16_t remote // under a live key would destroy that connection in place, leaving the // application's pointer to it dangling and its id finding this one. constexpr size_t EPHEMERAL_PORT_COUNT = 65536 - FIRST_EPHEMERAL_PORT; + const bool local_destination = this->is_local_address(remote_ip); uint16_t ephemeral_port = 0; bool found_free_port = false; for (size_t attempt = 0; attempt < EPHEMERAL_PORT_COUNT && !found_free_port; attempt++) @@ -514,6 +515,11 @@ TcpConnection* NetworkStack::connect(const IpAddress& remote_ip, uint16_t remote // ephemeral range (a socket layer that binds port 0) would otherwise // meet on its first loopback connect. found_free_port = found_free_port && this->_listening_ports.count(ephemeral_port) == 0; + // Nor, to a local peer, its own destination port: with no listener + // there the same collision arises (source == destination, equal + // ports). Linux would allow that simultaneous self-connect; this stack + // only wants not to fall into one by accident. + found_free_port = found_free_port && !(local_destination && ephemeral_port == remote_port); } if (!found_free_port) { diff --git a/tests/src/test_loopback.cpp b/tests/src/test_loopback.cpp index 969dd85..a9347b8 100644 --- a/tests/src/test_loopback.cpp +++ b/tests/src/test_loopback.cpp @@ -433,3 +433,14 @@ TEST(Loopback, TheQueueIsBoundedInBytesAsWellAsInDatagrams) ASSERT_EQ(host.stack->loopback_queued_bytes(), 0u); ASSERT_EQ(host.guard->writes(), 0u); } + +TEST(Loopback, ADestinationPortIsNeverTheSourcePortOfALocalConnect) +{ + // No listener, so only the destination port can collide: connecting to + // 49152 (the next ephemeral port) must not come from 49152, which would + // be a connection to itself. + Host host; + TcpConnection* client = host.stack->connect(LOOPBACK, 49152); + ASSERT_TRUE(client != nullptr); + ASSERT_NE(client->get_local_port(), 49152); +} From cc095eff96117667772883af2af352fd6864c7d6 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:31:01 +0200 Subject: [PATCH 11/13] loopback: decide local-ness once per send, and without allocating on receive _send_tcp_segment, _send_udp_datagram and _send_icmp_message ask once and hand the answer to _source_address_for and _send_ip_packet. The per-packet receive check read IPv4Address temporaries, each a heap Bytes; it now works on the header's octets. SimulatedBulkTransfer/0: 6.02 -> ~5.9 ms (base 5.82). Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 12 +++++++--- src/network_stack.cpp | 49 +++++++++++++++++++++++++++-------------- 2 files changed, 42 insertions(+), 19 deletions(-) diff --git a/include/network_stack.h b/include/network_stack.h index cc6c4e0..db834b8 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -733,8 +733,11 @@ class NetworkStack // not, because this stack fragments oversized datagrams itself and there is // no per-connection state to adjust in response. // `ecn` goes in the TOS octet's ECN field (RFC 3168); DSCP is 0. - void _send_ip_packet(const IPv4Address& dest_ip, uint8_t protocol, const Bytes& payload, bool dont_fragment = false, - Ecn ecn = Ecn::NOT_ECT); + // `local`: dest_ip is this host (_is_local_ipv4), decided once by the + // caller because the source address, the ARP hold-back and this function + // all need the answer. + void _send_ip_packet(const IPv4Address& dest_ip, bool local, uint8_t protocol, const Bytes& payload, + bool dont_fragment = false, Ecn ecn = Ecn::NOT_ECT); // local_v6 pins the source of a v6 segment - a connection's own address; // without it one is chosen for the destination. void _send_tcp_segment(const IpAddress& destination, const Tcp& header, const Bytes& payload, @@ -836,7 +839,7 @@ class NetworkStack // The address a packet to this destination will carry. Used by both the IP // header and the transport pseudo-header checksums, so that the two cannot // be computed from different answers - see its definition. - IPv4Address _source_address_for(const IPv4Address& destination) const; + IPv4Address _source_address_for(const IPv4Address& destination, bool local) const; // True if this address is the limited broadcast, or the directed broadcast // of ANY of this stack's links. // @@ -1048,6 +1051,9 @@ class NetworkStack static constexpr size_t LOOPBACK_INGRESS = static_cast(-1); // 127.0.0.0/8 or an address configured on an interface. bool _is_local_ipv4(const IPv4Address& address) const; + // The same test on the four raw octets, with no IPv4Address (and so no + // allocation) built - what the per-packet receive check uses. + bool _is_local_octets(const Bytes& octets) const; bool _is_local_ipv6(const IPv6Address& address) const; // The v6 receive path for a datagram off the loopback queue. void _handle_loopback_ipv6(const Bytes& packet); diff --git a/src/network_stack.cpp b/src/network_stack.cpp index fd0793b..7fe0442 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -49,6 +49,14 @@ namespace return address.get_address()[0] == 127; } + // The same on the raw octets of a parsed header. An IPv4Address owns a + // heap-allocated Bytes, so building one per packet just to look at it + // costs an allocation each; the receive path asks on every packet. + bool is_loopback_v4(const Bytes& octets) + { + return octets[0] == 127; + } + bool is_multicast(const IPv4Address& address) { return (address.get_address()[0] & 0xF0) == 0xE0; @@ -998,13 +1006,18 @@ bool NetworkStack::poll() bool NetworkStack::_is_local_ipv4(const IPv4Address& address) const { - if (is_loopback_v4(address)) + return this->_is_local_octets(address.get_address()); +} + +bool NetworkStack::_is_local_octets(const Bytes& octets) const +{ + if (is_loopback_v4(octets)) { return true; } for (const auto& interface : this->_interfaces) { - if (interface->config.has_address() && address == interface->config.ip) + if (interface->config.has_address() && octets == interface->config.ip.get_address()) { return true; } @@ -1543,9 +1556,7 @@ void NetworkStack::_handle_ip(size_t ingress, const Ip& ip, const Bytes& ip_byte // is us. Accepted, its replies would be addressed to a local address and // so land in the loopback queue - a spoofed SYN with source == destination // and equal ports (LAND) would make the stack talk to itself. - if (!from_loopback - && (this->_is_local_ipv4(IPv4Address(ip.get_src_address())) - || is_loopback_v4(IPv4Address(ip.get_dest_address())))) + if (!from_loopback && (this->_is_local_octets(ip.get_src_address()) || is_loopback_v4(ip.get_dest_address()))) { this->_loopback_martian_drops++; LOG_DEBUG("NetworkStack: dropping an IPv4 packet from " @@ -2817,7 +2828,7 @@ bool NetworkStack::_is_broadcast_for_any_interface(const IPv4Address& ip) const return false; } -IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip) const +IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip, bool local) const { // The single answer to "what address will a packet to dest_ip carry". // @@ -2832,7 +2843,7 @@ IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip) const // 127.0.0.1, an own address for that address), as on Linux: the peer that // answers then replies from the address it was sent to, and a reply // matches the connection it belongs to. - if (this->_is_local_ipv4(dest_ip)) + if (local) { return dest_ip; } @@ -2845,7 +2856,7 @@ IPv4Address NetworkStack::_source_address_for(const IPv4Address& dest_ip) const return this->_interfaces.at(egress)->config.ip; } -void NetworkStack::_send_ip_packet(const IPv4Address& dest_ip, uint8_t protocol, const Bytes& payload, +void NetworkStack::_send_ip_packet(const IPv4Address& dest_ip, bool local, uint8_t protocol, const Bytes& payload, bool dont_fragment, Ecn ecn) { // Local: no route, no ARP, no frame. The packet is built exactly as it @@ -2854,7 +2865,7 @@ void NetworkStack::_send_ip_packet(const IPv4Address& dest_ip, uint8_t protocol, // (see _source_address_for). Never fragmented: the loopback MTU is the // most an IPv4 total-length field can say, so anything that fits an IP // packet at all fits here. - if (this->_is_local_ipv4(dest_ip)) + if (local) { if (20 + payload.size() > LOOPBACK_MTU) { @@ -3023,8 +3034,12 @@ void NetworkStack::_send_tcp_segment(const IpAddress& destination, const Tcp& he } const IPv4Address& dest_ip = destination.v4(); + // Decided once per segment and handed down: it feeds the source address + // (and so the checksum), the ARP hold-back and the IP layer, and asking + // three times was measurable on the bulk path. + const bool local = this->_is_local_ipv4(dest_ip); uint16_t checksum = - transport_checksum(this->_source_address_for(dest_ip), dest_ip, IpProtocol::TCP, segment.to_bytes()); + transport_checksum(this->_source_address_for(dest_ip, local), dest_ip, IpProtocol::TCP, segment.to_bytes()); segment.set_checksum(checksum); // A next hop with no ARP entry - an idle peer's entry aged out mid- @@ -3034,7 +3049,7 @@ void NetworkStack::_send_tcp_segment(const IpAddress& destination, const Tcp& he // queue is needed here (unlike UDP, which has no retransmission). IPv4Address next_hop; size_t egress = 0; - if (!this->_is_local_ipv4(dest_ip) && this->_route_for(dest_ip, next_hop, egress)) + if (!local && this->_route_for(dest_ip, next_hop, egress)) { const Interface& interface = *this->_interfaces.at(egress); if (!is_broadcast_address(next_hop, interface.config) && !interface.arp_table.contains(next_hop)) @@ -3046,7 +3061,7 @@ void NetworkStack::_send_tcp_segment(const IpAddress& destination, const Tcp& he } } - this->_send_ip_packet(dest_ip, IpProtocol::TCP, segment.to_bytes(), true, ecn); + this->_send_ip_packet(dest_ip, local, IpProtocol::TCP, segment.to_bytes(), true, ecn); } void NetworkStack::_send_rst(const IpAddress& source, const IpAddress& destination, const Tcp& tcp) @@ -3210,14 +3225,15 @@ void NetworkStack::_send_udp_datagram(const IPv4Address& dest_ip, const Udp& hea datagram /= std::make_unique(payload); } + const bool local = this->_is_local_ipv4(dest_ip); uint16_t checksum = - transport_checksum(this->_source_address_for(dest_ip), dest_ip, IpProtocol::UDP, datagram.to_bytes()); + transport_checksum(this->_source_address_for(dest_ip, local), dest_ip, IpProtocol::UDP, datagram.to_bytes()); // RFC 768: an all-zero result must be transmitted as all-ones instead - // 0 is reserved to mean "no checksum was computed", so a genuine result // of 0 would otherwise be indistinguishable from that datagram.set_checksum(checksum == 0 ? 0xFFFF : checksum); - this->_send_ip_packet(dest_ip, IpProtocol::UDP, datagram.to_bytes()); + this->_send_ip_packet(dest_ip, local, IpProtocol::UDP, datagram.to_bytes()); } void NetworkStack::_send_icmp_message(const IPv4Address& dest_ip, const Icmp& header, const Bytes& payload) @@ -3250,7 +3266,8 @@ void NetworkStack::_send_icmp_message(const IPv4Address& dest_ip, const Icmp& he // hop, so this one check covers both the neighbour and the via-gateway case. // // A local destination has no next hop, so none of this applies to it. - if (!this->_is_local_ipv4(dest_ip)) + const bool local = this->_is_local_ipv4(dest_ip); + if (!local) { IPv4Address next_hop; size_t egress = 0; @@ -3274,7 +3291,7 @@ void NetworkStack::_send_icmp_message(const IPv4Address& dest_ip, const Icmp& he // a fresh one from header's fields instead Icmp message(header.get_type(), header.get_code(), 0, header.get_rest_of_header(), payload); message.compute_checksum(); // no pseudo-header, no transport_checksum() - see Icmp's own class comment - this->_send_ip_packet(dest_ip, IpProtocol::ICMP, message.to_bytes()); + this->_send_ip_packet(dest_ip, local, IpProtocol::ICMP, message.to_bytes()); } bool NetworkStack::_may_report_error_for(const IPv4Address& source, const IPv4Address& destination, From 12b96c936d148998e65c7e0c5a086345bf0a4512 Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:31:06 +0200 Subject: [PATCH 12/13] ipv6: _is_our_ipv6 iterates the stored addresses instead of copying them Co-Authored-By: Claude Opus 5.5 --- src/network_stack_ipv6.cpp | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/network_stack_ipv6.cpp b/src/network_stack_ipv6.cpp index 3006e53..cd8cd6e 100644 --- a/src/network_stack_ipv6.cpp +++ b/src/network_stack_ipv6.cpp @@ -211,9 +211,29 @@ std::vector NetworkStack::ipv6_addresses() const bool NetworkStack::_is_our_ipv6(const IPv6Address& address) const { - const std::vector usable = this->ipv6_addresses(); - return std::any_of(usable.begin(), usable.end(), - [&address](const Ipv6ConfiguredAddress& a) { return a.address == address; }); + // In place, over what ipv6_addresses() would have copied: this runs on + // every v6 packet sent or received, and the copy was a heap vector each + // time. Same set - the static addresses, and autoconfigured ones that are + // preferred or deprecated (not tentative). + for (const Ipv6ConfiguredAddress& configured : this->_v6.addresses) + { + if (configured.address == address) + { + return true; + } + } + if (this->_v6.autoconfig) + { + for (const Ipv6ConfiguredAddress& configured : this->_v6.autoconfig->addresses()) + { + if ((configured.state == Ipv6AddressState::PREFERRED || configured.state == Ipv6AddressState::DEPRECATED) + && configured.address == address) + { + return true; + } + } + } + return false; } bool NetworkStack::_ipv6_group_joined(const IPv6Address& group) const From 43d13ecb821f948713b606a2ab857241b216c68b Mon Sep 17 00:00:00 2001 From: Yuval Kogan Date: Thu, 19 Nov 2026 20:34:14 +0200 Subject: [PATCH 13/13] loopback: lint fixes (unused overload, explicit size_t product) Co-Authored-By: Claude Opus 5.5 --- include/network_stack.h | 2 +- src/network_stack.cpp | 16 +++++----------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/include/network_stack.h b/include/network_stack.h index db834b8..d196697 100644 --- a/include/network_stack.h +++ b/include/network_stack.h @@ -375,7 +375,7 @@ class NetworkStack // is derived from it (MTU less 40 for v4, less 60 for v6). // And in bytes: 1024 datagrams of 64 KiB would otherwise be 64 MiB held // for a loop that can be fed faster than it is drained. Either limit drops. - static constexpr size_t LOOPBACK_QUEUE_BYTE_LIMIT = 4 * 1024 * 1024; + static constexpr size_t LOOPBACK_QUEUE_BYTE_LIMIT = size_t{4} * 1024 * 1024; static constexpr uint16_t LOOPBACK_MTU = 65535; uint64_t loopback_drops() const { return _loopback_drops; } size_t loopback_queued_bytes() const { return _loopback_queued_bytes; } diff --git a/src/network_stack.cpp b/src/network_stack.cpp index 7fe0442..8ac7a08 100644 --- a/src/network_stack.cpp +++ b/src/network_stack.cpp @@ -40,23 +40,17 @@ namespace constexpr uint8_t FLAG_SYN = 0x02; constexpr uint8_t FLAG_FIN = 0x01; - // 224.0.0.0/4. Class E (240.0.0.0/4) is not multicast, but is no more a - // single host's address, so callers asking "is this one host" test both. // 127.0.0.0/8 (RFC 1122 3.2.1.3): the whole block is this host, not just - // 127.0.0.1. - bool is_loopback_v4(const IPv4Address& address) - { - return address.get_address()[0] == 127; - } - - // The same on the raw octets of a parsed header. An IPv4Address owns a - // heap-allocated Bytes, so building one per packet just to look at it - // costs an allocation each; the receive path asks on every packet. + // 127.0.0.1. Takes the raw octets of a parsed header: an IPv4Address owns a + // heap-allocated Bytes, so building one per packet just to look at it costs + // an allocation each, and the receive path asks on every packet. bool is_loopback_v4(const Bytes& octets) { return octets[0] == 127; } + // 224.0.0.0/4. Class E (240.0.0.0/4) is not multicast, but is no more a + // single host's address, so callers asking "is this one host" test both. bool is_multicast(const IPv4Address& address) { return (address.get_address()[0] & 0xF0) == 0xE0;