2 Commits
Author SHA1 Message Date
Dreaded_X 99cffd3f06 --wip-- [skip ci] 2026-10-13 04:51:05 +02:00
Dreaded_X e56d2d69cd --wip-- [skip ci] 2026-10-09 05:57:18 +02:00
8 changed files with 94 additions and 101 deletions
Generated
+45 -13
View File
@@ -375,10 +375,9 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
"socket-pktinfo",
"socket2",
"thiserror",
"tokio",
"udp_sas_async",
]
[[package]]
@@ -1461,6 +1460,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "os_socketaddr"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa149f3ec09cadeb41968390fcd71e6ea038a9a373d1d4eb070f4d9484d4b244"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -1946,17 +1955,6 @@ version = "1.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
[[package]]
name = "socket-pktinfo"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
dependencies = [
"libc",
"socket2",
"windows-sys",
]
[[package]]
name = "socket2"
version = "0.6.5"
@@ -2210,6 +2208,18 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "udp_sas_async"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "073390c0d7b1682a5f044db2f769b0564568f741b9a7e23b8494b79fc868d491"
dependencies = [
"cc",
"libc",
"os_socketaddr",
"tokio",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
@@ -2352,6 +2362,22 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -2361,6 +2387,12 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
+1 -2
View File
@@ -37,8 +37,7 @@ thiserror = "2.0.21"
tokio = { version = "1.52.1", features = ["full"] }
ipxe = { path = "./ipxe" }
axum = { version = "0.8.9", features = ["macros"] }
socket2 = "0.6.5"
socket-pktinfo = "0.4.1"
udp_sas_async = { version = "0.2.0", features = ["async_tokio"] }
[lib]
test = false
View File
+1
View File
@@ -1,3 +1,4 @@
{% set httpUrl = "http://192.168.1.1:8000" -%}
#!ipxe
echo Starting ${serial}
+1 -7
View File
@@ -1,4 +1,3 @@
use std::net::IpAddr;
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand};
@@ -51,10 +50,5 @@ pub enum Commands {
/// Generate completions for your current shell
ShellCompletions,
/// Serve config files over tftp
Serve {
#[arg(short, long, default_value = "3000")]
port: u16,
#[arg(long, default_value = "0.0.0.0")]
ip: IpAddr,
},
Serve,
}
+12 -28
View File
@@ -1,11 +1,9 @@
mod cli;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::pin::pin;
use axum::extract::Request;
use axum::http::Uri;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{Router, debug_handler};
@@ -104,25 +102,22 @@ async fn generate(opts: &GlobalOpts) -> Result<(), Error> {
#[debug_handler]
async fn handler(req: Request) -> impl IntoResponse {
println!("{req:?}");
let uri: Uri = req
let host = req
.headers()
.iter()
.find(|(name, _)| header::HOST.eq(name))
.map(|(_, value)| value)
.expect("Host header should exist")
.unwrap()
.to_str()
.expect("Header value should be valid ASCII")
.parse()
.expect("Host should be valid Uri");
.unwrap();
let host = uri.host().expect("Uri should have host");
let port = uri.port().map(|port| port.as_u16()).unwrap_or(80);
println!("{host}");
let Some(path) = req.uri().path().strip_prefix("/") else {
return StatusCode::BAD_REQUEST.into_response();
};
let Some((file, content_type)) = get_file(path, format!("http://{host}:{port}")).await else {
let Some((file, content_type)) = get_file(path).await else {
return StatusCode::NOT_FOUND.into_response();
};
@@ -140,15 +135,12 @@ async fn handler(req: Request) -> impl IntoResponse {
}
// TODO: Make this a proper async function
fn get_file(
filename: impl ToString,
http_url: impl ToString,
) -> impl Future<Output = Option<(Vec<u8>, &'static str)>> {
fn get_file(filename: impl Into<String>) -> impl Future<Output = Option<(Vec<u8>, &'static str)>> {
// TODO: Make this a static that is initialized once
let re =
Regex::new(r"^talos/(?<cluster>.+)/(?<node>.+)\.ya?ml$").expect("regex should be valid");
let filename: String = filename.to_string();
let filename: String = filename.into();
let re = re.clone();
async move {
@@ -166,7 +158,6 @@ fn get_file(
let content = template
.render(context! {
clusters => clusters.values().collect::<Vec<_>>(),
httpUrl => http_url.to_string()
})
.unwrap();
@@ -208,23 +199,16 @@ async fn main() -> Result<(), Error> {
"crete",
&mut std::io::stdout(),
),
Commands::Serve { port, ip } => {
tokio::spawn(async move {
Commands::Serve => {
tokio::spawn(async {
let app = Router::new().fallback_service(get(handler));
let addr: SocketAddr = (ip, port).into();
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
println!("Http server started on {addr}");
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tftp::serve(ip, move |filename, ip| {
tftp::serve(move |filename| {
let filename = filename.to_owned();
async move {
get_file(filename, format!("http://{ip}:{port}"))
.await
.map(|(file, _)| file)
}
async move { get_file(filename).await.map(|(file, _)| file) }
})
.await?;
}
+6 -9
View File
@@ -3,7 +3,7 @@ use std::net::SocketAddr;
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use tokio::net::UdpSocket;
use udp_sas_async::tokio::UdpSocketSas;
use crate::tftp::Error;
@@ -309,16 +309,15 @@ impl Packet {
Ok(())
}
pub async fn recv_from(socket: &UdpSocket) -> Result<(Self, SocketAddr), Error> {
let mut buf = [0u8; PACKET_SIZE];
pub async fn recv_from(socket: &UdpSocketSas) -> Result<(Self, SocketAddr), Error> {
let mut buf = Vec::with_capacity(PACKET_SIZE);
let (_, src) = socket.recv_from(&mut buf).await?;
let packet = buf.try_into()?;
Ok((packet, src))
}
pub async fn send_to(&self, socket: &UdpSocket, src: &SocketAddr) -> Result<(), Error> {
pub async fn send_to(&self, socket: &UdpSocketSas, src: SocketAddr) -> Result<(), Error> {
let buf: Vec<_> = self.try_into()?;
socket.send_to(&buf, src).await?;
@@ -342,12 +341,10 @@ impl TryFrom<&Packet> for Vec<u8> {
}
}
impl TryFrom<[u8; PACKET_SIZE]> for Packet {
impl TryFrom<Vec<u8>> for Packet {
type Error = Error;
fn try_from(
buf: [u8; PACKET_SIZE],
) -> Result<Self, <Packet as TryFrom<[u8; PACKET_SIZE]>>::Error> {
fn try_from(buf: Vec<u8>) -> Result<Self, <Packet as TryFrom<Vec<u8>>>::Error> {
let mut reader = BufReader::new(Cursor::new(buf));
Packet::decode(&mut reader)
+28 -42
View File
@@ -2,13 +2,10 @@ use std::io;
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;
use socket_pktinfo::{PktInfo, PktInfoUdpSocket};
use socket2::Domain;
use thiserror::Error;
use tokio::io::unix::AsyncFd;
use tokio::net::UdpSocket;
use udp_sas_async::tokio::UdpSocketSas;
use crate::tftp::packet::{ErrorCode, Mode, PACKET_SIZE};
use crate::tftp::packet::{ErrorCode, Mode};
use crate::tftp::{self, Packet};
#[derive(Debug, Error)]
@@ -32,25 +29,25 @@ pub enum Error {
}
pub async fn handle_connection<F, Fut>(
info: PktInfo,
packet: Packet,
src: SocketAddr,
dest: IpAddr,
callback: F,
) -> Result<(), Error>
where
F: Fn(&str, IpAddr) -> Fut,
F: Fn(&str) -> Fut,
Fut: Future<Output = Option<Vec<u8>>>,
{
let src = info.addr_src;
let socket = UdpSocket::bind((info.addr_dst, 0)).await?;
println!(
"{}: Connecting back from {}",
src,
socket.local_addr().expect("Local addr should be set")
);
let socket = UdpSocketSas::bind(
format!("{dest}:0")
.parse()
.expect("Address should be valid"),
)?;
println!("{src}: Connecting from {}", socket.local_addr());
let Packet::Read(request) = packet else {
Packet::error(ErrorCode::NotDefined, "Operation not supported")
.send_to(&socket, &info.addr_src)
.send_to(&socket, src)
.await?;
return Err(Error::UnsupportedOperation(packet));
@@ -59,9 +56,9 @@ where
let filename = request.filename();
println!("{src}: {filename} [{:?}]", request.mode());
let Some(data) = callback(filename, info.addr_dst).await else {
let Some(data) = callback(filename).await else {
Packet::error(ErrorCode::FileNotFound, "Unknown file")
.send_to(&socket, &src)
.send_to(&socket, src)
.await?;
return Err(Error::FileNotFound(filename.into()));
@@ -77,7 +74,7 @@ where
ErrorCode::NotDefined,
format!("Mode {mode:?} is not supported"),
)
.send_to(&socket, &src)
.send_to(&socket, src)
.await?;
return Err(Error::UnsupportedMode(mode));
@@ -93,10 +90,9 @@ where
// Send the first chunk
if let Some((index, chunk)) = chunk {
Packet::data((index + 1) as u16, chunk)
.send_to(&socket, &src)
.send_to(&socket, src)
.await?;
}
tokio::select! {
recv = Packet::recv_from(&socket) => {
timeout = 0;
@@ -106,7 +102,7 @@ where
// really know how to test it properly so we don't support it.
if new_src != src {
Packet::error(ErrorCode::Illegal, "Source changed")
.send_to(&socket, &src)
.send_to(&socket, src)
.await?;
return Err(Error::SourceChanged(new_src));
@@ -127,7 +123,7 @@ where
}
_ => {
Packet::error(ErrorCode::Illegal, "Unexpected packet")
.send_to(&socket, &src)
.send_to(&socket, src)
.await?;
@@ -150,36 +146,26 @@ where
Ok(())
}
pub async fn serve<F, Fut>(ip: IpAddr, callback: F) -> Result<!, Error>
pub async fn serve<F, Fut>(callback: F) -> Result<!, Error>
where
F: Fn(&str, IpAddr) -> Fut + Clone + Send + 'static,
F: Fn(&str) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Option<Vec<u8>>> + Send + 'static,
{
let socket = PktInfoUdpSocket::new(Domain::IPV4)?;
socket.set_nonblocking(true)?;
let socket = UdpSocketSas::bind("0.0.0.0:69".parse().expect("Address should be valid"))?;
let addr: SocketAddr = (ip, 69).into();
socket.bind(&addr.into())?;
let async_fd = AsyncFd::new(socket)?;
let mut buf = [0u8; PACKET_SIZE];
println!("Tftp server started on {addr}");
println!("Server started");
loop {
let mut guard = async_fd.readable().await?;
let mut buf = Vec::with_capacity(0);
let (bytes, src, dest) = socket.recv_sas(&mut buf).await?;
println!("{src} -> {dest}");
println!("{bytes}, {}", buf.len());
let (packet, info) = match guard.try_io(|inner| inner.get_ref().recv(&mut buf)) {
Ok(Ok((_, info))) => (buf.try_into()?, info),
Ok(Err(e)) => return Err(e)?,
// Socket was not ready
Err(_would_block) => continue,
};
let (packet, src) = Packet::recv_from(&socket).await?;
let callback = callback.clone();
let src = info.addr_src;
tokio::spawn({
async move {
if let Err(err) = handle_connection(info, packet, callback).await {
if let Err(err) = handle_connection(packet, src, dest, callback).await {
println!("{src}: {err}")
}
}