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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
use super::{Database, Definition, Match, Strategy};
use crate::reply::{ParseReplyError, Reply};
use crate::status::{Category, ReplyKind, Status};
use std::convert::From;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::net::TcpStream;

#[derive(Debug)]
pub enum DICTError {
    ReplyError(ParseReplyError),
    SystemError(Reply),
    UnexpectedPacket(DICTPacket),

    // Read / Write things
    NoAnswer,
    ReadWriteError(std::io::Error),
    MalformedAnswer(&'static str),
}

pub type DICTResult<T> = Result<(T, Reply), DICTError>;

#[derive(Debug)]
pub enum DICTPacketKind {
    // Generic
    ReplyOnly,
    OkReply,

    // TODO: parse capabilities too
    InitialConnection(String),

    // DEFINE packets
    DefinitionsFollow,
    Definition(Definition),

    // MATCH packets
    Matches(Vec<Match>),

    // SHOW packets
    Databases(Vec<Database>),
    Strategies(Vec<Strategy>), // TODO: There is way more specific packets
}

#[derive(Debug)]
pub struct DICTPacket(pub DICTPacketKind, pub Reply);

pub struct DICTConnection {
    input: BufReader<TcpStream>,
    output: BufWriter<TcpStream>,
}

impl DICTConnection {
    pub fn new(inner: TcpStream) -> std::io::Result<Self> {
        let input = BufReader::new(inner.try_clone()?);
        Ok(DICTConnection {
            input,
            output: BufWriter::new(inner),
        })
    }

    fn read_raw_text(&mut self) -> Vec<String> {
        let mut line = String::new();
        let mut text = Vec::with_capacity(10);

        loop {
            if self.input.read_line(&mut line).is_ok() {
                let line_t = line.trim_end_matches("\r\n");
                if line_t.eq(".") {
                    break;
                } else {
                    text.push(line_t.to_owned());
                    line.clear();
                }
            }
        }

        text
    }

    pub fn start(&mut self) -> DICTResult<String> {
        match self.next().ok_or(DICTError::NoAnswer)?? {
            DICTPacket(DICTPacketKind::InitialConnection(msg_id), r) => Ok((msg_id, r)),
            e => Err(DICTError::UnexpectedPacket(e)),
        }
    }

    pub fn client(&mut self, client: String) -> Result<Reply, DICTError> {
        writeln!(self.output, "CLIENT \"{}\"", client)?;
        self.output.flush()?;

        match self.next().ok_or(DICTError::NoAnswer)?? {
            DICTPacket(DICTPacketKind::OkReply, r) => Ok(r),
            e => Err(DICTError::UnexpectedPacket(e)),
        }
    }

