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
use crate::rc::{Array, CoreArrayProvider, Guard, CoreArrayProviderInner, Ref, RefCountable};
use crate::settings::Settings;
use crate::string::{BnStrCompatible, BnString};
use binaryninjacore_sys::*;
use std::collections::HashMap;
use std::ffi::{c_void, CStr};
use std::os::raw::c_char;
use std::ptr::null_mut;
use std::slice;

pub struct DownloadProvider {
    handle: *mut BNDownloadProvider,
}

impl DownloadProvider {
    pub fn get<S: BnStrCompatible>(name: S) -> Option<DownloadProvider> {
        let result = unsafe {
            BNGetDownloadProviderByName(
                name.into_bytes_with_nul().as_ref().as_ptr() as *const c_char
            )
        };
        if result.is_null() {
            return None;
        }
        Some(DownloadProvider { handle: result })
    }

    pub fn list() -> Result<Array<DownloadProvider>, ()> {
        let mut count = 0;
        let list: *mut *mut BNDownloadProvider = unsafe { BNGetDownloadProviderList(&mut count) };

        if list.is_null() {
            return Err(());
        }

        Ok(unsafe { Array::new(list, count, ()) })
    }

    /// TODO : We may want to `impl Default`....excessive error checking might be preventing us from doing so
    pub fn try_default() -> Result<DownloadProvider, ()> {
        let s = Settings::new("");
        let dp_name = s.get_string("network.downloadProviderName", None, None);
        Self::get(dp_name).ok_or(())
    }

    pub(crate) fn from_raw(handle: *mut BNDownloadProvider) -> DownloadProvider {
        Self { handle }
    }

    pub fn create_instance(&self) -> Result<Ref<DownloadInstance>, ()> {
        let result: *mut BNDownloadInstance =
            unsafe { BNCreateDownloadProviderInstance(self.handle) };
        if result.is_null() {
            return Err(());
        }

        Ok(unsafe { DownloadInstance::ref_from_raw(result) })
    }
}

impl CoreArrayProvider for DownloadProvider {
    type Raw = *mut BNDownloadProvider;
    type Context = ();
    type Wrapped<'a> = Guard<'a, DownloadProvider>;
}

unsafe impl CoreArrayProviderInner for DownloadProvider {
    unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) {
        BNFreeDownloadProviderList(raw);
    }
    unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
        Guard::new(DownloadProvider::from_raw(*raw), &())
    }
}

pub struct DownloadInstanceOutputCallbacks {
    pub write: Option<Box<dyn FnMut(&[u8]) -> usize>>,
    pub progress: Option<Box<dyn FnMut(u64, u64) -> bool>>,
}

pub struct DownloadInstanceInputOutputCallbacks {
    pub read: Option<Box<dyn FnMut(&mut [u8]) -> Option<isize>>>,
    pub write: Option<Box<dyn FnMut(&[u8]) -> usize>>,
    pub progress: Option<Box<dyn FnMut(u64, u64) -> bool>>,
}

pub struct DownloadResponse {
    pub status_code: u16,
    pub headers: HashMap<String, String>,
}

pub struct DownloadInstance {
    handle: *mut BNDownloadInstance,
}

impl DownloadInstance {
    pub(crate) unsafe fn from_raw(handle: *mut BNDownloadInstance) -> Self {
        debug_assert!(!handle.is_null());

        Self { handle }
    }

    pub(crate) unsafe fn ref_from_raw(handle: *mut BNDownloadInstance) -> Ref<Self> {
        Ref::new(Self::from_raw(handle))
    }

    fn get_error(&self) -> BnString {
        let err: *mut c_char = unsafe { BNGetErrorForDownloadInstance(self.handle) };
        unsafe { BnString::from_raw(err) }
    }

    unsafe extern "C" fn o_write_callback(data: *mut u8, len: u64, ctxt: *mut c_void) -> u64 {
        let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks;
        if let Some(func) = &mut (*callbacks).write {
            let slice = slice::from_raw_parts(data, len as usize);
            let result = (func)(slice);
            result as u64
        } else {
            0u64
        }
    }

    unsafe extern "C" fn o_progress_callback(ctxt: *mut c_void, progress: u64, total: u64) -> bool {
        let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks;
        if let Some(func) = &mut (*callbacks).progress {
            (func)(progress, total)
        } else {
            true
        }
    }

    pub fn perform_request<S: BnStrCompatible>(
        &mut self,
        url: S,
        callbacks: DownloadInstanceOutputCallbacks,
    ) -> Result<(), BnString> {
        let callbacks = Box::into_raw(Box::new(callbacks));
        let mut cbs = BNDownloadInstanceOutputCallbacks {
            writeCallback: Some(Self::o_write_callback),
            writeContext: callbacks as *mut c_void,
            progressCallback: Some(Self::o_progress_callback),
            progressContext: callbacks as *mut c_void,
        };

        let result = unsafe {
            BNPerformDownloadRequest(
                self.handle,
                url.into_bytes_with_nul().as_ref().as_ptr() as *const c_char,
                &mut cbs as *mut BNDownloadInstanceOutputCallbacks,
            )
        };

        // Drop it
        unsafe { drop(Box::from_raw(callbacks)) };
        if result < 0 {
            Err(self.get_error())
        } else {
            Ok(())
        }
    }

