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
//! Implement the infrastructure for custom streams.
//!
//! We actually get to do this on top of `Read` and `Seek` directly.
use crate::internal_prelude::*;
use std::borrow::Borrow;
use std::ffi::{c_void, CString};
use std::io::{Read, Seek};
use std::os::raw::{c_char, c_int, c_longlong, c_ulonglong};
use std::slice::from_raw_parts_mut;

/// A trait which custom streams must implement in order to support closing.
///
/// Rust's stdlib has no concept of closing in it, but simply dropping values
/// leads to panics.  This trait is therefore required to implement closing.
pub trait CloseStream {
    fn close(&mut self) -> std::result::Result<(), Box<dyn std::fmt::Display>>;
}

/// Marker trait for types which implement non-seekable streams.
///
/// A blanket impl is provided for anything implementing the supertraits.
pub trait Stream: Read + CloseStream + Send + 'static {}

impl<T: Read + CloseStream + Send + 'static> Stream for T {}

/// A [Stream], but one which also implements [Seek].
///
/// blanket impls are provided for anything implementing [Stream] and [Seek]
pub trait SeekableStream: Stream + Seek {}
impl<T: Stream + Seek> SeekableStream for T {}

pub(crate) struct CustomStreamData<T> {
    pub(crate) err_msg: CString,
    pub(crate) stream: T,
}

impl<T> CustomStreamData<T> {
    fn conv_err(&mut self, data: &dyn std::fmt::Display) -> *const c_char {
        let str = format!("{}", data);
        let cstr = CString::new(str).expect("Display impls must produce valid C strings");
        self.err_msg = cstr;
        self.err_msg.as_ptr()
    }
}

pub(crate) extern "C" fn stream_read_cb<T: Read>(
    read: *mut c_ulonglong,
    requested: c_ulonglong,
    destination: *mut c_char,
    userdata: *mut c_void,
    err_msg: *mut *const c_char,
) -> c_int {
    let data = unsafe { &mut *(userdata as *mut CustomStreamData<T>) };

    let dest = unsafe { from_raw_parts_mut(destination as *mut u8, requested as usize) };
    match data.stream.read(dest) {
        Ok(d) => {
            unsafe { *read = d as c_ulonglong };
            0
        }
        Err(e) => {
            unsafe { *err_msg = data.conv_err(&e) };
            1
        }
    }
}

pub(crate) extern "C" fn stream_seek_cb<T: Seek>(
    pos: c_ulonglong,
    userdata: *mut c_void,
    err_msg: *mut *const c_char,
) -> c_int {
    let data = unsafe { &mut *(userdata as *mut CustomStreamData<T>) };

    match data.stream.seek(std::io::SeekFrom::Start(pos as u64)) {
        Ok(_) => 0,
        Err(e) => {
            unsafe { *err_msg = data.conv_err(&e) };
            1
        }
    }
}

extern "C" fn close_cb<T: CloseStream>(
    userdata: *mut c_void,
    err_msg: *mut *const c_char,
) -> c_int {
    let data = unsafe { &mut *(userdata as *mut CustomStreamData<T>) };

    match data.stream.close() {
        Ok(_) => 0,
        Err(e) => {
            unsafe { *err_msg = data.conv_err(&e) };
            1
        }
    }
}

extern "C" fn destroy_cb<T>(userdata: *mut c_void) {
    // Build a box and immediately drop it.
    unsafe { Box::from_raw(userdata as *mut CustomStreamData<T>) };
}

/// Used as part of [StreamHandle] consumption.
fn drop_cb<T>(ptr: *mut c_void) {
    unsafe {
        Box::<T>::from_raw(ptr as *mut T);
    }
}

fn fillout_read<T: Stream>(dest: &mut syz_CustomStreamDef) {
    dest.read_cb = Some(stream_read_cb::<T>);
    dest.close_cb = Some(close_cb::<T>);
    dest.destroy_cb = Some(destroy_cb::<T>);
    dest.length = -1;
}

fn fillout_seekable<T: SeekableStream>(
    dest: &mut syz_CustomStreamDef,
    val: &mut T,
) -> std::io::Result<()> {
    dest.seek_cb = Some(stream_seek_cb::<T>);

    val.seek(std::io::SeekFrom::End(0))?;
    dest.length = val.stream_position()? as c_longlong;
    val.seek(std::io::SeekFrom::Start(0))?;
    Ok(())
}

