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
use chrono::prelude::*;
use futures::SinkExt;
use tokio::io::AsyncBufReadExt;

fn decode_line(data: &str, host: &str) -> Result<super::proto::DACResponse, ()> {
    let mut parts = data.split(',').collect::<Vec<_>>();
    if parts.len() < 2 {
        error!("Invalid syntax from {}: expected at least two parts", host);
        Err(())
    } else {
        parts.reverse();
        let domain = parts.pop().unwrap();
        let registered = parts.pop().unwrap();

        match registered {
            "C" => {
                if parts.len() != 4 {
                    error!(
                        "Invalid syntax from {}: expected at 6 parts for a usage response",
                        host
                    );
                    Err(())
                } else {
                    let limit_60_const = parts.pop().unwrap();
                    let limit_60 = parts.pop().unwrap();
                    let limit_24_const = parts.pop().unwrap();
                    let limit_24 = parts.pop().unwrap();

                    if limit_60_const != "60" || limit_24_const != "86400" {
                        error!("Invalid syntax from {}: invalid usage response", host);
                        Err(())
                    } else {
                        let limit_60 = match limit_60.parse::<u64>() {
                            Ok(l) => l,
                            Err(_) => {
                                error!("Invalid syntax from {}: invalid int", host);
                                return Err(());
                            }
                        };
                        let limit_24 = match limit_24.parse::<u64>() {
                            Ok(l) => l,
                            Err(_) => {
                                error!("Invalid syntax from {}: invalid int", host);
                                return Err(());
                            }
                        };

                        let usage = super::proto::Usage {
                            usage_60: limit_60,
                            usage_24: limit_24,
                        };

                        match domain {
                            "#usage" => Ok(super::proto::DACResponse::Usage(usage)),
                            "#limits" => Ok(super::proto::DACResponse::Limits(usage)),
                            o => {
                                error!("Invalid syntax from {}: invalid domain for a usage response ({})", host, o);
                                Err(())
                            }
                        }
                    }
                }
            }
            "B" => {
                if parts.len() != 1 {
                    error!(
                        "Invalid syntax from {}: expected 3 parts for an AUB response",
                        host
                    );
                    Err(())
                } else {
                    let delay = parts.pop().unwrap();
                    let delay = match delay.parse::<u64>() {
                        Ok(l) => l,
                        Err(_) => {
                            error!("Invalid syntax from {}: invalid int", host);
                            return Err(());
                        }
                    };
                    Ok(super::proto::DACResponse::Aub(super::proto::Aub {
                        domain: domain.to_string(),
                        delay,
                    }))
                }
            }
            "I" => {
                error!("Invalid syntax error received from {}", host);
                Err(())
            }
            r => {
                match parts.len() {
                    0 => {
                        let registered = match r {
                            "Y" => true,
                            "N" => false,
                            _ => {
                                error!("Invalid syntax from {}: invalid registered status", host);
                                return Err(());
                            }
                        };

                        Ok(super::proto::DACResponse::DomainRT(
                            super::proto::DomainRT {
                                domain: domain.to_string(),
                                registered,
                                detagged: false,
                                created: Utc.ymd(1970, 1, 1),
                                expiry: Utc.ymd(1970, 1, 1),
                                tag: String::default(),
                            },
                        ))
                    }
                    4 => {
                        let detagged = parts.pop().unwrap();
                        let created = parts.pop().unwrap();
                        let expiry = parts.pop().unwrap();
                        let tag = parts.pop().unwrap();

                        let registered = match r {
                            "Y" => true,
                            "N" => false,
                            _ => {
                                error!("Invalid syntax from {}: invalid registered status", host);
                                return Err(());
                            }
                        };
                        let detagged = match detagged {
                            "Y" => true,
                            "N" => false,
                            _ => {
                                error!("Invalid syntax from {}: invalid bool", host);
                                return Err(());
                            }
                        };
                        let created = match chrono::NaiveDate::parse_from_str(created, "%Y-%m-%d") {
                            Ok(d) => d,
                            Err(e) => {
                                error!("Invalid syntax from {}: invalid date {}", host, e);
                                return Err(());
                            }
                        };
                        let expiry = match chrono::NaiveDate::parse_from_str(expiry, "%Y-%m-%d") {
                            Ok(d) => d,
                            Err(e) => {
                                error!("Invalid syntax from {}: invalid date {}", host, e);
                                return Err(());
                            }
                        };
                        let created = chrono::Date::from_utc(created, chrono::offset::Utc);
                        let expiry = chrono::Date::from_utc(expiry, chrono::offset::Utc);

                        Ok(super::proto::DACResponse::DomainRT(
                            super::proto::DomainRT {
                                domain: domain.to_string(),
                                registered,
                                detagged,
                                created,
                                expiry,
                                tag: tag.to_string(),
                            },
                        ))
                    }
                    6 => {
                        let detagged = parts.pop().unwrap();
                        let suspended = parts.pop().unwrap();
                        let created = parts.pop().unwrap();
                        let expiry = parts.pop().unwrap();
                        let status = parts.pop().unwrap();
                        let tag = parts.pop().unwrap();

                        let registered = match r {
                            "Y" => super::proto::DomainRegistered::Registered,
                            "N" => super::proto::DomainRegistered::Available,
                            "E" => super::proto::DomainRegistered::NotWithinRegistry,
                            "R" => super::proto::DomainRegistered::RulesPrevent,
                            _ => {
                                error!("Invalid syntax from {}: invalid registered status", host);
                                return Err(());
                            }
                        };
                        let detagged = match detagged {
                            "Y" => true,
                            "N" => false,
                            _ => {
                                error!("Invalid syntax from {}: invalid bool", host);
                                return Err(());
                            }
                        };
                        let suspended = match suspended {
                            "Y" => true,
                            "N" => false,
                            _ => {
                                error!("Invalid syntax from {}: invalid bool", host);
                                return Err(());
                            }
                        };
                        let created = match chrono::NaiveDate::parse_from_str(created, "%Y-%m-%d") {
                            Ok(d) => d,
                            Err(e) => {
                                error!("Invalid syntax from {}: invalid date {}", host, e);
                                return Err(());
                            }
                        };
                        let expiry = match chrono::NaiveDate::parse_from_str(expiry, "%Y-%m-%d") {
                            Ok(d) => d,
                            Err(e) => {
                                error!("Invalid syntax from {}: invalid date {}", host, e);
                                return Err(());
                            }
                        };
                        let created = chrono::Date::from_utc(created, chrono::offset::Utc);
                        let expiry = chrono::Date::from_utc(expiry, chrono::offset::Utc);
                        let status = match status {
                            "0" => super::proto::DomainStatus::Unknown,
                            "2" => super::proto::DomainStatus::RegisteredUntilExpiry,
                            "4" => super::proto::DomainStatus::RenewalRequired,
                            "7" => super::proto::DomainStatus::NoLongerRequired,
                            _ => {
                                error!("Invalid syntax from {}: invalid status", host);
                                return Err(());
                            }
                        };

                        Ok(super::proto::DACResponse::DomainTD(
                            super::proto::DomainTD {
                                domain: domain.to_string(),
                                registered,
                                detagged,
                                suspended,
                                created,
                                expiry,
                                status,
                                tag: tag.to_string(),
                            },
                        ))
                    }
                    _ => {
                        error!("Invalid syntax from {}: expected 2, 6 or 8 parts for a domain response", host);
                        Err(())
                    }
                }
            }
        }
    }
}

