Compare commits

..
9 changed files with 293 additions and 343 deletions

No files matched your search

@@ -48,7 +48,7 @@ object StoreLaunch {
if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
lines += "cd /d \"%~dp0$dir\""
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR || sidecar.store == Store.GOG && (it.any { c -> c in BATCH_META } || ' ' in it && it.endsWith('\\'))) batchArg(it) else quoteArg(it) }
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
@@ -105,8 +105,6 @@ object StoreLaunch {
return lines.joinToString("\r\n") + "\r\n"
}
private const val BATCH_META = "%^&|<>()\""
private val ENV_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*")
private fun batchArg(arg: String): String {
@@ -143,7 +141,6 @@ object StoreLaunch {
}
fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
if (sidecar.store == Store.GOG) return com.droiddeck.launcher.stores.gog.GogBackend.adoptPlayTask(folder, sidecar)
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
@@ -10,7 +10,6 @@ import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreLaunch
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoresState
@@ -22,22 +21,6 @@ import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
object GogBackend : StoreBackend {
const val PLAY_TASK_READ = "gogPlayTaskRead"
fun withPlayTask(folder: File, sidecar: StoreGameSidecar, replaceExe: Boolean): StoreGameSidecar {
if (!runCatching { GogDownloadManager.manifestsReadable(folder) }.getOrDefault(false)) return sidecar.copy(extra = sidecar.extra - PLAY_TASK_READ)
val task = runCatching { GogDownloadManager.declaredGameTask(folder, sidecar.id) }.getOrNull()?.takeIf { replaceExe || it.args.isNotEmpty() }
val next = if (task != null) sidecar.copy(exe = task.path, workdir = task.workDir, args = task.args) else sidecar
return next.copy(extra = next.extra + (PLAY_TASK_READ to "1"))
}
fun adoptPlayTask(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
if (sidecar.store != Store.GOG || !sidecar.isInstalled || PLAY_TASK_READ in sidecar.extra) return sidecar
val next = withPlayTask(folder, sidecar, replaceExe = false)
if (PLAY_TASK_READ !in next.extra) return sidecar
return runCatching { StoreLaunch.writeLauncher(folder, next).also { it.write(folder) } }.getOrDefault(sidecar)
}
override val store: Store = Store.GOG
override fun signIn(context: Context) {
@@ -153,13 +136,12 @@ object GogBackend : StoreBackend {
val sidecar = StoreGameSidecar(
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
workdir = result.workDir,
args = result.args,
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
logo = item.logoUrl ?: fetchLogo(game.gameId),
extra = mapOf(com.droiddeck.launcher.frontend.WinCompSources.GOG_DEPENDENCIES to result.dependencies.joinToString(","))
+ (if (result.dependenciesRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap())
+ mapOf(StoreLanguage.EXTRA to installedLanguage, PLAY_TASK_READ to "1"),
+ mapOf(StoreLanguage.EXTRA to installedLanguage),
)
if (sidecar.exe.isEmpty()) handle.log("gog: no exe found in ${folder.name}; pick one in Steam settings › Added games")
StoreInstalls.complete(app, folder, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }, sidecar = if (sidecar.exe.isEmpty()) sidecar.copy(exe = "game.exe") else sidecar)
@@ -6,7 +6,6 @@ import android.util.Log;
import com.droiddeck.launcher.frontend.AddedGames;
import com.droiddeck.launcher.stores.StoreLanguage;
import com.droiddeck.launcher.stores.StoreLog;
import com.droiddeck.launcher.stores.ea.EaPaths;
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
import org.json.JSONArray;
@@ -69,7 +68,6 @@ public final class GogDownloadManager {
public String language;
/** GOG's working directory for the exe: "" is the install root, null when no task declared it. */
public String workDir;
public List<String> args = new ArrayList<>();
Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; }
}
@@ -252,7 +250,7 @@ public final class GogDownloadManager {
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"generation\":1}").getBytes("UTF-8"));
GameTask task = pickTask(installPath, game.gameId, null, game.title);
out.result = new Result(task == null ? "" : task.path, "", planned);
if (task != null) { out.result.workDir = task.workDir; out.result.args = task.args; }
if (task != null) out.result.workDir = task.workDir;
return out;
} catch (Exception e) {
out.error = "exception: " + e.getClass().getSimpleName();
@@ -308,7 +306,6 @@ public final class GogDownloadManager {
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
Result result = new Result(exe, "", total);
result.workDir = task.workDir;
result.args = task.args;
return result;
} catch (InstallerException e) {
throw e;
@@ -759,7 +756,7 @@ public final class GogDownloadManager {
* one; any other {@code goggame-*.info} in the folder is only the fallback. Builds without a
* manifest fall through to the hint and search below.
*/
static GameTask declaredGameTask(File installPath, String gameId) {
private static GameTask declaredGameTask(File installPath, String gameId) {
File own = gameId == null || gameId.isEmpty() ? null : new File(installPath, "goggame-" + gameId + ".info");
if (own != null && !own.isFile()) own = null;
List<File> others = new ArrayList<>();
@@ -783,28 +780,12 @@ public final class GogDownloadManager {
return best;
}
static boolean manifestsReadable(File installPath) {
File[] files = installPath.listFiles();
if (files == null) return false;
for (File f : files) {
if (!f.isFile() || !f.getName().startsWith("goggame-") || !f.getName().endsWith(".info")) continue;
try {
new JSONObject(new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8));
} catch (Exception e) {
return false;
}
}
return true;
}
static final class GameTask {
final String path;
/** GOG's working directory for the task: "" is the install root, null when no task declared it. */
final String workDir;
final int rank;
final List<String> args;
GameTask(String path, String workDir, int rank) { this(path, workDir, rank, Collections.<String>emptyList()); }
GameTask(String path, String workDir, int rank, List<String> args) { this.path = path; this.workDir = workDir; this.rank = rank; this.args = args; }
GameTask(String path, String workDir, int rank) { this.path = path; this.workDir = workDir; this.rank = rank; }
}
/** The task this manifest would be played from, or null when it names none that exists. */
@@ -825,11 +806,9 @@ public final class GogDownloadManager {
if (rank == 0 || (best != null && rank <= best.rank)) continue;
String path = task.optString("path", "").replace('\\', '/').replaceAll("/+", "/").replaceFirst("^(\\.?/)+", "");
if (path.isEmpty()) continue;
if (!new File(installPath, path).isFile()) path = EaPaths.INSTANCE.relativeOnDisk(installPath, path);
if (path == null) continue;
File exe = new File(installPath, path);
if (!exe.isFile() || gogSupportExe(exe.getName()) || !inside(installPath, exe)) continue;
best = new GameTask(path, taskWorkDir(installPath, task), rank, EaPaths.INSTANCE.splitArgs(task.optString("arguments", "")));
best = new GameTask(path, taskWorkDir(installPath, task), rank);
}
return best;
}
@@ -846,10 +825,6 @@ public final class GogDownloadManager {
while (dir.startsWith("./")) dir = dir.substring(2);
dir = dir.replaceAll("^/+", "").replaceAll("/+$", "");
if (dir.isEmpty() || dir.equals(".")) return "";
if (!new File(installPath, dir).isDirectory()) {
dir = EaPaths.INSTANCE.relativeOnDisk(installPath, dir);
if (dir == null) return "";
}
File folder = new File(installPath, dir);
return folder.isDirectory() && inside(installPath, folder) ? dir : "";
}
@@ -181,7 +181,7 @@ internal object GogMaintenance {
}
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("The original GOG settings are missing")
target.write(folder)
StoreInstalls.complete(context, folder, GogBackend.withPlayTask(folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED), replaceExe = true))
StoreInstalls.complete(context, folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
}
}
@@ -284,7 +284,7 @@ internal object GogMaintenance {
val target = GogInstallRecord.read(folder)?.takeIf { proposal.operation == GogOperation.PATCH || proposal.operation == GogOperation.REFRESH && proposal.target.source != "depot" } ?: proposal.target
check(target.verified) { "The patch completed, but its resulting version could not be verified. Inspect the game or use a full offline refresh." }
target.write(folder)
StoreInstalls.complete(app, folder, GogBackend.withPlayTask(folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED), replaceExe = true))
StoreInstalls.complete(app, folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
runCatching { cleanCaches() }.onFailure { handle.log("gog: completed; could not remove expendable cache: ${it.message}") }
checkedAt.remove(folder.path)
@@ -397,7 +397,6 @@ internal object GogMaintenance {
val task = GogDownloadManager.pickTask(folder, game.gameId, GogContent.tempExecutable(target.manifest), game.title)
val result = GogDownloadManager.Result(task?.path ?: "", build.id, disk)
result.workDir = task?.workDir
result.args = task?.args.orEmpty()
result.language = target.language
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
result.dependenciesRead = true
@@ -1,12 +1,7 @@
package com.droiddeck.launcher.stores.gog
import java.io.File
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreLaunch
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -341,161 +336,4 @@ class GogGameExeTest {
assertEquals("System", task.workDir)
}
}
private val dosboxManifest = """{"playTasks":[
{"category":"game","isPrimary":true,"path":"DOSBOX\\DOSBox.exe","workingDir":"DOSBOX","type":"FileTask",
"arguments":"-conf \"..\\dosboxRiva.conf\" -conf \"..\\dosboxRiva_single.conf\" -noconsole -c \"exit\""}]}"""
@Test
fun aCaseMismatchedDosboxTaskWinsOverTheDosExe() {
withFolder { root ->
root.exe("RIVA.EXE", 65536)
root.exe("dosbox/DOSBOX.EXE", 4096)
File(root, "goggame-1207658797.info").writeText(dosboxManifest)
val task = GogDownloadManager.pickTask(root, "1207658797", null, "Realms of Arkania 3")
assertEquals("dosbox/DOSBOX.EXE", task.path)
}
}
@Test
fun aTasksArgumentsAndWorkingDirectoryAreCarriedThrough() {
withFolder { root ->
root.exe("RIVA.EXE", 65536)
root.exe("dosbox/DOSBOX.EXE", 4096)
File(root, "goggame-1207658797.info").writeText(dosboxManifest)
val task = GogDownloadManager.pickTask(root, "1207658797", null, "Realms of Arkania 3")
assertEquals("dosbox", task.workDir)
assertEquals(
listOf("-conf", "..\\dosboxRiva.conf", "-conf", "..\\dosboxRiva_single.conf", "-noconsole", "-c", "exit"),
task.args,
)
}
}
@Test
fun aTasksArgumentsReachTheLauncherScript() {
withFolder { root ->
root.exe("dosbox/DOSBOX.EXE", 4096)
File(root, "goggame-1207658797.info").writeText(dosboxManifest)
val task = GogDownloadManager.pickTask(root, "1207658797", null, "Realms of Arkania 3")
val sidecar = StoreGameSidecar(Store.GOG, "1207658797", "Realms of Arkania 3", task.path, workdir = task.workDir, args = task.args)
val script = StoreLaunch.launcherText(sidecar)
assertTrue(script, script.contains("cd /d \"%~dp0dosbox\""))
assertTrue(script, script.contains("\"%~dp0dosbox\\DOSBOX.EXE\" -conf ..\\dosboxRiva.conf -conf ..\\dosboxRiva_single.conf -noconsole -c exit"))
}
}
@Test
fun anArgumentWithSpacesIsKeptAsOneArgument() {
withFolder { root ->
root.exe("game.exe", 4096)
File(root, "goggame-7.info").writeText(
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"game.exe","arguments":"-cfg \"my config.ini\" -windowed"}]}""",
)
assertEquals(listOf("-cfg", "my config.ini", "-windowed"), GogDownloadManager.pickTask(root, "7", null, "Some Game").args)
}
}
@Test
fun aTaskWithoutArgumentsKeepsNoneAndItsExactCasePath() {
withFolder { root ->
root.exe("System/witcher.exe", 4096)
File(root, "goggame-1207658924.info").writeText(
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"System\\witcher.exe","workingDir":"System","type":"FileTask"}]}""",
)
val task = GogDownloadManager.pickTask(root, "1207658924", null, "The Witcher: Enhanced Edition")
assertEquals("System/witcher.exe", task.path)
assertEquals("System", task.workDir)
assertEquals(emptyList<String>(), task.args)
}
}
@Test
fun aSearchedExecutableHasNoArguments() {
withFolder { root ->
root.exe("kain.exe", 4096)
assertEquals(emptyList<String>(), GogDownloadManager.pickTask(root, null, null, "Blood Omen: Legacy of Kain").args)
}
}
@Test
fun anInstalledGameWithoutItsTaskArgumentsIsRepairedOnce() {
withFolder { root ->
root.exe("RIVA.EXE", 65536)
root.exe("dosbox/DOSBOX.EXE", 4096)
File(root, "goggame-1207658797.info").writeText(dosboxManifest)
val stale = StoreGameSidecar(Store.GOG, "1207658797", "Realms of Arkania 3", "RIVA.EXE")
stale.write(root)
val adopted = StoreLaunch.adopt(root, stale)
assertEquals("dosbox/DOSBOX.EXE", adopted.exe)
assertEquals("dosbox", adopted.workdir)
assertEquals("-noconsole", adopted.args[4])
assertEquals(StoreLaunch.LAUNCHER, adopted.launcher)
assertTrue(File(root, StoreLaunch.LAUNCHER).readText().contains("DOSBOX.EXE\" -conf"))
val saved = StoreGameSidecar.read(root)!!
assertEquals("dosbox/DOSBOX.EXE", saved.exe)
assertEquals(adopted.args, saved.args)
assertEquals("1", saved.extra[GogBackend.PLAY_TASK_READ])
assertTrue(StoreLaunch.adopt(root, saved) === saved)
}
}
@Test
fun anInstalledGameWhoseTaskHasNoArgumentsKeepsItsExe() {
withFolder { root ->
root.exe("bin/game.exe", 4096)
root.exe("other.exe", 65536)
File(root, "goggame-1.info").writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"bin\\game.exe","type":"FileTask"}]}""")
val sidecar = StoreGameSidecar(Store.GOG, "1", "Game", "other.exe")
val adopted = StoreLaunch.adopt(root, sidecar)
assertEquals("other.exe", adopted.exe)
assertTrue(adopted.args.isEmpty())
assertEquals("1", adopted.extra[GogBackend.PLAY_TASK_READ])
}
}
@Test
fun anUnreadableManifestIsRetriedOnceItReadsAgain() {
withFolder { root ->
root.exe("RIVA.EXE", 65536)
root.exe("dosbox/DOSBOX.EXE", 4096)
val manifest = File(root, "goggame-1207658797.info")
manifest.writeText(dosboxManifest.take(40))
val stale = StoreGameSidecar(Store.GOG, "1207658797", "Realms of Arkania 3", "RIVA.EXE")
stale.write(root)
assertTrue(StoreLaunch.adopt(root, stale) === stale)
assertFalse(GogBackend.PLAY_TASK_READ in StoreGameSidecar.read(root)!!.extra)
manifest.writeText(dosboxManifest)
val adopted = StoreLaunch.adopt(root, StoreGameSidecar.read(root)!!)
assertEquals("dosbox/DOSBOX.EXE", adopted.exe)
assertEquals("1", adopted.extra[GogBackend.PLAY_TASK_READ])
}
}
@Test
fun anUpdatedBuildTakesItsNewPlayTask() {
withFolder { root ->
root.exe("bin/game.exe", 4096)
root.exe("old.exe", 65536)
File(root, "goggame-1.info").writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"bin\\game.exe","arguments":"-a b","type":"FileTask"}]}""")
val read = StoreGameSidecar(Store.GOG, "1", "Game", "old.exe", extra = mapOf(GogBackend.PLAY_TASK_READ to "1"))
val updated = GogBackend.withPlayTask(root, read, replaceExe = true)
assertEquals("bin/game.exe", updated.exe)
assertEquals(listOf("-a", "b"), updated.args)
File(root, "goggame-1.info").writeText("{")
assertFalse(GogBackend.PLAY_TASK_READ in GogBackend.withPlayTask(root, read, replaceExe = true).extra)
}
}
@Test
fun taskArgumentsWithBatchCharactersStayOneArgument() {
withFolder { root ->
root.exe("dosbox/DOSBOX.EXE", 4096)
val sidecar = StoreGameSidecar(Store.GOG, "1", "Game", "dosbox/DOSBOX.EXE", args = listOf("-conf", "base&extra.conf", "-noconsole", "-savedir", "C:\\My Saves\\", "-windowed"))
StoreLaunch.writeLauncher(root, sidecar)
val text = File(root, StoreLaunch.LAUNCHER).readText()
assertTrue(text.contains("-conf ^\"base^&extra.conf^\" -noconsole"))
assertTrue(text.contains("-savedir ^\"C:\\My Saves\\\\^\" -windowed"))
}
}
}
+17
View File
@@ -0,0 +1,17 @@
#define _GNU_SOURCE
#if defined(__x86_64__) || defined(__i386__)
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "named_semaphores.h"
#endif
+127
View File
@@ -0,0 +1,127 @@
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name) + strlen(prefix);
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
struct posix_sem {
dev_t dev;
ino_t ino;
sem_t *addr;
unsigned int refs;
struct posix_sem *next;
};
static struct posix_sem *g_posix_sems;
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
__attribute__((constructor)) static void posix_sems_across_fork(void) {
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
}
static void close_keeping_errno(int fd) {
int saved = errno;
close(fd);
errno = saved;
}
static sem_t *posix_sem_map(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return SEM_FAILED;
sem_t *sem = SEM_FAILED;
posix_sems_hold();
struct posix_sem *e = g_posix_sems;
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
if (e) {
e->refs++;
sem = e->addr;
} else {
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
if (e) {
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
g_posix_sems = e;
sem = addr;
} else if (addr != MAP_FAILED) {
munmap(addr, sizeof(sem_t));
errno = ENOMEM;
}
}
posix_sems_unlock();
return sem;
}
static sem_t *posix_sem_open_fd(int fd) {
if (fd < 0) return SEM_FAILED;
sem_t *sem = posix_sem_map(fd);
close_keeping_errno(fd);
return sem;
}
sem_t *sem_open(const char *name, int oflag, ...) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
va_list args;
va_start(args, oflag);
mode_t mode = va_arg(args, mode_t);
unsigned int value = va_arg(args, unsigned int);
va_end(args);
static unsigned int serial;
for (;;) {
if (!(oflag & O_EXCL)) {
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
}
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
sem_t initial;
memset(&initial, 0, sizeof(initial));
sem_init(&initial, 1, value);
char temp[PATH_MAX];
int fd;
do {
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
} while (fd < 0 && errno == EEXIST);
if (fd < 0) return SEM_FAILED;
errno = EIO;
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
close_keeping_errno(fd);
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
int saved = errno;
if (sem != SEM_FAILED) sem_close(sem);
unlink(temp);
errno = saved;
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
}
}
int sem_close(sem_t *sem) {
posix_sems_hold();
struct posix_sem **link = &g_posix_sems;
while (*link && (*link)->addr != sem) link = &(*link)->next;
struct posix_sem *e = *link;
if (e && --e->refs == 0) {
*link = e->next;
munmap(e->addr, sizeof(sem_t));
free(e);
}
posix_sems_unlock();
if (!e) { errno = EINVAL; return -1; }
return 0;
}
int sem_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
+1 -126
View File
@@ -6,17 +6,7 @@
#ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name) + strlen(prefix);
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
#include "../../linuxfs/preload/named_semaphores.h"
int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX];
@@ -30,121 +20,6 @@ int shm_unlink(const char *name) {
return unlink(path);
}
struct posix_sem {
dev_t dev;
ino_t ino;
sem_t *addr;
unsigned int refs;
struct posix_sem *next;
};
static struct posix_sem *g_posix_sems;
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
__attribute__((constructor)) static void posix_sems_across_fork(void) {
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
}
static void close_keeping_errno(int fd) {
int saved = errno;
close(fd);
errno = saved;
}
static sem_t *posix_sem_map(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return SEM_FAILED;
sem_t *sem = SEM_FAILED;
posix_sems_hold();
struct posix_sem *e = g_posix_sems;
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
if (e) {
e->refs++;
sem = e->addr;
} else {
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
if (e) {
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
g_posix_sems = e;
sem = addr;
} else if (addr != MAP_FAILED) {
munmap(addr, sizeof(sem_t));
errno = ENOMEM;
}
}
posix_sems_unlock();
return sem;
}
static sem_t *posix_sem_open_fd(int fd) {
if (fd < 0) return SEM_FAILED;
sem_t *sem = posix_sem_map(fd);
close_keeping_errno(fd);
return sem;
}
sem_t *sem_open(const char *name, int oflag, ...) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
va_list args;
va_start(args, oflag);
mode_t mode = va_arg(args, mode_t);
unsigned int value = va_arg(args, unsigned int);
va_end(args);
static unsigned int serial;
for (;;) {
if (!(oflag & O_EXCL)) {
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
}
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
sem_t initial;
memset(&initial, 0, sizeof(initial));
sem_init(&initial, 1, value);
char temp[PATH_MAX];
int fd;
do {
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
} while (fd < 0 && errno == EEXIST);
if (fd < 0) return SEM_FAILED;
errno = EIO;
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
close_keeping_errno(fd);
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
int saved = errno;
if (sem != SEM_FAILED) sem_close(sem);
unlink(temp);
errno = saved;
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
}
}
int sem_close(sem_t *sem) {
posix_sems_hold();
struct posix_sem **link = &g_posix_sems;
while (*link && (*link)->addr != sem) link = &(*link)->next;
struct posix_sem *e = *link;
if (e && --e->refs == 0) {
*link = e->next;
munmap(e->addr, sizeof(sem_t));
free(e);
}
posix_sems_unlock();
if (!e) { errno = EINVAL; return -1; }
return 0;
}
int sem_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
#endif /* !DDNATV_HOST_TEST */
@@ -0,0 +1,140 @@
from pathlib import Path
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import unittest
from tools.tests.test_native_hook_named_semaphores import CALLS, KEEP, PROBE
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
DENY_LINKS = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_link, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_linkat, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return 125;
execvp(argv[1], argv + 1);
return 126;
}
"""
OPEN_EXISTING = r"""
#include <fcntl.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char **argv) {
sem_t *sem = sem_open(argv[1], 0);
int value;
if (sem == SEM_FAILED || sem_getvalue(sem, &value) || value != atoi(argv[2])) return 1;
return sem_trywait(sem) || sem_close(sem);
}
"""
PYTHON_PROBE = '''
import multiprocessing as mp
import _multiprocessing
import os
import sys
def square(n):
return n * n
if __name__ == "__main__":
name = "/dd-py-sem-" + str(os.getpid())
sem = _multiprocessing.SemLock(1, 1, 1, name, True)
assert sem.acquire(False)
assert not sem.acquire(False)
sem.release()
for method in mp.get_all_start_methods():
ctx = mp.get_context(method)
lock = ctx.Lock()
with lock:
assert not lock.acquire(False)
queue = ctx.Queue()
queue.put(7)
assert queue.get(timeout=10) == 7
queue.close()
queue.join_thread()
with ctx.Pool(2) as pool:
assert pool.map(square, [1, 2, 3]) == [1, 4, 9]
print(method, flush=True)
'''
@unittest.skipUnless(platform.machine() == "x86_64" and shutil.which("cc"), "needs an x86-64 compiler and host")
class NamedSemaphoresPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.tmp.cleanup)
cls.root = Path(cls.tmp.name)
cls.lib = cls.root / "semaphores.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Werror", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "named_semaphores.c")], check=True)
for name, source in (("deny", DENY_LINKS), ("probe", PROBE), ("keep", KEEP), ("existing", OPEN_EXISTING)):
path = cls.root / (name + ".c")
path.write_text(source)
subprocess.run(["cc", "-pthread", "-o", str(cls.root / name), str(path)], check=True)
cls.script = cls.root / "pool.py"
cls.script.write_text(PYTHON_PROBE)
def run_program(self, args, hooked=True, denied=True):
env = dict(os.environ)
env.pop("LD_PRELOAD", None)
if hooked:
env["LD_PRELOAD"] = str(self.lib)
command = ([str(self.root / "deny")] if denied else []) + list(map(str, args))
return subprocess.run(command, env=env, text=True, capture_output=True, timeout=60)
def test_glibc_semlock_fails_when_hard_links_are_denied(self):
result = self.run_program([sys.executable, "-c",
"import multiprocessing; multiprocessing.Lock()"], hooked=False)
self.assertNotEqual(0, result.returncode)
self.assertIn("PermissionError: [Errno 1]", result.stderr)
def test_named_semaphore_contract_with_and_without_hard_links(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([self.root / "probe", f"/dd-preload-{os.getpid()}-{int(denied)}"], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({call: "1" for call in CALLS}, dict(line.split("\t") for line in result.stdout.splitlines()))
def test_semaphores_remain_compatible_with_glibc_and_keep_the_requested_mode(self):
for hooked in (True, False):
with self.subTest(creator_hooked=hooked):
name = f"/dd-preload-existing-{os.getpid()}-{int(hooked)}"
path = Path("/dev/shm/sem." + name[1:])
self.addCleanup(path.unlink, missing_ok=True)
result = self.run_program([self.root / "keep", name], hooked=hooked, denied=hooked)
self.assertEqual(0, result.returncode, result.stderr)
umask = os.umask(0)
os.umask(umask)
self.assertEqual(0o640 & ~umask, path.stat().st_mode & 0o777)
for reader, value in ((not hooked, 3), (hooked, 2)):
result = self.run_program([self.root / "existing", name, value], hooked=reader, denied=reader)
self.assertEqual(0, result.returncode, result.stderr)
def test_python_semlock_queues_and_explicit_pool_contexts(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([sys.executable, self.script], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({"fork", "forkserver", "spawn"}, set(result.stdout.splitlines()))