Compare commits

..
6 changed files with 70 additions and 144 deletions

No files matched your search

@@ -87,7 +87,8 @@ object Syncthing {
fun storageRoots(context: Context): List<File> =
listOf(context.dataDir) + context.getExternalFilesDirs(null).filterNotNull().mapNotNull { it.parentFile }
fun guard(context: Context) = SyncthingGuard(folderRoot(context), storageRoots(context), listOf(home(context)))
fun guard(context: Context, extraRoots: List<File> = emptyList()) =
SyncthingGuard(folderRoot(context), storageRoots(context) + extraRoots, listOf(home(context)))
fun init(application: Application) {
app = application.applicationContext
@@ -578,7 +578,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
else GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back)
}
if (savedDialog) SavedDialog(emptyList(), onOpen = { id -> onSelect("sound:$id") }) { savedDialog = false }
if (addingSoundtrack) SyncFolderPicker(stringResource(R.string.soundtracks_add_title), null, onDismiss = { addingSoundtrack = false }) { dir ->
if (addingSoundtrack) SyncFolderPicker(stringResource(R.string.soundtracks_add_title), null, sharedStorage = true, onDismiss = { addingSoundtrack = false }) { dir ->
addingSoundtrack = false
a.onSoundtrackAdded(dir)
}
@@ -48,8 +48,11 @@ internal class SyncLocation(val root: File, val label: String, val icon: ImageVe
internal fun containerHome(context: Context) = File(LinuxRuntime.rootDir(context), "root")
internal fun syncLocations(context: Context): List<SyncLocation> {
internal fun syncLocations(context: Context, sharedStorage: Boolean = false): List<SyncLocation> {
val volumes = pickVolumes(context)
val storage = if (!sharedStorage) emptyList() else volumes.map {
SyncLocation(it.root, it.label, if (it.removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone)
}
val roots = Syncthing.storageRoots(context)
val shared = roots.drop(1).mapIndexed { i, root ->
val volume = volumes.firstOrNull { root.path.startsWith(it.root.path + "/") }
@@ -58,18 +61,23 @@ internal fun syncLocations(context: Context): List<SyncLocation> {
}
val home = containerHome(context).takeIf { it.isDirectory }?.let { SyncLocation(it, context.getString(R.string.sync_location_home), Icons.Outlined.Home) }
return listOfNotNull(home, SyncLocation(Syncthing.folderRoot(context), context.getString(R.string.sync_location_sync), Icons.Outlined.FolderSpecial)) +
shared + SyncLocation(roots.first(), context.getString(R.string.sync_location_app), Icons.Outlined.Folder)
storage + shared + SyncLocation(roots.first(), context.getString(R.string.sync_location_app), Icons.Outlined.Folder)
}
internal fun syncPickerGuard(context: Context, locations: List<SyncLocation>, sharedStorage: Boolean) =
Syncthing.guard(context, if (sharedStorage) locations.map { it.root } else emptyList())
@Composable
internal fun SyncFolderPicker(title: String, suggestedName: String?, onDismiss: () -> Unit, onPick: (File) -> Unit) {
internal fun SyncFolderPicker(
title: String, suggestedName: String?, sharedStorage: Boolean = false, onDismiss: () -> Unit, onPick: (File) -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val density = LocalDensity.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val locations = remember { syncLocations(ctx) }
val guard = remember { Syncthing.guard(ctx) }
val locations = remember { syncLocations(ctx, sharedStorage) }
val guard = remember { syncPickerGuard(ctx, locations, sharedStorage) }
fun locationOf(d: File) = locations.filter { d.path == it.root.path || d.path.startsWith(it.root.path + "/") }.maxByOrNull { it.root.path.length }
var dir by remember { mutableStateOf<File?>(containerHome(ctx).takeIf { it.isDirectory } ?: Syncthing.folderRoot(ctx).also { it.mkdirs() }) }
var refresh by remember { mutableIntStateOf(0) }
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.ui
import android.os.Environment
import com.droiddeck.launcher.R
import com.droiddeck.launcher.sync.Syncthing
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SyncFolderPickerTest {
private val context = RuntimeEnvironment.getApplication()
private val internal = Environment.getExternalStorageDirectory()
private val music = File(internal, "Music")
@Test fun sharedStorageListsInternalStorageAndAllowsItsMusicFolder() {
val locations = syncLocations(context, sharedStorage = true)
val guard = syncPickerGuard(context, locations, sharedStorage = true)
assertTrue(locations.any { it.root.path == internal.path && it.label == context.getString(R.string.games_internal) })
assertTrue(guard.allows(music.path))
assertTrue(guard.browsable(music))
}
@Test fun sharedStorageKeepsTheSyncthingConfigBlocked() {
val guard = syncPickerGuard(context, syncLocations(context, sharedStorage = true), sharedStorage = true)
assertFalse(guard.allows(Syncthing.home(context).path))
assertFalse(guard.browsable(Syncthing.home(context)))
}
@Test fun theSyncthingPickerStaysInsideAppStorage() {
val locations = syncLocations(context)
val guard = syncPickerGuard(context, locations, sharedStorage = false)
assertFalse(locations.any { it.root.path == internal.path })
assertFalse(guard.allows(music.path))
assertTrue(guard.allows(Syncthing.folderRoot(context).path))
}
}
+3 -55
View File
@@ -16,7 +16,6 @@
#include <limits.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>
#include <netpacket/packet.h>
#include <netinet/in.h>
#include <pthread.h>
@@ -534,8 +533,6 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
}
}
#define ROUTE_TABLE 0
#define IPV6_ROUTE_TABLE 1
#define CARRIER_TABLE 5
#define SOCKET_TABLES 6
@@ -609,48 +606,6 @@ static FILE *synthesize(int table) {
return out;
}
static int link_has_gateway(int family) {
struct link link;
if (!load_link(&link)) return 0;
for (int i = 0; i < link.gateway_count; i++) {
if (link.gateways[i].family == family) return 1;
}
return 0;
}
static int default_route_line(const char *line, int table) {
unsigned flags, prefix;
if (table == ROUTE_TABLE) {
unsigned destination, gateway, mask;
return sscanf(line, "%*s %x %x %x %*d %*d %*d %x", &destination, &gateway, &flags, &mask) == 4
&& destination == 0 && mask == 0 && (flags & RTF_UP);
}
char destination[33];
return sscanf(line, "%32s %x %*s %*x %*s %*x %*x %*x %x", destination, &prefix, &flags) == 3
&& prefix == 0 && strspn(destination, "0") == 32 && (flags & RTF_UP) && !(flags & RTF_REJECT);
}
static int misses_default_route(int fd, int table) {
if (table != ROUTE_TABLE && table != IPV6_ROUTE_TABLE) return 0;
if (!link_has_gateway(table == ROUTE_TABLE ? AF_INET : AF_INET6)) return 0;
size_t capacity = 65536, size = 0;
char *text = malloc(capacity + 1);
if (text == NULL) return 0;
ssize_t got = 1;
while (size < capacity && (got = pread(fd, text + size, capacity - size, (off_t) size)) > 0) size += (size_t) got;
int misses = got == 0;
text[size] = '\0';
for (char *line = text; misses && *line;) {
char *end = strchr(line, '\n');
if (end) *end = '\0';
if (default_route_line(line, table)) misses = 0;
if (end == NULL) break;
line = end + 1;
}
free(text);
return misses;
}
int dd_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
@@ -668,12 +623,6 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f;
f = real(path, mode);
if (f && table >= 0 && misses_default_route(fileno(f), table)) {
FILE *link_table = synthesize(table);
if (link_table == NULL) return f;
fclose(f);
return link_table;
}
if (f || table < 0) return f;
int saved = errno;
if ((f = synthesize(table)) != NULL) {
@@ -687,9 +636,9 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) {
if (path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
int table = denied_table(path);
if (table < 0 || (fd >= 0 && !misses_default_route(fd, table))) return fd;
if (table < 0) return fd;
int saved = errno;
FILE *f = synthesize(table);
if (f == NULL) {
@@ -707,8 +656,7 @@ int dd_net_open(const char *path, int flags, int fd) {
errno = saved;
return fd;
}
if (fd >= 0) close(fd);
else if (saved == EACCES) remember_denial(table, path);
if (saved == EACCES) remember_denial(table, path);
return copy;
}
+5 -82
View File
@@ -87,21 +87,12 @@ int getsockopt(int fd, int level, int option, void *value, socklen_t *len) {
return real(fd, level, option, value, len);
}
static __thread char fixture_path[4096];
static const char *table_fixture(const char *path) {
const char *directory = getenv("NETLINK_TEST_TABLES");
if (!directory || !path || strncmp(path, "/proc/net/", 10)) return path;
snprintf(fixture_path, sizeof(fixture_path), "%s/%s", directory, path + 10);
return access(fixture_path, F_OK) == 0 ? fixture_path : path;
}
FILE *fopen(const char *path, const char *mode) {
static FILE *(*real)(const char *, const char *);
if (!real) real = dlsym(RTLD_NEXT, "fopen");
const char *snapshot = getenv("NETLINK_TEST_SNAPSHOT");
if (snapshot && !strcmp(path, "/etc/droiddeck-net")) path = snapshot;
return real(table_fixture(path), mode);
return real(path, mode);
}
static int denied(const char *path) {
@@ -125,13 +116,13 @@ int open(const char *path, int flags, ...) {
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(table_fixture(path), flags, mode);
return denied(path) ? -1 : real(path, flags, mode);
}
int __open_2(const char *path, int flags) {
static int (*real)(const char *, int);
if (!real) real = dlsym(RTLD_NEXT, "__open_2");
return denied(path) ? -1 : real(table_fixture(path), flags);
return denied(path) ? -1 : real(path, flags);
}
int openat(int dirfd, const char *path, int flags, ...) {
@@ -141,7 +132,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(dirfd, table_fixture(path), flags, mode);
return denied(path) ? -1 : real(dirfd, path, flags, mode);
}
int close_range(unsigned int first, unsigned int last, int flags) {
@@ -223,37 +214,6 @@ static void proc_net_test(int denied, int sealed) {
}
}
static const char *table_source(int descriptor) {
char link[64], target[4096];
snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor);
ssize_t length = readlink(link, target, sizeof(target) - 1);
require(length > 0, "route table target");
target[length] = 0;
return strncmp(target, "/memfd:droiddeck-net", 20) == 0 ? "link" : "real";
}
static void route_tables_test(void) {
static const char *const tables[] = {"/proc/net/route", "/proc/net/ipv6_route"};
static const char *const gateways[] = {"\t00000000\t0101A8C0\t0003\t", "20010db8000000000000000000000001 "};
char text[4096];
for (unsigned i = 0; i < 2; i++) {
FILE *stream = fopen(tables[i], "r");
require(stream != NULL, "route table fopen");
const char *source = table_source(fileno(stream));
size_t total = fread(text, 1, sizeof(text) - 1, stream);
text[total] = 0;
require(strcmp(source, "link") || strstr(text, gateways[i]), "link table lists the default gateway");
printf("%s ", source);
fclose(stream);
int descriptor = i ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC);
require(descriptor >= 0, "route table open");
require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "route table keeps close-on-exec");
printf("%s ", table_source(descriptor));
close(descriptor);
}
printf("\n");
}
static unsigned port_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
@@ -1249,7 +1209,6 @@ int main(int argc, char **argv) {
}
else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom"))
close_range_test(argv[1]);
else if (!strcmp(argv[1], "route_tables")) route_tables_test();
else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed"));
else if (!strcmp(argv[1], "route")) {
require(argc >= 3, "route destination");
@@ -1259,21 +1218,6 @@ int main(int argc, char **argv) {
}
"""
ROUTE_HEADER = "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n"
ZERO_V6 = "0" * 32
ANDROID_ROUTE_TABLES = {
"route": ROUTE_HEADER + "wlan0\t0001A8C0\t00000000\t0001\t0\t0\t0\t00FFFFFF\t0\t0\t0\n",
"ipv6_route": f"fe800000000000000000000000000000 40 {ZERO_V6} 00 {ZERO_V6} 00000100 00000001 00000000 00000001 wlan0\n"
f"{ZERO_V6} 00 {ZERO_V6} 00 {ZERO_V6} ffffffff 00000001 00000000 00200200 lo\n",
}
DEFAULT_ROUTE_TABLES = {
"route": ANDROID_ROUTE_TABLES["route"] + "wlan0\t00000000\t0101A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n",
"ipv6_route": ANDROID_ROUTE_TABLES["ipv6_route"]
+ f"{ZERO_V6} 00 {ZERO_V6} 00 fe800000000000000000000000000001 00000400 00000001 00000000 00450003 wlan0\n",
}
SNAPSHOT = """if wlan0 2 1500
mac 02:11:22:33:44:55
addr 192.168.1.10 24
@@ -1313,14 +1257,12 @@ class NetlinkPreloadTest(unittest.TestCase):
def tearDownClass(cls):
cls.temp.cleanup()
def run_program(self, mode, *arguments, snapshot=None, denied=None, tables=None):
def run_program(self, mode, *arguments, snapshot=None, denied=None):
env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}",
NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot),
DD_SYSV_DIR=str(self.directory / "sysv"))
if denied:
env["NETLINK_TEST_DENIED"] = denied
if tables:
env["NETLINK_TEST_TABLES"] = str(tables)
result = subprocess.run([str(self.program), mode, *arguments], env=env,
capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
@@ -1449,25 +1391,6 @@ class NetlinkPreloadTest(unittest.TestCase):
def test_readable_socket_tables_stay_real(self):
self.run_program("proc_net")
def route_tables(self, name, contents):
directory = self.directory / name
directory.mkdir(exist_ok=True)
for table, text in contents.items():
(directory / table).write_text(text)
return directory
def test_route_tables_without_a_default_route_answer_from_the_link(self):
tables = self.route_tables("android-routes", ANDROID_ROUTE_TABLES)
self.assertEqual(["link"] * 4, self.run_program("route_tables", tables=tables))
def test_route_tables_with_a_default_route_stay_real(self):
tables = self.route_tables("default-routes", DEFAULT_ROUTE_TABLES)
self.assertEqual(["real"] * 4, self.run_program("route_tables", tables=tables))
def test_route_tables_stay_real_when_the_link_has_no_gateway(self):
tables = self.route_tables("android-routes", ANDROID_ROUTE_TABLES)
self.assertEqual(["real"] * 4, self.run_program("route_tables", tables=tables, snapshot=self.direct))
def test_loopback_and_own_addresses_are_local_routes(self):
for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"),
("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")):