    unsafe extern "C" fn i_read_callback(data: *mut u8, len: u64, ctxt: *mut c_void) -> i64 {
        let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks;
        if let Some(func) = &mut (*callbacks).read {
            let slice = slice::from_raw_parts_mut(data, len as usize);
            let result = (func)(slice);
            if let Some(count) = result {
                count as i64
            } else {
                -1
            }
        } else {
            0
        }
    }

    unsafe extern "C" fn i_write_callback(data: *mut u8, len: u64, ctxt: *mut c_void) -> u64 {
        let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks;
        if let Some(func) = &mut (*callbacks).write {
            let slice = slice::from_raw_parts(data, len as usize);
            let result = (func)(slice);
            result as u64
        } else {
            0
        }
    }

    unsafe extern "C" fn i_progress_callback(ctxt: *mut c_void, progress: u64, total: u64) -> bool {
        let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks;
        if let Some(func) = &mut (*callbacks).progress {
            (func)(progress, total)
        } else {
            true
        }
    }

    pub fn perform_custom_request<
        M: BnStrCompatible,
        U: BnStrCompatible,
        HK: BnStrCompatible,
        HV: BnStrCompatible,
        I: IntoIterator<Item = (HK, HV)>,
    >(
        &mut self,
        method: M,
        url: U,
        headers: I,
        callbacks: DownloadInstanceInputOutputCallbacks,
    ) -> Result<DownloadResponse, BnString> {
        let mut header_keys = vec![];
        let mut header_values = vec![];
        for (key, value) in headers {
            header_keys.push(key.into_bytes_with_nul());
            header_values.push(value.into_bytes_with_nul());
        }

        let mut header_key_ptrs = vec![];
        let mut header_value_ptrs = vec![];

        for (key, value) in header_keys.iter().zip(header_values.iter()) {
            header_key_ptrs.push(key.as_ref().as_ptr() as *const c_char);
            header_value_ptrs.push(value.as_ref().as_ptr() as *const c_char);
        }

        let callbacks = Box::into_raw(Box::new(callbacks));
        let mut cbs = BNDownloadInstanceInputOutputCallbacks {
            readCallback: Some(Self::i_read_callback),
            readContext: callbacks as *mut c_void,
            writeCallback: Some(Self::i_write_callback),
            writeContext: callbacks as *mut c_void,
            progressCallback: Some(Self::i_progress_callback),
            progressContext: callbacks as *mut c_void,
        };

        let mut response: *mut BNDownloadInstanceResponse = null_mut();

        let result = unsafe {
            BNPerformCustomRequest(
                self.handle,
                method.into_bytes_with_nul().as_ref().as_ptr() as *const c_char,
                url.into_bytes_with_nul().as_ref().as_ptr() as *const c_char,
                header_key_ptrs.len() as u64,
                header_key_ptrs.as_ptr(),
                header_value_ptrs.as_ptr(),
                &mut response as *mut *mut BNDownloadInstanceResponse,
                &mut cbs as *mut BNDownloadInstanceInputOutputCallbacks,
            )
        };

        if result < 0 {
            unsafe { BNFreeDownloadInstanceResponse(response) };
            return Err(self.get_error());
        }

        let mut response_headers = HashMap::new();
        unsafe {
            let response_header_keys: &[*mut c_char] =
                slice::from_raw_parts((*response).headerKeys, (*response).headerCount as usize);
            let response_header_values: &[*mut c_char] =
                slice::from_raw_parts((*response).headerValues, (*response).headerCount as usize);

            for (key, value) in response_header_keys
                .iter()
                .zip(response_header_values.iter())
            {
                response_headers.insert(
                    CStr::from_ptr(*key).to_str().unwrap().to_owned(),
                    CStr::from_ptr(*value).to_str().unwrap().to_owned(),
                );
            }
        }

        let r = DownloadResponse {
            status_code: unsafe { (*response).statusCode },
            headers: response_headers,
        };

        unsafe { BNFreeDownloadInstanceResponse(response) };

        Ok(r)
    }
}

impl ToOwned for DownloadInstance {
    type Owned = Ref<Self>;

    fn to_owned(&self) -> Self::Owned {
        unsafe { RefCountable::inc_ref(self) }
    }
}

unsafe impl RefCountable for DownloadInstance {
    unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
        Ref::new(Self {
            handle: BNNewDownloadInstanceReference(handle.handle),
        })
    }

    unsafe fn dec_ref(handle: &Self) {
        BNFreeDownloadInstance(handle.handle);
    }
}