-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathudp.rs
More file actions
241 lines (216 loc) · 6.93 KB
/
Copy pathudp.rs
File metadata and controls
241 lines (216 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//! Handles [`UdpRequest`]
use crate::{
find_mac,
state::{State, UnitSelector},
};
use anyhow::{ensure, Context, Result};
use futures::FutureExt;
use ipnet::Ipv4Net;
use pixie_shared::{
chunk_codec::Encoder, ChunkHash, HintPacket, InterfaceConfig, RegistrationInfo, UdpRequest,
ACTION_PORT, CHUNKS_PORT, HINT_PORT, UDP_BODY_LEN,
};
use std::{
collections::BTreeSet,
net::{IpAddr, Ipv4Addr, SocketAddrV4},
ops::Bound,
sync::Arc,
};
use tokio::{
net::UdpSocket,
sync::mpsc::{self, Receiver, Sender},
time::{self, Duration, Instant},
};
async fn broadcast_chunks(
state: &State,
socket: &UdpSocket,
iface: &InterfaceConfig,
mut rx: Receiver<ChunkHash>,
) -> Result<()> {
let mut queue = BTreeSet::<ChunkHash>::new();
let mut write_buf = [0; UDP_BODY_LEN];
let mut wait_for = Instant::now();
let mut index = [0; 32];
loop {
let get_index = async {
while let Ok(hash) = rx.try_recv() {
queue.insert(hash);
}
let hash = queue
.range((Bound::Excluded(index), Bound::Unbounded))
.next()
.or_else(|| queue.iter().next())
.copied();
match hash {
Some(hash) => {
queue.remove(&hash);
Some(hash)
}
None => {
let hash = rx.recv().await;
wait_for = wait_for.max(Instant::now());
hash
}
}
};
tokio::select! {
hash = get_index => {
let Some(hash) = hash else {
break;
};
index = hash;
}
_ = state.cancel_token.cancelled() => break,
};
let Some(cdata) = state
.get_chunk_cdata(index)
.with_context(|| format!("get chunk {}", hex::encode(index)))?
else {
log::warn!("Chunk {} not found", hex::encode(index));
continue;
};
let chunks_addr = SocketAddrV4::new(iface.network.broadcast(), CHUNKS_PORT);
let mut encoder = Encoder::new(cdata);
write_buf[..32].clone_from_slice(&index);
while let Some(len) = encoder.next_packet(&mut write_buf[32..]) {
time::sleep_until(wait_for).await;
let sent_len = socket.send_to(&write_buf[..32 + len], chunks_addr).await?;
ensure!(sent_len == 32 + len, "Could not send packet");
wait_for += 8 * (sent_len as u32) * Duration::from_secs(1) / iface.broadcast_speed;
}
}
Ok(())
}
fn compute_hint(state: &State) -> Result<RegistrationInfo> {
let Some(mut last) = state.get_registration_hint() else {
return Ok(RegistrationInfo {
group: state
.config
.groups
.iter()
.next()
.context("there should be at least one group")?
.0
.clone(),
row: 1,
col: 1,
image: state
.config
.images
.first()
.context("there should be at least one image")?
.clone(),
});
};
let units = state.get_units(UnitSelector::Group(
*state.config.groups.get_by_first(&last.group).unwrap(),
));
let positions = units
.into_iter()
.map(|unit| (unit.row, unit.col))
.collect::<Vec<_>>();
if last.row == 0 {
if let Some(&(r, c)) = positions.iter().max() {
last.row = r;
last.col = c;
}
}
let (mrow, mcol) = positions
.iter()
.fold((0, 0), |(r1, c1), &(r2, c2)| (r1.max(r2), c1.max(c2)));
let (row, col) = match mrow {
0 => (1, 1),
1 => (1, mcol + 1),
_ => (last.row + last.col / mcol, last.col % mcol + 1),
};
Ok(RegistrationInfo {
group: last.group.clone(),
row,
col,
image: last.image.clone(),
})
}
async fn broadcast_hint(state: &State, socket: &UdpSocket, ip: Ipv4Addr) -> Result<()> {
loop {
tokio::select! {
_ = time::sleep(Duration::from_secs(1)) => {}
_ = state.cancel_token.cancelled() => break,
}
let hint = HintPacket {
station: compute_hint(state)?,
images: state.config.images.clone(),
groups: state.config.groups.clone(),
};
let data = postcard::to_allocvec(&hint)?;
let hint_addr = SocketAddrV4::new(ip, HINT_PORT);
socket.send_to(&data, hint_addr).await?;
}
Ok(())
}
async fn handle_requests(
state: &State,
socket: &UdpSocket,
net_tx: Vec<(Ipv4Net, Sender<[u8; 32]>)>,
) -> Result<()> {
let mut buf = [0; UDP_BODY_LEN];
loop {
let (len, peer_addr) = tokio::select! {
x = socket.recv_from(&mut buf) => x?,
_ = state.cancel_token.cancelled() => break,
};
let peer_ip = match peer_addr.ip() {
IpAddr::V4(ip) => ip,
_ => panic!(),
};
let Some((_, tx)) = net_tx.iter().find(|(net, _)| net.contains(&peer_ip)) else {
continue;
};
let req: postcard::Result<UdpRequest> = postcard::from_bytes(&buf[..len]);
match req {
Ok(UdpRequest::Discover) => {
socket.send_to(&[], peer_addr).await?;
}
Ok(UdpRequest::ActionProgress(frac, tot)) => {
match find_mac(peer_addr.ip()) {
Ok(peer_mac) => {
state.set_unit_progress(UnitSelector::MacAddr(peer_mac), Some((frac, tot)));
}
Err(err) => {
log::error!("Error handling udp packet: {err}");
}
};
}
Ok(UdpRequest::RequestChunks(chunks)) => {
for hash in chunks {
tx.send(hash).await?;
}
}
Err(e) => {
log::warn!("Invalid request from {peer_addr}: {e}");
}
}
}
Ok(())
}
pub async fn main(state: Arc<State>) -> Result<()> {
let (net_tx, net_rx): (_, Vec<_>) = state
.config
.hosts
.interfaces
.iter()
.map(|iface| {
let (tx, rx) = mpsc::channel(128);
((iface.network, tx), (iface, rx))
})
.unzip();
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, ACTION_PORT)).await?;
log::info!("Listening on {}", socket.local_addr()?);
socket.set_broadcast(true)?;
let mut tasks = vec![handle_requests(&state, &socket, net_tx).boxed()];
for (iface, rx) in net_rx {
tasks.push(broadcast_chunks(&state, &socket, iface, rx).boxed());
tasks.push(broadcast_hint(&state, &socket, iface.network.broadcast()).boxed());
}
futures::future::try_join_all(tasks).await?;
Ok(())
}