fn fillout_userdata<T>(dest: &mut syz_CustomStreamDef, val: T) {
    dest.userdata = Box::into_raw(Box::new(CustomStreamData {
        stream: val,
        err_msg: Default::default(),
    })) as *mut c_void;
}

/// A definition for a custom stream.  This can come from a variety of places
/// and is consumed by e.g. [StreamingGenerator::from_stream_handle], or
/// returned as a result of the callback passed to [register_stream_protocol].
pub struct CustomStreamDef {
    def: syz_CustomStreamDef,
    /// Has this handle been used yet? If not, the drop impl needs to do cleanup
    /// so that the user's failure to consume the value with [CustomStreamDef]
    /// does not leak their value.
    used: bool,
}

impl CustomStreamDef {
    /// Convert a [Read] to a stream.
    pub fn from_reader<T: Stream>(value: T) -> CustomStreamDef {
        let mut ret = CustomStreamDef {
            def: Default::default(),
            used: false,
        };

        fillout_read::<T>(&mut ret.def);
        fillout_userdata(&mut ret.def, value);
        ret
    }

    /// Build a stream from something seekable.
    pub fn from_seekable<T: SeekableStream>(mut value: T) -> std::io::Result<CustomStreamDef> {
        let mut ret = CustomStreamDef {
            def: Default::default(),
            used: false,
        };
        fillout_read::<T>(&mut ret.def);
        fillout_seekable(&mut ret.def, &mut value)?;
        fillout_userdata(&mut ret.def, value);
        Ok(ret)
    }
}

impl Drop for CustomStreamDef {
    fn drop(&mut self) {
        let mut err_msg: *const c_char = std::ptr::null();
        if !self.used {
            unsafe {
                if let Some(cb) = self.def.close_cb {
                    cb(self.def.userdata, &mut err_msg as *mut *const c_char);
                }
                if let Some(cb) = self.def.destroy_cb {
                    cb(self.def.userdata);
                }
            }
        }
    }
}

/// A `StreamHandle` binds Synthizer custom streams, as well as other kinds of
/// streaming functionality.
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct StreamHandle {
    handle: syz_Handle,
    // If set, this stream will move the given value into Synthizer userdata for freeing later.
    needs_drop: Option<(std::ptr::NonNull<c_void>, fn(*mut c_void))>,
}

impl StreamHandle {
    pub fn from_stream_def(mut def: CustomStreamDef) -> Result<StreamHandle> {
        let mut h = Default::default();
        check_error(unsafe {
            syz_createStreamHandleFromCustomStream(
                &mut h as *mut syz_Handle,
                &mut def.def as *mut syz_CustomStreamDef,
                std::ptr::null_mut(),
                None,
            )
        })?;
        def.used = true;

        Ok(StreamHandle {
            handle: h,
            needs_drop: None,
        })
    }

    /// Create a stream handle which is backed by memory.
    pub fn from_vec(data: Vec<u8>) -> Result<StreamHandle> {
        if data.is_empty() {
            return Err(Error::rust_error("Cannot create streams from empty vecs"));
        };
        let mut h = Default::default();
        check_error(unsafe {
            let ptr = &data[0] as *const u8 as *const i8;
            syz_createStreamHandleFromMemory(
                &mut h as *mut syz_Handle,
                data.len() as u64,
                ptr,
                std::ptr::null_mut(),
                None,
            )
        })?;

        Ok(StreamHandle {
            handle: h,
            needs_drop: Some((
                unsafe {
                    std::ptr::NonNull::new_unchecked(Box::into_raw(Box::new(data)) as *mut c_void)
                },
                drop_cb::<Vec<u8>>,
            )),
        })
    }