    pub fn define(
        &mut self,
        database: Database,
        word: String,
    ) -> Result<(Vec<Definition>, Reply), DICTError> {
        writeln!(self.output, "DEFINE \"{}\" \"{}\"", database.name, word)?;
        self.output.flush()?;

        let reply = self.next().ok_or(DICTError::NoAnswer)??;

        // start of answer
        match reply {
            DICTPacket(DICTPacketKind::DefinitionsFollow, _) => {}
            p => {
                return Err(DICTError::UnexpectedPacket(p));
            }
        }

        let mut defs: Vec<Definition> = Vec::new();

        for p in self {
            match p {
                Ok(DICTPacket(DICTPacketKind::Definition(def), _)) => {
                    defs.push(def);
                }
                Ok(DICTPacket(DICTPacketKind::OkReply, _)) => {
                    break;
                }
                Ok(unexp) => {
                    return Err(DICTError::UnexpectedPacket(unexp));
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }

        Ok((defs, reply.1))
    }

    pub fn match_db(
        &mut self,
        db: Database,
        strat: Strategy,
        word: String,
    ) -> Result<(Vec<Match>, Reply), DICTError> {
        writeln!(
            self.output,
            "MATCH \"{}\" \"{}\" \"{}\"",
            db.name, strat.name, word
        )?;
        self.output.flush()?;

        match self.next().ok_or(DICTError::NoAnswer)?? {
            DICTPacket(DICTPacketKind::Matches(matches), r) => {
                let ok = self.next().ok_or(DICTError::NoAnswer)??;

                if let DICTPacket(DICTPacketKind::OkReply, _) = ok {
                    Ok((matches, r))
                } else {
                    Err(DICTError::UnexpectedPacket(ok))
                }
            }
            e => Err(DICTError::UnexpectedPacket(e)),
        }
    }

    pub fn show_db(&mut self) -> Result<(Vec<Database>, Reply), DICTError> {
        writeln!(self.output, "SHOW DATABASES")?;
        self.output.flush()?;

        match self.next().ok_or(DICTError::NoAnswer)?? {
            DICTPacket(DICTPacketKind::Databases(dbs), r) => {
                let ok = self.next().ok_or(DICTError::NoAnswer)??;

                if let DICTPacket(DICTPacketKind::OkReply, _) = ok {
                    Ok((dbs, r))
                } else {
                    Err(DICTError::UnexpectedPacket(ok))
                }
            }
            e => Err(DICTError::UnexpectedPacket(e)),
        }
    }

    pub fn show_strat(&mut self) -> Result<(Vec<Strategy>, Reply), DICTError> {
        writeln!(self.output, "SHOW STRATEGIES")?;
        self.output.flush()?;

        match self.next().ok_or(DICTError::NoAnswer)?? {
            DICTPacket(DICTPacketKind::Strategies(strats), r) => {
                let ok = self.next().ok_or(DICTError::NoAnswer)??;

                if let DICTPacket(DICTPacketKind::OkReply, _) = ok {
                    Ok((strats, r))
                } else {
                    Err(DICTError::UnexpectedPacket(ok))
                }
            }
            e => Err(DICTError::UnexpectedPacket(e)),
        }
    }
}

macro_rules! get_argument {
    ($arguments:ident, $index:expr, $err:expr) => {
        if let Some(arg) = $arguments.get($index) {
            arg
        } else {
            return Some(Err($err));
        }
    };
}

fn parse_cmd_argument(reply_text: &String) -> Vec<String> {
    let mut ret: Vec<String> = Vec::new();
    let mut tmp: String = String::new();

    let mut in_string: bool = false;

    for part in reply_text.split_ascii_whitespace() {
        if !in_string {
            // Starting a string
            if let Some(suffix) = part.strip_prefix('"') {
                if let Some(oneword) = suffix.strip_suffix('"') {
                    // That ends here too
                    ret.push(String::from(oneword));
                } else {
                    in_string = true;

                    tmp.push_str(suffix);
                }
            } else {
                ret.push(String::from(part));
            }
        } else {
            tmp.push_str(" ");
            if let Some(preffix) = part.strip_suffix('"') {
                tmp.push_str(preffix);
                ret.push(tmp);

                in_string = false;
                tmp = String::new();
            } else {
                tmp.push_str(part);
            }
        }
    }

    ret
}

impl Iterator for DICTConnection {
    type Item = Result<DICTPacket, DICTError>;

    fn next(&mut self) -> Option<Self::Item> {
        let reply = match Reply::from_reader(&mut self.input) {
            Ok(rep) => rep,
            Err(e) => {
                return Some(Err(DICTError::ReplyError(e)));
            }
        };

        match reply.status {
            // Generic
            Status(ReplyKind::PositiveCompletion, Category::System, 0) => {
                Some(Ok(DICTPacket(DICTPacketKind::OkReply, reply)))
            }

            // Connection open
            Status(ReplyKind::PositiveCompletion, Category::Connection, 0) => {
                let arguments = reply.text.split_whitespace().collect::<Vec<&str>>();

                let msg_id = get_argument!(
                    arguments,
                    arguments.len() - 1,
                    DICTError::MalformedAnswer("Missing starting text")
                );
                Some(Ok(DICTPacket(
                    DICTPacketKind::InitialConnection((*msg_id).to_owned()),
                    reply,
                )))
            }

            // DEFINE Command
            Status(ReplyKind::PositivePreliminary, Category::System, 0) => {
                Some(Ok(DICTPacket(DICTPacketKind::DefinitionsFollow, reply)))
            }
            Status(ReplyKind::PositivePreliminary, Category::System, 1) => {
                // Definition

                let arguments = parse_cmd_argument(&reply.text);
                let dbname = get_argument!(
                    arguments,
                    1,
                    DICTError::MalformedAnswer("Missing database name")
                );
                let dbdesc = get_argument!(
                    arguments,
                    2,
                    DICTError::MalformedAnswer("Missing database description")
                );

                let text = self.read_raw_text();

                let def = Definition {
                    source: Database {
                        name: String::from(dbname),
                        desc: String::from(dbdesc),
                    },
                    text,
                };

                Some(Ok(DICTPacket(DICTPacketKind::Definition(def), reply)))
            }

            // MATCH command
            Status(ReplyKind::PositivePreliminary, Category::System, 2) => {
                let mut matches: Vec<Match> = Vec::new();
                for match_def in self.read_raw_text() {
                    let arguments = parse_cmd_argument(&match_def);
                    let dbname = get_argument!(
                        arguments,
                        0,
                        DICTError::MalformedAnswer("Missing database name")
                    );
                    let word = get_argument!(
                        arguments,
                        1,
                        DICTError::MalformedAnswer("Missing database description")
                    );

                    matches.push(Match {
                        source: Database::from(dbname.to_owned()),
                        word: word.to_owned(),
                    });
                }

                Some(Ok(DICTPacket(DICTPacketKind::Matches(matches), reply)))
            }

            // SHOW DB command
            Status(ReplyKind::PositivePreliminary, Category::Information, 0) => {
                let mut dbs: Vec<Database> = Vec::new();
                for db_def in self.read_raw_text() {
                    let arguments = parse_cmd_argument(&db_def);
                    let name = get_argument!(
                        arguments,
                        0,
                        DICTError::MalformedAnswer("Missing database name")
                    );
                    let desc = get_argument!(
                        arguments,
                        1,
                        DICTError::MalformedAnswer("Missing database description")
                    );

                    dbs.push(Database {
                        name: name.to_owned(),
                        desc: desc.to_owned(),
                    });
                }

                Some(Ok(DICTPacket(DICTPacketKind::Databases(dbs), reply)))
            }

            // SHOW STRAT command
            Status(ReplyKind::PositivePreliminary, Category::Information, 1) => {
                let mut strats: Vec<Strategy> = Vec::new();
                for strat_def in self.read_raw_text() {
                    let arguments = parse_cmd_argument(&strat_def);
                    let name = get_argument!(
                        arguments,
                        0,
                        DICTError::MalformedAnswer("Missing database name")
                    );
                    let desc = get_argument!(
                        arguments,
                        1,
                        DICTError::MalformedAnswer("Missing database description")
                    );

                    strats.push(Strategy {
                        name: name.to_owned(),
                        desc: desc.to_owned(),
                    });
                }

                Some(Ok(DICTPacket(DICTPacketKind::Strategies(strats), reply)))
            }
            ref r if r.is_positive() => Some(Ok(DICTPacket(DICTPacketKind::ReplyOnly, reply))),
            _ => Some(Err(DICTError::SystemError(reply))),
        }
    }
}

impl From<ParseReplyError> for DICTError {
    fn from(src: ParseReplyError) -> Self {
        DICTError::ReplyError(src)
    }
}

impl From<std::io::Error> for DICTError {
    fn from(src: std::io::Error) -> Self {
        DICTError::ReadWriteError(src)
    }
}