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
use bstr::ByteSlice;
use std::fmt::{self, Debug, Display};

/// A wrapper type for symlink targets.
/// Internally uses a [bytes::Bytes], but disallows empty targets and those
/// containing null bytes.
#[repr(transparent)]
#[derive(Clone, PartialEq, Eq)]
pub struct SymlinkTarget {
    inner: bytes::Bytes,
}

/// The maximum length a symlink target can have.
/// Linux allows 4095 bytes here.
pub const MAX_TARGET_LEN: usize = 4095;

impl AsRef<[u8]> for SymlinkTarget {
    fn as_ref(&self) -> &[u8] {
        self.inner.as_ref()
    }
}

impl From<SymlinkTarget> for bytes::Bytes {
    fn from(value: SymlinkTarget) -> Self {
        value.inner
    }
}

fn validate_symlink_target<B: AsRef<[u8]>>(symlink_target: B) -> Result<B, SymlinkTargetError> {
    let v = symlink_target.as_ref();

    if v.is_empty() {
        return Err(SymlinkTargetError::Empty);
    }
    if v.len() > MAX_TARGET_LEN {
        return Err(SymlinkTargetError::TooLong);
    }
    if v.contains(&0x00) {
        return Err(SymlinkTargetError::Null);
    }

    Ok(symlink_target)
}

impl TryFrom<bytes::Bytes> for SymlinkTarget {
    type Error = SymlinkTargetError;

    fn try_from(value: bytes::Bytes) -> Result<Self, Self::Error> {
        if let Err(e) = validate_symlink_target(&value) {
            return Err(SymlinkTargetError::Convert(value, Box::new(e)));
        }

        Ok(Self { inner: value })
    }
}

impl TryFrom<&'static [u8]> for SymlinkTarget {
    type Error = SymlinkTargetError;

    fn try_from(value: &'static [u8]) -> Result<Self, Self::Error> {
        if let Err(e) = validate_symlink_target(&value) {
            return Err(SymlinkTargetError::Convert(value.into(), Box::new(e)));
        }

        Ok(Self {
            inner: bytes::Bytes::from_static(value),
        })
    }
}

impl TryFrom<&str> for SymlinkTarget {
    type Error = SymlinkTargetError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if let Err(e) = validate_symlink_target(value) {
            return Err(SymlinkTargetError::Convert(
                value.to_owned().into(),
                Box::new(e),
            ));
        }

        Ok(Self {
            inner: bytes::Bytes::copy_from_slice(value.as_bytes()),
        })
    }
}

impl Debug for SymlinkTarget {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self.inner.as_bstr(), f)
    }
}

impl Display for SymlinkTarget {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self.inner.as_bstr(), f)
    }
}

/// Errors created when constructing / converting to [SymlinkTarget].
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(test, derive(Clone))]
pub enum SymlinkTargetError {
    #[error("cannot be empty")]
    Empty,
    #[error("cannot contain null bytes")]
    Null,
    #[error("cannot be over {} bytes long", MAX_TARGET_LEN)]
    TooLong,
    #[error("unable to convert '{:?}", .0.as_bstr())]
    Convert(bytes::Bytes, Box<Self>),
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;
    use rstest::rstest;

    use super::validate_symlink_target;
    use super::{SymlinkTarget, SymlinkTargetError};

    #[rstest]
    #[case::empty(b"", SymlinkTargetError::Empty)]
    #[case::null(b"foo\0", SymlinkTargetError::Null)]
    fn errors(#[case] v: &'static [u8], #[case] err: SymlinkTargetError) {
        {
            assert_eq!(
                Err(err.clone()),
                validate_symlink_target(v),
                "validate_symlink_target must fail as expected"
            );
        }

        let exp_err_v = Bytes::from_static(v);

        // Bytes
        {
            let v = Bytes::from_static(v);
            assert_eq!(
                Err(SymlinkTargetError::Convert(
                    exp_err_v.clone(),
                    Box::new(err.clone())
                )),
                SymlinkTarget::try_from(v),
                "conversion must fail as expected"
            );
        }
        // &[u8]
        {
            assert_eq!(
                Err(SymlinkTargetError::Convert(
                    exp_err_v.clone(),
                    Box::new(err.clone())
                )),
                SymlinkTarget::try_from(v),
                "conversion must fail as expected"
            );
        }
        // &str, if this is valid UTF-8
        {
            if let Ok(v) = std::str::from_utf8(v) {
                assert_eq!(
                    Err(SymlinkTargetError::Convert(
                        exp_err_v.clone(),
                        Box::new(err.clone())
                    )),
                    SymlinkTarget::try_from(v),
                    "conversion must fail as expected"
                );
            }
        }
    }

    #[test]
    fn error_toolong() {
        assert_eq!(
            Err(SymlinkTargetError::TooLong),
            validate_symlink_target("X".repeat(5000).into_bytes().as_slice())
        )
    }

    #[rstest]
    #[case::boring(b"aa")]
    #[case::dot(b".")]
    #[case::dotsandslashes(b"./..")]
    #[case::dotdot(b"..")]
    #[case::slashes(b"a/b")]
    #[case::slashes_and_absolute(b"/a/b")]
    #[case::invalid_utf8(b"\xc5\xc4\xd6")]
    fn success(#[case] v: &'static [u8]) {
        let exp = SymlinkTarget { inner: v.into() };

        // Bytes
        {
            let v: Bytes = v.into();
            assert_eq!(
                Ok(exp.clone()),
                SymlinkTarget::try_from(v),
                "conversion must succeed"
            )
        }

        // &[u8]
        {
            assert_eq!(
                Ok(exp.clone()),
                SymlinkTarget::try_from(v),
                "conversion must succeed"
            )
        }

        // &str, if this is valid UTF-8
        {
            if let Ok(v) = std::str::from_utf8(v) {
                assert_eq!(
                    Ok(exp.clone()),
                    SymlinkTarget::try_from(v),
                    "conversion must succeed"
                )
            }
        }
    }
}