idevice 0.1.68

A Rust library to interact with services on 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
//! iOS Device OsTraceRelay Service Abstraction
//! Note that there are unknown fields that will hopefully be filled in the future.
//! Huge thanks to pymobiledevice3 for the struct implementation
//! https://github.com/doronz88/pymobiledevice3/blob/master/pymobiledevice3/services/os_trace.py

use chrono::{DateTime, NaiveDateTime};
use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt;

use crate::{Idevice, IdeviceError, IdeviceService, obf};

/// Client for interacting with the iOS device OsTraceRelay service
#[derive(Debug)]
pub struct OsTraceRelayClient {
    /// The underlying device connection with established OsTraceRelay service
    pub idevice: Idevice,
}

impl IdeviceService for OsTraceRelayClient {
    /// Returns the OsTraceRelay service name as registered with lockdownd
    fn service_name() -> std::borrow::Cow<'static, str> {
        obf!("com.apple.os_trace_relay")
    }

    async fn from_stream(idevice: Idevice) -> Result<Self, crate::IdeviceError> {
        Ok(Self { idevice })
    }
}

/// An initialized client for receiving logs
#[derive(Debug)]
pub struct OsTraceRelayReceiver {
    inner: OsTraceRelayClient,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OsTraceLog {
    pub pid: u32,
    pub timestamp: NaiveDateTime,
    pub level: LogLevel,
    pub image_name: String,
    pub filename: String,
    pub message: String,
    pub label: Option<SyslogLabel>,
    /// Unique process ID (the activity stream's `procid` field). Equals `pid` in
    /// practice on iOS.
    pub procid: u64,
    /// ID of the thread that emitted the entry (the stream's `thread` field).
    pub thread_id: u64,
    /// Load address offset of the log call site within the sender image. Pair
    /// with `image_uuid` to symbolicate.
    pub image_offset: u32,
    /// UUID of the sender image, i.e. the one named by `image_name`.
    pub image_uuid: uuid::Uuid,
    /// UUID of the process' main executable, i.e. the one named by `filename`.
    pub process_image_uuid: uuid::Uuid,
    /// Raw monotonic device timestamp in mach ticks.
    pub mach_timestamp: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyslogLabel {
    pub subsystem: String,
    pub category: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Copy)]
pub enum LogLevel {
    Notice = 0,
    Info = 1,
    Debug = 2,
    Error = 10,
    Fault = 11,
}

impl OsTraceRelayClient {
    /// Starts the stream of logs from the relay
    ///
    /// # Arguments
    /// * `pid` - An optional pid to stream logs from
    pub async fn start_trace(
        mut self,
        pid: Option<u32>,
    ) -> Result<OsTraceRelayReceiver, IdeviceError> {
        let pid = match pid {
            Some(p) => p as i64,
            None => -1,
        };
        let req = crate::plist!({
            "Request": "StartActivity",
            "Pid": pid,
            "MessageFilter": 65_535,
            "StreamFlags": 60
        });

        self.idevice.send_bplist(req).await?;

        // Read a single byte
        self.idevice.read_raw(1).await?;

        // Result
        let res = self.idevice.read_plist().await?;

        match res.get("Status").and_then(|x| x.as_string()) {
            Some(r) => {
                if r == "RequestSuccessful" {
                    Ok(OsTraceRelayReceiver { inner: self })
                } else {
                    Err(IdeviceError::UnexpectedResponse(
                        "Status was not RequestSuccessful in StartActivity response".into(),
                    ))
                }
            }
            None => Err(IdeviceError::UnexpectedResponse(
                "missing Status in StartActivity response".into(),
            )),
        }
    }

    /// Get the list of available PIDs
    pub async fn get_pid_list(&mut self) -> Result<Vec<u64>, IdeviceError> {
        let req = crate::plist!({
            "Request": "PidList"
        });

        self.idevice.send_bplist(req).await?;

        // Read a single byte
        self.idevice.read_raw(1).await?;

        // Result
        let res = self.idevice.read_plist().await?;

        // Device returns { "Payload": { "<pid>": { "ProcessName": "..." }, ... } }
        // where the PIDs are the string keys of the Payload dictionary.
        if let Some(payload) = res.get("Payload").and_then(|x| x.as_dictionary()) {
            payload
                .keys()
                .map(|k| {
                    k.parse::<u64>().map_err(|_| {
                        IdeviceError::UnexpectedResponse(format!(
                            "PidList Payload key is not a valid PID: {k}"
                        ))
                    })
                })
                .collect()
        } else {
            Err(IdeviceError::UnexpectedResponse(
                "missing Payload dictionary in PidList response".into(),
            ))
        }
    }

