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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Die Pakete liegen unter [Releases](../../releases).
|---|---|---|
| **Windows** (x64) | `freizeichen-<version>-windows-x64.msi` ausführen | SmartScreen → „Weitere Informationen“ → „Trotzdem ausführen“ |
| **macOS** | `.dmg` öffnen (`arm64` für Apple-Chips, `x64` für Intel), Freizeichen in „Programme“ ziehen | Rechtsklick auf Freizeichen.app → „Öffnen“ |
| **Linux** | kein Paket – aus dem Quellcode starten, siehe [For developers](#for-developers) | Port mit `rfcomm bind` anlegen |
| **Linux** | kein Paket – aus dem Quellcode bauen, siehe [For developers](#for-developers) | Port mit `rfcomm bind` anlegen; „Als Standard festlegen“ trägt Freizeichen für `tel:`-Links ein |

Die Pakete sind noch nicht signiert. Ob ein Download unverändert ist, zeigt `SHA256SUMS.txt` im
Release: `sha256sum -c SHA256SUMS.txt` (Linux) bzw. `shasum -a 256 -c SHA256SUMS.txt` (macOS).
Expand Down Expand Up @@ -153,8 +153,9 @@ make screenshots # regenerate docs/screenshots/ for this README
make help # everything else
```

On Linux the phone appears as a serial port only after `sudo rfcomm bind 0 <phone-mac> 1`, and
the `tel:` handler is not registered automatically.
On Linux the phone appears as a serial port only after `sudo rfcomm bind 0 <phone-mac> 1`.
*Als Standard festlegen* writes `~/.local/share/applications/freizeichen.desktop`, pointing at the
running executable, and makes it the `x-scheme-handler/tel` default with `xdg-mime`.

### Layout

Expand Down
5 changes: 3 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ hand it input**. Whatever reaches the phone after `ATD` is executed by the phone
- **Dialling without confirmation.** Every link must go through the confirm window, and a keypress
in the first second after the window opens must not dial. Any path that places a call without
the Lagebuchführer pressing *Wählen* is a vulnerability.
- **The `tel:` registration**, meaning the Windows registry entries and the macOS bundle claim. For
example, a way for Freizeichen's registration to be hijacked, or to hijack another scheme.
- **The `tel:` registration**, meaning the Windows registry entries, the macOS bundle claim and
the Linux desktop entry with its `Exec` line. For example, a way for Freizeichen's
registration to be hijacked, or to hijack another scheme.
- **Settings file handling**, such as path or deserialization issues in the stored settings.
- **The release supply chain**: the build workflows, pinned actions, and the published installers
and `SHA256SUMS.txt`.
Expand Down
5 changes: 5 additions & 0 deletions src/Freizeichen.App/CompositionRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ private static ITelHandlerRegistration CreateRegistration()
return new MacTelHandlerRegistration();
}

if (OperatingSystem.IsLinux())
{
return new LinuxTelHandlerRegistration();
}

return new UnsupportedTelHandlerRegistration();
}
}
157 changes: 157 additions & 0 deletions src/Freizeichen.App/Platform/LinuxTelHandlerRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using Freizeichen.AppLogic;

namespace Freizeichen.App.Platform;

/// <summary>
/// Linux has no installer to declare the handler, so Freizeichen writes its own desktop entry to
/// the user's applications directory and asks <c>xdg-mime</c> (xdg-utils, present on every
/// desktop) to make it the default for <c>x-scheme-handler/tel</c>. The desktop opens the link
/// by running the entry's <c>Exec</c> line with the link as the argument, which is how
/// <see cref="LaunchArguments"/> receives it.
/// </summary>
internal sealed class LinuxTelHandlerRegistration : ITelHandlerRegistration
{
internal const string EntryName = "freizeichen.desktop";

private const string MimeType = "x-scheme-handler/tel";
private static readonly TimeSpan XdgMimeTimeout = TimeSpan.FromSeconds(5);

// The characters that force an Exec argument into quotes (Desktop Entry spec, "The Exec key").
private static readonly SearchValues<char> ExecReservedCharacters = SearchValues.Create(" \t\n\"'\\><~|&;$*?#()`");

private readonly string _applicationsDirectory;
private readonly string? _executablePath;
private readonly Func<IReadOnlyList<string>, string?> _xdgMime;

public LinuxTelHandlerRegistration()
: this(DefaultApplicationsDirectory(), Environment.ProcessPath, RunXdgMime)
{
}

/// <param name="applicationsDirectory">Where the desktop entry goes, normally <c>~/.local/share/applications</c>.</param>
/// <param name="executablePath">The program the entry runs; <c>null</c> when the process cannot tell.</param>
/// <param name="xdgMime">Runs <c>xdg-mime</c> with the arguments and returns its output, or <c>null</c> when it failed.</param>
internal LinuxTelHandlerRegistration(string applicationsDirectory, string? executablePath, Func<IReadOnlyList<string>, string?> xdgMime)
{
_applicationsDirectory = applicationsDirectory;
_executablePath = executablePath;
_xdgMime = xdgMime;
}

public bool IsDefaultHandler() =>
string.Equals(_xdgMime(["query", "default", MimeType])?.Trim(), EntryName, StringComparison.Ordinal);

public async Task MakeDefaultAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(_executablePath) || _executablePath.AsSpan().IndexOfAny('\r', '\n') >= 0)
{
throw new InvalidOperationException("The executable path cannot be written to a desktop entry.");
}

Directory.CreateDirectory(_applicationsDirectory);
await File.WriteAllTextAsync(Path.Join(_applicationsDirectory, EntryName), DesktopEntry(_executablePath), cancellationToken);

if (_xdgMime(["default", EntryName, MimeType]) is null)
{
throw new InvalidOperationException("xdg-mime could not make Freizeichen the tel: handler.");
}
}