async fn recv_msg<R: std::marker::Unpin + tokio::io::AsyncBufRead>(
    lines: &mut tokio::io::Lines<R>,
    host: &str,
) -> Result<super::proto::DACResponse, bool> {
    let line = match lines.next_line().await {
        Ok(Some(l)) => l,
        Ok(None) => {
            warn!("{} has closed the connection", host);
            return Err(true);
        }
        Err(err) => {
            return Err(match err.kind() {
                std::io::ErrorKind::UnexpectedEof => {
                    warn!("{} has closed the connection", host);
                    true
                }
                _ => {
                    error!("Error reading next data line from {}: {}", host, err);
                    false
                }
            });
        }
    };
    debug!("Received message from {} with contents: {}", host, line);
    let msg = decode_line(&line, host).map_err(|_| false)?;
    Ok(msg)
}

/// Tokio task that attemps to read in messages and push them onto a tokio channel as received.
pub(super) struct ClientReceiver<R: std::marker::Unpin + tokio::io::AsyncBufRead> {
    /// Host name for error reporting
    pub host: String,
    /// Read half of the TCP stream used to connect to the server
    pub reader: R,
}

impl<R: 'static + std::marker::Unpin + tokio::io::AsyncBufRead + std::marker::Send>
    ClientReceiver<R>
{
    /// Starts the tokio task, and returns the receiving end of the channel to read messages from.
    pub fn run(self) -> futures::channel::mpsc::Receiver<Result<super::proto::DACResponse, bool>> {
        let (mut sender, receiver) =
            futures::channel::mpsc::channel::<Result<super::proto::DACResponse, bool>>(16);
        tokio::spawn(async move {
            let mut lines = self.reader.lines();
            loop {
                let msg = recv_msg(&mut lines, &self.host).await;
                let is_close = if let Err(c) = &msg { *c } else { false };
                match sender.send(msg).await {
                    Ok(_) => {}
                    Err(_) => break,
                }
                if is_close {
                    break;
                }
            }
        });
        receiver
    }
}