rusty_libimobiledevice 0.1.3

An ergonomic library to communicate with iOS devices
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// jkcoxson

use std::{convert::TryFrom, ffi::CStr, os::raw::c_char};

use log::warn;

use crate::{
    bindings as unsafe_bindings, error::AfcError, idevice::Device,
    services::house_arrest::HouseArrest, services::lockdownd::LockdowndService,
};

/// Transfers files between host and the iDevice
pub struct AfcClient<'a> {
    pub(crate) pointer: unsafe_bindings::afc_client_t,
    phantom: std::marker::PhantomData<&'a Device>,
}

impl AfcClient<'_> {
    /// Creates a new afc service connection to the device
    /// The use of this function is unknown
    /// # Arguments
    /// * `device` - The device to create the service with
    /// # Returns
    /// The lockdownd service
    ///
    /// ***Verified:*** False
    pub fn new(device: &Device) -> Result<(Self, LockdowndService), String> {
        let mut pointer = unsafe { std::mem::zeroed() };
        let mut client_pointer = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_client_new(device.pointer, &mut pointer, &mut client_pointer)
        };
        if result != 0 {
            return Err(format!("afc_client_new failed: {}", result));
        }
        Ok((
            AfcClient {
                pointer: client_pointer,
                phantom: std::marker::PhantomData,
            },
            LockdowndService {
                pointer: &mut pointer,
                port: pointer.port as u32,
                phantom: std::marker::PhantomData,
            },
        ))
    }

    /// Starts an afc service connection to the device
    /// # Arguments
    /// * `device` - The device to create the service with
    /// * `service_name` - The name of the service to start
    /// # Returns
    /// An afc service connection
    ///
    /// ***Verified:*** False
    pub fn start_service(
        device: &Device,
        service_name: impl Into<String>,
    ) -> Result<Self, AfcError> {
        let service_name = service_name.into();
        let mut pointer = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_client_start_service(
                device.pointer,
                &mut pointer,
                service_name.as_ptr() as *const c_char,
            )
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(AfcClient {
            pointer,
            phantom: std::marker::PhantomData,
        })
    }

    /// Get information about the device
    /// # Arguments
    /// *none*
    /// # Returns
    /// A string containing the device information
    ///
    /// ***Verified:*** False
    pub fn get_device_info(&self) -> Result<String, AfcError> {
        let mut info = unsafe { std::mem::zeroed() };
        let mut info_ptr: *mut *mut c_char = &mut info;
        let result =
            unsafe { unsafe_bindings::afc_get_device_info(self.pointer, &mut info_ptr) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(unsafe { CStr::from_ptr(info) }
            .to_string_lossy()
            .into_owned())
    }

    /// Read a directory on the device
    /// # Arguments
    /// * `directory` - The directory to read
    /// # Returns
    /// A vector of strings containing the directory contents
    ///
    /// ***Verified:*** False
    pub fn read_directory(&self, directory: impl Into<String>) -> Result<Vec<String>, AfcError> {
        let directory = directory.into();
        if directory.is_empty() {
            warn!("Cannot use empty string as directory");
            return Err(AfcError::InvalidArg);
        }
        let directory_ptr: *const c_char = directory.as_ptr() as *const c_char;
        let mut list: *mut *mut libc::c_char = std::ptr::null_mut::<*mut libc::c_char>();

        let result =
            unsafe { unsafe_bindings::afc_read_directory(self.pointer, directory_ptr, &mut list) }
                .into();
        if result != AfcError::Success {
            return Err(result);
        }

        let mut list_vec: Vec<String> = Vec::new();
        let mut list_ptr: *mut *mut libc::c_char = list;
        while !list_ptr.is_null() {
            if unsafe { *list_ptr }.is_null() {
                break;
            }
            let list_str = unsafe { CStr::from_ptr(*list_ptr).to_string_lossy().into_owned() };
            list_vec.push(list_str);
            list_ptr = unsafe { list_ptr.offset(1) };
        }
        unsafe { unsafe_bindings::afc_dictionary_free(list) };
        Ok(list_vec)
    }

    /// Get information about a file on the device
    /// # Arguments
    /// * `path` - The path to the file
    /// # Returns
    /// A string containing the file information
    ///
    /// ***Verified:*** False
    pub fn get_file_info(&self, path: impl Into<String>) -> Result<String, AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;

        let mut info = Vec::new();
        let mut info_ptr: *mut *mut libc::c_char = &mut info.as_mut_ptr();

        let result =
            unsafe { unsafe_bindings::afc_get_file_info(self.pointer, path_ptr, &mut info_ptr) }
                .into();
        if result != AfcError::Success {
            return Err(result);
        }
        println!("got here 2: {:?}", info);
        println!("ptr: {:?}", info_ptr);

        todo!();
    }

    /// Open a file on the device and return a handle to it
    /// # Arguments
    /// * `path` - The path to the file
    /// * `mode` - The mode to open the file in
    /// # Returns
    /// The file handle
    ///
    /// ***Verified:*** False
    pub fn file_open(&self, path: impl Into<String>, mode: AfcFileMode) -> Result<u64, AfcError> {
        let file_name_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let mut handle = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_file_open(self.pointer, file_name_ptr, mode.into(), &mut handle)
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(handle)
    }

    /// Closes a file on the device
    /// # Arguments
    /// * `handle` - The handle to the file
    /// # Returns
    /// An error code
    ///
    /// ***Verified:*** False
    pub fn file_close(&self, handle: u64) -> Result<(), AfcError> {
        let result = unsafe { unsafe_bindings::afc_file_close(self.pointer, handle) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Locks a file on the device
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `lock_type` - The type of lock to lock the file with
    /// # Returns
    /// An error code
    ///
    /// ***Verified:*** False
    pub fn file_lock(&self, handle: u64, lock_type: AfcLockOp) -> Result<(), AfcError> {
        let result =
            unsafe { unsafe_bindings::afc_file_lock(self.pointer, handle, lock_type.into()) }
                .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Reads out a file from the device
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `length` - The length of the data to read
    /// # Returns
    /// A vector of bytes containing the data read
    ///
    /// ***Verified:*** False
    pub fn file_read(&self, handle: u64, length: u32) -> Result<Vec<i8>, AfcError> {
        let mut buffer = unsafe { std::mem::zeroed() };
        let mut bytes_written = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_file_read(
                self.pointer,
                handle,
                &mut buffer,
                length,
                &mut bytes_written,
            )
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }

        let vec = unsafe {
            Vec::from_raw_parts(
                buffer as *mut i8,
                bytes_written as usize,
                bytes_written as usize,
            )
        };

        Ok(vec)
    }

    /// Writes data to a file on the device
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `data` - The data to write
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn file_write(&self, handle: u64, data: impl Into<String>) -> Result<(), AfcError> {
        let data = data.into();
        let data_ptr: *const c_char = data.as_ptr() as *const c_char;
        let mut bytes_written = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_file_write(
                self.pointer,
                handle,
                data_ptr,
                data.len() as u32,
                &mut bytes_written,
            )
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Seeks for a file or something
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `offset` - Unknown
    /// * `whence` - Unknown
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn file_seek(&self, handle: u64, offset: i64, whence: u8) -> Result<(), AfcError> {
        let result =
            unsafe { unsafe_bindings::afc_file_seek(self.pointer, handle, offset, whence.into()) }
                .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Unknown usage
    /// # Arguments
    /// * `handle` - The handle to the file
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn file_tell(&self, handle: u64) -> Result<u64, AfcError> {
        let mut position = unsafe { std::mem::zeroed() };
        let result =
            unsafe { unsafe_bindings::afc_file_tell(self.pointer, handle, &mut position) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(position)
    }

    /// Truncates a file on the iOS device
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `length` - The length of which to truncate the file to
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn file_truncate(&self, handle: u64, length: u64) -> Result<(), AfcError> {
        let result =
            unsafe { unsafe_bindings::afc_file_truncate(self.pointer, handle, length) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Removes a path on the iOS device
    /// # Arguments
    /// * `path` - The path to the folder that's being removed
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn remove_path(&self, path: impl Into<String>) -> Result<(), AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let result = unsafe { unsafe_bindings::afc_remove_path(self.pointer, path_ptr) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Renames or moves a folder on the iOS device
    /// # Arguments
    /// * `old_path` - The path to the folder to rename
    /// * `new_path` - The destination path
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn rename_path(
        &self,
        old_path: impl Into<String>,
        new_path: impl Into<String>,
    ) -> Result<(), AfcError> {
        let old_path_ptr: *const c_char = old_path.into().as_ptr() as *const c_char;
        let new_path_ptr: *const c_char = new_path.into().as_ptr() as *const c_char;
        let result =
            unsafe { unsafe_bindings::afc_rename_path(self.pointer, old_path_ptr, new_path_ptr) }
                .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Creates a directory on the iOS device
    /// # Arguments
    /// * `path` - The path to create
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn make_directory(&self, path: impl Into<String>) -> Result<(), AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let result = unsafe { unsafe_bindings::afc_make_directory(self.pointer, path_ptr) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Usage unknown
    /// # Arguments
    /// * `handle` - The handle to the file
    /// * `length` - Unknown
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn truncate(&self, path: impl Into<String>, length: u64) -> Result<(), AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let result =
            unsafe { unsafe_bindings::afc_truncate(self.pointer, path_ptr, length) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Creates a symbolic link on the iOS device
    /// # Arguments
    /// * `target` - The path to the file/folder being linked
    /// * `link_type` - The type of link being created
    /// * `link_path` - The path to place the link
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn make_link(
        &self,
        target: impl Into<String>,
        link_type: LinkType,
        link_path: impl Into<String>,
    ) -> Result<(), AfcError> {
        let target_ptr: *const c_char = target.into().as_ptr() as *const c_char;
        let link_name_ptr: *const c_char = link_path.into().as_ptr() as *const c_char;
        let result = unsafe {
            unsafe_bindings::afc_make_link(
                self.pointer,
                link_type.into(),
                target_ptr,
                link_name_ptr,
            )
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Sets the time metadata of a file
    /// # Arguments
    /// * `path` - The path to the file
    /// * `mtime` - The unix epoch time in miliseconds
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn set_file_time(&self, path: impl Into<String>, mtime: u64) -> Result<(), AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let result =
            unsafe { unsafe_bindings::afc_set_file_time(self.pointer, path_ptr, mtime) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Removes a path and the files inside it
    /// # Arguments
    /// * `path` - The path to the folder being destroyed
    /// # Returns
    /// *none*
    ///
    /// ***Verified:*** False
    pub fn remove_path_and_contents(&self, path: impl Into<String>) -> Result<(), AfcError> {
        let path_ptr: *const c_char = path.into().as_ptr() as *const c_char;
        let result =
            unsafe { unsafe_bindings::afc_remove_path_and_contents(self.pointer, path_ptr) }.into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(())
    }

    /// Gets a specific value for a key on the device's connection
    /// # Arguments
    /// * `key` - The key of which to look up
    /// # Returns
    /// The info value of the lookup
    ///
    /// ***Verified:*** False
    pub fn get_device_info_key(&self, key: impl Into<String>) -> Result<String, AfcError> {
        let key_ptr: *const c_char = key.into().as_ptr() as *const c_char;
        let mut value_ptr = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_get_device_info_key(self.pointer, key_ptr, &mut value_ptr)
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(unsafe { CStr::from_ptr(value_ptr) }
            .to_string_lossy()
            .into_owned())
    }
}

impl TryFrom<HouseArrest<'_>> for AfcClient<'_> {
    type Error = AfcError;

    fn try_from(house_arrest: HouseArrest<'_>) -> Result<Self, Self::Error> {
        let mut to_fill = unsafe { std::mem::zeroed() };
        let result = unsafe {
            unsafe_bindings::afc_client_new_from_house_arrest_client(
                house_arrest.pointer,
                &mut to_fill,
            )
        }
        .into();
        if result != AfcError::Success {
            return Err(result);
        }
        Ok(Self {
            pointer: to_fill,
            phantom: std::marker::PhantomData,
        })
    }
}

pub enum AfcFileMode {
    ReadOnly,
    ReadWrite,
    WriteOnly,
    WriteRead,
    Append,
    ReadAppend,
}

impl From<i8> for AfcFileMode {
    fn from(mode: i8) -> Self {
        match mode {
            1 => AfcFileMode::ReadOnly,
            2 => AfcFileMode::ReadWrite,
            3 => AfcFileMode::WriteOnly,
            4 => AfcFileMode::WriteRead,
            5 => AfcFileMode::Append,
            6 => AfcFileMode::ReadAppend,
            _ => panic!("Invalid file mode"),
        }
    }
}

impl From<AfcFileMode> for u32 {
    fn from(mode: AfcFileMode) -> Self {
        match mode {
            AfcFileMode::ReadOnly => 1,
            AfcFileMode::ReadWrite => 2,
            AfcFileMode::WriteOnly => 3,
            AfcFileMode::WriteRead => 4,
            AfcFileMode::Append => 5,
            AfcFileMode::ReadAppend => 6,
        }
    }
}

pub enum AfcLockOp {
    Sh,
    Ex,
    Un,
}

impl From<AfcLockOp> for u32 {
    fn from(op: AfcLockOp) -> Self {
        match op {
            AfcLockOp::Sh => 5,
            AfcLockOp::Ex => 6,
            AfcLockOp::Un => 12,
        }
    }
}

pub enum LinkType {
    HardLink,
    SymbolicLink,
}

impl From<LinkType> for u32 {
    fn from(link_type: LinkType) -> Self {
        match link_type {
            LinkType::HardLink => 1,
            LinkType::SymbolicLink => 2,
        }
    }
}

impl Drop for AfcClient<'_> {
    fn drop(&mut self) {
        unsafe {
            unsafe_bindings::afc_client_free(self.pointer);
        }
    }
}