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
//! gophermap is a Rust crate that can parse and generate Gopher responses.
//! It can be used to implement Gopher clients and servers. It doesn't handle
//! any I/O on purpose. This library is meant to be used by other servers and
//! clients in order to avoid re-implementing the gophermap logic.
//!
use std::io::Write;

/// A single entry in a Gopher map. This struct can be filled in order to
/// generate Gopher responses. It can also be the result of parsing one.
pub struct GopherEntry<'a> {
    /// The type of the link
    pub item_type: ItemType,
    /// The human-readable description of the link. Displayed on the UI.
    pub display_string: &'a str,
    /// The target page (selector) of the link
    pub selector: &'a str,
    /// The host for the target of the link
    pub host: &'a str,
    /// The port for the target of the link
    pub port: u16,
}

impl<'a> GopherEntry<'a> {
    /// Parse a line into a Gopher directory entry.
    /// ```rust
    /// use gophermap::GopherEntry;
    /// let entry = GopherEntry::from("1Floodgap Home	/home	gopher.floodgap.com	70\r\n")
    ///     .unwrap();
    /// assert_eq!(entry.selector, "/home");
    /// ```
    pub fn from(line: &'a str) -> Option<Self> {
        let line = {
            let mut chars = line.chars();
            if !(chars.next_back()? == '\n' && chars.next_back()? == '\r') {
                return None;
            }
            chars.as_str()
        };

        let mut parts = line.split('\t');

        Some(GopherEntry {
            item_type: ItemType::from(line.chars().next()?),
            display_string: {
                let part = parts.next()?;
                let (index, _) = part.char_indices().skip(1).next()?;
                &part[index..]
            },
            selector: parts.next()?,
            host: parts.next()?,
            port: parts.next()?.parse().ok()?,
        })
    }

    /// Serializes a Gopher entry into bytes. This function can be used to
    /// generate Gopher responses.
    pub fn write<W>(&self, mut buf: W) -> std::io::Result<()>
    where
        W: Write,
    {
        write!(
            buf,
            "{}{}\t{}\t{}\t{}\r\n",
            self.item_type.to_char(),
            self.display_string,
            self.selector,
            self.host,
            self.port
        )?;
        Ok(())
    }
}

pub struct GopherMenu<W>
where
    W: Write,
{
    target: W,
}

impl<'a, W> GopherMenu<&'a W>
where
    &'a W: Write,
{
    pub fn with_write(target: &'a W) -> Self {
        GopherMenu { target: &target }
    }

    pub fn info(&self, text: &str) -> std::io::Result<()> {
        self.write_entry(ItemType::Info, text, "FAKE", "fake.host", 1)
    }

    pub fn write_entry(
        &self,
        item_type: ItemType,
        text: &str,
        selector: &str,
        host: &str,
        port: u16,
    ) -> std::io::Result<()> {
        GopherEntry {
            item_type,
            display_string: text,
            selector,
            host,
            port,
        }
        .write(self.target)
    }

    pub fn end(&mut self) -> std::io::Result<()> {
        write!(self.target, ".\r\n")
    }
}

/// Item type for a Gopher directory entry
#[derive(Debug, PartialEq)]
pub enum ItemType {
    /// Item is a file
    File,
    /// Item is a directory
    Directory,
    /// Item is a CSO phone-book server
    CsoServer,
    /// Error
    Error,
    /// Item is a BinHexed Macintosh file.
    BinHex,
    /// Item is a DOS binary archive of some sort.
    /// Client must read until the TCP connection closes. Beware.
    DosBinary,
    /// Item is a UNIX uuencoded file.
    Uuencoded,
    /// Item is an Index-Search server.
    Search,
    /// Item points to a text-based telnet session.
    Telnet,
    /// Item is a binary file!
    /// Client must read until the TCP connection closes. Beware.
    Binary,
    /// Item is a redundant server
    RedundantServer,
    /// Item points to a text-based tn3270 session.
    Tn3270,
    /// Item is a GIF format graphics file.
    Gif,
    /// Item is some sort of image file. Client decides how to display.
    Image,
    /// Informational message
    Info,
    /// Other types
    Other(char),
}

impl ItemType {
    /// Parses a char into an Item Type
    pub fn from(c: char) -> Self {
        match c {
            '0' => ItemType::File,
            '1' => ItemType::Directory,
            '2' => ItemType::CsoServer,
            '3' => ItemType::Error,
            '4' => ItemType::BinHex,
            '5' => ItemType::DosBinary,
            '6' => ItemType::Uuencoded,
            '7' => ItemType::Search,
            '8' => ItemType::Telnet,
            '9' => ItemType::Binary,
            '+' => ItemType::RedundantServer,
            'T' => ItemType::Tn3270,
            'g' => ItemType::Gif,
            'I' => ItemType::Image,
            'i' => ItemType::Info,
            c => ItemType::Other(c),
        }
    }

    /// Turns an Item Type into a char
    pub fn to_char(&self) -> char {
        match self {
            ItemType::File => '0',
            ItemType::Directory => '1',
            ItemType::CsoServer => '2',
            ItemType::Error => '3',
            ItemType::BinHex => '4',
            ItemType::DosBinary => '5',
            ItemType::Uuencoded => '6',
            ItemType::Search => '7',
            ItemType::Telnet => '8',
            ItemType::Binary => '9',
            ItemType::RedundantServer => '+',
            ItemType::Tn3270 => 'T',
            ItemType::Gif => 'g',
            ItemType::Image => 'I',
            ItemType::Info => 'i',
            ItemType::Other(c) => *c,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get_test_pairs() -> Vec<(String, GopherEntry<'static>)> {
        let mut pairs = Vec::new();

        pairs.push((
            "1Floodgap Home	/home	gopher.floodgap.com	70\r\n".to_owned(),
            GopherEntry {
                item_type: ItemType::Directory,
                display_string: "Floodgap Home",
                selector: "/home",
                host: "gopher.floodgap.com",
                port: 70,
            },
        ));

        pairs.push((
            "iWelcome to my page	FAKE	(NULL)	0\r\n".to_owned(),
            GopherEntry {
                item_type: ItemType::Info,
                display_string: "Welcome to my page",
                selector: "FAKE",
                host: "(NULL)",
                port: 0,
            },
        ));

        return pairs;
    }

    #[test]
    fn test_parse() {
        for (raw, parsed) in get_test_pairs() {
            let entry = GopherEntry::from(&raw).unwrap();
            assert_eq!(entry.item_type, parsed.item_type);
            assert_eq!(entry.display_string, parsed.display_string);
            assert_eq!(entry.selector, parsed.selector);
            assert_eq!(entry.host, parsed.host);
            assert_eq!(entry.port, parsed.port);
        }
    }

    #[test]
    fn test_write() {
        for (raw, parsed) in get_test_pairs() {
            let mut output = Vec::new();
            parsed.write(&mut output).unwrap();
            let line = String::from_utf8(output).unwrap();
            assert_eq!(raw, line);
        }
    }
}