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
///! Packet definitions.
use bytes::BytesMut;
use num_derive::FromPrimitive;
use std::convert::From;
use std::io;
use std::str;

use crate::bytes_ext::BytesMutExt;
use crate::error::Result;
use crate::parse::*;

pub(crate) const PACKET_DATA_HEADER_LEN: usize = 4;

#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive)]
#[repr(u16)]
pub(crate) enum PacketType {
    Rrq = 1,
    Wrq = 2,
    Data = 3,
    Ack = 4,
    Error = 5,
    OAck = 6,
}

/// TFTP protocol error. Should not be confused with `async_tftp::Error`.
#[derive(Debug, Clone)]
pub enum Error {
    Msg(String),
    UnknownError,
    FileNotFound,
    PermissionDenied,
    DiskFull,
    IllegalOperation,
    UnknownTransferId,
    FileAlreadyExists,
    NoSuchUser,
}

#[derive(Debug)]
pub(crate) enum Packet<'a> {
    Rrq(RwReq),
    Wrq(RwReq),
    Data(u16, &'a [u8]),
    Ack(u16),
    Error(Error),
    OAck(Opts),
}

#[derive(Debug, PartialEq)]
pub(crate) enum Mode {
    Netascii,
    Octet,
    Mail,
}

#[derive(Debug, PartialEq)]
pub(crate) struct RwReq {
    pub filename: String,
    pub mode: Mode,
    pub opts: Opts,
}

#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct Opts {
    pub block_size: Option<u16>,
    pub timeout: Option<u8>,
    pub transfer_size: Option<u64>,
}

impl<'a> Packet<'a> {
    pub(crate) fn decode(data: &[u8]) -> Result<Packet> {
        parse_packet(data)
    }

    pub(crate) fn encode(&self, buf: &mut BytesMut) {
        match self {
            Packet::Rrq(req) => {
                buf.extend_u16_be(PacketType::Rrq as u16);
                buf.extend_buf(&req.filename);
                buf.extend_u8(0);
                buf.extend_buf(req.mode.to_str());
                buf.extend_u8(0);
                req.opts.encode(buf);
            }
            Packet::Wrq(req) => {
                buf.extend_u16_be(PacketType::Wrq as u16);
                buf.extend_buf(&req.filename);
                buf.extend_u8(0);
                buf.extend_buf(req.mode.to_str());
                buf.extend_u8(0);
                req.opts.encode(buf);
            }
            Packet::Data(block, data) => {
                buf.extend_u16_be(PacketType::Data as u16);
                buf.extend_u16_be(*block);
                buf.extend_buf(&data[..]);
            }
            Packet::Ack(block) => {
                buf.extend_u16_be(PacketType::Ack as u16);
                buf.extend_u16_be(*block);
            }
            Packet::Error(error) => {
                buf.extend_u16_be(PacketType::Error as u16);
                buf.extend_u16_be(error.code());
                buf.extend_buf(error.msg());
                buf.extend_u8(0);
            }
            Packet::OAck(opts) => {
                buf.extend_u16_be(PacketType::OAck as u16);
                opts.encode(buf);
            }
        }
    }

    pub(crate) fn encode_data_head(block_id: u16, buf: &mut BytesMut) {
        buf.extend_u16_be(PacketType::Data as u16);
        buf.extend_u16_be(block_id);
    }
}

impl Opts {
    fn encode(&self, buf: &mut BytesMut) {
        if let Some(block_size) = self.block_size {
            buf.extend_buf("blksize\0");
            buf.extend_buf(block_size.to_string());
            buf.extend_u8(0);
        }

        if let Some(timeout) = self.timeout {
            buf.extend_buf("timeout\0");
            buf.extend_buf(timeout.to_string());
            buf.extend_u8(0);
        }

        if let Some(transfer_size) = self.transfer_size {
            buf.extend_buf("tsize\0");
            buf.extend_buf(transfer_size.to_string());
            buf.extend_u8(0);
        }
    }
}

impl Mode {
    pub(crate) fn to_str(&self) -> &'static str {
        match self {
            Mode::Netascii => "netascii",
            Mode::Octet => "octet",
            Mode::Mail => "mail",
        }
    }
}

impl Error {
    pub(crate) fn from_code(code: u16, msg: Option<&str>) -> Self {
        match code {
            1 => Error::FileNotFound,
            2 => Error::PermissionDenied,
            3 => Error::DiskFull,
            4 => Error::IllegalOperation,
            5 => Error::UnknownTransferId,
            6 => Error::FileAlreadyExists,
            7 => Error::NoSuchUser,
            0 | _ => match msg {
                Some(msg) => Error::Msg(msg.to_string()),
                None => Error::UnknownError,
            },
        }
    }

    pub(crate) fn code(&self) -> u16 {
        match self {
            Error::Msg(..) => 0,
            Error::UnknownError => 0,
            Error::FileNotFound => 1,
            Error::PermissionDenied => 2,
            Error::DiskFull => 3,
            Error::IllegalOperation => 4,
            Error::UnknownTransferId => 5,
            Error::FileAlreadyExists => 6,
            Error::NoSuchUser => 7,
        }
    }

    pub(crate) fn msg(&self) -> &str {
        match self {
            Error::Msg(msg) => msg,
            Error::UnknownError => "Unknown error",
            Error::FileNotFound => "File not found",
            Error::PermissionDenied => "Permission denied",
            Error::DiskFull => "Disk is full",
            Error::IllegalOperation => "Illegal operation",
            Error::UnknownTransferId => "Unknown transfer ID",
            Error::FileAlreadyExists => "File already exists",
            Error::NoSuchUser => "No such user",
        }
    }
}

impl From<Error> for Packet<'_> {
    fn from(inner: Error) -> Self {
        Packet::Error(inner)
    }
}

impl From<io::Error> for Error {
    fn from(io_err: io::Error) -> Self {
        match io_err.kind() {
            io::ErrorKind::NotFound => Error::FileNotFound,
            io::ErrorKind::PermissionDenied => Error::PermissionDenied,
            io::ErrorKind::WriteZero => Error::DiskFull,
            io::ErrorKind::AlreadyExists => Error::FileAlreadyExists,
            _ => match io_err.raw_os_error() {
                Some(rc) => Error::Msg(format!("IO error: {}", rc)),
                None => Error::UnknownError,
            },
        }
    }
}

impl From<crate::Error> for Error {
    fn from(err: crate::Error) -> Self {
        match err {
            crate::Error::Packet(e) => e,
            crate::Error::Io(e) => e.into(),
            crate::Error::InvalidPacket => Error::IllegalOperation,
            _ => Error::UnknownError,
        }
    }
}