    /// Create a log archive and write it to the provided writer
    pub async fn create_archive<W: tokio::io::AsyncWrite + Unpin>(
        &mut self,
        out: &mut W,
        size_limit: Option<u64>,
        age_limit: Option<u64>,
        start_time: Option<u64>,
    ) -> Result<(), IdeviceError> {
        let req = crate::plist!({
            "Request": "CreateArchive",
            "SizeLimit":? size_limit,
            "AgeLimit":? age_limit,
            "StartTime":? start_time,
        });

        self.idevice.send_bplist(req).await?;

        // Read a single byte
        if self.idevice.read_raw(1).await?[0] != 1 {
            return Err(IdeviceError::UnexpectedResponse(
                "expected leading byte 0x01 in CreateArchive response".into(),
            ));
        }

        // Check status
        let res = self.idevice.read_plist().await?;
        match res.get("Status").and_then(|x| x.as_string()) {
            Some("RequestSuccessful") => {}
            _ => {
                return Err(IdeviceError::UnexpectedResponse(
                    "Status was not RequestSuccessful in CreateArchive response".into(),
                ));
            }
        }

        // Read archive data
        loop {
            match self.idevice.read_raw(1).await {
                Ok(data) if data[0] == 0x03 => {
                    let length_bytes = self.idevice.read_raw(4).await?;
                    let length = u32::from_le_bytes([
                        length_bytes[0],
                        length_bytes[1],
                        length_bytes[2],
                        length_bytes[3],
                    ]);
                    let data = self.idevice.read_raw(length as usize).await?;
                    out.write_all(&data).await?;
                }
                Err(IdeviceError::Socket(_)) => break,
                _ => {
                    return Err(IdeviceError::UnexpectedResponse(
                        "unexpected data format in archive stream".into(),
                    ));
                }
            }
        }

        Ok(())
    }
}

impl OsTraceRelayReceiver {
    /// Get the next log from the relay
    ///
    /// # Returns
    /// A string containing the log
    ///
    /// # Errors
    /// UnexpectedResponse if the service sends an EOF
    pub async fn next(&mut self) -> Result<OsTraceLog, IdeviceError> {
        // Read 0x02, at the beginning of each packet
        if self.inner.idevice.read_raw(1).await?[0] != 0x02 {
            return Err(IdeviceError::UnexpectedResponse(
                "expected leading byte 0x02 at start of log packet".into(),
            ));
        }

        // Read the len of the packet
        let pl = self.inner.idevice.read_raw(4).await?;
        let packet_length = u32::from_le_bytes([pl[0], pl[1], pl[2], pl[3]]);

        let packet = self.inner.idevice.read_raw(packet_length as usize).await?;
        if packet.len() < ENTRY_HEADER_LEN {
            return Err(IdeviceError::UnexpectedResponse(
                "log packet shorter than the fixed entry header".into(),
            ));
        }

        // 9 bytes of padding
        let packet = &packet[9..];

        // Parse PID (4 bytes)
        let pid = u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]);
        let packet = &packet[4..];

        // The next 42 bytes hold the procid, then the process' main executable
        // UUID at +8. The rest is unidentified.
        let procid = read_u64(packet, 0);
        let process_image_uuid = read_uuid(packet, 8);
        let packet = &packet[42..];

