interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-drive / src / http.rs

186 lines · 6271 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Minimal plain-HTTP client over `std::net`, loopback endpoints only: every
17//! address the host resolves to must be loopback, and the connection goes to
18//! those resolved addresses (no second lookup between the check and connect).
19//! Sends HTTP/1.0 with `Connection: close` and decodes chunked bodies if the
20//! server uses them anyway.
21
22use std::io::{BufRead, BufReader, Read, Write};
23use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
24use std::time::Duration;
25
26pub struct Response {
27 pub status: u16,
28 pub body: Box<dyn BufRead>,
29}
30
31fn split_url(url: &str) -> Result<(String, String), String> {
32 let rest = url
33 .strip_prefix("http://")
34 .ok_or_else(|| format!("only http:// endpoints are supported: {url}"))?;
35 let (host, path) = match rest.find('/') {
36 Some(i) => (&rest[..i], &rest[i..]),
37 None => (rest, "/"),
38 };
39 let host = if host.starts_with('[') && host.ends_with(']') {
40 format!("{host}:80")
41 } else if host.contains(':') {
42 host.to_string()
43 } else {
44 format!("{host}:80")
45 };
46 Ok((host, path.to_string()))
47}
48
49/// Resolve `host:port` and refuse it unless every address is loopback.
50fn loopback_addrs(host: &str) -> Result<Vec<SocketAddr>, String> {
51 let addrs: Vec<SocketAddr> = host
52 .to_socket_addrs()
53 .map_err(|e| format!("resolve {host}: {e}"))?
54 .collect();
55 if addrs.is_empty() {
56 return Err(format!("resolve {host}: no addresses"));
57 }
58 if let Some(a) = addrs.iter().find(|a| !a.ip().is_loopback()) {
59 return Err(format!("refused: {host} resolves to non-loopback {a}"));
60 }
61 Ok(addrs)
62}
63
64struct Chunked<R: BufRead> {
65 inner: R,
66 left: usize,
67 done: bool,
68}
69
70impl<R: BufRead> Read for Chunked<R> {
71 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
72 if self.done {
73 return Ok(0);
74 }
75 if self.left == 0 {
76 let mut line = String::new();
77 self.inner.read_line(&mut line)?;
78 let size = usize::from_str_radix(line.trim().split(';').next().unwrap_or(""), 16)
79 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
80 if size == 0 {
81 self.done = true;
82 return Ok(0);
83 }
84 self.left = size;
85 }
86 let n = buf.len().min(self.left);
87 let got = self.inner.read(&mut buf[..n])?;
88 self.left -= got;
89 if self.left == 0 {
90 let mut crlf = String::new();
91 self.inner.read_line(&mut crlf)?;
92 }
93 Ok(got)
94 }
95}
96
97/// POST a JSON body. `timeout` bounds each socket read and write.
98pub fn post_json(url: &str, body: &str, timeout: Duration) -> Result<Response, String> {
99 post_json_auth(url, body, timeout, None)
100}
101
102pub fn post_json_auth(
103 url: &str,
104 body: &str,
105 timeout: Duration,
106 bearer: Option<&str>,
107) -> Result<Response, String> {
108 let (host, path) = split_url(url)?;
109 let addrs = loopback_addrs(&host)?;
110 let mut s = TcpStream::connect(&addrs[..]).map_err(|e| format!("connect {host}: {e}"))?;
111 s.set_read_timeout(Some(timeout))
112 .map_err(|e| e.to_string())?;
113 s.set_write_timeout(Some(timeout))
114 .map_err(|e| e.to_string())?;
115 let auth = match bearer {
116 Some(token) if !token.is_empty() => format!("Authorization: Bearer {token}\r\n"),
117 _ => String::new(),
118 };
119 let req = format!(
120 "POST {path} HTTP/1.0\r\nHost: {host}\r\nContent-Type: application/json\r\n{auth}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
121 body.len()
122 );
123 s.write_all(req.as_bytes())
124 .map_err(|e| format!("write: {e}"))?;
125 let mut r = BufReader::new(s);
126 let mut status_line = String::new();
127 r.read_line(&mut status_line)
128 .map_err(|e| format!("read: {e}"))?;
129 let status: u16 = status_line
130 .split_whitespace()
131 .nth(1)
132 .and_then(|c| c.parse().ok())
133 .ok_or_else(|| format!("bad status line: {status_line:?}"))?;
134 let mut chunked = false;
135 loop {
136 let mut h = String::new();
137 let n = r.read_line(&mut h).map_err(|e| format!("read: {e}"))?;
138 if n == 0 || h.trim().is_empty() {
139 break;
140 }
141 let l = h.to_ascii_lowercase();
142 if l.starts_with("transfer-encoding:") && l.contains("chunked") {
143 chunked = true;
144 }
145 }
146 let body: Box<dyn BufRead> = if chunked {
147 Box::new(BufReader::new(Chunked {
148 inner: r,
149 left: 0,
150 done: false,
151 }))
152 } else {
153 Box::new(r)
154 };
155 Ok(Response { status, body })
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn loopback_hosts_are_accepted() {
164 for h in ["127.0.0.1:18080", "127.8.9.10:1", "[::1]:1", "localhost:1"] {
165 let a = loopback_addrs(h).unwrap_or_else(|e| panic!("{h}: {e}"));
166 assert!(a.iter().all(|a| a.ip().is_loopback()), "{h}");
167 }
168 assert_eq!(split_url("http://[::1]/x").unwrap().0, "[::1]:80");
169 }
170
171 #[test]
172 fn non_loopback_hosts_are_refused_before_connecting() {
173 for url in [
174 "http://10.0.0.1:18080/v1",
175 "http://192.168.0.192/v1",
176 "http://0.0.0.0:18080/v1",
177 "http://[2001:db8::1]:80/v1",
178 "http://203.0.113.7/v1",
179 ] {
180 let err = post_json(url, "{}", Duration::from_millis(50))
181 .err()
182 .unwrap_or_else(|| panic!("{url} was not refused"));
183 assert!(err.starts_with("refused: "), "{url}: {err}");
184 }
185 }
186}