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
//! Simple embeddable TFTP server.
//! Implements RFC1350
//! No WRITE support yet

#![cfg_attr(all(feature = "cargo-clippy", feature = "pedantic"), warn(clippy_pedantic))]
#![cfg_attr(feature = "cargo-clippy", warn(use_self))]
#![deny(missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/libtftp/0.1.2")]

extern crate bytes;
extern crate futures;
#[macro_use]
extern crate log;
extern crate tokio_core;

mod server;
mod tftp;

use std::io::{Read, Write};
use std::net::ToSocketAddrs;
use std::path::Path;

use bytes::Bytes;
use futures::{Future, Sink, Stream};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Handle;

use server::TftpServer;
use tftp::TftpCodec;

pub trait DataProvider {
    type Reader: Read;
    type Writer: Write;
    fn read(name: String) -> Result<Self::Reader, u8>;
    fn write(name: String) -> Result<Self::Writer, u8>;
}

#[derive(Debug)]
pub struct Tftp<'a, A: ToSocketAddrs> {
    addr: A,
    handle: &'a Handle,
    data: Bytes,
}

impl<'a, A> Tftp<'a, A>
where
    A: ToSocketAddrs,
{
    pub fn new(addr: A, handle: &'a Handle) -> Self {
        let data = Bytes::new();
        Self { addr, handle, data }
    }

    pub fn with_data<B: Into<Bytes>>(self, data: B) -> Self {
        let data = data.into();
        Self { data, ..self }
    }

    pub fn with_file<P: AsRef<Path>>(self, path: P) -> Self {
        // FIXME: Actually read file
        let data = path.as_ref().to_str().unwrap().into();
        Self { data, ..self }
    }

    pub fn data_handler(self) -> Self {
        self
    }

    pub fn spawn_server(self) {
        let socket = std::net::UdpSocket::bind(self.addr).unwrap();
        let socket = UdpSocket::from_socket(socket, self.handle).unwrap();
        info!("TFTP Server started on {:?}", socket);
        let (sink, stream) = socket.framed(TftpCodec).split();
        let mut tftp = TftpServer::with_data(self.data);
        let replies = stream.filter_map(move |(addr, packet)| tftp.reply(addr, packet));
        let driver = sink.send_all(replies).then(|_| Ok(()));
        self.handle.spawn(driver);
    }
}