Compare commits

..

8 Commits

Author SHA1 Message Date
Arkitu
75d280f928 cleaning dhcp 2025-04-26 18:10:42 +02:00
Arkitu
2bfca4ad1d dhcp working!!!!!!!!! 2025-04-26 17:41:26 +02:00
71502147da save 2025-04-26 16:28:11 +02:00
c8c3d37220 clean + make everything work in parallel 2025-04-23 19:24:00 +02:00
e16dee3b9b dhcp works! (without rapid commit) 2025-04-23 18:27:13 +02:00
6f5ebbd752 DHCPOFFER works 2025-04-23 10:18:44 +02:00
a6ef2702a3 keep that for the records if I need dhcparse options 2025-04-22 20:58:39 +02:00
Arkitu
2a15f4c503 save 2025-04-14 22:17:43 +02:00
5 changed files with 261 additions and 37 deletions

33
Cargo.lock generated
View File

@ -326,6 +326,18 @@ dependencies = [
"defmt",
]
[[package]]
name = "dhcparse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c1b7bc252945fef54ffa028dec6a3fcf7b1931968f4db476c93d0eab0d92d62"
dependencies = [
"bitflags 1.3.2",
"byteorder",
"memchr",
"ref-cast",
]
[[package]]
name = "digest"
version = "0.10.7"
@ -1080,6 +1092,7 @@ dependencies = [
"cyw43-pio",
"defmt",
"defmt-rtt",
"dhcparse",
"embassy-executor",
"embassy-net",
"embassy-rp",
@ -1226,6 +1239,26 @@ dependencies = [
"bitflags 2.9.0",
]
[[package]]
name = "ref-cast"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0ae411dbe946a674d89546582cea4ba2bb8defac896622d6496f14c23ba5cf"
dependencies = [
"ref-cast-impl",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.100",
]
[[package]]
name = "regex"
version = "1.11.1"

View File

@ -4,8 +4,12 @@ version = "0.1.0"
edition = "2024"
[features]
wifi-connect = ["dep:serde-json-core", "dep:serde"] # you need to add a wifi.conf file with your wifi credentials (for example : "Example Wifi name:pa$$w0rd")
default = ["wifi-connect"]
wifi-connect = [
"dep:serde-json-core",
"dep:serde",
] # you need to add a wifi.conf file for this to work
dhcp = ["dep:dhcparse"]
default = ["dhcp"]
[dependencies]
embassy-executor = { git = "https://github.com/embassy-rs/embassy", features = [
@ -22,19 +26,17 @@ embassy-rp = { git = "https://github.com/embassy-rs/embassy", features = [
"time-driver",
"critical-section-impl",
] }
embassy-time = {git = "https://github.com/embassy-rs/embassy"}
embassy-usb-logger = {git = "https://github.com/embassy-rs/embassy"}
embassy-time = { git = "https://github.com/embassy-rs/embassy" }
embassy-usb-logger = { git = "https://github.com/embassy-rs/embassy" }
embassy-net = { git = "https://github.com/embassy-rs/embassy", features = [
"defmt",
"proto-ipv4",
"tcp",
"udp",
"dhcpv4",
# "dns",
# "icmp",
"packet-trace"
] }
cyw43-pio = {git = "https://github.com/embassy-rs/embassy"}
cyw43 = {git = "https://github.com/embassy-rs/embassy"}
cyw43-pio = { git = "https://github.com/embassy-rs/embassy" }
cyw43 = { git = "https://github.com/embassy-rs/embassy" }
embedded-io-async = "*"
defmt = "*"
@ -48,5 +50,8 @@ heapless = "*"
rand_core = "*"
log = "*"
serde-json-core = {version = "*", optional = true}
serde = {version = "*", optional = true, default-features = false, features = ["derive"]}
serde-json-core = { version = "*", optional = true }
serde = { version = "*", optional = true, default-features = false, features = [
"derive",
] }
dhcparse = { version = "*", default-features = false, optional = true }

173
src/dhcp.rs Normal file
View File

@ -0,0 +1,173 @@
use core::net::Ipv4Addr;
use dhcparse::{
dhcpv4::{self, DhcpOption, MessageType as DhcpMsgType},
v4_options,
};
use embassy_net::{
IpEndpoint, Stack,
udp::{PacketMetadata, UdpMetadata, UdpSocket},
};
use embassy_time::Timer;
use heapless::Vec;
use log::{info, warn};
use pico_website::unwrap;
#[embassy_executor::task(pool_size = 1)]
pub async fn dhcp_server(stack: Stack<'static>) {
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut rx_meta = [PacketMetadata::EMPTY; 16];
let mut tx_meta = [PacketMetadata::EMPTY; 16];
let mut buf = [0; 4096];
let mut res_buf = Vec::<u8, 4096>::new();
let mut opts = Vec::<u8, 255>::new();
let mut current_ip = 10_u8; // add one at each new connection, loop at 250, hope not to get on occupied ip
'listen: loop {
let mut socket = UdpSocket::new(
stack,
&mut rx_meta,
&mut rx_buffer,
&mut tx_meta,
&mut tx_buffer,
);
unwrap(socket.bind(67)).await;
info!("Starting DHCP server");
loop {
let (n, _) = unwrap(socket.recv_from(&mut buf).await).await;
let msg = unwrap(dhcpv4::Message::new(&buf[..n])).await;
let msg_type = unwrap(v4_options!(msg; MessageType required)).await;
let mut rapid_commit = false;
if unwrap(msg.options())
.await
.any(|opt| matches!(opt, Ok((DhcpOption::Unknown(80, _), _))))
{
if msg_type != DhcpMsgType::DISCOVER {
warn!("WARN : dhcp rapid commit option on {:?} message", msg_type);
continue 'listen;
}
rapid_commit = true;
}
info!("Dhcp: received {:?} message", msg_type);
Timer::after_secs(0).await;
match msg_type {
DhcpMsgType::DISCOVER | DhcpMsgType::REQUEST => {
res_buf.clear();
res_buf.push(2).unwrap(); // op
res_buf.push(1).unwrap(); // htype
res_buf.push(6).unwrap(); // hlen
res_buf.push(0).unwrap(); // hops
res_buf.extend_from_slice(&buf[4..8]).unwrap(); // xid
res_buf.extend_from_slice(&[0; 2]).unwrap(); // secs
res_buf.extend_from_slice(&[0x80, 0x00]).unwrap(); // flags
res_buf.extend_from_slice(&buf[12..16]).unwrap(); // ciaddr
res_buf
.extend_from_slice(&[192, 254, 0, current_ip])
.unwrap(); // yiaddr
res_buf.extend_from_slice(&[0; 4]).unwrap(); // siaddr
res_buf.extend_from_slice(&buf[24..28]).unwrap(); // giaddr
res_buf.extend_from_slice(&buf[28..44]).unwrap(); // chaddr
res_buf.extend_from_slice(&[0; 192]).unwrap(); // sname/file
res_buf.extend_from_slice(&[99, 130, 83, 99]).unwrap(); // magic cookie
res_buf
.extend_from_slice(&[
53,
1,
match (msg_type, rapid_commit) {
(DhcpMsgType::DISCOVER, false) => 2, // DHCP_OFFER
_ => 5, // DHCP_ACK
},
])
.unwrap(); // opt message type
opts.clear();
opts.extend_from_slice(
unwrap(v4_options!(msg; ParameterRequestList))
.await
.unwrap_or(&[]),
)
.unwrap();
let default_opts: &[u8] = match (msg_type, rapid_commit) {
(DhcpMsgType::DISCOVER, false) => &[54],
(DhcpMsgType::DISCOVER, true) => &[54, 80],
(DhcpMsgType::REQUEST, false) => &[1, 3, 51, 6, 54],
_ => unreachable!(),
};
for o in default_opts {
if !opts.contains(o) {
opts.push(*o).unwrap();
}
}
unwrap(write_dhcp_opts(&mut res_buf, &opts).await).await;
res_buf.push(255).unwrap(); // end option
unwrap(
socket
.send_to(
&res_buf,
UdpMetadata {
endpoint: IpEndpoint::new(
Ipv4Addr::new(255, 255, 255, 255).into(),
68,
),
local_address: Some(Ipv4Addr::new(192, 254, 0, 2).into()),
meta: Default::default(),
},
)
.await,
)
.await;
info!("Dhcp: offer/ack sent for ip 192.254.0.{}", current_ip);
Timer::after_secs(0).await;
if msg_type == DhcpMsgType::REQUEST || rapid_commit {
current_ip += 1;
if current_ip > 250 {
current_ip = 10;
}
}
}
_ => {}
}
// unwrap(socket.send_to(&buf[..n], ep).await).await;
}
}
}
async fn write_dhcp_opts<const N: usize>(buf: &mut Vec<u8, N>, op_codes: &[u8]) -> Result<(), ()> {
for o in op_codes {
let (opt_len, opt): (u8, &[u8]) = match o {
1 => (4, &[255, 255, 255, 0]), // DhcpOption::SubnetMask(&dhcpv4::Addr([255, 255, 255, 0])),
2 => (4, &3600_i32.to_be_bytes()), // DhcpOption::TimeOffset(3600),
3 => (4, &[192, 254, 0, 2]), // DhcpOption::Router(&[dhcpv4::Addr([192, 254, 0, 2])]),
6 => (4, &[0, 0, 0, 0]), // DhcpOption::DomainNameServer(&[dhcpv4::Addr([0, 0, 0, 0])]),
12 => (4, b"blue"), // DhcpOption::HostName(b"blue"),
15 => (11, b"LocalDomain"), // DhcpOption::DomainName(b"LocalDomain"),
26 => (2, &1514_u16.to_be_bytes()), // DhcpOption::Unknown(26, &[0x5, 0xEA]), // mtu
28 => (4, &[192, 254, 0, 255]), // DhcpOption::Unknown(28, &[192, 254, 0, 255]), // broadcast
51 => (4, &700_u32.to_be_bytes()), // DhcpOption::AddressLeaseTime(700),
54 => (4, &[192, 254, 0, 2]), // DhcpOption::ServerIdentifier(&dhcpv4::Addr([192, 254, 0, 2])),
58 => (4, &500_u32.to_be_bytes()), // DhcpOption::Unknown(58, &[0, 0, 0x1, 0xF4]), // renewal time = 500s
59 => (4, &600_u32.to_be_bytes()), // DhcpOption::Unknown(59, &[0, 0, 0x2, 0x58]), // rebinding time = 600s
80 => (0, &[]),
_ => {
info!("Dhcp: unhandled requested option {}", o);
Timer::after_secs(0).await;
continue;
}
};
buf.push(*o).map_err(|_| ())?;
buf.push(opt_len).map_err(|_| ())?;
buf.extend_from_slice(opt)?;
}
Ok(())
}

View File

@ -2,16 +2,17 @@
use core::fmt::Debug;
use embassy_time::Timer;
use log::error;
use log::info;
pub async fn unwrap<T, E: Debug>(res: Result<T, E>) -> T {
match res {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR : {:?}", e);
info!("FATAL ERROR : {:?}", e);
loop {
Timer::after_millis(0).await;
info!("FATAL ERROR : {:?}", e);
Timer::after_secs(5).await;
}
}
}
}
}