    pub fn from_stream_params(protocol: &str, path: &str, param: usize) -> Result<StreamHandle> {
        // The below transmute uses the fact that `usize` is the size of a
        // pointer on all common platforms.
        let mut h = Default::default();
        let protocol_c = std::ffi::CString::new(protocol)
            .map_err(|_| Error::rust_error("Unable to convert protocol to a C string"))?;
        let path_c = std::ffi::CString::new(path)
            .map_err(|_| Error::rust_error("Unable to convert path to a C string"))?;
        let protocol_ptr = protocol_c.as_ptr();
        let path_ptr = path_c.as_ptr();
        check_error(unsafe {
            syz_createStreamHandleFromStreamParams(
                &mut h as *mut syz_Handle,
                protocol_ptr as *const c_char,
                path_ptr as *const c_char,
                std::mem::transmute(param),
                std::ptr::null_mut(),
                None,
            )
        })?;
        Ok(StreamHandle {
            handle: h,
            needs_drop: None,
        })
    }

    pub(crate) fn get_handle(&self) -> syz_Handle {
        self.handle
    }

    fn get_userdata(mut self) -> UserdataBox {
        // Be sure to take here so that Drop doesn't try to double free.
        let ret = if let Some((ud, free_cb)) = self.needs_drop.take() {
            UserdataBox::from_streaming_userdata(ud, free_cb)
        } else {
            UserdataBox::new()
        };
        ret
    }

    /// Wrap getting userdata and also make sure to free the handle once the
    /// closure ends, regardless of if it succeeded.
    // The closure gets the stream handle, as well as the userdata pointer and
    // free callback.
    pub(crate) fn with_userdata<T>(
        mut self,
        mut closure: impl (FnMut(syz_Handle, *mut c_void, extern "C" fn(*mut c_void)) -> Result<T>),
    ) -> Result<T> {
        let sh = self.handle;
        // Take the handle.
        self.handle = 0;
        let ud = self.get_userdata();
        ud.consume(move |ud, cb| closure(sh, ud, cb))
    }
}

impl Drop for StreamHandle {
    fn drop(&mut self) {
        unsafe { syz_handleDecRef(self.handle) };
        if let Some((ud, cb)) = self.needs_drop {
            cb(ud.as_ptr());
        }
    }
}

static mut STREAM_ERR_CONSTANT: *const c_char = std::ptr::null();

extern "C" fn stream_open_callback<
    E,
    T: 'static + Send + Sync + Fn(&str, &str, usize) -> std::result::Result<CustomStreamDef, E>,
>(
    out: *mut syz_CustomStreamDef,
    protocol: *const c_char,
    path: *const c_char,
    param: *mut c_void,
    userdata: *mut c_void,
    err_msg: *mut *const c_char,
) -> c_int {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let cstr = std::ffi::CString::new("Unable to create stream").unwrap();
        unsafe { STREAM_ERR_CONSTANT = cstr.into_raw() };
    });

    let protocol = unsafe { std::ffi::CStr::from_ptr(protocol) };
    let path = unsafe { std::ffi::CStr::from_ptr(path) };
    let protocol = protocol.to_string_lossy();
    let path = path.to_string_lossy();
    let param: usize = unsafe { std::mem::transmute(param) };

    let cb: Box<T> = unsafe { Box::from_raw(userdata as *mut T) };
    let res = cb(protocol.borrow(), path.borrow(), param);
    // Be sure not to drop the callback.
    Box::into_raw(cb);

    match res {
        Ok(mut s) => {
            unsafe { *out = s.def };
            s.used = true;
            0
        }
        Err(_) => {
            unsafe { *err_msg = STREAM_ERR_CONSTANT };
            1
        }
    }
}

/// register a custom protocol.
///
/// The callback here must return a [CustomStreamDef] which represents the
/// custom stream.  Synthizer is also not safely reentrant, and the callback
/// must not call back into Synthizer.
pub fn register_stream_protocol<
    E,
    T: 'static + Send + Sync + Fn(&str, &str, usize) -> std::result::Result<CustomStreamDef, E>,
>(
    protocol: &str,
    callback: T,
) -> Result<()> {
    let protocol_c = std::ffi::CString::new(protocol)
        .map_err(|_| Error::rust_error("Unable to convert protocol to a C string"))?;
    let leaked = Box::into_raw(Box::new(callback));
    let res = check_error(unsafe {
        syz_registerStreamProtocol(
            protocol_c.as_ptr(),
            Some(stream_open_callback::<E, T>),
            leaked as *mut c_void,
        )
    });
    match res {
        Ok(_) => Ok(()),
        Err(e) => {
            unsafe { Box::from_raw(leaked) };
            Err(e)
        }
    }
}