private static string DesktopEntry(string executablePath) =>
new StringBuilder()
.Append("[Desktop Entry]\n")
.Append("Type=Application\n")
.Append("Name=Freizeichen\n")
.Append("Comment=Wählt tel:-Links über ein Gigaset DL500A per Bluetooth\n")
.Append("Exec=").Append(QuoteExecArgument(executablePath)).Append(" %u\n")
.Append("Terminal=false\n")
.Append("Categories=Network;Telephony;\n")
.Append("MimeType=").Append(MimeType).Append(";\n")
.ToString();

// A path without the Desktop Entry spec's reserved characters is written bare: xdg-mime
// (xdg-utils 1.2) reads the first word of Exec literally, quotes included, and ignores a default
// whose program it cannot find. Any other path is quoted as the spec requires: double quotes,
// with ", `, $ and \ backslash-escaped inside them; the value as a whole is then a string,
// whose own escaping doubles every backslash. A literal % is always written %% so it is not
// read as a field code.
private static string QuoteExecArgument(string argument)
{
if (argument.AsSpan().IndexOfAny(ExecReservedCharacters) < 0)
{
return argument.Replace("%", "%%", StringComparison.Ordinal);
}

var quoted = new StringBuilder("\"");
foreach (var c in argument)
{
switch (c)
{
case '"' or '`' or '$' or '\\':
quoted.Append(@"\\").Append(c == '\\' ? @"\\" : c.ToString());
break;
case '%':
quoted.Append("%%");
break;
default:
quoted.Append(c);
break;
}
}

return quoted.Append('"').ToString();
}

private static string DefaultApplicationsDirectory()
{
var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
if (string.IsNullOrEmpty(dataHome) || !Path.IsPathRooted(dataHome))
{
dataHome = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
}

return Path.Join(dataHome, "applications");
}

// Arguments go through ArgumentList, never a command line, and none of them come from input.
private static string? RunXdgMime(IReadOnlyList<string> arguments)
{
var start = new ProcessStartInfo("xdg-mime")
{
UseShellExecute = false,
RedirectStandardOutput = true,
};
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}

try
{
using var process = Process.Start(start);
if (process is null)
{
return null;
}

// The answer is one line, far below the pipe buffer, so waiting before reading cannot
// block the process on a full pipe.
if (!process.WaitForExit(XdgMimeTimeout))
{
process.Kill();
return null;
}

return process.ExitCode == 0 ? process.StandardOutput.ReadToEnd() : null;
}
catch (Win32Exception)
{
// xdg-utils is not installed: there is no desktop to register with.
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace Freizeichen.App.Platform;

/// <summary>Linux: Freizeichen dials there (it is where the DL500A is tested), but ships no handler registration.</summary>
/// <summary>Any other OS .NET runs on (FreeBSD): Freizeichen dials there, but registers no handler.</summary>
internal sealed class UnsupportedTelHandlerRegistration : ITelHandlerRegistration
{
public bool IsDefaultHandler() => false;

public Task MakeDefaultAsync(CancellationToken cancellationToken = default) =>
throw new PlatformNotSupportedException("Freizeichen registers as the tel: handler on Windows and macOS only.");
throw new PlatformNotSupportedException("Freizeichen registers as the tel: handler on Windows, macOS and Linux only.");
}
10 changes: 9 additions & 1 deletion src/Freizeichen.AppLogic/ViewModels/SettingsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,15 @@ private async Task MakeDefaultHandlerAsync()
}

[RelayCommand]
private void RefreshDefaultHandler() => IsDefaultHandler = _registration.IsDefaultHandler();
private void RefreshDefaultHandler()
{
IsDefaultHandler = _registration.IsDefaultHandler();
Show(
IsDefaultHandler
? "Geprüft: Freizeichen öffnet tel:-Links."
: "Geprüft: Ein anderes Programm öffnet tel:-Links.",
isError: false);
}

[SuppressMessage("Design", "CA1031", Justification = "Any failure of the test surfaces in Status.")]
private async Task RunAsync(string port, Func<Task<DialResult>> test)
Expand Down
114 changes: 114 additions & 0 deletions tests/Freizeichen.App.Tests/LinuxTelHandlerRegistrationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using Freizeichen.App.Platform;