View File

@ -4,10 +4,9 @@
#![feature(impl_trait_in_assoc_type)]
#![feature(slice_split_once)]
use core::net::Ipv4Addr;
use cyw43_pio::{DEFAULT_CLOCK_DIVIDER, PioSpi};
use embassy_executor::Spawner;
use embassy_net::{Config, DhcpConfig, StackResources};
use embassy_net::{Config, StackResources};
use embassy_rp::bind_interrupts;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Level, Output};
@ -15,14 +14,16 @@ use embassy_rp::peripherals::USB;
use embassy_rp::peripherals::{DMA_CH0, PIO0};
use embassy_rp::pio::{InterruptHandler as PioInterruptHandler, Pio};
use embassy_rp::usb::{Driver, InterruptHandler as UsbInterruptHandler};
use log::info;
use pico_website::unwrap;
use rand_core::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
use pico_website::unwrap;
mod socket;
#[cfg(feature = "dhcp")]
mod dhcp;
mod game;
mod socket;
bind_interrupts!(struct Irqs {
USBCTRL_IRQ => UsbInterruptHandler<USB>;
@ -82,26 +83,31 @@ async fn main(spawner: Spawner) {
#[cfg(not(feature = "wifi-connect"))]
// Use a link-local address for communication without DHCP server
let config = Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(192, 254, 0, 2), 16),
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(192, 254, 0, 2), 24),
dns_servers: heapless::Vec::new(),
gateway: None,
});
#[cfg(feature = "wifi-connect")]
let wifi_conf = unwrap(serde_json_core::from_slice::<WifiConnectConf>(include_bytes!("../wifi.json"))).await.0;
// Use a link-local address for communication without DHCP server
// let config = Config::dhcpv4(embassy_net::DhcpConfig::default());
#[cfg(feature = "wifi-connect")]
let config = match wifi_conf.ip {
Some(ip) => Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(ip, 24),
dns_servers: heapless::Vec::new(),
gateway: None,
}),
None => Config::dhcpv4(DhcpConfig::default())
let (wifi_conf, config) = {
let wifi_conf = unwrap(serde_json_core::from_slice::<WifiConnectConf>(
include_bytes!("../wifi.json"),
))
.await
.0;
// Use a link-local address for communication without DHCP server
// let config = Config::dhcpv4(embassy_net::DhcpConfig::default());
let config = match wifi_conf.ip {
Some(ip) => Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(ip, 24),
dns_servers: heapless::Vec::new(),
gateway: None,
}),
None => Config::dhcpv4(DhcpConfig::default()),
};
(wifi_conf, config)
};
// Generate random seed
let seed = rng.next_u64();
@ -124,7 +130,10 @@ async fn main(spawner: Spawner) {
{
loop {
match control
.join(wifi_conf.name, cyw43::JoinOptions::new(wifi_conf.password.as_bytes()))
.join(
wifi_conf.name,
cyw43::JoinOptions::new(wifi_conf.password.as_bytes()),
)
.await
{
Ok(_) => break,
@ -151,14 +160,17 @@ async fn main(spawner: Spawner) {
)
}
#[cfg(feature = "dhcp")]
unwrap(spawner.spawn(dhcp::dhcp_server(stack))).await;
unwrap(spawner.spawn(socket::listen_task(stack, game::Team::Zero, 80))).await;
unwrap(spawner.spawn(socket::listen_task(stack, game::Team::One, 81))).await;
}
#[cfg(feature="wifi-connect")]
#[cfg(feature = "wifi-connect")]
#[derive(serde::Deserialize)]
struct WifiConnectConf<'a> {
name: &'a str,
password: &'a str,
ip: Option<Ipv4Addr>
}
ip: Option<Ipv4Addr>,
}