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
use libc::{c_char, size_t};
use std::marker::PhantomData;
use std::{
    convert::{TryFrom, TryInto},
    ptr::null,
};

/// A read-only view on a Rust byte slice.
///
/// This is used to pass data from crustls to callback functions provided
/// by the user of the API.
/// `len` indicates the number of bytes than can be safely read.
///
/// The memory exposed is available as specified by the function
/// using this in its signature. For instance, when this is a parameter to a
/// callback, the lifetime will usually be the duration of the callback.
/// Functions that receive one of these must not dereference the data pointer
/// beyond the allowed lifetime.
#[repr(C)]
pub struct rustls_slice_bytes<'a> {
    pub data: *const u8,
    pub len: size_t,
    phantom: PhantomData<&'a [u8]>,
}

impl<'a> From<&'a [u8]> for rustls_slice_bytes<'a> {
    fn from(s: &[u8]) -> Self {
        rustls_slice_bytes {
            data: s.as_ptr(),
            len: s.len(),
            phantom: PhantomData,
        }
    }
}

#[test]
fn test_rustls_slice_bytes() {
    let bytes = b"abcd";
    let rsb: rustls_slice_bytes = bytes.as_ref().into();
    unsafe {
        assert_eq!(*rsb.data, b'a');
        assert_eq!(*rsb.data.offset(3), b'd');
        assert_eq!(rsb.len, 4);
    }
}

/// A read-only view of a slice of Rust byte slices.
///
/// This is used to pass data from crustls to callback functions provided
/// by the user of the API. Because Vec and slice are not `#[repr(C)]`, we
/// provide access via a pointer to an opaque struct and an accessor method
/// that acts on that struct to get entries of type `rustls_slice_bytes`.
/// Internally, the pointee is a `&[&[u8]]`.
///
/// The memory exposed is available as specified by the function
/// using this in its signature. For instance, when this is a parameter to a
/// callback, the lifetime will usually be the duration of the callback.
/// Functions that receive one of these must not call its methods beyond the
/// allowed lifetime.
pub struct rustls_slice_slice_bytes<'a> {
    pub(crate) inner: &'a [&'a [u8]],
}

/// Return the length of the outer slice. If the input pointer is NULL,
/// returns 0.
#[no_mangle]
pub extern "C" fn rustls_slice_slice_bytes_len(input: *const rustls_slice_slice_bytes) -> size_t {
    unsafe {
        match input.as_ref() {
            Some(c) => c.inner.len(),
            None => 0,
        }
    }
}

/// Retrieve the nth element from the input slice of slices. If the input
/// pointer is NULL, or n is greater than the length of the
/// rustls_slice_slice_bytes, returns rustls_slice_bytes{NULL, 0}.
#[no_mangle]
pub extern "C" fn rustls_slice_slice_bytes_get(
    input: *const rustls_slice_slice_bytes,
    n: size_t,
) -> rustls_slice_bytes {
    let input: &rustls_slice_slice_bytes = unsafe {
        match input.as_ref() {
            Some(c) => c,
            None => {
                return rustls_slice_bytes {
                    data: null(),
                    len: 0,
                    phantom: PhantomData,
                }
            }
        }
    };
    match input.inner.get(n) {
        Some(rsb) => (*rsb).into(),
        None => rustls_slice_bytes {
            data: null(),
            len: 0,
            phantom: PhantomData,
        },
    }
}

#[test]
fn test_rustls_slice_slice_bytes() {
    let many_bytes: Vec<&[u8]> = vec![b"abcd", b"", b"xyz"];
    let rssb = rustls_slice_slice_bytes { inner: &many_bytes };

    assert_eq!(rustls_slice_slice_bytes_len(&rssb), 3);

    assert_eq!(rustls_slice_slice_bytes_get(&rssb, 0).len, 4);
    assert_eq!(rustls_slice_slice_bytes_get(&rssb, 1).len, 0);
    assert_ne!(rustls_slice_slice_bytes_get(&rssb, 1).data, null());
    assert_eq!(rustls_slice_slice_bytes_get(&rssb, 2).len, 3);
    assert_eq!(rustls_slice_slice_bytes_get(&rssb, 3).len, 0);
    assert_eq!(rustls_slice_slice_bytes_get(&rssb, 3).data, null());

    unsafe {
        assert_eq!(*rustls_slice_slice_bytes_get(&rssb, 0).data, b'a');
        assert_eq!(*rustls_slice_slice_bytes_get(&rssb, 0).data.offset(3), b'd');
        assert_eq!(*rustls_slice_slice_bytes_get(&rssb, 2).data, b'x');
        assert_eq!(*rustls_slice_slice_bytes_get(&rssb, 2).data.offset(2), b'z');
    }
}

/// A read-only view on a Rust `&str`. The contents are guaranteed to be valid
/// UTF-8. As an additional guarantee on top of Rust's normal UTF-8 guarantee,
/// a `rustls_str` is guaranteed not to contain internal NUL bytes, so it is
/// safe to interpolate into a C string or compare using strncmp. Keep in mind
/// that it is not NUL-terminated.
///
/// The memory exposed is available as specified by the function
/// using this in its signature. For instance, when this is a parameter to a
/// callback, the lifetime will usually be the duration of the callback.
/// Functions that receive one of these must not dereference the data pointer
/// beyond the allowed lifetime.
#[repr(C)]
pub struct rustls_str<'a> {
    pub data: *const c_char,
    pub len: size_t,
    phantom: PhantomData<&'a str>,
}

/// NulByte represents an error converting `&str` to `rustls_str` when the &str
/// contains a NUL.
#[derive(Debug)]
pub struct NulByte {}

