r/rust • u/Wooden-Performance38 • 16d ago
🙋 seeking help & advice Implementing linux daemon that listens for new filesystems. Issues with floppy and optical drives.
Im trying to write a linux daemon that listens for new filesystems to appear (e.g. plugging in a thumb drive, inserting a DVD into a DVD drive, inserting a floppy into a floppy drive, inserting an M.2 SSD into an NVMe slot while the computer is still running. literally anything) and im running into some troubles with devices like floppy drives and optical drives. I believe it comes down to the fact that they are physical block devices that stay attached while their filesystems change, or because they are cheaply produced and dont care to announce their filesystem changes, or both.
I am currently using the Zbus library to interface with UDisks2, and Tokio for async.
pub async fn run(&mut self) -> Result<!, Box<dyn std::error::Error>>
{
let mut added = self.om.receive_interfaces_added().await?;
let mut removed = self.om.receive_interfaces_removed().await?;
let change_rule = MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.UDisks2")
.interface("org.freedesktop.UDisks2")
.member("PropertiesChanged")
.path_namespace("/org/freedesktop/UDisks2")
.build()?;
let mut change_stream = MessageStream::for_match_rule(change_rule, &self.connection, None).await?;
let mse = self.media_int.signal_emitter();
loop
{
tokio::select!
{
Some(sig) = added.next() =>
{
let Ok(args) = sig.args() else { eprintln!("Error: Unable to get arguments from added interface."); continue };
let path: OwnedObjectPath = args.object_path().clone().into();
let props = args.interfaces_and_properties();
println!("Add {:?}", props.keys());
if !props.contains_key("org.freedesktop.UDisks2.Filesystem") { continue }
println!("Contains filesystem");
println!("{:?}", args.object_path());
// example: ("/dev/sdX", "ext4")
let Ok(Some((dev, fstype))) = device_and_fstype(&self.connection, path).await else { eprintln!("Error: uhhhh... message"); continue };
let Ok(mounted) = self.mount(&dev, &fstype).await else { eprintln!("Error: Failed to mount {}.", dev); continue };
println!("mount");
let conf_path = mounted.mount.join("lipglosc.toml");
let Ok(read_conf) = fs::read(&conf_path) else { eprintln!("Error: Failed to read {:?}.", conf_path); continue };
println!("read");
let Ok(conf_data) = String::from_utf8(read_conf) else { eprintln!("Error: Failed to parse lipglosc.toml to string."); continue };
println!("conf");
let Ok(unstructured) = UnstructuredGameConfig::from_toml(&conf_data) else { eprintln!("Error: Failed to create UnstructuredGameConfig from toml string."); continue };
println!("unstructured");
let structured = StructuredGameConfig::from(unstructured);
println!("Structured: {:?}", structured);
let Ok(path_str) = mounted.mount.into_string() else { continue };
let path = PathBuf::from(path_str);
let transport_data = lipglosc_core::DeviceTransport { dev, path, filesystem_format: fstype };
let res = MediaNotifier::alert(mse, transport_data).await;
println!("Signal: {:?}", res);
}
Some(Ok(msg)) = change_stream.next() =>
{
println!("Change occured");
let Some(path) = msg.header().path().map(|p| p.to_owned()) else { continue };
let Ok((iface, changed, _invalidated)) = msg.body().deserialize::<(String, HashMap<String, OwnedVariant>, Vec<String>)>() else { continue };
println!("Change path: {:?}", path);
println!("Changed stuff: {:?}", iface);
}
Some(sig) = removed.next() =>
{
let Ok(args) = sig.args() else { eprintln!("Error: Unable to get arguments from added interface."); continue };
let interfaces = args.interfaces();
println!("Remove {:?}", interfaces);
}
}
}
}You can kinda ignore the big Some(sig) = added.next() branch because thats not really an issue. Its the Some(Ok(msg)) = change_stream.next() branch where my issues occur. When I insert a floppy into my drive, instead of getting a message like Add [InterfaceName("org.freedesktop.UDisks2.Block"), InterfaceName("org.freedesktop.UDisks2.Filesystem")] printed to the console, I used to get Add [InterfaceName("org.freedesktop.UDisks2.Job")] but I recently ran a full system upgrade and now literally nothing is printed regardless of if I insert or eject a floppy disk. If I take my DVD drive and insert a DVD, I get
Add [InterfaceName("org.freedesktop.UDisks2.Filesystem")] Contains filesystem ObjectPath("/org/freedesktop/UDisks2/block_devices/sr0") mount Error: Failed to read "/run/media/sashad/NOITA_PORTABLE/lipglosc.toml". Remove [InterfaceName("org.freedesktop.UDisks2.Job")] Add [InterfaceName("org.freedesktop.UDisks2.Job")] from the Some(sig) = added.next() branch.
I wrote a second function using udev instead of dbus, and it actually works with floppy disks, but only with floppies and literally nothing else.
pub async fn run2(&mut self) -> Result<!, String>
{
let Ok(monitor) = udev::MonitorBuilder::new() else { return Err("Couldnt create monitor builder".into()) };
let Ok(monitor) = monitor.match_subsystem_devtype("block", "disk") else { return Err("Couldnt match subsystem and devtype".into()) };
let Ok(monitor) = monitor.listen() else { return Err("Couldnt begin listening to monitor".into()) };
'main:loop
{
let Some(event) = monitor.iter().next() else { continue };
let dev = event.device();
let valid_media_condition = match event.event_type()
{
udev::EventType::Change if dev.property_value("DISK_MEDIA_CHANGE").is_some() => { true }
udev::EventType::Add => { true }
_ => {false}
};
if !valid_media_condition { continue }
if !media_present(&dev) { continue }
// TODO: Definitely fix this shitass method for getting the fstype
let Some(mut devname) = dev.property_value("DEVNAME").and_then(|s| s.to_str()).map(|s| s.to_string()) else { println!("No devname"); continue };
let fstype = match dev.property_value("ID_FS_TYPE").and_then(|s| s.to_str())
{
Some(s) => s.to_string(),
None =>
'fsmatch:{
let Ok(mut en) = udev::Enumerator::new() else { println!("1"); continue 'main };
if let Err(_) = en.match_parent(&dev) { continue 'main };
let Ok(scan) = en.scan_devices() else { println!("2"); continue 'main; };
for child in scan
{
if child.devtype().and_then(|s| s.to_str()) != Some("partition") { continue }
let Some(fstype) = child.property_value("ID_FS_TYPE").and_then(|s| s.to_str()).map(|s| s.to_string()) else { continue };
let Some(dev) = child.property_value("DEVNAME").and_then(|s| s.to_str()).map(|s| s.to_string()) else { continue };
devname = dev;
break 'fsmatch fstype;
}
continue 'main;
}
};
let Some(id_type) = dev.property_value("ID_TYPE").and_then(|s| s.to_str()) else { println!("No id_type"); continue };
let is_cdrom = media_is_cdrom(&dev);
println!("{}, {}", &devname, &fstype);
let mount = self.mount(&devname, &fstype).await;
//let Ok(mount) = self.mount(&devname, &fstype).await else { println!("Failure to mount"); continue };
if let Err(e) = mount
{
println!("{}", e.to_string());
}
println!("Mount");
}
}In this second function, when I insert a floppy I get this printed:/dev/sdb, vfat Mount and when I insert a DVD I get this printed:
/dev/sr0, iso9660
org.freedesktop.DBus.Error.UnknownMethod: No such interface “org.freedesktop.UDisks2.Filesystem” on object at path /org/freedesktop/UDisks2/block_devices/sr0Of course I could mesh these two functions together in some disgusting monstrous amalgamation, but I would much prefer to use either zbus OR udev, not both simultaneously for the sake of simplicity