Skip to main content

strate_net_silo/
state.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use alloc::{collections::BTreeMap, string::String};
24
25use smoltcp::{
26    iface::{Config, Interface, SocketHandle, SocketSet},
27    socket::{dhcpv4, dns, icmp, tcp, udp},
28    time::Instant,
29    wire::{EthernetAddress, IpAddress, IpCidr, IpEndpoint, Ipv4Address, Ipv6Address},
30};
31use strate_net::IpcMessage;
32
33use crate::{
34    device::NetDevice,
35    ip::{link_local_from_mac, IpConfig, Ipv6Config},
36    ipc::reply_read,
37};
38
39pub(crate) const PING_TIMEOUT_NS: u64 = 5_000_000_000;
40
41pub(crate) struct PendingPing {
42    pub(crate) seq: u16,
43    pub(crate) token: u64,
44    pub(crate) send_ts_ns: u64,
45    pub(crate) is_v6: bool,
46}
47
48/// Maximum number of accepted-but-not-yet-served connections kept per
49/// listener.  smoltcp has no accept queue, so strate-net emulates one: the
50/// listening socket is replaced as soon as the handshake starts, and the
51/// accepted socket waits here until the previous session ends.
52pub(crate) const LISTEN_BACKLOG: usize = 4;
53
54#[derive(Clone, Copy)]
55pub(crate) struct TcpListenerState {
56    /// Socket that is always kept in `LISTEN` on `port` (except for the
57    /// instant between handshake detection and replacement).
58    pub(crate) socket: SocketHandle,
59    pub(crate) port: u16,
60    pub(crate) auto_relisten: bool,
61    /// Accepted connection currently served by this fid, if any.
62    pub(crate) session: Option<SocketHandle>,
63    /// Accepted connections waiting for `session` to finish.
64    pub(crate) backlog: [Option<SocketHandle>; LISTEN_BACKLOG],
65    /// Set when a session ended and the next read should report EOF (0 bytes).
66    pub(crate) eof: bool,
67}
68
69impl TcpListenerState {
70    pub(crate) fn new(socket: SocketHandle, port: u16, auto_relisten: bool) -> Self {
71        Self {
72            socket,
73            port,
74            auto_relisten,
75            session: None,
76            backlog: [None; LISTEN_BACKLOG],
77            eof: false,
78        }
79    }
80
81    /// Number of queued connections (diagnostics only).
82    pub(crate) fn backlog_len(&self) -> usize {
83        self.backlog.iter().filter(|slot| slot.is_some()).count()
84    }
85
86    /// Queue an accepted connection.  Returns false when the backlog is full.
87    pub(crate) fn push_backlog(&mut self, handle: SocketHandle) -> bool {
88        for slot in self.backlog.iter_mut() {
89            if slot.is_none() {
90                *slot = Some(handle);
91                return true;
92            }
93        }
94        false
95    }
96
97    /// Take the oldest queued connection.
98    pub(crate) fn pop_backlog(&mut self) -> Option<SocketHandle> {
99        for slot in self.backlog.iter_mut() {
100            if let Some(handle) = slot.take() {
101                return Some(handle);
102            }
103        }
104        None
105    }
106}
107
108#[derive(Copy, Clone)]
109pub(crate) struct TcpConnState {
110    pub(crate) socket: SocketHandle,
111    pub(crate) local_port: u16,
112    pub(crate) remote: IpEndpoint,
113}
114
115#[derive(Copy, Clone)]
116pub(crate) struct UdpBoundState {
117    pub(crate) socket: SocketHandle,
118    pub(crate) local_port: u16,
119    pub(crate) last_peer: Option<IpEndpoint>,
120}
121
122#[derive(Copy, Clone)]
123pub(crate) struct UdpConnState {
124    pub(crate) socket: SocketHandle,
125    pub(crate) local_port: u16,
126    pub(crate) remote: IpEndpoint,
127}
128
129pub(crate) struct OpenedFile {
130    pub(crate) path: String,
131    pub(crate) cached_content: Option<alloc::vec::Vec<u8>>,
132    pub(crate) read_spill: Option<alloc::vec::Vec<u8>>,
133    /// Server-side base of the optional bulk ring (0 = none).
134    pub(crate) bulk_base: u64,
135    pub(crate) bulk_len: usize,
136    /// `(sec, nsec)` when the handle was opened (reported as ctime).
137    pub(crate) opened_at: (i64, u32),
138    /// `(sec, nsec)` of the last read / readdir (reported as atime).
139    pub(crate) accessed_at: (i64, u32),
140}
141
142impl OpenedFile {
143    pub(crate) fn new(path: &str) -> Self {
144        let now = strate_net::syscalls::realtime();
145        Self {
146            opened_at: now,
147            accessed_at: now,
148            path: String::from(path),
149            cached_content: None,
150            read_spill: None,
151            bulk_base: 0,
152            bulk_len: 0,
153        }
154    }
155}
156
157pub(crate) struct NetworkStrate {
158    pub(crate) device: NetDevice,
159    pub(crate) interface: Interface,
160    pub(crate) sockets: SocketSet<'static>,
161    pub(crate) dhcp_handle: SocketHandle,
162    pub(crate) dns_handle: SocketHandle,
163    pub(crate) icmp_handle: SocketHandle,
164    pub(crate) ip_config: Option<IpConfig>,
165    pub(crate) ipv6_config: Option<Ipv6Config>,
166    pub(crate) dns_servers: [Option<IpAddress>; 3],
167    pub(crate) dns_from_dhcp: bool,
168    pub(crate) link_local_addr: Ipv6Address,
169    pub(crate) open_handles: BTreeMap<u64, OpenedFile>,
170    /// fid -> sender that opened it. See `new_fid` / `is_owner`:
171    /// sequential fids are guessable, so every operation must be checked
172    /// against the opener's identity.
173    pub(crate) handle_owners: BTreeMap<u64, u64>,
174    pub(crate) tcp_listeners: BTreeMap<u64, TcpListenerState>,
175    pub(crate) tcp_connections: BTreeMap<u64, TcpConnState>,
176    pub(crate) udp_bound: BTreeMap<u64, UdpBoundState>,
177    pub(crate) udp_connections: BTreeMap<u64, UdpConnState>,
178    pub(crate) lingering_sockets: alloc::vec::Vec<SocketHandle>,
179    pub(crate) next_fid: u64,
180    pub(crate) ping_ident: u16,
181    pub(crate) next_ping_token: u64,
182    pub(crate) pending_pings: alloc::vec::Vec<PendingPing>,
183    pub(crate) ping_replies: alloc::vec::Vec<(u16, u64)>,
184    pub(crate) dhcp_enabled: bool,
185}
186
187impl NetworkStrate {
188    pub(crate) fn new(mac: [u8; 6], mut device: NetDevice) -> Self {
189        let config = Config::new(EthernetAddress(mac).into());
190        let mut interface = Interface::new(config, &mut device, Instant::from_micros(0));
191        let mut sockets = SocketSet::new(alloc::vec![]);
192
193        let link_local = link_local_from_mac(mac);
194        interface.update_ip_addrs(|addrs| {
195            let _ = addrs.push(IpCidr::new(IpAddress::Ipv6(link_local), 64));
196        });
197
198        let dhcp_socket = dhcpv4::Socket::new();
199        let dhcp_handle = sockets.add(dhcp_socket);
200
201        let dns_socket = dns::Socket::new(&[], alloc::vec![]);
202        let dns_handle = sockets.add(dns_socket);
203
204        let icmp_rx_buf = icmp::PacketBuffer::new(
205            alloc::vec![icmp::PacketMetadata::EMPTY; 16],
206            alloc::vec![0u8; 4096],
207        );
208        let icmp_tx_buf = icmp::PacketBuffer::new(
209            alloc::vec![icmp::PacketMetadata::EMPTY; 16],
210            alloc::vec![0u8; 4096],
211        );
212        let mut icmp_socket = icmp::Socket::new(icmp_rx_buf, icmp_tx_buf);
213        icmp_socket.bind(icmp::Endpoint::Unspecified).ok();
214        let icmp_handle = sockets.add(icmp_socket);
215
216        Self {
217            device,
218            interface,
219            sockets,
220            dhcp_handle,
221            dns_handle,
222            icmp_handle,
223            ip_config: None,
224            ipv6_config: None,
225            dns_servers: [None; 3],
226            dns_from_dhcp: false,
227            link_local_addr: link_local,
228            open_handles: BTreeMap::new(),
229            handle_owners: BTreeMap::new(),
230            tcp_listeners: BTreeMap::new(),
231            tcp_connections: BTreeMap::new(),
232            udp_bound: BTreeMap::new(),
233            udp_connections: BTreeMap::new(),
234            lingering_sockets: alloc::vec::Vec::new(),
235            next_fid: 1,
236            ping_ident: 0x9001,
237            next_ping_token: 1,
238            pending_pings: alloc::vec::Vec::new(),
239            ping_replies: alloc::vec::Vec::new(),
240            dhcp_enabled: true,
241        }
242    }
243
244    pub(crate) fn clear_ipv4_runtime_config(&mut self) {
245        self.ip_config = None;
246        self.interface.update_ip_addrs(|addrs| {
247            let mut kept = [IpCidr::new(IpAddress::Ipv4(Ipv4Address::UNSPECIFIED), 0); 8];
248            let mut n = 0usize;
249            for addr in addrs.iter() {
250                if matches!(addr, IpCidr::Ipv6(_)) && n < kept.len() {
251                    kept[n] = *addr;
252                    n += 1;
253                }
254            }
255            addrs.clear();
256            for addr in kept.into_iter().take(n) {
257                let _ = addrs.push(addr);
258            }
259        });
260        let _ = self.interface.routes_mut().remove_default_ipv4_route();
261        self.refresh_dns_servers();
262    }
263
264    pub(crate) fn drain_spilled_read(
265        &mut self,
266        sender: u64,
267        file_id: u64,
268        requested: usize,
269    ) -> Option<IpcMessage> {
270        let max_inline = requested.min(IpcMessage::READ_INLINE_CAPACITY);
271        let mut spill = self.open_handles.get_mut(&file_id)?.read_spill.take()?;
272        if spill.len() > max_inline {
273            let rest = spill.split_off(max_inline);
274            if let Some(handle) = self.open_handles.get_mut(&file_id) {
275                handle.read_spill = Some(rest);
276            }
277        }
278        Some(reply_read(sender, &spill))
279    }
280
281    pub(crate) fn reply_read_spilling(
282        &mut self,
283        sender: u64,
284        file_id: u64,
285        requested: usize,
286        mut data: alloc::vec::Vec<u8>,
287    ) -> IpcMessage {
288        let max_inline = requested.min(IpcMessage::READ_INLINE_CAPACITY);
289        if data.len() > max_inline {
290            let rest = data.split_off(max_inline);
291            if let Some(handle) = self.open_handles.get_mut(&file_id) {
292                handle.read_spill = Some(rest);
293            }
294        }
295        reply_read(sender, &data)
296    }
297
298    pub(crate) fn reset_dhcp_socket(&mut self) {
299        self.sockets
300            .get_mut::<dhcpv4::Socket>(self.dhcp_handle)
301            .reset();
302    }
303
304    pub(crate) fn enable_dhcp(&mut self) {
305        self.dhcp_enabled = true;
306        self.dns_servers = [None; 3];
307        self.dns_from_dhcp = false;
308        self.clear_ipv4_runtime_config();
309        self.reset_dhcp_socket();
310    }
311
312    pub(crate) fn alloc_ping_token(&mut self) -> u64 {
313        let token = self.next_ping_token;
314        self.next_ping_token = self.next_ping_token.wrapping_add(1);
315        token
316    }
317
318    pub(crate) fn udp_port_in_use(&self, port: u16) -> bool {
319        self.udp_bound
320            .values()
321            .any(|state| state.local_port == port)
322            || self
323                .udp_connections
324                .values()
325                .any(|state| state.local_port == port)
326    }
327
328    pub(crate) fn alloc_udp_ephemeral_port(&self) -> Option<u16> {
329        const BASE: u16 = 49_152;
330        const COUNT: usize = 16_384;
331        let start = (self.next_fid as usize) % COUNT;
332        for step in 0..COUNT {
333            let port = BASE + ((start + step) % COUNT) as u16;
334            if !self.udp_port_in_use(port) {
335                return Some(port);
336            }
337        }
338        None
339    }
340
341    pub(crate) fn create_udp_socket(
342        &mut self,
343        local_port: u16,
344    ) -> core::result::Result<SocketHandle, i32> {
345        let rx_buf = udp::PacketBuffer::new(
346            alloc::vec![udp::PacketMetadata::EMPTY; 32],
347            alloc::vec![0u8; 65536],
348        );
349        let tx_buf = udp::PacketBuffer::new(
350            alloc::vec![udp::PacketMetadata::EMPTY; 32],
351            alloc::vec![0u8; 65536],
352        );
353        let mut socket = udp::Socket::new(rx_buf, tx_buf);
354        if socket.bind(local_port).is_err() {
355            return Err(-98);
356        }
357        Ok(self.sockets.add(socket))
358    }
359
360    pub(crate) fn tcp_state_name(state: tcp::State) -> &'static str {
361        match state {
362            tcp::State::Closed => "CLOSED",
363            tcp::State::Listen => "LISTEN",
364            tcp::State::SynSent => "SYN-SENT",
365            tcp::State::SynReceived => "SYN-RECEIVED",
366            tcp::State::Established => "ESTABLISHED",
367            tcp::State::FinWait1 => "FIN-WAIT-1",
368            tcp::State::FinWait2 => "FIN-WAIT-2",
369            tcp::State::CloseWait => "CLOSE-WAIT",
370            tcp::State::Closing => "CLOSING",
371            tcp::State::LastAck => "LAST-ACK",
372            tcp::State::TimeWait => "TIME-WAIT",
373        }
374    }
375
376    pub(crate) fn alloc_fid(&mut self) -> u64 {
377        let id = self.next_fid;
378        self.next_fid += 1;
379        id
380    }
381
382    /// Allocate the next fid and record its owner (the sender that opened
383    /// it).
384    ///
385    /// Fids are small sequential integers, trivially guessable: without
386    /// this ownership record, any process could read another process's TCP
387    /// connection, hijack its UDP socket or reconfigure the IP stack by
388    /// issuing operations on a guessed fid.
389    pub(crate) fn new_fid(&mut self, owner: u64) -> u64 {
390        let id = self.alloc_fid();
391        self.handle_owners.insert(id, owner);
392        id
393    }
394
395    /// True when `sender` opened `fid`. Unknown fids belong to nobody:
396    /// every sender gets EBADF for them.
397    pub(crate) fn is_owner(&self, fid: u64, sender: u64) -> bool {
398        self.handle_owners.get(&fid) == Some(&sender)
399    }
400
401    /// Drop the ownership record of a closed fid.
402    pub(crate) fn forget_handle(&mut self, fid: u64) {
403        self.handle_owners.remove(&fid);
404    }
405}