///|
/// Native non-blocking HTTP/1.1-over-I2P proxy integrated into `Router`.
/// Routes `.i2p` and `.b32.i2p` HTTP requests through embedded ECIES Garlic +
/// Ed25519 I2P Streaming, blocks clearnet leaks (`403`) and `CONNECT` (`501`),
/// and supports `?i2paddresshelper=` jump links.
///|
priv struct HttpProxyConn {
sock : @ntcp2_net.TcpSocket
recv_buf : Array[Byte]
mut state : Int32 // 0 = reading_headers, 1 = waiting_lookup
mut target_host : String
mut target_hash : @common.Hash?
mut target_port : UInt32
mut wire_request : Bytes
started_ms : UInt64
mut closed : Bool
}
///|
priv struct ParsedProxyRequest {
http_method : String
host : String
port : UInt32
origin_path : String
wire_headers : String
helper_dest_b64 : String?
clean_redirect_url : String?
}
///|
priv enum ProxyParseResult {
Ok(ParsedProxyRequest)
Error(Int32, String, String)
}
///|
fn find_http_header_end(buf : Array[Byte]) -> (Int32, Int32)? {
let n = buf.length()
for i = 0; i < n; i = i + 1 {
if i + 3 < n &&
buf[i] == b'\r' &&
buf[i + 1] == b'\n' &&
buf[i + 2] == b'\r' &&
buf[i + 3] == b'\n' {
return Some((i, 4))
}
if i + 1 < n && buf[i] == b'\n' && buf[i + 1] == b'\n' {
return Some((i, 2))
}
}
None
}
///|
fn split_crlf_or_lf_lines(s : String) -> Array[String] {
let out : Array[String] = []
for raw in s.split("\n") {
let line = raw.to_owned()
if line.has_suffix("\r") {
out.push(line[:line.length() - 1].to_owned())
} else {
out.push(line)
}
}
out
}
///|
fn find_char_idx(s : String, target : Char, start~ : Int32 = 0) -> Int32 {
for i = start; i < s.length(); i = i + 1 {
if s[i].to_int() == target.to_int() {
return i
}
}
-1
}
///|
fn find_first_ws(s : String, start~ : Int32 = 0) -> Int32 {
for i = start; i < s.length(); i = i + 1 {
if s[i] == ' ' || s[i] == '\t' {
return i
}
}
-1
}
///|
fn parse_u32_port_exact(s : String) -> UInt32? {
if s.length() == 0 {
return None
}
let mut val = 0U
for ch in s {
if ch < '0' || ch > '9' {
return None
}
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
if val > 65535U {
return None
}
}
if val == 0U {
None
} else {
Some(val)
}
}
///|
fn parse_authority_host_port(raw_auth : String) -> (String, UInt32)? {
let trimmed = raw_auth.trim().to_owned()
if trimmed.length() == 0 {
return None
}
// Reject IPv6 bracket hosts or embedded userinfo '@' confusion
let at = find_char_idx(trimmed, '@')
let auth = if at >= 0 { trimmed[at + 1:].to_owned() } else { trimmed }
if auth.length() == 0 || auth.contains("[") || auth.contains("]") {
return None
}
let colon = find_char_idx(auth, ':')
if colon < 0 {
return Some((auth, 80U))
}
if colon == 0 {
return None
}
// Reject multiple colons
if find_char_idx(auth, ':', start=colon + 1) >= 0 {
return None
}
let host = auth[:colon].to_owned()
let port_str = auth[colon + 1:].to_owned()
match parse_u32_port_exact(port_str) {
Some(p) => Some((host, p))
None => None
}
}
///|
fn is_valid_i2p_hostname(host : String) -> Bool {
if host.length() == 0 {
return false
}
for ch in host {
if ch <= ' ' || ch == '/' || ch == '?' || ch == '#' || ch == '@' {
return false
}
}
true
}
///|
fn hex_nibble(c : Int32) -> Int32 {
if c >= 48 && c <= 57 {
c - 48
} else if c >= 65 && c <= 70 {
c - 55
} else if c >= 97 && c <= 102 {
c - 87
} else {
-1
}
}
///|
fn percent_decode_url_component(s : String) -> String {
let bytes : Array[Byte] = []
let raw = @encoding.string_to_utf8_bytes(s)
let mut i = 0
while i < raw.length() {
if raw[i] == b'%' && i + 2 < raw.length() {
let hi = hex_nibble(raw[i + 1].to_int())
let lo = hex_nibble(raw[i + 2].to_int())
if hi >= 0 && lo >= 0 {
bytes.push(((hi << 4) | lo).to_byte())
i += 3
continue
}
}
bytes.push(raw[i])
i += 1
}
@encoding.utf8_bytes_to_string(Bytes::from_array(bytes)) catch {
_ => s
}
}
///|
fn extract_address_helper(
origin_path : String,
host : String,
port : UInt32,
) -> (String?, String?) {
let q_idx = find_char_idx(origin_path, '?')
if q_idx < 0 {
return (None, None)
}
let base_path = origin_path[:q_idx].to_owned()
let query = origin_path[q_idx + 1:].to_owned()
let kept : Array[String] = []
let mut helper : String? = None
for part_view in query.split("&") {
let part = part_view.to_owned()
if part.length() == 0 {
continue
}
if part.has_prefix("i2paddresshelper=") {
let val = percent_decode_url_component(part[17:].to_owned())
if val.length() > 0 {
helper = Some(val)
}
} else {
kept.push(part)
}
}
match helper {
Some(h) => {
let clean_q = if kept.length() > 0 { "?" + kept.join("&") } else { "" }
let host_part = if port == 80U { host } else { "\{host}:\{port}" }
(Some(h), Some("http://\{host_part}\{base_path}\{clean_q}"))
}
None => (None, None)
}
}
///|
fn is_stripped_proxy_header(lower_name : String) -> Bool {
lower_name == "proxy-connection" ||
lower_name == "proxy-authorization" ||
lower_name == "proxy-authenticate" ||
lower_name == "connection" ||
lower_name == "keep-alive" ||
lower_name == "te" ||
lower_name == "upgrade" ||
lower_name == "x-forwarded-for" ||
lower_name == "forwarded" ||
lower_name == "via" ||
lower_name == "user-agent"
}
///|
fn is_i2p_referer(val : String) -> Bool {
let lower = val.trim().to_owned().to_lower()
if !lower.has_prefix("http://") {
return false
}
let rest = lower[7:].to_owned()
let mut end = rest.length()
for i = 0; i < rest.length(); i = i + 1 {
if rest[i] == '/' || rest[i] == '?' || rest[i] == '#' {
end = i
break
}
}
match parse_authority_host_port(rest[:end].to_owned()) {
Some((h, _)) => {
let nh = if h.has_suffix(".") { h[:h.length() - 1].to_owned() } else { h }
nh.has_suffix(".i2p") && nh.length() > 4
}
None => false
}
}
///|
fn parse_http_proxy_request(header_bytes : Bytes) -> ProxyParseResult {
let header_text = @encoding.utf8_bytes_to_string(header_bytes) catch {
_ => return Error(400, "Bad Request", "Malformed UTF-8 in HTTP headers.")
}
let lines = split_crlf_or_lf_lines(header_text)
if lines.length() == 0 {
return Error(400, "Bad Request", "Empty HTTP request.")
}
let req_line = lines[0].trim().to_owned()
let sp1 = find_first_ws(req_line)
if sp1 <= 0 {
return Error(400, "Bad Request", "Malformed HTTP request line.")
}
let http_method = req_line[:sp1].to_owned().to_upper()
let rest1 = req_line[sp1 + 1:].to_owned().trim().to_owned()
let sp2 = find_first_ws(rest1)
if sp2 <= 0 {
return Error(
400, "Bad Request", "Malformed HTTP request target or version.",
)
}
let raw_target = rest1[:sp2].to_owned()
let version = rest1[sp2 + 1:].to_owned().trim().to_owned()
if !version.to_upper().has_prefix("HTTP/1.") {
return Error(
505,
"HTTP Version Not Supported",
"Unsupported HTTP version: \{version}.",
)
}
if http_method == "CONNECT" {
return Error(
501, "Not Implemented", "CONNECT tunneling is disabled on the moon-i2p HTTP proxy. Use plain http:// URLs for .i2p eepsites (traffic is already end-to-end encrypted inside I2P).",
)
}
let headers : Array[(String, String)] = []
let mut header_host_val : String? = None
for i = 1; i < lines.length(); i = i + 1 {
let line = lines[i]
if line.length() == 0 {
continue
}
let colon = find_char_idx(line, ':')
if colon <= 0 {
return Error(400, "Bad Request", "Malformed HTTP header line.")
}
let name = line[:colon].to_owned().trim().to_owned()
let val = line[colon + 1:].to_owned().trim().to_owned()
if name.to_lower() == "host" && header_host_val is None {
header_host_val = Some(val)
}
headers.push((name, val))
}
// Strip optional #fragment if sent in request target
let hash_idx = find_char_idx(raw_target, '#')
let clean_target = if hash_idx >= 0 {
raw_target[:hash_idx].to_owned()
} else {
raw_target
}
let lower_target = clean_target.to_lower()
let (raw_host, port, origin_path) = if lower_target.has_prefix("http://") {
let after_scheme = clean_target[7:].to_owned()
let mut split_at = after_scheme.length()
for i = 0; i < after_scheme.length(); i = i + 1 {
if after_scheme[i] == '/' || after_scheme[i] == '?' {
split_at = i
break
}
}
let auth = after_scheme[:split_at].to_owned()
let tail = after_scheme[split_at:].to_owned()
let path = if tail.length() == 0 {
"/"
} else if tail.has_prefix("?") {
"/" + tail
} else {
tail
}
match parse_authority_host_port(auth) {
Some((h, p)) => (h, p, path)
None =>
return Error(400, "Bad Request", "Invalid target host or port in URL.")
}
} else if lower_target.has_prefix("https://") {
return Error(
501, "Not Implemented", "Use http:// instead of https:// for .i2p eepsites (I2P encrypts traffic end-to-end inside tunnels and Garlic).",
)
} else if clean_target.has_prefix("/") {
match header_host_val {
Some(hv) =>
match parse_authority_host_port(hv) {
Some((h, p)) => (h, p, clean_target)
None => return Error(400, "Bad Request", "Invalid Host header value.")
}
None =>
return Error(
400, "Bad Request", "Missing Host header in origin-form HTTP request.",
)
}
} else {
return Error(400, "Bad Request", "Unsupported request target URI.")
}
let mut host = raw_host.to_lower()
while host.has_suffix(".") {
host = host[:host.length() - 1].to_owned()
}
if !is_valid_i2p_hostname(host) {
return Error(400, "Bad Request", "Invalid target hostname.")
}
if !host.has_suffix(".i2p") || host.length() <= 4 {
return Error(
403,
"Forbidden",
"Clearnet host '\{host}' blocked: moon-i2p HTTP proxy only routes .i2p destinations.",
)
}
let (helper_dest_b64, clean_redirect_url) = extract_address_helper(
origin_path, host, port,
)
let out = StringBuilder()
out.write_string("\{http_method} \{origin_path} HTTP/1.1\r\n")
let mut has_host = false
for kv in headers {
let lname = kv.0.to_lower()
if is_stripped_proxy_header(lname) {
continue
}
if lname == "referer" && !is_i2p_referer(kv.1) {
continue
}
if lname == "host" {
has_host = true
}
out.write_string("\{kv.0}: \{kv.1}\r\n")
}
if !has_host {
let host_hdr = if port == 80U { host } else { "\{host}:\{port}" }
out.write_string("Host: \{host_hdr}\r\n")
}
out.write_string("User-Agent: MYOB/6.66 (AN/ON)\r\n")
out.write_string("Connection: close\r\n\r\n")
Ok({
http_method,
host,
port,
origin_path,
wire_headers: out.to_string(),
helper_dest_b64,
clean_redirect_url,
})
}
///|
fn escape_html(s : String) -> String {
let out = StringBuilder()
for ch in s {
match ch {
'&' => out.write_string("&")
'<' => out.write_string("<")
'>' => out.write_string(">")
'"' => out.write_string(""")
_ => out.write_char(ch)
}
}
out.to_string()
}
///|
fn send_http_proxy_error(
sock : @ntcp2_net.TcpSocket,
status : Int32,
reason : String,
detail : String,
refresh_sec~ : Int32 = 0,
) -> Unit {
let safe_reason = escape_html(reason)
let safe_detail = escape_html(detail)
let refresh_meta = if refresh_sec > 0 {
""
} else {
""
}
let refresh_hdr = if refresh_sec > 0 {
"Retry-After: \{refresh_sec}\r\n"
} else {
""
}
let body = "
\{refresh_meta}\{status} \{safe_reason}\{status} \{safe_reason}
\{safe_detail}
moon-i2p HTTP Proxy\n"
let body_bytes = @encoding.string_to_utf8_bytes(body)
let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\n\{refresh_hdr}Connection: close\r\n\r\n"
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch {
_ => return
}
let _ = sock.write_all(body_bytes) catch { _ => () }
}
///|
fn send_http_proxy_redirect(
sock : @ntcp2_net.TcpSocket,
location : String,
) -> Unit {
let hdr = "HTTP/1.1 302 Found\r\nLocation: \{location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { _ => () }
}
///|
/// Starts a non-blocking HTTP-over-I2P proxy listener (default `127.0.0.1:4444`)
/// inside the router event loop. Returns the bound local TCP port.
pub fn Router::start_http_proxy(
self : Router,
host~ : String = "127.0.0.1",
port~ : Int32 = 4444,
) -> Int32 raise RouterError {
match self.http_proxy_listener {
Some(existing) => existing.close()
None => ()
}
let l = @ntcp2_net.TcpListener::bind(host, port) catch { e => raise Net(e) }
self.http_proxy_listener = Some(l)
l.local_port()
}
///|
/// Returns the bound HTTP proxy TCP port, or `0` if the HTTP proxy is disabled.
pub fn Router::http_proxy_port(self : Router) -> Int32 {
match self.http_proxy_listener {
Some(l) => l.local_port()
None => 0
}
}
///|
fn Router::ensure_http_proxy_session(self : Router) -> SamSession? {
match self.http_proxy_session_id {
Some(sid) =>
match self.find_session_by_id(sid) {
Some(s) => return Some(s)
None => ()
}
None => ()
}
let sid = "__http_proxy__"
match self.find_session_by_id(sid) {
Some(s) => {
self.http_proxy_session_id = Some(sid)
return Some(s)
}
None => ()
}
let (dest, pub_b64, _priv_b64, xkp, seed) = generate_transient_destination() catch {
_ => return None
}
let hash = dest.hash()
let b32 = dest.b32_address()
let sess : SamSession = {
id: sid,
dest,
hash,
pub_b64,
b32,
virtual_tid: self.alloc_tunnel_id(),
x25519_pub: Some(xkp.public_key),
ed_seed: Some(seed),
ratchet: Some(@ratchet.RatchetSessionManager::new(xkp)),
stream_mgr: Some(
@streaming.StreamManager::new(
dest,
seed,
initial_stream_id=self.alloc_stream_id(),
),
),
}
self.sessions.push(sess)
self.publish_session_leaseset2(sess)
self.http_proxy_session_id = Some(sid)
Some(sess)
}
///|
fn Router::has_registered_alias(self : Router, host : String) -> Bool {
let key = host.to_lower()
for e in self.aliases {
if e.0 == key {
return true
}
}
for e in self.b32_aliases {
if e.0 == key {
return true
}
}
false
}
///|
fn Router::attach_http_proxy_remote_stream(
self : Router,
pc : HttpProxyConn,
sess : SamSession,
target_dest : @common.Destination,
ls2 : @common.LeaseSet2,
) -> Bool {
let mgr = match sess.stream_mgr {
Some(m) => m
None => {
send_http_proxy_error(
pc.sock,
500,
"Internal Server Error",
"HTTP proxy I2P session lacks a stream manager.",
)
return false
}
}
let peer_static = match extract_x25519_key(ls2) {
Some(k) => k
None => {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Target LeaseSet2 for \{pc.target_host} has no usable X25519 encryption key.",
)
return false
}
}
if ls2.leases.length() == 0 {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Target LeaseSet2 for \{pc.target_host} contains zero active inbound leases.",
)
return false
}
let lease = ls2.leases[0]
let now_ms = @ntcp2_net.unix_time_ms()
let peer_hash = target_dest.hash()
let to_port = if pc.target_port == 80U { 0U } else { pc.target_port }
let conn = mgr.connect(peer_hash, now_ms, from_port=0U, to_port~) catch {
_ => {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Failed to initiate I2P Streaming handshake to \{pc.target_host}.",
)
return false
}
}
if self.debug {
println(
"[debug] http-proxy -> \{pc.target_host} (\{peer_hash.to_b32_address()}) port=\{to_port}",
)
}
let pending_buf : Array[Byte] = []
for i = 0; i < pc.wire_request.length(); i = i + 1 {
pending_buf.push(pc.wire_request[i])
}
self.remote_bridges.push({
sock: pc.sock,
session_id: sess.id,
peer_hash,
peer_static_pub: peer_static,
lease_gw: lease.tunnel_gw,
lease_tid: lease.tunnel_id,
local_stream_id: conn.local_stream_id,
state: 0,
silent: true,
local_eof: false,
remote_eof_sent: false,
closed: false,
started_ms: now_ms,
pending_buf,
is_http_proxy: true,
http_host: pc.target_host,
closing_since_ms: 0UL,
ratchet_reset: false,
})
self.flush_stream_outbound(
sess,
conn,
peer_hash,
peer_static,
lease.tunnel_gw,
lease.tunnel_id,
send_ls2=true,
)
true
}
///|
fn Router::step_http_proxy(self : Router) -> Bool {
let listener = match self.http_proxy_listener {
Some(l) => l
None => return false
}
let mut did_work = false
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
// 1. Accept incoming HTTP proxy TCP connections
for _i = 0; _i < 8; _i = _i + 1 {
match (listener.accept(timeout_ms=0) catch { _ => None }) {
Some(sock) => {
self.http_proxy_conns.push({
sock,
recv_buf: [],
state: 0,
target_host: "",
target_hash: None,
target_port: 80U,
wire_request: b"",
started_ms: now_ms,
closed: false,
})
did_work = true
}
None => break
}
}
// 2. Drive pending HTTP proxy header reads and NetDB lookups
let lookup_timeout_ms = if self.public_mode { 30000UL } else { 10000UL }
let mut pi = 0
while pi < self.http_proxy_conns.length() {
let pc = self.http_proxy_conns[pi]
if pc.closed {
let _ = self.http_proxy_conns.remove(pi)
continue
}
if pc.state == 0 {
if now_ms > pc.started_ms + 15000UL {
send_http_proxy_error(
pc.sock,
408,
"Request Timeout",
"Timed out waiting for complete HTTP request headers.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
did_work = true
continue
}
let prev_len = pc.recv_buf.length()
let eof = try {
let _ = pc.sock.pump_nonblocking(pc.recv_buf, 8192)
false
} catch {
_ => true
}
if pc.recv_buf.length() != prev_len {
did_work = true
}
if pc.recv_buf.length() > 65536 {
send_http_proxy_error(
pc.sock,
431,
"Request Header Fields Too Large",
"HTTP request headers exceed the 64 KiB proxy limit.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
did_work = true
continue
}
match find_http_header_end(pc.recv_buf) {
Some((hdr_end, sep_len)) => {
did_work = true
let raw_all = Bytes::from_array(pc.recv_buf)
let hdr_bytes = raw_all[:hdr_end].to_owned()
let body_bytes = raw_all[hdr_end + sep_len:].to_owned()
pc.recv_buf.clear()
match parse_http_proxy_request(hdr_bytes) {
Error(code, reason, detail) => {
send_http_proxy_error(pc.sock, code, reason, detail)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
Ok(parsed) => {
// Handle ?i2paddresshelper=
match (parsed.helper_dest_b64, parsed.clean_redirect_url) {
(Some(dest_b64), Some(redir)) => {
let valid_dest = try {
let _ = @common.Destination::from_base64(dest_b64)
true
} catch {
_ => false
}
if !valid_dest {
send_http_proxy_error(
pc.sock,
400,
"Bad Request",
"Invalid Base64 I2P Destination in i2paddresshelper parameter.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
if !self.has_registered_alias(parsed.host) {
self.register_alias(parsed.host, dest_b64)
}
send_http_proxy_redirect(pc.sock, redir)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
_ => ()
}
if self.public_mode &&
(
self.tunnels.inbound.length() == 0 ||
self.tunnels.outbound.length() == 0
) {
send_http_proxy_error(
pc.sock,
503,
"Service Unavailable",
"I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retrying automatically...",
refresh_sec=3,
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
let sess = match self.ensure_http_proxy_session() {
Some(s) => s
None => {
send_http_proxy_error(
pc.sock,
500,
"Internal Server Error",
"Failed to initialize HTTP proxy SAM session.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
}
let hdr_wire = @encoding.string_to_utf8_bytes(parsed.wire_headers)
let wire_buf = @encoding.Writer::new(
capacity=hdr_wire.length() + body_bytes.length(),
)
wire_buf.write_bytes(hdr_wire)
wire_buf.write_bytes(body_bytes)
let wire_req = wire_buf.to_bytes()
pc.target_host = parsed.host
pc.target_port = parsed.port
pc.wire_request = wire_req
if self.debug {
println(
"[debug] http-proxy req: \{parsed.http_method} http://\{parsed.host}:\{parsed.port}\{parsed.origin_path}",
)
}
// 1. Check co-hosted local SAM session fast path first
match self.resolve_name_local(parsed.host, None) {
Some(dest_b64) =>
match self.find_session_by_pub(dest_b64) {
Some(target_sess) => {
let mut acceptor_idx = -1
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if !c.closed &&
c.mode == 1 &&
c.accept_session_id == target_sess.id {
acceptor_idx = i
break
}
}
if acceptor_idx < 0 {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Local destination \{parsed.host} is not currently accepting streams.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
let acceptor = self.sam_clients[acceptor_idx]
if !acceptor.accept_silent {
let _ = send_sam_line(acceptor.sock, sess.pub_b64)
}
let ok_write = try {
acceptor.sock.write_all(wire_req)
true
} catch {
_ => false
}
if !ok_write {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Failed writing HTTP request to local destination \{parsed.host}.",
)
pc.sock.close()
pc.closed = true
acceptor.closed = true
acceptor.sock.close()
let _ = self.http_proxy_conns.remove(pi)
continue
}
acceptor.mode = 2
self.bridges.push({
a: pc.sock,
b: acceptor.sock,
a_eof: false,
b_eof: false,
})
let _ = self.http_proxy_conns.remove(pi)
continue
}
None => {
let target_dest = @common.Destination::from_base64(
dest_b64,
) catch {
_ => {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Resolved destination for \{parsed.host} is invalid.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
}
let target_hash = target_dest.hash()
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(ls2) => {
let attached = self.attach_http_proxy_remote_stream(
pc, sess, target_dest, ls2,
)
if !attached {
pc.sock.close()
pc.closed = true
}
let _ = self.http_proxy_conns.remove(pi)
continue
}
None => {
pc.target_hash = Some(target_hash)
pc.state = 1
if !self.start_proxy_netdb_lookup(target_hash) {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"No NetDB floodfill peers available to look up \{parsed.host}.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
pi += 1
continue
}
}
}
}
None => ()
}
// 2. Try .b32.i2p address or built-in/hosts.txt .b32.i2p alias
let hash_opt = match parse_b32_hash(parsed.host) {
Some(h) => Some(h)
None => self.resolve_b32_alias(parsed.host)
}
match hash_opt {
Some(target_hash) =>
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(ls2) => {
let attached = self.attach_http_proxy_remote_stream(
pc,
sess,
ls2.destination,
ls2,
)
if !attached {
pc.sock.close()
pc.closed = true
}
let _ = self.http_proxy_conns.remove(pi)
continue
}
None => {
pc.target_hash = Some(target_hash)
pc.state = 1
if !self.start_proxy_netdb_lookup(target_hash) {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"No NetDB floodfill peers available to look up \{parsed.host}.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
pi += 1
continue
}
}
None => {
send_http_proxy_error(
pc.sock,
502,
"Bad Gateway",
"Unknown .i2p host '\{parsed.host}'. Use its .b32.i2p address, add it via --hosts , or visit an ?i2paddresshelper= jump URL.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
}
}
}
}
None =>
if eof {
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
did_work = true
continue
}
}
pi += 1
} else if pc.state == 1 {
let target_hash = match pc.target_hash {
Some(h) => h
None => {
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
}
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(ls2) => {
did_work = true
match self.ensure_http_proxy_session() {
Some(sess) => {
let attached = self.attach_http_proxy_remote_stream(
pc,
sess,
ls2.destination,
ls2,
)
if !attached {
pc.sock.close()
pc.closed = true
}
}
None => {
send_http_proxy_error(
pc.sock,
500,
"Internal Server Error",
"Failed to initialize HTTP proxy SAM session.",
)
pc.sock.close()
pc.closed = true
}
}
let _ = self.http_proxy_conns.remove(pi)
continue
}
None => ()
}
if now_ms > pc.started_ms + lookup_timeout_ms ||
!self.has_pending_lookup(target_hash, 1) {
did_work = true
send_http_proxy_error(
pc.sock,
504,
"Gateway Timeout",
"Could not resolve LeaseSet2 for \{pc.target_host} (\{target_hash.to_b32_address()}) in I2P NetDB.",
)
pc.sock.close()
pc.closed = true
let _ = self.http_proxy_conns.remove(pi)
continue
}
pi += 1
} else {
pi += 1
}
}
did_work
}