Feature/dvt_notifications (#31)

* "feat: Monitor memory and app notifications  "

* "[MOD] treat both as the negative and positive representation of the channel code in the response"

* "feat: dvt add the notifications to Monitor memory and app notifications"

* "[MOD]print the notifications in tools"

* PR cleanup

* Fix clippy warning

---------

Co-authored-by: Jackson Coxson <jkcoxson@gmail.com>
This commit is contained in:
ValorBao
2025-09-25 23:34:13 +08:00
committed by GitHub
parent d2b9b7acba
commit ec81169347
7 changed files with 275 additions and 3 deletions

View File

@@ -405,7 +405,9 @@ impl Message {
length: u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]), length: u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]),
identifier: u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]), identifier: u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]),
conversation_index: u32::from_le_bytes([buf[20], buf[21], buf[22], buf[23]]), conversation_index: u32::from_le_bytes([buf[20], buf[21], buf[22], buf[23]]),
channel: u32::from_le_bytes([buf[24], buf[25], buf[26], buf[27]]), //treat both as the negative and positive representation of the channel code in the response
// the same when performing fragmentation
channel: i32::abs(i32::from_le_bytes([buf[24], buf[25], buf[26], buf[27]])) as u32,
expects_reply: u32::from_le_bytes([buf[28], buf[29], buf[30], buf[31]]) == 1, expects_reply: u32::from_le_bytes([buf[28], buf[29], buf[30], buf[31]]) == 1,
}; };
if header.fragment_count > 1 && header.fragment_id == 0 { if header.fragment_count > 1 && header.fragment_id == 0 {

View File

@@ -7,6 +7,7 @@ use crate::{Idevice, IdeviceError, ReadWrite, RsdService, obf};
#[cfg(feature = "location_simulation")] #[cfg(feature = "location_simulation")]
pub mod location_simulation; pub mod location_simulation;
pub mod message; pub mod message;
pub mod notifications;
pub mod process_control; pub mod process_control;
pub mod remote_server; pub mod remote_server;
pub mod screenshot; pub mod screenshot;

View File

@@ -0,0 +1,163 @@
//! Notificaitons service client for iOS instruments protocol.
//!
//! Monitor memory and app notifications
use crate::{
IdeviceError, ReadWrite,
dvt::{
message::AuxValue,
remote_server::{Channel, RemoteServerClient},
},
obf,
};
use log::warn;
use plist::Value;
#[derive(Debug)]
pub struct NotificationInfo {
notification_type: String,
mach_absolute_time: i64,
exec_name: String,
app_name: String,
pid: u32,
state_description: String,
}
pub struct NotificationsClient<'a, R: ReadWrite> {
/// The underlying channel used for communication
pub channel: Channel<'a, R>,
}
impl<'a, R: ReadWrite> NotificationsClient<'a, R> {
/// Opens a new channel on the remote server client for app notifications
///
/// # Arguments
/// * `client` - The remote server client to connect with
///
/// # Returns
/// The client on success, IdeviceError on failure
pub async fn new(client: &'a mut RemoteServerClient<R>) -> Result<Self, IdeviceError> {
let channel = client
.make_channel(obf!(
"com.apple.instruments.server.services.mobilenotifications"
))
.await?; // Drop `&mut client` before continuing
Ok(Self { channel })
}
/// set the applicaitons and memory notifications enabled
pub async fn start_notifications(&mut self) -> Result<(), IdeviceError> {
let application_method = Value::String("setApplicationStateNotificationsEnabled:".into());
self.channel
.call_method(
Some(application_method),
Some(vec![AuxValue::archived_value(true)]),
false,
)
.await?;
let memory_method = Value::String("setMemoryNotificationsEnabled:".into());
self.channel
.call_method(
Some(memory_method),
Some(vec![AuxValue::archived_value(true)]),
false,
)
.await?;
Ok(())
}
/// Reads the next notification from the service
pub async fn get_notification(&mut self) -> Result<NotificationInfo, IdeviceError> {
let message = self.channel.read_message().await?;
let mut notification = NotificationInfo {
notification_type: "".to_string(),
mach_absolute_time: 0,
exec_name: String::new(),
app_name: String::new(),
pid: 0,
state_description: String::new(),
};
if let Some(aux) = message.aux {
for v in aux.values {
match v {
AuxValue::Array(a) => match ns_keyed_archive::decode::from_bytes(&a) {
Ok(archive) => {
if let Some(dict) = archive.into_dictionary() {
for (key, value) in dict.into_iter() {
match key.as_str() {
"mach_absolute_time" => {
if let Value::Integer(time) = value {
notification.mach_absolute_time =
time.as_signed().unwrap_or(0);
}
}
"execName" => {
if let Value::String(name) = value {
notification.exec_name = name;
}
}
"appName" => {
if let Value::String(name) = value {
notification.app_name = name;
}
}
"pid" => {
if let Value::Integer(pid) = value {
notification.pid =
pid.as_unsigned().unwrap_or(0) as u32;
}
}
"state_description" => {
if let Value::String(desc) = value {
notification.state_description = desc;
}
}
_ => {
warn!("Unknown notificaton key: {} = {:?}", key, value);
}
}
}
}
}
Err(e) => {
warn!("Failed to decode archive: {:?}", e);
}
},
_ => {
warn!("Non-array aux value: {:?}", v);
}
}
}
}
if let Some(Value::String(data)) = message.data {
notification.notification_type = data;
Ok(notification)
} else {
Err(IdeviceError::UnexpectedResponse)
}
}
/// set the applicaitons and memory notifications disable
pub async fn stop_notifications(&mut self) -> Result<(), IdeviceError> {
let application_method = Value::String("setApplicationStateNotificationsEnabled:".into());
self.channel
.call_method(
Some(application_method),
Some(vec![AuxValue::archived_value(false)]),
false,
)
.await?;
let memory_method = Value::String("setMemoryNotificationsEnabled:".into());
self.channel
.call_method(
Some(memory_method),
Some(vec![AuxValue::archived_value(false)]),
false,
)
.await?;
Ok(())
}
}

View File

@@ -201,6 +201,7 @@ impl<R: ReadWrite> RemoteServerClient<R> {
let message = Message::new(mheader, pheader, aux, data); let message = Message::new(mheader, pheader, aux, data);
debug!("Sending message: {message:#?}"); debug!("Sending message: {message:#?}");
self.idevice.write_all(&message.serialize()).await?; self.idevice.write_all(&message.serialize()).await?;
self.idevice.flush().await?; self.idevice.flush().await?;

View File

@@ -125,6 +125,7 @@ path = "src/pcapd.rs"
name = "preboard" name = "preboard"
path = "src/preboard.rs" path = "src/preboard.rs"
[[bin]] [[bin]]
name = "screenshot" name = "screenshot"
path = "src/screenshot.rs" path = "src/screenshot.rs"
@@ -133,6 +134,10 @@ path = "src/screenshot.rs"
name = "activation" name = "activation"
path = "src/activation.rs" path = "src/activation.rs"
[[bin]]
name = "notifications"
path = "src/notifications.rs"
[dependencies] [dependencies]
idevice = { path = "../idevice", features = ["full"], default-features = false } idevice = { path = "../idevice", features = ["full"], default-features = false }
tokio = { version = "1.43", features = ["full"] } tokio = { version = "1.43", features = ["full"] }

View File

@@ -2,8 +2,7 @@
use clap::{Arg, Command}; use clap::{Arg, Command};
use idevice::{ use idevice::{
IdeviceService, amfi::AmfiClient, lockdown::LockdownClient, IdeviceService, lockdown::LockdownClient, mobileactivationd::MobileActivationdClient,
mobileactivationd::MobileActivationdClient,
}; };
mod common; mod common;

101
tools/src/notifications.rs Normal file
View File

@@ -0,0 +1,101 @@
// Monitor memory and app notifications
use clap::{Arg, Command};
use idevice::{IdeviceService, RsdService, core_device_proxy::CoreDeviceProxy, rsd::RsdHandshake};
mod common;
#[tokio::main]
async fn main() {
env_logger::init();
let matches = Command::new("notifications")
.about("start notifications")
.arg(
Arg::new("host")
.long("host")
.value_name("HOST")
.help("IP address of the device"),
)
.arg(
Arg::new("pairing_file")
.long("pairing-file")
.value_name("PATH")
.help("Path to the pairing file"),
)
.arg(
Arg::new("udid")
.value_name("UDID")
.help("UDID of the device (overrides host/pairing file)")
.index(1),
)
.arg(
Arg::new("about")
.long("about")
.help("Show about information")
.action(clap::ArgAction::SetTrue),
)
.get_matches();
if matches.get_flag("about") {
print!("notifications - start notifications to ios device");
println!("Copyright (c) 2025 Jackson Coxson");
return;
}
let udid = matches.get_one::<String>("udid");
let host = matches.get_one::<String>("host");
let pairing_file = matches.get_one::<String>("pairing_file");
let provider =
match common::get_provider(udid, host, pairing_file, "notifications-jkcoxson").await {
Ok(p) => p,
Err(e) => {
eprintln!("{e}");
return;
}
};
let proxy = CoreDeviceProxy::connect(&*provider)
.await
.expect("no core proxy");
let rsd_port = proxy.handshake.server_rsd_port;
let adapter = proxy.create_software_tunnel().expect("no software tunnel");
let mut adapter = adapter.to_async_handle();
let stream = adapter.connect(rsd_port).await.expect("no RSD connect");
// Make the connection to RemoteXPC
let mut handshake = RsdHandshake::new(stream).await.unwrap();
let mut ts_client =
idevice::dvt::remote_server::RemoteServerClient::connect_rsd(&mut adapter, &mut handshake)
.await
.expect("Failed to connect");
ts_client.read_message(0).await.expect("no read??");
let mut notification_client =
idevice::dvt::notifications::NotificationsClient::new(&mut ts_client)
.await
.expect("Unable to get channel for notifications");
notification_client
.start_notifications()
.await
.expect("Failed to start notifications");
// Handle Ctrl+C gracefully
loop {
tokio::select! {
_ = tokio::signal::ctrl_c() => {
println!("\nShutdown signal received, exiting.");
break;
}
// Branch 2: Wait for the next batch of notifications.
result = notification_client.get_notification() => {
if let Err(e) = result {
eprintln!("Failed to get notifications: {}", e);
} else {
println!("Received notifications: {:#?}", result.unwrap());
}
}
}
}
}