namespace Freizeichen.App.Tests;

public sealed class LinuxTelHandlerRegistrationTests : IDisposable
{
private readonly string _applications = Path.Join(Path.GetTempPath(), "freizeichen-tests-" + Guid.NewGuid().ToString("N"));
private readonly List<string[]> _calls = [];
private string? _xdgMimeOutput = string.Empty;

public void Dispose()
{
if (Directory.Exists(_applications))
{
Directory.Delete(_applications, recursive: true);
}
}

[Fact]
public async Task Writes_a_desktop_entry_that_opens_tel_links_with_this_executable()
{
await Registration("/opt/freizeichen/Freizeichen").MakeDefaultAsync(TestContext.Current.CancellationToken);

var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken);
Assert.Equal("[Desktop Entry]", entry[0]);
Assert.Contains("Exec=/opt/freizeichen/Freizeichen %u", entry);
Assert.Contains("MimeType=x-scheme-handler/tel;", entry);
}

// xdg-mime (xdg-utils 1.2) takes the first word of Exec literally, quotes included, and drops a
// default whose program it cannot find: a quoted plain path made "Prüfen" report another
// handler although the default was set.
[Theory]
[InlineData("/home/user/Freizeichen-1.0/bin/Freizeichen")]
[InlineData("/usr/lib/freizeichen/Freizeichen")]
public async Task Leaves_a_plain_executable_path_unquoted_so_xdg_mime_can_resolve_it(string executable)
{
await Registration(executable).MakeDefaultAsync(TestContext.Current.CancellationToken);

var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken);
Assert.Contains($"Exec={executable} %u", entry);
}

[Fact]
public async Task Quotes_a_path_with_a_space()
{
await Registration("/home/a b/Freizeichen").MakeDefaultAsync(TestContext.Current.CancellationToken);

var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken);
Assert.Contains("Exec=\"/home/a b/Freizeichen\" %u", entry);
}

[Fact]
public async Task Quotes_an_executable_path_the_way_the_desktop_entry_spec_requires()
{
await Registration("/home/a b/$x`y\"z\\Free%zeichen").MakeDefaultAsync(TestContext.Current.CancellationToken);

var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken);
Assert.Contains("Exec=\"/home/a b/\\\\$x\\\\`y\\\\\"z\\\\\\\\Free%%zeichen\" %u", entry);
}

[Fact]
public async Task Refuses_an_executable_path_with_a_line_break()
{
await Assert.ThrowsAsync<InvalidOperationException>(
() => Registration("/opt/x\nExec=evil").MakeDefaultAsync(TestContext.Current.CancellationToken));

Assert.False(File.Exists(Path.Join(_applications, "freizeichen.desktop")));
}

[Fact]
public async Task Makes_the_entry_the_default_for_tel_links_through_xdg_mime()
{
await Registration().MakeDefaultAsync(TestContext.Current.CancellationToken);

Assert.Equal([["default", "freizeichen.desktop", "x-scheme-handler/tel"]], _calls);
}

[Fact]
public async Task Fails_when_xdg_mime_cannot_set_the_default()
{
_xdgMimeOutput = null;

await Assert.ThrowsAsync<InvalidOperationException>(
() => Registration().MakeDefaultAsync(TestContext.Current.CancellationToken));
}

[Fact]
public void Is_the_default_when_xdg_mime_names_the_entry()
{
_xdgMimeOutput = "freizeichen.desktop\n";

Assert.True(Registration().IsDefaultHandler());
Assert.Equal([["query", "default", "x-scheme-handler/tel"]], _calls);
}

[Theory]
[InlineData("org.gnome.Calls.desktop\n")]
[InlineData("")]
[InlineData(null)]
public void Is_not_the_default_when_xdg_mime_names_another_program_or_fails(string? output)
{
_xdgMimeOutput = output;

Assert.False(Registration().IsDefaultHandler());
}

private LinuxTelHandlerRegistration Registration(string executable = "/opt/freizeichen/Freizeichen") =>
new(_applications, executable, args =>
{
_calls.Add([.. args]);
return _xdgMimeOutput;
});
}
16 changes: 16 additions & 0 deletions tests/Freizeichen.AppLogic.Tests/SettingsViewModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,20 @@ public async Task Re_reads_the_handler_state_after_the_user_returns_from_the_os_

Assert.True(vm.IsDefaultHandler);
}

// When the answer has not changed, the line under TEL:-LINKS stays as it was; the status is the
// only sign the check ran at all.
[Theory]
[InlineData(true, "Geprüft: Freizeichen öffnet tel:-Links.")]
[InlineData(false, "Geprüft: Ein anderes Programm öffnet tel:-Links.")]
public void Check_answers_in_the_status_even_when_nothing_changed(bool isDefault, string status)
{
_registration.IsDefault = isDefault;
var vm = ViewModel();

vm.RefreshDefaultHandlerCommand.Execute(null);

Assert.Equal(status, vm.Status);
Assert.False(vm.IsError);
}
}
Loading