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
use crate::Error;

const VERSION: &str = "2.0";

/// The SSH identification string as defined in the SSH protocol.
///
/// The format must match the following pattern:
/// `SSH-<protoversion>-<softwareversion>[ <comments>]`.
///
/// see <https://datatracker.ietf.org/doc/html/rfc4253#section-4.2>.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Id {
    /// The SSH's protocol version, should be `2.0` in our case.
    pub protoversion: String,

    /// A string identifying the software curently used, in example `billsSSH_3.6.3q3`.
    pub softwareversion: String,

    /// Optional comments with additionnal informations about the software.
    pub comments: Option<String>,
}

impl Id {
    /// Convenience method to create an `SSH-2.0` identifier string.
    pub fn v2(softwareversion: impl Into<String>, comments: Option<impl Into<String>>) -> Self {
        Self {
            protoversion: VERSION.into(),
            softwareversion: softwareversion.into(),
            comments: comments.map(Into::into),
        }
    }

    /// Read an [`Id`], discarding any _extra lines_ sent by the server
    /// from the provided `reader`.
    pub fn from_reader<R>(reader: &mut R) -> Result<Self, Error>
    where
        R: std::io::BufRead,
    {
        let text = std::io::BufRead::lines(reader)
            // Skip extra lines the server can send before identifying
            .find(|line| {
                line.as_deref()
                    .map(|line| line.starts_with("SSH"))
                    .unwrap_or(true)
            })
            .ok_or(Error::UnexpectedEof)??;

        text.parse()
    }

    #[cfg(feature = "futures")]
    #[cfg_attr(docsrs, doc(cfg(feature = "futures")))]
    /// Read an [`Id`], discarding any _extra lines_ sent by the server
    /// from the provided asynchronous `reader`.
    pub async fn from_async_reader<R>(reader: &mut R) -> Result<Self, Error>
    where
        R: futures::io::AsyncBufRead + Unpin,
    {
        use futures::TryStreamExt;

        let text = futures::io::AsyncBufReadExt::lines(reader)
            // Skip extra lines the server can send before identifying
            .try_skip_while(|line| futures::future::ok(!line.starts_with("SSH")))
            .try_next()
            .await?
            .ok_or(Error::UnexpectedEof)?;

        text.parse()
    }

    /// Write the [`Id`] to the provided `writer`.
    pub fn to_writer<W>(&self, writer: &mut W) -> Result<(), Error>
    where
        W: std::io::Write,
    {
        writer.write_all(self.to_string().as_bytes())?;
        writer.write_all(b"\r\n")?;

        Ok(())
    }

    /// Write the [`Id`] to the provided asynchronous `writer`.
    #[cfg(feature = "futures")]
    #[cfg_attr(docsrs, doc(cfg(feature = "futures")))]
    pub async fn to_async_writer<W>(&self, writer: &mut W) -> Result<(), Error>
    where
        W: futures::io::AsyncWrite + Unpin,
    {
        use futures::io::AsyncWriteExt;

        writer.write_all(self.to_string().as_bytes()).await?;
        writer.write_all(b"\r\n").await?;

        Ok(())
    }
}

impl std::fmt::Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SSH-{}-{}", self.protoversion, self.softwareversion)?;

        if let Some(comments) = &self.comments {
            write!(f, " {comments}")?;
        }

        Ok(())
    }
}

impl std::str::FromStr for Id {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (id, comments) = s
            .split_once(' ')
            .map_or_else(|| (s, None), |(id, comments)| (id, Some(comments)));

        match id.splitn(3, '-').collect::<Vec<_>>()[..] {
            ["SSH", protoversion, softwareversion]
                if !protoversion.is_empty() && !softwareversion.is_empty() =>
            {
                Ok(Self {
                    protoversion: protoversion.to_string(),
                    softwareversion: softwareversion.to_string(),
                    comments: comments.map(str::to_string),
                })
            }
            _ => Err(Error::BadIdentifer(s.into())),
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::unimplemented)]
    use rstest::rstest;
    use std::str::FromStr;

    use super::*;

    impl PartialEq for Error {
        fn eq(&self, other: &Self) -> bool {
            match (self, other) {
                (Self::Io(l0), Self::Io(r0)) => l0.kind() == r0.kind(),
                _ => core::mem::discriminant(self) == core::mem::discriminant(other),
            }
        }
    }

    #[rstest]
    #[case("SSH-2.0-billsSSH_3.6.3q3")]
    #[case("SSH-1.99-billsSSH_3.6.3q3")]
    #[case("SSH-2.0-billsSSH_3.6.3q3 with-comment")]
    #[case("SSH-2.0-billsSSH_3.6.3q3 utf∞-comment")]
    #[case("SSH-2.0-billsSSH_3.6.3q3 ")] // empty comment
    fn it_parses_valid(#[case] text: &str) {
        Id::from_str(text).expect(text);
    }

    #[rstest]
    #[case("")]
    #[case("FOO-2.0-billsSSH_3.6.3q3")]
    #[case("-2.0-billsSSH_3.6.3q3")]
    #[case("SSH--billsSSH_3.6.3q3")]
    #[case("SSH-2.0-")]
    fn it_rejects_invalid(#[case] text: &str) {
        Id::from_str(text).expect_err(text);
    }

    #[rstest]
    #[case(Id::v2("billsSSH_3.6.3q3", None::<String>))]
    #[case(Id::v2("billsSSH_utf∞", None::<String>))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("with-comment")))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("utf∞-comment")))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("")))] // empty comment
    fn it_reparses_consistently(#[case] id: Id) {
        assert_eq!(id, id.to_string().parse().unwrap());
    }

    #[rstest]
    #[case(b"")]
    #[case(&[255])]
    #[case(&[255, 255])]
    #[case(b"SSH-2.0-billsSSH_3.6.3q3\r\n")]
    #[case(b"SSH-1.99-billsSSH_3.6.3q3\n")]
    #[case(b"SSH-2.0-billsSSH_3.6.3q3 with-comment\r\n")]
    #[case(b"This is extra text\r\nIt is skipped by the parser\r\nSSH-2.0-billsSSH_3.6.3q3\r\n")]
    #[case(b"This is extra text\r\nIt is skipped by the parser\r\n")]
    #[case(b"This is extra text")]
    #[cfg(feature = "futures")]
    async fn it_reads_consistently(#[case] bytes: &[u8]) {
        assert_eq!(
            Id::from_reader(&mut std::io::BufReader::new(bytes)),
            Id::from_async_reader(&mut futures::io::BufReader::new(bytes)).await
        )
    }

    #[rstest]
    #[case(Id::v2("billsSSH_3.6.3q3", None::<String>))]
    #[case(Id::v2("billsSSH_utf∞", None::<String>))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("with-comment")))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("utf∞-comment")))]
    #[case(Id::v2("billsSSH_3.6.3q3", Some("")))] // empty comment
    #[cfg(feature = "futures")]
    async fn it_writes_consistently(#[case] id: Id) {
        let (mut stdbuf, mut asyncbuf) = (Vec::new(), Vec::new());

        assert_eq!(
            id.to_writer(&mut stdbuf),
            id.to_async_writer(&mut asyncbuf).await
        );
        assert_eq!(stdbuf, asyncbuf);
    }
}