Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 39 additions & 17 deletions agent/PhoneBox.Agent/UpdateService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Diagnostics;
using System.IO.Compression;
using System.Net.Http.Json;
using System.Runtime.InteropServices;
using System.Text.Json;

namespace PhoneBox.Agent;
Expand Down Expand Up @@ -32,9 +33,30 @@ public sealed class UpdateService(ConfigStore cfg, AdbReverse adb, IHostApplicat
/// <summary>Phone app version, reported by the app on every request (X-PhoneBox-App header).</summary>
public static volatile string? AppVersion;

public static bool RunningInstalled =>
string.Equals(Path.GetFullPath(AppContext.BaseDirectory).TrimEnd('\\', '/'), Path.GetFullPath(InstallDir).TrimEnd('\\', '/'),
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
public static bool RunningInstalled => SameFolder(AppContext.BaseDirectory, InstallDir);

/// <summary>
/// On macOS/Linux the .NET host reports the agent's folder with symbolic links resolved, while the install folder
/// comes from HOME / XDG_DATA_HOME and may go through one (a home folder moved to another disk and linked back), so
/// both sides are resolved before comparing.
/// </summary>
internal static bool SameFolder(string a, string b) =>
string.Equals(Resolved(a), Resolved(b), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);

private static string Resolved(string folder)
{
var full = Path.GetFullPath(folder).TrimEnd('\\', '/');
if (OperatingSystem.IsWindows()) return full;
IntPtr real;
try { real = realpath(full, IntPtr.Zero); } // null when the folder does not exist: compare the path as it is
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) { return full; } // runs at startup: never fail it
if (real == IntPtr.Zero) return full;
try { return (Marshal.PtrToStringUTF8(real) ?? full).TrimEnd('/'); }
finally { free(real); }
}

[DllImport("libc")] private static extern IntPtr realpath(string path, IntPtr resolved);
[DllImport("libc")] private static extern void free(IntPtr pointer);

public UpdateStatus Status()
{
Expand Down Expand Up @@ -149,7 +171,7 @@ public async Task ApplyAsync(CancellationToken ct = default)
var adbExe = AdbReverse.FindAdb(cfg.Get().AdbPath) ?? throw new InvalidOperationException("adb not found");
foreach (var serial in targets)
{
var output = await Run(adbExe, $"-s {serial} install \"{apk}\"", ct);
var output = await Run(adbExe, ["-s", serial, "install", apk], ct);
if (!output.Contains("Success")) return $"installing on {serial} failed: {output.Trim().Split('\n').LastOrDefault()}";
log.LogInformation("phone app {Version} installed on {Serial}", _latest.Version, serial);
}
Expand All @@ -170,10 +192,10 @@ private async Task UpdatePhoneAsync(CancellationToken ct)
var adbExe = AdbReverse.FindAdb(cfg.Get().AdbPath) ?? throw new InvalidOperationException("adb not found");
foreach (var serial in adb.Devices.Split(", ", StringSplitOptions.RemoveEmptyEntries))
{
var output = await Run(adbExe, $"-s {serial} install -r \"{apk}\"", ct);
var output = await Run(adbExe, ["-s", serial, "install", "-r", apk], ct);
if (!output.Contains("Success"))
throw new InvalidOperationException($"phone update on {serial} failed: {output.Trim().Split('\n').LastOrDefault()}");
await Run(adbExe, $"-s {serial} shell am start -n {AdbReverse.PanelActivity}", ct);
await Run(adbExe, ["-s", serial, "shell", "am", "start", "-n", AdbReverse.PanelActivity], ct);
log.LogInformation("phone app on {Serial} updated to {Version}", serial, _latest.Version);
}
AppVersion = _latest.Version;
Expand Down Expand Up @@ -334,18 +356,18 @@ internal static void RemoveFrameworkDependentLeftovers(string dir, bool singleFi
private static bool Newer(string candidate, string current) =>
Version.TryParse(candidate, out var a) && Version.TryParse(current.Split('-')[0], out var b) && a > b;

private static async Task<string> Run(string file, string args, CancellationToken ct)
/// <summary>
/// Runs adb for the updater, bounded and reaped like every other tool (<see cref="ToolProcess"/>): an install that
/// never returns (a stuck phone or cable) would otherwise hold the update gate until the agent restarts, and a
/// cancelled update would leave adb running. A slow phone can take a while to install, hence the generous default.
/// Each argument is passed on its own (ArgumentList), so a path with spaces or quotes needs no quoting.
/// </summary>
private static async Task<string> Run(string file, string[] args, CancellationToken ct, TimeSpan? timeout = null)
{
var psi = new ProcessStartInfo(file, args)
{
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true,
WorkingDirectory = AppPaths.NeutralCwd,
};
using var p = Process.Start(psi)!;
var stdout = p.StandardOutput.ReadToEndAsync(ct);
var stderr = p.StandardError.ReadToEndAsync(ct);
await p.WaitForExitAsync(ct);
return await stdout + await stderr;
var start = new ProcessStartInfo(file);
foreach (var arg in args) start.ArgumentList.Add(arg);
var result = await ToolProcess.RunAsync(start, timeout ?? TimeSpan.FromMinutes(3), ct);
return result.Output + result.Error;
}

private sealed record Release(string Version, string? Url, string? Apk, string? AgentZip);
Expand Down
22 changes: 13 additions & 9 deletions setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -288,14 +288,18 @@ write_autostart() {
caution "Add $app/PhoneBoxAgent to your desktop's startup applications instead."
return 1
fi
case "$app$HOME${XDG_DATA_HOME:-}${XDG_CONFIG_HOME:-}" in
*'$'*|*'
'*)
caution "The install or settings path contains \$ or a line break, which a systemd service cannot be given safely;"
caution "add $app/PhoneBoxAgent to your desktop's startup applications instead."
remove_autostart # an older unit would otherwise start the previous install at login and in start_agent
return 1 ;;
esac
local unsafe=0
case "$app$HOME${XDG_DATA_HOME:-}${XDG_CONFIG_HOME:-}" in *'$'*|*'
'*) unsafe=1 ;; esac
# systemd also refuses an executable path with a quote, an apostrophe or a backslash ("special characters"),
# e.g. an AD home such as /home/o'brien@corp.example: the unit would be enabled but never start
case "$app" in *'"'*|*"'"*|*[\\]*) unsafe=1 ;; esac
if [ "$unsafe" = 1 ]; then
caution "The install or settings path contains \$, a quote, a backslash or a line break, which a systemd service cannot be given safely;"
caution "add $app/PhoneBoxAgent to your desktop's startup applications instead."
remove_autostart # an older unit would otherwise start the previous install at login and in start_agent
return 1
fi
# the service must see the same XDG folders as this shell, or the agent would use other settings and install folders
local env_lines="" v
for v in XDG_DATA_HOME XDG_CONFIG_HOME; do
Expand Down Expand Up @@ -377,7 +381,7 @@ select_phone() { # prints the serial of the one authorised phone, or nothing to
caution "Several phones are connected: $(printf '%s' "$ready" | tr '\n' ' ')" >&2
if [ "$yes" = 1 ] || [ "$tty_ok" = 0 ]; then caution 'Run setup again with --serial <id> to pick one; skipping the phone app.' >&2; return; fi
wanted="$(read_line 'Type the serial of the phone to use (empty to skip):')"
[ -n "$wanted" ] || return
[ -n "$wanted" ] || return 0 # skipping is not an error: main runs under set -e
continue
fi
if [ -z "$devices" ]; then
Expand Down
Loading