338 lines
11 KiB
C#
338 lines
11 KiB
C#
|
|
using System.Net.Sockets;
|
|||
|
|
using System.Runtime.InteropServices;
|
|||
|
|
using System.Text;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Monitors block devices via kernel netlink and manages the Micronona USB stick.
|
|||
|
|
///
|
|||
|
|
/// Events:
|
|||
|
|
/// OnMicrononaStickInserted – stick is ready (initialized if necessary), includes mount path
|
|||
|
|
/// OnStickRemoved – stick was removed
|
|||
|
|
///
|
|||
|
|
/// Empty sticks are initialized automatically with a new .micronona file.
|
|||
|
|
/// Only one stick is tracked at a time.
|
|||
|
|
/// </summary>
|
|||
|
|
public class DiskManager : IDisposable
|
|||
|
|
{
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Events
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
public event Action<string>? OnMicrononaStickInserted;
|
|||
|
|
public event Action? OnStickRemoved;
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// State
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private string? _mountedDevice; // e.g. "/dev/sda1"
|
|||
|
|
private string? _mountPath; // e.g. "/mnt/micronona"
|
|||
|
|
|
|||
|
|
private const string MarkerFile = ".micronona";
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Netlink socket
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private const int AF_NETLINK = 16;
|
|||
|
|
private const int NETLINK_KOBJECT_UEVENT = 15;
|
|||
|
|
|
|||
|
|
[StructLayout(LayoutKind.Sequential)]
|
|||
|
|
private struct SockaddrNl
|
|||
|
|
{
|
|||
|
|
public ushort nl_family;
|
|||
|
|
public ushort nl_pad;
|
|||
|
|
public uint nl_pid;
|
|||
|
|
public uint nl_groups;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
[DllImport("libc", SetLastError = true)]
|
|||
|
|
private static extern int socket(int domain, int type, int protocol);
|
|||
|
|
|
|||
|
|
[DllImport("libc", SetLastError = true)]
|
|||
|
|
private static extern int bind(int sockfd, ref SockaddrNl addr, int addrlen);
|
|||
|
|
|
|||
|
|
[DllImport("libc", SetLastError = true)]
|
|||
|
|
private static extern int recv(int sockfd, byte[] buf, int len, int flags);
|
|||
|
|
|
|||
|
|
[DllImport("libc", SetLastError = true)]
|
|||
|
|
private static extern int close(int fd);
|
|||
|
|
|
|||
|
|
private int _fd = -1;
|
|||
|
|
private CancellationTokenSource? _cts;
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Lifecycle
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
public void Start()
|
|||
|
|
{
|
|||
|
|
_fd = socket(AF_NETLINK, (int)SocketType.Raw, NETLINK_KOBJECT_UEVENT);
|
|||
|
|
if (_fd < 0)
|
|||
|
|
throw new InvalidOperationException("Failed to open netlink socket.");
|
|||
|
|
|
|||
|
|
var addr = new SockaddrNl
|
|||
|
|
{
|
|||
|
|
nl_family = AF_NETLINK,
|
|||
|
|
nl_groups = 1
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
if (bind(_fd, ref addr, Marshal.SizeOf<SockaddrNl>()) < 0)
|
|||
|
|
throw new InvalidOperationException("Failed to bind netlink socket.");
|
|||
|
|
|
|||
|
|
_cts = new CancellationTokenSource();
|
|||
|
|
Task.Run(() => WatchLoop(_cts.Token));
|
|||
|
|
|
|||
|
|
// Scan for sticks that were already inserted at startup
|
|||
|
|
foreach (var entry in Directory.EnumerateDirectories("/sys/class/block/"))
|
|||
|
|
{
|
|||
|
|
var name = Path.GetFileName(entry);
|
|||
|
|
if (name.StartsWith("mmcblk")) continue;
|
|||
|
|
if (!name[^1..].All(char.IsDigit)) continue;
|
|||
|
|
|
|||
|
|
// Only consider removable devices (USB sticks)
|
|||
|
|
var parent = name.TrimEnd('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
|
|||
|
|
var removablePath = $"/sys/class/block/{parent}/removable";
|
|||
|
|
if (!File.Exists(removablePath)) continue;
|
|||
|
|
if (File.ReadAllText(removablePath).Trim() != "1") continue;
|
|||
|
|
|
|||
|
|
HandleAdd("/dev/" + name);
|
|||
|
|
if (_mountedDevice != null) break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Console.WriteLine("[DiskManager] Started.");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void WatchLoop(CancellationToken ct)
|
|||
|
|
{
|
|||
|
|
var buffer = new byte[4096];
|
|||
|
|
|
|||
|
|
while (!ct.IsCancellationRequested)
|
|||
|
|
{
|
|||
|
|
int len = recv(_fd, buffer, buffer.Length, 0);
|
|||
|
|
if (len <= 0) continue;
|
|||
|
|
|
|||
|
|
var message = Encoding.UTF8.GetString(buffer, 0, len);
|
|||
|
|
ParseUevent(message);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Uevent parsing
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private void ParseUevent(string message)
|
|||
|
|
{
|
|||
|
|
var parts = message.Split('\0', StringSplitOptions.RemoveEmptyEntries);
|
|||
|
|
|
|||
|
|
string? action = null;
|
|||
|
|
string? devtype = null;
|
|||
|
|
string? devname = null;
|
|||
|
|
|
|||
|
|
foreach (var part in parts)
|
|||
|
|
{
|
|||
|
|
if (part.StartsWith("ACTION=")) action = part[7..];
|
|||
|
|
if (part.StartsWith("DEVTYPE=")) devtype = part[8..];
|
|||
|
|
if (part.StartsWith("DEVNAME=")) devname = part[8..];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Only care about partitions (or disks without partitions)
|
|||
|
|
if (devtype != "partition" && devtype != "disk") return;
|
|||
|
|
if (devname == null) return;
|
|||
|
|
|
|||
|
|
// Ignore internal SD card
|
|||
|
|
if (devname.StartsWith("mmcblk")) return;
|
|||
|
|
|
|||
|
|
var devPath = "/dev/" + devname;
|
|||
|
|
|
|||
|
|
if (action == "add")
|
|||
|
|
HandleAdd(devPath);
|
|||
|
|
else if (action == "remove")
|
|||
|
|
HandleRemove(devPath);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Add / Remove
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private void HandleAdd(string devPath)
|
|||
|
|
{
|
|||
|
|
if (_mountedDevice != null) return; // already tracking a stick
|
|||
|
|
if (!devPath[^1..].All(char.IsDigit)) return;
|
|||
|
|
|
|||
|
|
Console.WriteLine($"[DiskManager] Device added: {devPath}");
|
|||
|
|
|
|||
|
|
string? mountPath = null;
|
|||
|
|
for (int i = 0; i < 5; i++)
|
|||
|
|
{
|
|||
|
|
Thread.Sleep(300);
|
|||
|
|
mountPath = UdisksMount(devPath);
|
|||
|
|
if (mountPath != null) break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (mountPath == null)
|
|||
|
|
{
|
|||
|
|
Console.WriteLine($"[DiskManager] Mount failed for {devPath}, ignoring.");
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
_mountedDevice = devPath;
|
|||
|
|
_mountPath = mountPath;
|
|||
|
|
|
|||
|
|
var markerPath = Path.Combine(mountPath, MarkerFile);
|
|||
|
|
if (!File.Exists(markerPath))
|
|||
|
|
{
|
|||
|
|
bool isEmpty;
|
|||
|
|
try { isEmpty = !Directory.EnumerateFileSystemEntries(mountPath).Any(); }
|
|||
|
|
catch (UnauthorizedAccessException) { isEmpty = false; }
|
|||
|
|
if (!isEmpty)
|
|||
|
|
{
|
|||
|
|
Console.WriteLine($"[DiskManager] Not a Micronona stick, ignoring: {mountPath}");
|
|||
|
|
UdisksUnmount(devPath);
|
|||
|
|
_mountedDevice = null;
|
|||
|
|
_mountPath = null;
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Console.WriteLine($"[DiskManager] Initializing new stick at {mountPath}");
|
|||
|
|
InitializeStick(markerPath);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Console.WriteLine($"[DiskManager] Micronona stick at {mountPath}");
|
|||
|
|
OnMicrononaStickInserted?.Invoke(mountPath);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void HandleRemove(string devPath)
|
|||
|
|
{
|
|||
|
|
if (_mountedDevice != devPath) return;
|
|||
|
|
|
|||
|
|
Console.WriteLine($"[DiskManager] Device removed: {devPath}");
|
|||
|
|
|
|||
|
|
UdisksUnmount(devPath);
|
|||
|
|
|
|||
|
|
_mountedDevice = null;
|
|||
|
|
_mountPath = null;
|
|||
|
|
|
|||
|
|
OnStickRemoved?.Invoke();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Stick initialization
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private static void InitializeStick(string markerPath)
|
|||
|
|
{
|
|||
|
|
var model = new Tomlyn.Model.TomlTable
|
|||
|
|
{
|
|||
|
|
["drive"] = new Tomlyn.Model.TomlTable
|
|||
|
|
{
|
|||
|
|
["id"] = Guid.NewGuid().ToString()
|
|||
|
|
}
|
|||
|
|
};
|
|||
|
|
File.WriteAllText(markerPath, Tomlyn.Toml.FromModel(model));
|
|||
|
|
Console.WriteLine($"[DiskManager] Written {markerPath}");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Mount helpers (udisksctl — no root required)
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
private static string? UdisksMount(string devPath)
|
|||
|
|
{
|
|||
|
|
var psi = new System.Diagnostics.ProcessStartInfo
|
|||
|
|
{
|
|||
|
|
FileName = "udisksctl",
|
|||
|
|
Arguments = $"mount -b {devPath} --no-user-interaction",
|
|||
|
|
RedirectStandardOutput = true,
|
|||
|
|
RedirectStandardError = true
|
|||
|
|
};
|
|||
|
|
var p = System.Diagnostics.Process.Start(psi)!;
|
|||
|
|
var output = p.StandardOutput.ReadToEnd();
|
|||
|
|
var error = p.StandardError.ReadToEnd();
|
|||
|
|
p.WaitForExit();
|
|||
|
|
|
|||
|
|
// Erfolgreich gemountet
|
|||
|
|
var idx = output.IndexOf(" at ");
|
|||
|
|
if (idx >= 0) return output[(idx + 4)..].Trim().TrimEnd('.');
|
|||
|
|
|
|||
|
|
// Bereits gemountet — Pfad aus Fehlermeldung lesen
|
|||
|
|
var alreadyIdx = error.IndexOf("already mounted at `");
|
|||
|
|
if (alreadyIdx >= 0)
|
|||
|
|
{
|
|||
|
|
var start = alreadyIdx + 20;
|
|||
|
|
var end = error.IndexOf("'", start);
|
|||
|
|
if (end > start) return error[start..end];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Console.WriteLine($"[DiskManager] udisksctl: {error.Trim()}");
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static void UdisksUnmount(string devPath)
|
|||
|
|
{
|
|||
|
|
var psi = new System.Diagnostics.ProcessStartInfo
|
|||
|
|
{
|
|||
|
|
FileName = "udisksctl",
|
|||
|
|
RedirectStandardError = true
|
|||
|
|
};
|
|||
|
|
psi.ArgumentList.Add("unmount");
|
|||
|
|
psi.ArgumentList.Add("-b");
|
|||
|
|
psi.ArgumentList.Add(devPath);
|
|||
|
|
psi.ArgumentList.Add("--no-user-interaction");
|
|||
|
|
var p = System.Diagnostics.Process.Start(psi)!;
|
|||
|
|
p.WaitForExit();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// Public accessors
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Current mount path, or null if no stick is present.
|
|||
|
|
/// </summary>
|
|||
|
|
public string? MountPath => _mountPath;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Lists files on the inserted stick, sorted by last-edited descending.
|
|||
|
|
/// Excludes the marker file, directories, files with names longer than 12
|
|||
|
|
/// characters, and files whose names contain non-elementary ASCII characters.
|
|||
|
|
/// Returns (null, files) on success, or (error message, null) on failure.
|
|||
|
|
/// </summary>
|
|||
|
|
public (string? Error, IReadOnlyList<FileInfo>? Files) Dir()
|
|||
|
|
{
|
|||
|
|
if (_mountPath == null)
|
|||
|
|
return ("no disk inserted", null);
|
|||
|
|
|
|||
|
|
var files = new DirectoryInfo(_mountPath)
|
|||
|
|
.GetFiles()
|
|||
|
|
.Where(f => f.Name != MarkerFile
|
|||
|
|
&& f.Name.Length <= 12
|
|||
|
|
&& f.Name.All(IsElementaryAscii))
|
|||
|
|
.OrderByDescending(f => f.LastWriteTime)
|
|||
|
|
.ToList();
|
|||
|
|
|
|||
|
|
if (files.Count == 0)
|
|||
|
|
return ("disk empty", null);
|
|||
|
|
|
|||
|
|
return (null, files);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static bool IsElementaryAscii(char c)
|
|||
|
|
=> (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
|
|||
|
|
(c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_';
|
|||
|
|
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
// IDisposable
|
|||
|
|
// -------------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
public void Dispose()
|
|||
|
|
{
|
|||
|
|
_cts?.Cancel();
|
|||
|
|
if (_fd >= 0)
|
|||
|
|
{
|
|||
|
|
close(_fd);
|
|||
|
|
_fd = -1;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|