| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Process startup primitives shared by the standalone and eventual managed |
| 4 | //! celld adapters. |
| 5 | //! |
| 6 | //! Listener policy is copied from celld's production startup path. Keeping it |
| 7 | //! outside the executor matters: both sockets are reserved before storage or |
| 8 | //! V8 work starts, and the executor receives an already-validated peer |
| 9 | //! address for the internal socket. |
| 10 | |
| 11 | use anyhow::{anyhow, Context}; |
| 12 | use std::fmt; |
| 13 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; |
| 14 | use tokio::net::{TcpListener, TcpSocket}; |
| 15 | use tracing::warn; |
| 16 | |
| 17 | const AUTO_LISTEN_START: u16 = 8080; |
| 18 | const AUTO_LISTEN_END: u16 = 8099; |
| 19 | |
| 20 | /// `TcpListener::bind` inherits socket2's historical backlog of 128. That is |
| 21 | /// smaller than a routine reconnect cohort at the target fleet density: 1,200 |
| 22 | /// chat clients returning together filled every node's accept queue and |
| 23 | /// produced connection resets while the runtime itself remained healthy. |
| 24 | /// Request the common Linux `somaxconn` default; the kernel still applies its |
| 25 | /// configured ceiling. |
| 26 | const LISTEN_BACKLOG: u32 = 4_096; |
| 27 | |
| 28 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 29 | pub enum Listen { |
| 30 | AutoLoopback, |
| 31 | LoopbackEphemeral, |
| 32 | Explicit(String), |
| 33 | } |
| 34 | |
| 35 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 36 | pub struct InternalListenerSettings { |
| 37 | pub listen: Listen, |
| 38 | pub advertise: Option<String>, |
| 39 | pub unsafe_public_advertise: bool, |
| 40 | } |
| 41 | |
| 42 | /// How peers should reach this node. |
| 43 | /// |
| 44 | /// A hostname is allowed because container and PaaS environments often hand |
| 45 | /// out a stable name and an unstable or ambiguous IP. The name is deliberately |
| 46 | /// not resolved here: reachability is defined from each peer's network. |
| 47 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 48 | pub enum Advertise { |
| 49 | Addr(SocketAddr), |
| 50 | Name { host: String, port: u16 }, |
| 51 | } |
| 52 | |
| 53 | impl Advertise { |
| 54 | pub fn scope(&self) -> &'static str { |
| 55 | match self { |
| 56 | Self::Addr(address) => advertise_scope(address.ip()), |
| 57 | Self::Name { .. } => "resolved by each peer", |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | pub fn is_public_ip(&self) -> bool { |
| 62 | matches!(self, Self::Addr(address) if advertise_scope(address.ip()) == "operator-routed network") |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl fmt::Display for Advertise { |
| 67 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 68 | match self { |
| 69 | Self::Addr(address) => write!(formatter, "{address}"), |
| 70 | Self::Name { host, port } => write!(formatter, "{host}:{port}"), |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn advertise_scope(address: IpAddr) -> &'static str { |
| 76 | match address { |
| 77 | IpAddr::V4(address) if address.is_loopback() => "same host only", |
| 78 | IpAddr::V4(address) if address.is_private() || is_shared_overlay(address) => { |
| 79 | "private network" |
| 80 | } |
| 81 | IpAddr::V4(address) if address.is_link_local() => "local link only", |
| 82 | IpAddr::V6(address) if address.is_loopback() => "same host only", |
| 83 | IpAddr::V6(address) if address.is_unique_local() => "private network", |
| 84 | IpAddr::V6(address) if address.is_unicast_link_local() => "local link only", |
| 85 | _ => "operator-routed network", |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// RFC 6598 shared address space is not globally routable. Overlay networks |
| 90 | /// such as Tailscale allocate peer addresses from this exact `100.64.0.0/10` |
| 91 | /// block, so treating it as public rejects the private overlay operators are |
| 92 | /// otherwise instructed to use. |
| 93 | fn is_shared_overlay(address: Ipv4Addr) -> bool { |
| 94 | let octets = address.octets(); |
| 95 | octets[0] == 100 && (64..=127).contains(&octets[1]) |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug)] |
| 99 | pub struct BoundListener { |
| 100 | pub listener: TcpListener, |
| 101 | pub listen: SocketAddr, |
| 102 | } |
| 103 | |
| 104 | #[derive(Debug)] |
| 105 | pub struct BoundInternalListener { |
| 106 | pub listener: TcpListener, |
| 107 | pub listen: SocketAddr, |
| 108 | pub advertise: Advertise, |
| 109 | } |
| 110 | |
| 111 | /// Descriptors one resident cell holds: its SQLite database, WAL, and shared- |
| 112 | /// memory file, plus what replication keeps open for them. Measured at ~7 on |
| 113 | /// Linux; budgeted at 8. |
| 114 | const FDS_PER_CELL: u64 = 8; |
| 115 | |
| 116 | /// Below this the node cannot reach the density the runtime is designed for, |
| 117 | /// so say so at startup rather than at the failing activation. |
| 118 | const MIN_RESIDENT_CELLS: u64 = 1_000; |
| 119 | |
| 120 | /// Raise the descriptor limit to its hard ceiling, and warn when even that |
| 121 | /// bounds residency. |
| 122 | #[cfg(unix)] |
| 123 | pub fn raise_file_limit() { |
| 124 | let mut limit = libc::rlimit { |
| 125 | rlim_cur: 0, |
| 126 | rlim_max: 0, |
| 127 | }; |
| 128 | if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 { |
| 129 | return; |
| 130 | } |
| 131 | if limit.rlim_cur < limit.rlim_max { |
| 132 | let raised = libc::rlimit { |
| 133 | rlim_cur: limit.rlim_max, |
| 134 | ..limit |
| 135 | }; |
| 136 | unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raised) }; |
| 137 | // Re-read rather than assume the raise took: macOS reports an |
| 138 | // unlimited hard limit, refuses it as a soft limit, and caps the |
| 139 | // process at kern.maxfilesperproc. |
| 140 | if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 { |
| 141 | return; |
| 142 | } |
| 143 | } |
| 144 | let cells = limit.rlim_cur / FDS_PER_CELL; |
| 145 | if cells < MIN_RESIDENT_CELLS { |
| 146 | warn!( |
| 147 | event = "file_limit_bounds_residency", |
| 148 | open_files = limit.rlim_cur, |
| 149 | resident_cells = cells, |
| 150 | "the open-file limit caps this node near {cells} resident cells; \ |
| 151 | raise it (ulimit -n {}, or LimitNOFILE= in the unit file)", |
| 152 | MIN_RESIDENT_CELLS * FDS_PER_CELL |
| 153 | ); |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | #[cfg(not(unix))] |
| 158 | pub fn raise_file_limit() {} |
| 159 | |
| 160 | fn bind_tcp_listener(address: SocketAddr) -> std::io::Result<TcpListener> { |
| 161 | let socket = match address { |
| 162 | SocketAddr::V4(_) => TcpSocket::new_v4()?, |
| 163 | SocketAddr::V6(_) => TcpSocket::new_v6()?, |
| 164 | }; |
| 165 | #[cfg(unix)] |
| 166 | socket.set_reuseaddr(true)?; |
| 167 | socket.bind(address)?; |
| 168 | socket.listen(LISTEN_BACKLOG) |
| 169 | } |
| 170 | |
| 171 | async fn bind_listener(listen: &Listen, option: &str) -> anyhow::Result<BoundListener> { |
| 172 | let (listener, listen) = match listen { |
| 173 | Listen::Explicit(address) => { |
| 174 | let address = parse_socket_address(address, option)?; |
| 175 | let listener = |
| 176 | bind_tcp_listener(address).with_context(|| format!("bind {option} {address}"))?; |
| 177 | let listen = listener.local_addr().context("read bound listen address")?; |
| 178 | (listener, listen) |
| 179 | } |
| 180 | Listen::AutoLoopback => { |
| 181 | let mut last_error = None; |
| 182 | let mut bound = None; |
| 183 | for port in AUTO_LISTEN_START..=AUTO_LISTEN_END { |
| 184 | let address = SocketAddr::from(([127, 0, 0, 1], port)); |
| 185 | match bind_tcp_listener(address) { |
| 186 | Ok(listener) => { |
| 187 | bound = Some((listener, address)); |
| 188 | break; |
| 189 | } |
| 190 | Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => { |
| 191 | last_error = Some(error); |
| 192 | } |
| 193 | Err(error) => return Err(error).with_context(|| format!("bind {address}")), |
| 194 | } |
| 195 | } |
| 196 | bound.ok_or_else(|| { |
| 197 | anyhow!( |
| 198 | "no free managed demo port in 127.0.0.1:{AUTO_LISTEN_START}-{AUTO_LISTEN_END}: {}", |
| 199 | last_error |
| 200 | .map(|error| error.to_string()) |
| 201 | .unwrap_or_else(|| "range exhausted".to_string()) |
| 202 | ) |
| 203 | })? |
| 204 | } |
| 205 | Listen::LoopbackEphemeral => { |
| 206 | let address = SocketAddr::from(([127, 0, 0, 1], 0)); |
| 207 | let listener = |
| 208 | bind_tcp_listener(address).with_context(|| format!("bind {option} {address}"))?; |
| 209 | let listen = listener.local_addr().context("read bound listen address")?; |
| 210 | (listener, listen) |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | Ok(BoundListener { listener, listen }) |
| 215 | } |
| 216 | |
| 217 | pub async fn bind_ingress_listener(listen: &Listen) -> anyhow::Result<BoundListener> { |
| 218 | bind_listener(listen, "--listen").await |
| 219 | } |
| 220 | |
| 221 | pub async fn bind_internal_listener( |
| 222 | settings: &InternalListenerSettings, |
| 223 | ) -> anyhow::Result<BoundInternalListener> { |
| 224 | let bound = bind_listener(&settings.listen, "--internal-listen").await?; |
| 225 | let listen = bound.listen; |
| 226 | |
| 227 | let advertise = if let Some(address) = settings.advertise.as_deref() { |
| 228 | parse_advertise(address)? |
| 229 | } else if listen.ip().is_unspecified() { |
| 230 | return Err(anyhow!( |
| 231 | "--advertise is required when --internal-listen uses an unspecified address ({listen}).\n\ |
| 232 | Give the address peers should dial, for example --advertise \ |
| 233 | {}:{} or --advertise node1.example.com:{}", |
| 234 | "10.0.0.1", |
| 235 | listen.port(), |
| 236 | listen.port() |
| 237 | )); |
| 238 | } else { |
| 239 | Advertise::Addr(listen) |
| 240 | }; |
| 241 | if advertise.is_public_ip() && !settings.unsafe_public_advertise { |
| 242 | return Err(anyhow!( |
| 243 | "--advertise {advertise} is a public IP address; the internal listener \ |
| 244 | has an unauthenticated operator API, and peer HTTP carries application \ |
| 245 | data without built-in TLS. Use a private overlay, or pass \ |
| 246 | --unsafe-public-advertise to accept this exposure explicitly" |
| 247 | )); |
| 248 | } |
| 249 | |
| 250 | Ok(BoundInternalListener { |
| 251 | listener: bound.listener, |
| 252 | listen, |
| 253 | advertise, |
| 254 | }) |
| 255 | } |
| 256 | |
| 257 | fn parse_socket_address(value: &str, option: &str) -> anyhow::Result<SocketAddr> { |
| 258 | value |
| 259 | .parse() |
| 260 | .with_context(|| format!("{option} must be an IP socket address such as 127.0.0.1:8080")) |
| 261 | } |
| 262 | |
| 263 | /// Parse `--advertise`, accepting `IP:PORT` or `HOST:PORT`. |
| 264 | pub fn parse_advertise(value: &str) -> anyhow::Result<Advertise> { |
| 265 | let value = value.trim(); |
| 266 | if let Ok(address) = value.parse::<SocketAddr>() { |
| 267 | if address.port() == 0 { |
| 268 | return Err(anyhow!("--advertise must use a nonzero port")); |
| 269 | } |
| 270 | if address.ip().is_unspecified() || address.ip().is_multicast() { |
| 271 | return Err(anyhow!( |
| 272 | "--advertise must be a concrete unicast address, not {address}" |
| 273 | )); |
| 274 | } |
| 275 | if matches!(address.ip(), IpAddr::V4(ip) if ip.is_broadcast()) { |
| 276 | return Err(anyhow!("--advertise cannot use the IPv4 broadcast address")); |
| 277 | } |
| 278 | return Ok(Advertise::Addr(address)); |
| 279 | } |
| 280 | |
| 281 | let (host, port) = value.rsplit_once(':').ok_or_else(|| { |
| 282 | anyhow!("--advertise must be HOST:PORT or IP:PORT, such as node1.example.com:8080") |
| 283 | })?; |
| 284 | let port: u16 = port.parse().with_context(|| { |
| 285 | format!("--advertise port {port:?} is not a number between 1 and 65535") |
| 286 | })?; |
| 287 | if port == 0 { |
| 288 | return Err(anyhow!("--advertise must use a nonzero port")); |
| 289 | } |
| 290 | if !is_dns_name(host) { |
| 291 | return Err(anyhow!( |
| 292 | "--advertise host {host:?} is not a valid hostname or IP address" |
| 293 | )); |
| 294 | } |
| 295 | Ok(Advertise::Name { |
| 296 | host: host.to_string(), |
| 297 | port, |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | fn is_dns_name(host: &str) -> bool { |
| 302 | !host.is_empty() |
| 303 | && host.len() <= 253 |
| 304 | && host.split('.').all(|label| { |
| 305 | !label.is_empty() |
| 306 | && label.len() <= 63 |
| 307 | && !label.starts_with('-') |
| 308 | && !label.ends_with('-') |
| 309 | && label |
| 310 | .chars() |
| 311 | .all(|character| character.is_ascii_alphanumeric() || character == '-') |
| 312 | }) |
| 313 | } |
| 314 | |
| 315 | pub fn validate_peer_id(value: &str) -> anyhow::Result<()> { |
| 316 | crate::machine::validate_node_name(value).map_err(|_| { |
| 317 | anyhow!("--peer must be one safe node-session ID without a path or whitespace") |
| 318 | }) |
| 319 | } |