impl<'a> TryFrom<&'a str> for rustls_str<'a> {
    type Error = NulByte;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.contains('\0') {
            return Err(NulByte {});
        }
        Ok(rustls_str {
            data: s.as_ptr() as *const c_char,
            len: s.len(),
            phantom: PhantomData,
        })
    }
}

impl<'a> rustls_str<'a> {
    pub fn from_str_unchecked(s: &'static str) -> rustls_str<'static> {
        rustls_str {
            data: s.as_ptr() as *const _,
            len: s.len(),
            phantom: PhantomData,
        }
    }
}

#[test]
fn test_rustls_str() {
    let s = "abcd";
    let rs: rustls_str = s.try_into().unwrap();
    assert_eq!(rs.len, 4);
    unsafe {
        assert_eq!(*rs.data, 'a' as c_char);
        assert_eq!(*rs.data.offset(3), 'd' as c_char);
    }
}

#[test]
fn test_rustls_str_rejects_nul() {
    assert!(matches!(rustls_str::try_from("\0"), Err(NulByte {})));
    assert!(matches!(rustls_str::try_from("abc\0"), Err(NulByte {})));
    assert!(matches!(rustls_str::try_from("ab\0cd"), Err(NulByte {})));
}

/// A read-only view of a slice of multiple Rust `&str`'s (that is, multiple
/// strings). Like `rustls_str`, this guarantees that each string contains
/// UTF-8 and no NUL bytes. Strings are not NUL-terminated.
///
/// This is used to pass data from crustls to callback functions provided
/// by the user of the API. Because Vec and slice are not `#[repr(C)]`, we
/// can't provide a straightforward `data` and `len` structure. Instead, we
/// provide access via a pointer to an opaque struct and accessor methods.
/// Internally, the pointee is a `&[&str]`.
///
/// The memory exposed is available as specified by the function
/// using this in its signature. For instance, when this is a parameter to a
/// callback, the lifetime will usually be the duration of the callback.
/// Functions that receive one of these must not call its methods beyond the
/// allowed lifetime.
pub struct rustls_slice_str<'a> {
    pub(crate) inner: &'a [&'a str],
}

/// Return the length of the outer slice. If the input pointer is NULL,
/// returns 0.
#[no_mangle]
pub extern "C" fn rustls_slice_str_len(input: *const rustls_slice_str) -> size_t {
    unsafe {
        match input.as_ref() {
            Some(c) => c.inner.len(),
            None => 0,
        }
    }
}

/// Retrieve the nth element from the input slice of `&str`s. If the input
/// pointer is NULL, or n is greater than the length of the
/// rustls_slice_str, returns rustls_str{NULL, 0}.
#[no_mangle]
pub extern "C" fn rustls_slice_str_get(input: *const rustls_slice_str, n: size_t) -> rustls_str {
    let input: &rustls_slice_str = unsafe {
        match input.as_ref() {
            Some(c) => c,
            None => {
                return rustls_str {
                    data: null(),
                    len: 0,
                    phantom: PhantomData,
                }
            }
        }
    };
    input
        .inner
        .get(n)
        .and_then(|&s| s.try_into().ok())
        .unwrap_or(rustls_str {
            data: null(),
            len: 0,
            phantom: PhantomData,
        })
}

#[test]
fn test_rustls_slice_str() {
    let many_strings = vec!["abcd", "", "xyz"];
    let rss = rustls_slice_str {
        inner: &many_strings,
    };

    assert_eq!(rustls_slice_str_len(&rss), 3);

    assert_eq!(rustls_slice_str_get(&rss, 0).len, 4);
    assert_eq!(rustls_slice_str_get(&rss, 1).len, 0);
    assert_ne!(rustls_slice_str_get(&rss, 1).data, null());
    assert_eq!(rustls_slice_str_get(&rss, 2).len, 3);
    assert_eq!(rustls_slice_str_get(&rss, 3).len, 0);
    assert_eq!(rustls_slice_str_get(&rss, 3).data, null());

    unsafe {
        assert_eq!(*rustls_slice_str_get(&rss, 0).data, 'a' as c_char);
        assert_eq!(*rustls_slice_str_get(&rss, 0).data.offset(3), 'd' as c_char);
        assert_eq!(*rustls_slice_str_get(&rss, 2).data, 'x' as c_char);
        assert_eq!(*rustls_slice_str_get(&rss, 2).data.offset(2), 'z' as c_char);
    }
}

/// A read-only view on a Rust slice of 16-bit integers in platform endianness.
///
/// This is used to pass data from crustls to callback functions provided
/// by the user of the API.
/// `len` indicates the number of bytes than can be safely read.
///
/// The memory exposed is available as specified by the function
/// using this in its signature. For instance, when this is a parameter to a
/// callback, the lifetime will usually be the duration of the callback.
/// Functions that receive one of these must not dereference the data pointer
/// beyond the allowed lifetime.
#[repr(C)]
pub struct rustls_slice_u16<'a> {
    pub data: *const u16,
    pub len: size_t,
    phantom: PhantomData<&'a [u16]>,
}

impl<'a> From<&'a [u16]> for rustls_slice_u16<'a> {
    fn from(s: &[u16]) -> Self {
        rustls_slice_u16 {
            data: s.as_ptr(),
            len: s.len(),
            phantom: PhantomData,
        }
    }
}

#[test]
fn test_rustls_slice_u16() {
    let u16s: Vec<u16> = vec![101, 314, 2718];
    let rsu: rustls_slice_u16 = (&*u16s).into();
    assert_eq!(rsu.len, 3);
    unsafe {
        assert_eq!(*rsu.data, 101);
        assert_eq!(*rsu.data.offset(1), 314);
        assert_eq!(*rsu.data.offset(2), 2718);
    }
}