        // Parse timestamp (seconds + microseconds)
        let seconds = u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]);
        let packet = &packet[8..]; // skip 4 bytes padding after seconds
        let microseconds = u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]);
        let packet = &packet[4..];

        // Skip 1 byte padding
        let packet = &packet[1..];

        // Parse log level
        let log_level = packet[0];
        let log_level: LogLevel = log_level.try_into()?;
        let packet = &packet[1..];

        // The next 38 bytes hold the raw mach timestamp at +4, the emitting
        // thread's ID at +14, and the sender image's UUID at +22.
        let mach_timestamp = read_u64(packet, 4);
        let thread_id = read_u64(packet, 14);
        let image_uuid = read_uuid(packet, 22);
        let packet = &packet[38..];

        // Parse string sizes
        let image_name_size = u16::from_le_bytes([packet[0], packet[1]]) as usize;
        let packet = &packet[2..];
        let message_size = u16::from_le_bytes([packet[0], packet[1]]) as usize;
        let packet = &packet[2..];

        // Skip 2 bytes, then the sender image offset
        let packet = &packet[2..];
        let image_offset = u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]);
        let packet = &packet[4..];

        // Parse subsystem and category sizes
        let subsystem_size =
            u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]) as usize;
        let packet = &packet[4..];
        let category_size =
            u32::from_le_bytes([packet[0], packet[1], packet[2], packet[3]]) as usize;
        let packet = &packet[4..];

        // Skip 4 bytes
        let packet = &packet[4..];

        // Parse filename (null-terminated string)
        let filename_end =
            packet
                .iter()
                .position(|&b| b == 0)
                .ok_or(IdeviceError::UnexpectedResponse(
                    "filename not null-terminated in log packet".into(),
                ))?;
        let filename = String::from_utf8_lossy(&packet[..filename_end]).into_owned();
        let packet = &packet[filename_end + 1..];

        // Parse image name
        let image_name_bytes = &packet[..image_name_size];
        let image_name =
            String::from_utf8_lossy(&image_name_bytes[..image_name_bytes.len() - 1]).into_owned();
        let packet = &packet[image_name_size..];

        // Parse message
        let message_bytes = &packet[..message_size];
        let message =
            String::from_utf8_lossy(&message_bytes[..message_bytes.len() - 1]).into_owned();
        let packet = &packet[message_size..];

        // Parse label if subsystem and category exist
        let label = if subsystem_size > 0 && category_size > 0 && !packet.is_empty() {
            let subsystem_bytes = &packet[..subsystem_size];
            let subsystem =
                String::from_utf8_lossy(&subsystem_bytes[..subsystem_bytes.len() - 1]).into_owned();
            let packet = &packet[subsystem_size..];

            let category_bytes = &packet[..category_size];
            let category =
                String::from_utf8_lossy(&category_bytes[..category_bytes.len() - 1]).into_owned();

            Some(SyslogLabel {
                subsystem,
                category,
            })
        } else {
            None
        };

        let timestamp = match DateTime::from_timestamp(seconds as i64, microseconds) {
            Some(t) => t.naive_local(),
            None => {
                return Err(IdeviceError::UnexpectedResponse(
                    "invalid timestamp in log packet".into(),
                ));
            }
        };

        Ok(OsTraceLog {
            pid,
            timestamp,
            level: log_level,
            image_name,
            filename,
            message,
            label,
            procid,
            thread_id,
            image_offset,
            image_uuid,
            process_image_uuid,
            mach_timestamp,
        })
    }
}

impl TryFrom<u8> for LogLevel {
    type Error = IdeviceError;

    fn try_from(value: u8) -> Result<Self, IdeviceError> {
        Ok(match value {
            0 => Self::Notice,
            1 => Self::Info,
            2 => Self::Debug,
            0x10 => Self::Error,
            0x11 => Self::Fault,
            _ => {
                return Err(IdeviceError::UnexpectedResponse(
                    "unknown log level byte value".into(),
                ));
            }
        })
    }
}

#[cfg(feature = "rsd")]
impl crate::RsdService for OsTraceRelayClient {
    fn rsd_service_name() -> std::borrow::Cow<'static, str> {
        crate::obf!("com.apple.os_trace_relay.shim.remote")
    }
    async fn from_stream(stream: Box<dyn crate::ReadWrite>) -> Result<Self, crate::IdeviceError> {
        let mut idevice = crate::Idevice::new(stream, "");
        idevice.rsd_checkin().await?;
        Ok(Self { idevice })
    }
}

/// Size of the fixed header at the start of every binary syslog entry. Every
/// fixed-offset field below lives inside it.
const ENTRY_HEADER_LEN: usize = 129;

/// Reads a little-endian `u64` at `offset` within `buf`, which the caller has
/// already length-checked against [`ENTRY_HEADER_LEN`].
fn read_u64(buf: &[u8], offset: usize) -> u64 {
    let mut b = [0u8; 8];
    b.copy_from_slice(&buf[offset..offset + 8]);
    u64::from_le_bytes(b)
}

/// Reads a 16-byte UUID at `offset` within `buf`, which the caller has already
/// length-checked against [`ENTRY_HEADER_LEN`].
fn read_uuid(buf: &[u8], offset: usize) -> uuid::Uuid {
    let mut b = [0u8; 16];
    b.copy_from_slice(&buf[offset..offset + 16]);
    uuid::Uuid::from_bytes(b)
}