forked from altugbakan/rs-tftpd
/
worker.rs
388 lines (342 loc) · 12.6 KB
/
worker.rs
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Testing:
// clear && cargo build && sudo cargo run -- -i 0.0.0.0 -p 69 -d "$HOME/tftproot"
// curl -v --output initrd tftp://192.168.x.x/initrd
use crate::{Packet, Socket, Window};
use std::{
error::Error,
fs::{self, File},
path::PathBuf,
thread,
time::{Duration, Instant},
};
const MAX_RETRIES: u32 = 6;
const TIMEOUT_BUFFER: Duration = Duration::from_secs(1);
/// Worker `struct` is used for multithreaded file sending and receiving.
/// It creates a new socket using the Server's IP and a random port
/// requested from the OS to communicate with the requesting client.
///
/// See [`Worker::send()`] and [`Worker::receive()`] for more details.
///
/// # Example
///
/// ```rust
/// use std::{net::{UdpSocket, SocketAddr}, path::PathBuf, str::FromStr, time::Duration};
/// use tftpd::Worker;
///
/// // Send a file, responding to a read request.
/// let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
/// socket.connect(SocketAddr::from_str("127.0.0.1:12345").unwrap()).unwrap();
///
/// let worker = Worker::new(
/// Box::new(socket),
/// PathBuf::from_str("Cargo.toml").unwrap(),
/// 512,
/// Duration::from_secs(1),
/// 1,
/// );
///
/// worker.send().unwrap();
/// ```
pub struct Worker<T: Socket + ?Sized> {
socket: Box<T>,
file_name: PathBuf,
blk_size: usize,
timeout: Duration,
windowsize: u16,
}
impl<T: Socket + ?Sized> Worker<T> {
/// Creates a new [`Worker`] with the supplied options.
pub fn new(
socket: Box<T>,
file_name: PathBuf,
blk_size: usize,
timeout: Duration,
windowsize: u16,
) -> Worker<T> {
Worker {
socket,
file_name,
blk_size,
timeout,
windowsize,
}
}
/// Sends a file to the remote [`SocketAddr`] that has sent a read request using
/// a random port, asynchronously.
pub fn send(self) -> Result<(), Box<dyn Error>> {
let file_name = self.file_name.clone();
let remote_addr = self.socket.remote_addr().unwrap();
thread::spawn(move || {
let handle_send = || -> Result<(), Box<dyn Error>> {
self.send_file(File::open(&file_name)?)?;
Ok(())
};
match handle_send() {
Ok(_) => {
println!(
"Sent {} to {}",
&file_name.file_name().unwrap().to_string_lossy(),
&remote_addr
);
}
Err(err) => {
eprintln!("{err}");
}
}
});
Ok(())
}
/// Receives a file from the remote [`SocketAddr`] that has sent a write request using
/// the supplied socket, asynchronously.
pub fn receive(self) -> Result<(), Box<dyn Error>> {
let file_name = self.file_name.clone();
let remote_addr = self.socket.remote_addr().unwrap();
thread::spawn(move || {
let handle_receive = || -> Result<(), Box<dyn Error>> {
self.receive_file(File::create(&file_name)?)?;
Ok(())
};
match handle_receive() {
Ok(_) => {
println!(
"Received {} from {}",
&file_name.file_name().unwrap().to_string_lossy(),
remote_addr
);
}
Err(err) => {
eprintln!("{err}");
if fs::remove_file(&file_name).is_err() {
eprintln!("Error while cleaning {}", &file_name.to_str().unwrap());
}
}
}
});
Ok(())
}
fn send_file(self, file: File) -> Result<(), Box<dyn Error>> {
let mut block_number = 1;
let mut window = Window::new(self.windowsize, self.blk_size, file);
loop {
let filled = window.fill()?;
let mut retry_cnt = 0;
// println!("timeout={} ms", self.timeout.as_millis());//// 5000 ms
let mut time = Instant::now() - (self.timeout + TIMEOUT_BUFFER);
loop {
if time.elapsed() >= self.timeout {
send_window(&self.socket, &window, block_number)?;
time = Instant::now();
}
match self.socket.recv() {
Ok(Packet::Ack(received_block_number)) => {
let diff = received_block_number.wrapping_sub(block_number);
if diff <= self.windowsize {
block_number = received_block_number.wrapping_add(1);
window.remove(diff + 1)?;
break;
}
}
Ok(Packet::Error { code, msg }) => {
return Err(format!("Received error code {code}: {msg}").into());
}
_ => {
retry_cnt += 1;
if retry_cnt == MAX_RETRIES {
return Err(
format!("Transfer timed out after {MAX_RETRIES} tries").into()
);
}
}
}
}
if !filled && window.is_empty() {
break;
}
}
Ok(())
}
fn receive_file(self, file: File) -> Result<(), Box<dyn Error>> {
let mut block_number: u16 = 0;
let mut window = Window::new(self.windowsize, self.blk_size, file);
loop {
let mut size;
let mut retry_cnt = 0;
loop {
match self.socket.recv_with_size(self.blk_size) {
Ok(Packet::Data {
block_num: received_block_number,
data,
}) => {
if received_block_number == block_number.wrapping_add(1) {
block_number = received_block_number;
size = data.len();
window.add(data)?;
if size < self.blk_size {
break;
}
if window.is_full() {
break;
}
}
}
Ok(Packet::Error { code, msg }) => {
return Err(format!("Received error code {code}: {msg}").into());
}
_ => {
retry_cnt += 1;
if retry_cnt == MAX_RETRIES {
return Err(
format!("Transfer timed out after {MAX_RETRIES} tries").into()
);
}
}
}
}
window.empty()?;
self.socket.send(&Packet::Ack(block_number))?;
if size < self.blk_size {
break;
};
}
Ok(())
}
}
fn send_window<T: Socket>(
socket: &T,
window: &Window,
mut block_num: u16,
) -> Result<(), Box<dyn Error>> {
// println!("send_window: block_num={}", block_num);////
for frame in window.get_elements() {
socket.send(&Packet::Data {
block_num,
data: frame.to_vec(),
})?;
// Wait a while before sending the same block
std::thread::sleep(
Duration::from_millis(1)
);
// Send the same block again (Why does this work?)
socket.send(&Packet::Data {
block_num,
data: frame.to_vec(),
})?;
block_num = block_num.wrapping_add(1);
}
Ok(())
}
/* Output Log
Running TFTP Server on 0.0.0.0:69 in /Users/Luppy/tftproot
Sending Image to 192.168.31.141:3995
Sent Image to 192.168.31.141:3995
Sending jh7110-star64-pine64.dtb to 192.168.31.141:2788
Sent jh7110-star64-pine64.dtb to 192.168.31.141:2788
Sending initrd to 192.168.31.141:2852
Sent initrd to 192.168.31.141:2852
Sending Image to 192.168.31.141:3921
Sent Image to 192.168.31.141:3921
Sending jh7110-star64-pine64.dtb to 192.168.31.141:2707
Sent jh7110-star64-pine64.dtb to 192.168.31.141:2707
Sending initrd to 192.168.31.141:2771
Sent initrd to 192.168.31.141:2771
Sending Image to 192.168.31.141:3898
Sent Image to 192.168.31.141:3898
Sending jh7110-star64-pine64.dtb to 192.168.31.141:2669
Sent jh7110-star64-pine64.dtb to 192.168.31.141:2669
Sending initrd to 192.168.31.141:2733
Sent initrd to 192.168.31.141:2733
Sending Image to 192.168.31.141:3767
Sent Image to 192.168.31.141:3767
Sending jh7110-star64-pine64.dtb to 192.168.31.141:2534
Sent jh7110-star64-pine64.dtb to 192.168.31.141:2534
Sending initrd to 192.168.31.141:2598
Sent initrd to 192.168.31.141:2598
Filename 'Image'.
Load address: 0x40200000
Loading: #################################################################
. #################################################################
. #############
. 1.1 MiB/s
Filename 'jh7110-star64-pine64.dtb'.
Load address: 0x46000000
Loading: ####
. 1.1 MiB/s
Filename 'initrd'.
Load address: 0x46100000
Loading: #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. ################################
. 1.1 MiB/s
Filename 'Image'.
Load address: 0x40200000
Loading: #################################################################
. #################################################################
. #############
. 1.1 MiB/s
Filename 'jh7110-star64-pine64.dtb'.
Load address: 0x46000000
Loading: ####
. 1.1 MiB/s
Filename 'initrd'.
Load address: 0x46100000
Loading: #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. ################################
. 1.1 MiB/s
Filename 'Image'.
Load address: 0x40200000
Loading: #################################################################
. #################################################################
. #############
. 1.1 MiB/s
Filename 'jh7110-star64-pine64.dtb'.
Load address: 0x46000000
Loading: ####
. 1.1 MiB/s
Filename 'initrd'.
Load address: 0x46100000
Loading: #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. ################################
. 1.1 MiB/s
Filename 'Image'.
Load address: 0x40200000
Loading: #################################################################
. #################################################################
. #############
. 1.1 MiB/s
Filename 'jh7110-star64-pine64.dtb'.
Load address: 0x46000000
Loading: ####
. 1.1 MiB/s
Filename 'initrd'.
Load address: 0x46100000
Loading: #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. #################################################################
. ################################
. 1.1 MiB/s
*/