diff --git a/Cargo.lock b/Cargo.lock index a51d11de3cf..03718b55e40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,6 +842,7 @@ checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" dependencies = [ "compression-codecs", "compression-core", + "futures-io", "pin-project-lite", "tokio", ] @@ -1142,6 +1143,22 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "async_zip" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c50d65ce1b0e0cb65a785ff615f78860d7754290647d3b983208daa4f85e6" +dependencies = [ + "async-compression", + "chrono", + "crc32fast", + "futures-lite", + "pin-project", + "thiserror 2.0.21", + "tokio", + "tokio-util", +] + [[package]] name = "atk" version = "0.18.2" @@ -2977,7 +2994,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" dependencies = [ "brotli 9.0.0", + "bzip2", "compression-core", + "deflate64", "flate2", "memchr", "zstd", @@ -4319,6 +4338,18 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -4595,6 +4626,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "file-id" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1fc6a637b6dc58414714eddd9170ff187ecb0933d4c7024d1abbd23a3cc26e9" +dependencies = [ + "windows-sys 0.60.2", +] + [[package]] name = "filetime" version = "0.2.29" @@ -4781,6 +4821,26 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "fuser" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b82b6597d216503555ead6b358f341ef748869bf5c6fbae6a0cb9dd231baecfd" +dependencies = [ + "bitflags 2.13.2", + "libc", + "log", + "memchr", + "nix", + "num_enum", + "page_size", + "parking_lot", + "pkg-config", + "ref-cast", + "smallvec", + "zerocopy", +] + [[package]] name = "futf" version = "0.1.5" @@ -6992,6 +7052,24 @@ dependencies = [ "libc", ] +[[package]] +name = "libseccomp" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e5310a2c5b6ffbc094b5f70a2ca7b79ed36ad90e6f90994b166489a1bce3fcc" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libseccomp-sys", + "pkg-config", +] + +[[package]] +name = "libseccomp-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60276e2d41bbb68b323e566047a1bfbf952050b157d8b5cdc74c07c1bf4ca3b6" + [[package]] name = "libsqlite3-sys" version = "0.30.1" @@ -8335,6 +8413,53 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "modrinth-sandbox" +version = "0.1.0" +dependencies = [ + "ashpd", + "async-trait", + "async_zip", + "bitflags 2.13.2", + "block2", + "clap 4.6.7", + "derive_more 2.1.1", + "directories", + "dispatch2", + "enum_dispatch", + "eyre", + "fuser", + "futures", + "hex", + "httparse", + "indexmap 2.14.2", + "infer 0.22.0", + "libc", + "libseccomp", + "objc2-app-kit", + "objc2-foundation", + "objc2-uniform-type-identifiers", + "open", + "parking_lot", + "rand 0.10.3", + "reqwest 0.13.5", + "rustix 1.1.5", + "scopeguard", + "serde", + "serde_json", + "sha1 0.11.0", + "tempfile", + "tokio", + "tracing", + "tracing-subscriber", + "url", + "urlencoding", + "uuid 1.28.0", + "windows 0.61.3", + "winreg", + "zbus 6.0.0", +] + [[package]] name = "modrinth-util" version = "0.0.0" @@ -8539,6 +8664,7 @@ dependencies = [ "cfg-if", "cfg_aliases", "libc", + "memoffset", ] [[package]] @@ -8615,15 +8741,16 @@ dependencies = [ ] [[package]] -name = "notify-debouncer-mini" -version = "0.7.0" +name = "notify-debouncer-full" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17849edfaabd9a5fef1c606d99cfc615a8e99f7ac4366406d86c7942a3184cf2" +checksum = "375bd3a138be7bfeff3480e4a623df4cbfb55b79df617c055cd810ba466fa078" dependencies = [ + "file-id", "log", "notify", "notify-types", - "tempfile", + "walkdir", ] [[package]] @@ -8813,10 +8940,18 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2", + "libc", "objc2", + "objc2-cloud-kit", + "objc2-core-data", "objc2-core-foundation", "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", "objc2-foundation", + "objc2-quartz-core", + "objc2-uniform-type-identifiers", ] [[package]] @@ -8836,6 +8971,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" dependencies = [ + "bitflags 2.13.2", "objc2", "objc2-foundation", ] @@ -8896,6 +9032,19 @@ dependencies = [ "objc2-core-graphics", ] +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -8999,6 +9148,17 @@ dependencies = [ "objc2-user-notifications", ] +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-user-notifications" version = "0.3.2" @@ -9340,6 +9500,16 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "page_size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "pango" version = "0.18.3" @@ -13839,8 +14009,9 @@ dependencies = [ "libc", "minecraft-meta-manifest", "modrinth-content-management", + "modrinth-sandbox", "notify", - "notify-debouncer-mini", + "notify-debouncer-full", "p256", "parking_lot", "paste", @@ -13907,6 +14078,7 @@ dependencies = [ "hyper 1.12.0", "hyper-util", "image", + "modrinth-sandbox", "native-dialog", "objc2-app-kit", "p256", diff --git a/Cargo.toml b/Cargo.toml index ca462e9d00d..1013543e9ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "packages/modrinth-content-management", "packages/modrinth-log", "packages/modrinth-maxmind", + "packages/modrinth-sandbox", "packages/modrinth-util", "packages/neverbounce", "packages/path-util", @@ -40,6 +41,7 @@ anyhow = "1.0.104" arc-swap = "1.9.3" argon2 = { version = "0.6.0" } ariadne = { path = "packages/ariadne" } +ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] } async-compression = "0.4.32" async-minecraft-ping = { path = "packages/async-minecraft-ping" } async-recursion = "1.2.0" @@ -55,6 +57,7 @@ async-stripe-webhook = { version = "=1.0.0-rc.10", default-features = false } async-trait = "0.1.92" async-tungstenite = { version = "0.35.0", default-features = false, features = ["futures-03-sink"] } async-walkdir = "2.2.0" +async_zip = "0.0.18" aws-sdk-s3 = { version = "=1.122.0", default-features = false, features = [ "default-https-client", "rt-tokio", @@ -62,6 +65,7 @@ aws-sdk-s3 = { version = "=1.122.0", default-features = false, features = [ ] } base64 = "0.23.1" bitflags = "2.13.2" +block2 = "0.6.2" blocklist = { version = "1.0.0" } bon = "3.10.2" bytemuck = "1.25.2" @@ -89,17 +93,22 @@ dioxus-devtools = "0.7.10" directories = "6.0.0" dirs = "7.0.0" discord-rich-presence = "1.1.0" +dispatch2 = "0.3.1" dotenv-build = "0.1.1" dotenvy = "0.15.7" dunce = "1.0.5" either = "1.19.0" encoding_rs = "0.8.42" +enum_dispatch = { version = "0.3.13" } enumset = "1.1.14" eyre = "0.6.14" figment = { version = "0.10.19" } flate2 = "1.1.10" +foldhash = { version = "0.2.0" } fs4 = { version = "1.1.0", default-features = false } +fuser = "0.18.0" futures = "0.3.34" +futures-lite = "2.6.1" futures-util = "0.3.34" governor = "0.10.4" heck = "0.5.0" @@ -107,6 +116,7 @@ hex = "0.4.3" hickory-resolver = "0.26.3" hkdf = "0.13.0" hmac = "0.13.0" +httparse = "1.10.1" httpdate = "1.0.3" humansize = "2.1.3" hyper = "1.12.0" @@ -139,6 +149,7 @@ lettre = { version = "0.11.23", default-features = false, features = [ "tokio1-rustls", ] } libc = "0.2.191" +libseccomp = "0.4.0" lingua = "=1.8.0" linkify = "0.11.0" lz4_flex = { version = "0.14.0", default-features = false, features = [ @@ -152,14 +163,20 @@ minecraft-meta-manifest = { path = "packages/minecraft-meta-manifest" } minecraft-meta-model = { path = "packages/minecraft-meta-model" } modrinth-content-management = { path = "packages/modrinth-content-management" } modrinth-log = { path = "packages/modrinth-log" } +modrinth-sandbox = { path = "packages/modrinth-sandbox" } modrinth-util = { path = "packages/modrinth-util" } muralpay = { path = "packages/muralpay" } murmur2 = "0.1.0" native-dialog = "0.9.7" neverbounce = { path = "packages/neverbounce" } notify = { version = "8.2.0", default-features = false } +notify-debouncer-full = { version = "0.6.0", default-features = false } notify-debouncer-mini = { version = "0.7.0", default-features = false } -objc2-app-kit = { version = "0.3.2", default-features = false } +objc2 = "0.6.4" +objc2-app-kit = { version = "0.3.2", features = ["objc2-uniform-type-identifiers"] } +objc2-foundation = "0.3.2" +objc2-uniform-type-identifiers = "0.3.2" +open = "5.4.4" p256 = "0.14.0" parking_lot = "0.12.5" paste = "1.0.15" @@ -181,21 +198,23 @@ rand_chacha = "=0.10.0" rdkafka = { version = "0.39.0", features = ["cmake-build"] } redis = "1.7.1" regex = "1.13.1" -reqwest = { version = "0.13.5", default-features = false, features = ["form", "query"] } +reqwest = { version = "0.13.5", default-features = false, features = ["form", "query", "json", "stream"] } rgb = "0.8.53" rhai = "1.27.0" -rust_decimal = { version = "1.43.0", features = ["serde-with-float", "serde-with-str"] } -rust_iso3166 = "0.2.0" rust-s3 = { version = "0.38.0", default-features = false, features = [ "fail-on-err", "tags", "tokio-rustls-tls", ] } +rust_decimal = { version = "1.43.0", features = ["serde-with-float", "serde-with-str"] } +rust_iso3166 = "0.2.0" +rustix = "1.1.5" rustls = { version = "0.23.46", default-features = false } rustrict = { version = "0.7.39", default-features = false, features = ["censor"] } rusty-money = "0.5.1" same-file = "1.0.6" scalar_api_reference = { version = "0.2.16", default-features = false } +scopeguard = "1.2.0" secrecy = "0.10.3" sentry = { version = "0.49.3", default-features = false, features = [ "backtrace", @@ -205,7 +224,7 @@ sentry = { version = "0.49.3", default-features = false, features = [ "reqwest", "rustls", ] } -serde = "1.0.229" +serde = { version = "1.0.229", features = ["rc", "alloc", "derive"] } serde-binhum = { path = "packages/serde-binhum" } serde_bytes = "0.11.19" serde_cbor = "0.11.2" @@ -266,14 +285,14 @@ url = "2.5.8" urlencoding = "2.1.3" utoipa = { version = "6.0.0", features = ["actix_extras", "chrono", "decimal"] } utoipa-actix-web = "0.2.0" -uuid = "1.28.0" +uuid = { version = "1.28.0", features = ["serde"] } validator = "0.21.0" webauthn-rs = "0.5.5" webauthn-rs-proto = "0.5.5" webp = { version = "0.3.1", default-features = false } webview2-com = "=0.38.2" # Must match the bindings used by the pinned Tauri/Wry whoami = "2.1.3" -windows = "=0.61.3" # Must match the bindings used by the pinned Tauri/Wry +windows = { version = "=0.61.3", features = ["Win32_Foundation", "Win32_NetworkManagement_WindowsFirewall", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_Console", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_System_StationsAndDesktops", "Wdk_System_SystemServices", "Win32_System_SystemServices", "Win32_System_SystemInformation", "Win32_System_WindowsProgramming", "Win32_Security", "Win32_Security_Isolation", "Win32_Security_Credentials", "Win32_Security_Authorization"] } # Must match the bindings used by the pinned Tauri/Wry windows-core = "=0.61.2" winreg = "0.56.0" woothee = "0.13.0" diff --git a/apps/app-frontend/src/features/instances/settings-modal/index.vue b/apps/app-frontend/src/features/instances/settings-modal/index.vue index e223e941715..eae0fc557fe 100644 --- a/apps/app-frontend/src/features/instances/settings-modal/index.vue +++ b/apps/app-frontend/src/features/instances/settings-modal/index.vue @@ -5,6 +5,7 @@ import { CoffeeIcon, InfoIcon, Settings2Icon, + ShieldIcon, UsersIcon, WindowIcon, WrenchIcon, @@ -35,6 +36,7 @@ import HooksSettings from './hooks-settings.vue' import InstallationSettings from './installation-settings.vue' import { provideInstanceSettings } from './instance-settings-context.ts' import JavaSettings from './java-settings.vue' +import SandboxSettings from './sandbox-settings.vue' import SharingSettings from './sharing-settings/index.vue' import SyncedOptionsSettings from './synced-options-settings.vue' import WindowSettings from './window-settings.vue' @@ -146,6 +148,15 @@ const tabs = computed(() => [ content: SharingSettings, shown: props.instance.shared_instance?.role === 'owner' && !props.instance.quarantined, }, + { + name: defineMessage({ + id: 'instance.settings.tabs.sandbox', + defaultMessage: 'Sandboxing', + }), + icon: ShieldIcon, + category: tabCategories.game, + content: SandboxSettings, + }, { name: defineMessage({ id: 'instance.settings.tabs.java.label', diff --git a/apps/app-frontend/src/features/instances/settings-modal/sandbox-settings.vue b/apps/app-frontend/src/features/instances/settings-modal/sandbox-settings.vue new file mode 100644 index 00000000000..8a871f159ba --- /dev/null +++ b/apps/app-frontend/src/features/instances/settings-modal/sandbox-settings.vue @@ -0,0 +1,100 @@ + + + diff --git a/apps/app-frontend/src/features/settings/app-settings-modal/index.vue b/apps/app-frontend/src/features/settings/app-settings-modal/index.vue index a669ece1b69..b3cee4613eb 100644 --- a/apps/app-frontend/src/features/settings/app-settings-modal/index.vue +++ b/apps/app-frontend/src/features/settings/app-settings-modal/index.vue @@ -11,6 +11,7 @@ import { PaintbrushIcon, RefreshCwIcon, Settings2Icon, + ShieldIcon, ToggleRightIcon, UserIcon, WindowIcon, @@ -43,6 +44,7 @@ import FeaturesSettings from '@/features/settings/display/features-settings.vue' import LanguageSettings from '@/features/settings/display/language-settings.vue' import JavaAndMemorySettings from '@/features/settings/instance-defaults/java-and-memory-settings/index.vue' import LaunchHooksSettings from '@/features/settings/instance-defaults/launch-hooks-settings.vue' +import SandboxSettings from '@/features/settings/instance-defaults/sandbox-settings.vue' import WindowSettings from '@/features/settings/instance-defaults/window-settings.vue' import type { InstanceDefaultsTab } from '@/features/settings/settings-actions' import SyncingSettings from '@/features/settings/syncing/syncing-settings.vue' @@ -153,6 +155,15 @@ const tabs = [ icon: EyeOffIcon, content: PrivacySettings, }, + { + name: defineMessage({ + id: 'app.settings.tabs.sandbox', + defaultMessage: 'Sandboxing', + }), + category: tabCategories.instanceDefaults, + icon: ShieldIcon, + content: SandboxSettings, + }, { name: defineMessage({ id: 'app.settings.tabs.java-and-memory', @@ -260,6 +271,7 @@ function showSyncedOptions(): void { function showInstanceDefaults(tab: InstanceDefaultsTab): void { const content = { + sandbox: SandboxSettings, java: JavaAndMemorySettings, window: WindowSettings, hooks: LaunchHooksSettings, diff --git a/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings-form.vue b/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings-form.vue new file mode 100644 index 00000000000..babaf7800ae --- /dev/null +++ b/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings-form.vue @@ -0,0 +1,356 @@ + + + diff --git a/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings.vue b/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings.vue new file mode 100644 index 00000000000..d31b5193fea --- /dev/null +++ b/apps/app-frontend/src/features/settings/instance-defaults/sandbox-settings.vue @@ -0,0 +1,27 @@ + + + diff --git a/apps/app-frontend/src/features/settings/settings-actions.ts b/apps/app-frontend/src/features/settings/settings-actions.ts index 615cdf702bf..e7bfa5158e8 100644 --- a/apps/app-frontend/src/features/settings/settings-actions.ts +++ b/apps/app-frontend/src/features/settings/settings-actions.ts @@ -1,6 +1,6 @@ import { createContext } from '@modrinth/ui' -export type InstanceDefaultsTab = 'java' | 'window' | 'hooks' +export type InstanceDefaultsTab = 'sandbox' | 'java' | 'window' | 'hooks' /** * Opens the app settings modal from anywhere in the app, optionally on a specific tab. diff --git a/apps/app-frontend/src/helpers/settings.ts b/apps/app-frontend/src/helpers/settings.ts index 29a9e79c7b5..b04bdac7810 100644 --- a/apps/app-frontend/src/helpers/settings.ts +++ b/apps/app-frontend/src/helpers/settings.ts @@ -8,7 +8,7 @@ import { invoke } from '@tauri-apps/api/core' import type { FeatureFlag } from '@/composables/use-app-settings.ts' import type { ColorTheme } from '@/composables/use-theme.ts' -import type { Hooks, MemorySettings, WindowSize } from '@/helpers/types' +import type { Hooks, MemorySettings, SandboxSettings, WindowSize } from '@/helpers/types' // Settings object /* @@ -78,6 +78,7 @@ export type AppSettings = { warn_on_unknown_modpacks: boolean skip_non_essential_warnings: boolean hooks: Hooks + sandbox: SandboxSettings custom_dir?: string | null prev_custom_dir?: string | null @@ -137,6 +138,10 @@ export async function set(settings: AppSettings) { return await invoke('plugin:settings|settings_set', { settings }) } +export async function getSandboxUnavailableReason(): Promise { + return await invoke('plugin:settings|settings_sandbox_unavailable_reason') +} + export async function cancel_directory_change(): Promise { return await invoke('plugin:settings|cancel_directory_change') } diff --git a/apps/app-frontend/src/helpers/types.d.ts b/apps/app-frontend/src/helpers/types.d.ts index 2791ead9e3c..b2e7e8c9a2c 100644 --- a/apps/app-frontend/src/helpers/types.d.ts +++ b/apps/app-frontend/src/helpers/types.d.ts @@ -49,6 +49,7 @@ export type GameInstance = { force_fullscreen?: boolean game_resolution?: [number, number] hooks: Hooks + sandbox: SandboxOverrides visible_tabs: { files: boolean worlds: boolean @@ -179,6 +180,20 @@ type Hooks = { post_exit?: string } +type SandboxMode = 'never' | 'unrecognized' | 'always' + +type SandboxSettings = { + mode: SandboxMode + allow_network: boolean + allow_downloads: boolean + allow_documents: boolean + extra_paths: string[] +} + +type SandboxOverrides = { + [K in keyof SandboxSettings]: SandboxSettings[K] | null +} + export type Manifest = { gameVersions: ManifestGameVersion[] versionGroups?: ManifestVersionGroup[] @@ -246,6 +261,7 @@ export type AppSettings = { warn_on_unknown_modpacks: boolean skip_non_essential_warnings: boolean hooks: Hooks + sandbox: SandboxSettings custom_dir?: string prev_custom_dir?: string diff --git a/apps/app-frontend/src/locales/en-US/index.json b/apps/app-frontend/src/locales/en-US/index.json index ee5c83c6183..4902ec6cca1 100644 --- a/apps/app-frontend/src/locales/en-US/index.json +++ b/apps/app-frontend/src/locales/en-US/index.json @@ -3128,6 +3128,81 @@ "app.settings.resource-management.store.unused.label": { "message": "Orphaned" }, + "app.settings.sandbox.always": { + "message": "Always" + }, + "app.settings.sandbox.always.description": { + "message": "Run instances always in the sandbox." + }, + "app.settings.sandbox.description": { + "message": "Runs Minecraft in an isolated environment, so mods can only access your .minecraft folder and anything you allow below." + }, + "app.settings.sandbox.documents": { + "message": "Access documents folder" + }, + "app.settings.sandbox.documents.description": { + "message": "Allows access to files in your Documents folder." + }, + "app.settings.sandbox.downloads": { + "message": "Access downloads folder" + }, + "app.settings.sandbox.downloads.description": { + "message": "Allows access to files in your Downloads folder." + }, + "app.settings.sandbox.folders": { + "message": "Access other folders" + }, + "app.settings.sandbox.folders.add": { + "message": "Add" + }, + "app.settings.sandbox.folders.browse": { + "message": "Browse for a folder" + }, + "app.settings.sandbox.folders.description": { + "message": "Allows mods to read or modify files you choose. Only add folders you’re comfortable giving them access to." + }, + "app.settings.sandbox.folders.placeholder": { + "message": "Path to folder..." + }, + "app.settings.sandbox.instance.always.description": { + "message": "Always run this instance in the sandbox." + }, + "app.settings.sandbox.instance.never.description": { + "message": "Run this instance with full access to your computer." + }, + "app.settings.sandbox.instance.title": { + "message": "Sandbox instance" + }, + "app.settings.sandbox.instance.unrecognized.description": { + "message": "Sandbox this instance if it contains files not from Modrinth." + }, + "app.settings.sandbox.network": { + "message": "Access network" + }, + "app.settings.sandbox.network.description": { + "message": "Allows connections to the internet, multiplayer servers, and online services." + }, + "app.settings.sandbox.never": { + "message": "Never" + }, + "app.settings.sandbox.never.description": { + "message": "Run instances with full access to your computer." + }, + "app.settings.sandbox.title": { + "message": "Sandbox instances" + }, + "app.settings.sandbox.unavailable": { + "message": "Sandboxing is unavailable on this system, so instances that need the sandbox will not launch: {reason}" + }, + "app.settings.sandbox.unrecognized": { + "message": "Unrecognized files" + }, + "app.settings.sandbox.unrecognized.description": { + "message": "Sandbox instances containing files not from Modrinth." + }, + "app.settings.sandbox.warning": { + "message": "Some mods may not work if they require access blocked by the sandbox." + }, "app.settings.sidebar.label.instance-defaults": { "message": "Instance defaults" }, @@ -3383,6 +3458,9 @@ "app.settings.tabs.resources": { "message": "Resources" }, + "app.settings.tabs.sandbox": { + "message": "Sandboxing" + }, "app.settings.tabs.syncing": { "message": "Syncing" }, @@ -4316,6 +4394,12 @@ "instance.settings.tabs.java.recommended-java-version": { "message": "Java {version} is recommended for the Minecraft version of this instance." }, + "instance.settings.tabs.sandbox": { + "message": "Sandboxing" + }, + "instance.settings.tabs.sandbox.default-settings-description": { + "message": "Your instance uses the default sandbox permissions unless you override them here." + }, "instance.settings.tabs.sharing": { "message": "Sharing" }, diff --git a/apps/app/Cargo.toml b/apps/app/Cargo.toml index f8c9bb12d9f..1b6162b2e1a 100644 --- a/apps/app/Cargo.toml +++ b/apps/app/Cargo.toml @@ -20,6 +20,7 @@ hkdf = { workspace = true } hyper = { workspace = true, features = ["server"] } hyper-util = { workspace = true } image = { workspace = true, features = ["gif", "jpeg", "png", "webp"] } +modrinth-sandbox = { workspace = true } native-dialog = { workspace = true } p256 = { workspace = true, features = ["ecdh"] } paste = { workspace = true } diff --git a/apps/app/build.rs b/apps/app/build.rs index 5413d1ba5a1..e05118a14fd 100644 --- a/apps/app/build.rs +++ b/apps/app/build.rs @@ -339,6 +339,7 @@ fn main() { "store_set_cache_limit", "cancel_directory_change", "default_app_directory", + "settings_sandbox_unavailable_reason", ]) .default_permission( DefaultPermissionRule::AllowAllCommands, diff --git a/apps/app/src/api/instance.rs b/apps/app/src/api/instance.rs index 56eb01ebdc8..b33b94c6c34 100644 --- a/apps/app/src/api/instance.rs +++ b/apps/app/src/api/instance.rs @@ -174,6 +174,7 @@ pub struct Instance { pub force_fullscreen: Option, pub game_resolution: Option, pub hooks: Hooks, + pub sandbox: SandboxOverrides, pub visible_tabs: InstanceTabVisibility, } @@ -317,6 +318,7 @@ pub struct EditInstance { )] pub game_resolution: Option>, pub hooks: Option, + pub sandbox: Option, pub visible_tabs: Option, } @@ -358,6 +360,7 @@ impl From for Instance { force_fullscreen: metadata.launch_overrides.force_fullscreen, game_resolution: metadata.launch_overrides.game_resolution, hooks: metadata.launch_overrides.hooks, + sandbox: metadata.launch_overrides.sandbox, visible_tabs: metadata.launch_overrides.visible_tabs, } } @@ -517,6 +520,7 @@ fn edit_to_core(edit_instance: EditInstance) -> Result { force_fullscreen: edit_instance.force_fullscreen, game_resolution: edit_instance.game_resolution, hooks: edit_instance.hooks, + sandbox: edit_instance.sandbox, visible_tabs: edit_instance.visible_tabs, }), content_set_patch: Some(AppliedContentSetPatch { diff --git a/apps/app/src/api/settings.rs b/apps/app/src/api/settings.rs index 8068f682612..cc688c6174a 100644 --- a/apps/app/src/api/settings.rs +++ b/apps/app/src/api/settings.rs @@ -11,7 +11,8 @@ pub fn init() -> tauri::plugin::TauriPlugin { store_cleanup, store_set_cache_limit, cancel_directory_change, - default_app_directory + default_app_directory, + settings_sandbox_unavailable_reason ]) .build() } @@ -21,6 +22,11 @@ pub async fn default_app_directory() -> Result { Ok(settings::default_app_directory().await?) } +#[tauri::command] +pub async fn settings_sandbox_unavailable_reason() -> Result> { + Ok(settings::sandbox_unavailable_reason().await?) +} + #[tauri::command] pub async fn store_usage() -> Result { Ok(settings::store_usage().await?) diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index 5347d24003a..81e1011f4fb 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -115,6 +115,15 @@ async fn set_restart_after_pending_update( // if Tauri app is called with arguments, then those arguments will be treated as commands // ie: deep links or filepaths for .mrpacks fn main() { + match modrinth_sandbox::helper::run_default() { + Ok(true) => return, + Ok(false) => {} + Err(error) => { + eprintln!("Error running sandbox helper: {error:?}"); + std::process::exit(1); + } + } + theseus::install_crypto_provider(); let runtime = tokio::runtime::Builder::new_multi_thread() diff --git a/packages/app-lib/.sqlx/query-781feeaa43114c4ebefa5d3200db329a3bdaa66917e8c798e4e6d1830d3e5320.json b/packages/app-lib/.sqlx/query-b8b0d22d03f99a44eba392065bcd883999fc11891f09182e93428f1787b2633e.json similarity index 93% rename from packages/app-lib/.sqlx/query-781feeaa43114c4ebefa5d3200db329a3bdaa66917e8c798e4e6d1830d3e5320.json rename to packages/app-lib/.sqlx/query-b8b0d22d03f99a44eba392065bcd883999fc11891f09182e93428f1787b2633e.json index 21c02a7dfec..d9280744c2d 100644 --- a/packages/app-lib/.sqlx/query-781feeaa43114c4ebefa5d3200db329a3bdaa66917e8c798e4e6d1830d3e5320.json +++ b/packages/app-lib/.sqlx/query-b8b0d22d03f99a44eba392065bcd883999fc11891f09182e93428f1787b2633e.json @@ -1,12 +1,12 @@ { "db_name": "SQLite", - "query": "\n UPDATE settings\n SET\n max_concurrent_writes = $1,\n max_concurrent_downloads = $2,\n\n theme = $3,\n locale = $4,\n default_page = $5,\n collapsed_navigation = $6,\n advanced_rendering = $7,\n native_decorations = $8,\n\n discord_rpc = $9,\n developer_mode = $10,\n telemetry = $11,\n personalized_ads = $12,\n\n extra_launch_args = jsonb($13),\n custom_env_vars = jsonb($14),\n mc_memory_max = $15,\n mc_force_fullscreen = $16,\n mc_game_resolution_x = $17,\n mc_game_resolution_y = $18,\n hide_on_process_start = $19,\n\n hook_pre_launch = $20,\n hook_wrapper = $21,\n hook_post_exit = $22,\n\n custom_dir = $23,\n prev_custom_dir = $24,\n migrated = $25,\n\n toggle_sidebar = $26,\n feature_flags = $27,\n hide_nametag_skins_page = $28,\n\n skipped_update = $29,\n pending_update_toast_for_version = $30,\n auto_download_updates = $31,\n\n sync_theme_across_devices = $32,\n sync_behavior_across_devices = $33,\n\t\t\t\tsync_features_across_devices = $34,\n\t\t\t\tshow_files_tab_in_instances = $35,\n\t\t\t\tshow_worlds_tab_in_instances = $36,\n\t\t\t\tshow_screenshots_tab_in_instances = $37,\n\t\t\t\tshow_skin_selector_in_sidebar = $38,\n\n\t\t\t\tversion = $39,\n\t\t\t\trefocus_on_game_close = $40,\n\t\t\t\tcompact_instance_cards = $41,\n\t\t\t\tshow_play_time = $42,\n\t\t\t\twarn_on_unknown_modpacks = $43,\n\t\t\t\tskip_non_essential_warnings = $44,\n\t\t\t\tshow_jump_in = $45,\n\t\t\t\talways_show_copy_details = $46,\n\t\t\t\thide_installed_modpacks = $47,\n\t\t\t\tadvanced_filters_collapsed = $48,\n\t\t\t\tdismissed_photosensitivity_filter_warning = $49,\n\t\t\t\tfriends_active_collapsed = $50,\n\t\t\t\tfriends_online_collapsed = $51,\n\t\t\t\tfriends_offline_collapsed = $52,\n\t\t\t\tfriends_pending_collapsed = $53\n ", + "query": "\n UPDATE settings\n SET\n max_concurrent_writes = $1,\n max_concurrent_downloads = $2,\n\n theme = $3,\n locale = $4,\n default_page = $5,\n collapsed_navigation = $6,\n advanced_rendering = $7,\n native_decorations = $8,\n\n discord_rpc = $9,\n developer_mode = $10,\n telemetry = $11,\n personalized_ads = $12,\n\n extra_launch_args = jsonb($13),\n custom_env_vars = jsonb($14),\n mc_memory_max = $15,\n mc_force_fullscreen = $16,\n mc_game_resolution_x = $17,\n mc_game_resolution_y = $18,\n hide_on_process_start = $19,\n\n hook_pre_launch = $20,\n hook_wrapper = $21,\n hook_post_exit = $22,\n\n custom_dir = $23,\n prev_custom_dir = $24,\n migrated = $25,\n\n toggle_sidebar = $26,\n feature_flags = $27,\n hide_nametag_skins_page = $28,\n\n skipped_update = $29,\n pending_update_toast_for_version = $30,\n auto_download_updates = $31,\n\n sync_theme_across_devices = $32,\n sync_behavior_across_devices = $33,\n\t\t\t\tsync_features_across_devices = $34,\n\t\t\t\tshow_files_tab_in_instances = $35,\n\t\t\t\tshow_worlds_tab_in_instances = $36,\n\t\t\t\tshow_screenshots_tab_in_instances = $37,\n\t\t\t\tshow_skin_selector_in_sidebar = $38,\n\n\t\t\t\tversion = $39,\n\t\t\t\trefocus_on_game_close = $40,\n\t\t\t\tcompact_instance_cards = $41,\n\t\t\t\tshow_play_time = $42,\n\t\t\t\twarn_on_unknown_modpacks = $43,\n\t\t\t\tskip_non_essential_warnings = $44,\n\t\t\t\tshow_jump_in = $45,\n\t\t\t\talways_show_copy_details = $46,\n\t\t\t\thide_installed_modpacks = $47,\n\t\t\t\tadvanced_filters_collapsed = $48,\n\t\t\t\tdismissed_photosensitivity_filter_warning = $49,\n\t\t\t\tfriends_active_collapsed = $50,\n\t\t\t\tfriends_online_collapsed = $51,\n\t\t\t\tfriends_offline_collapsed = $52,\n\t\t\t\tfriends_pending_collapsed = $53,\n\t\t\t\tsandbox = jsonb($54)\n ", "describe": { "columns": [], "parameters": { - "Right": 53 + "Right": 54 }, "nullable": [] }, - "hash": "781feeaa43114c4ebefa5d3200db329a3bdaa66917e8c798e4e6d1830d3e5320" + "hash": "b8b0d22d03f99a44eba392065bcd883999fc11891f09182e93428f1787b2633e" } diff --git a/packages/app-lib/.sqlx/query-73280fdb7c56d365237cbda6eafe9b137ebf2cb7af6dcaa7f62ab53f9e359ba1.json b/packages/app-lib/.sqlx/query-be6898466740f9675fd569c2bff09f507d79c0445878d3016d69b29ed457869b.json similarity index 92% rename from packages/app-lib/.sqlx/query-73280fdb7c56d365237cbda6eafe9b137ebf2cb7af6dcaa7f62ab53f9e359ba1.json rename to packages/app-lib/.sqlx/query-be6898466740f9675fd569c2bff09f507d79c0445878d3016d69b29ed457869b.json index f83b21f5aaa..dd793aebe08 100644 --- a/packages/app-lib/.sqlx/query-73280fdb7c56d365237cbda6eafe9b137ebf2cb7af6dcaa7f62ab53f9e359ba1.json +++ b/packages/app-lib/.sqlx/query-be6898466740f9675fd569c2bff09f507d79c0445878d3016d69b29ed457869b.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "\n SELECT\n max_concurrent_writes, max_concurrent_downloads,\n theme, locale, default_page, collapsed_navigation, hide_nametag_skins_page, advanced_rendering, native_decorations,\n discord_rpc, developer_mode, telemetry, personalized_ads,\n json(extra_launch_args) extra_launch_args, json(custom_env_vars) custom_env_vars,\n mc_memory_max, mc_force_fullscreen, mc_game_resolution_x, mc_game_resolution_y, hide_on_process_start,\n hook_pre_launch, hook_wrapper, hook_post_exit,\n custom_dir, prev_custom_dir, migrated, json(feature_flags) feature_flags, toggle_sidebar,\n skipped_update, pending_update_toast_for_version, auto_download_updates,\n\t\t\t\tsync_theme_across_devices, sync_behavior_across_devices, sync_features_across_devices,\n\t\t\t\tshow_files_tab_in_instances, show_worlds_tab_in_instances,\n\t\t\t\tshow_screenshots_tab_in_instances, show_skin_selector_in_sidebar,\n\t\t\t\trefocus_on_game_close, compact_instance_cards, show_play_time, warn_on_unknown_modpacks, skip_non_essential_warnings,\n\t\t\t\tshow_jump_in,\n\t\t\t\talways_show_copy_details,\n\t\t\t\thide_installed_modpacks,\n\t\t\t\tadvanced_filters_collapsed,\n\t\t\t\tdismissed_photosensitivity_filter_warning,\n\t\t\t\tfriends_active_collapsed,\n\t\t\t\tfriends_online_collapsed,\n\t\t\t\tfriends_offline_collapsed,\n\t\t\t\tfriends_pending_collapsed,\n version\n FROM settings\n ", + "query": "\n SELECT\n max_concurrent_writes, max_concurrent_downloads,\n theme, locale, default_page, collapsed_navigation, hide_nametag_skins_page, advanced_rendering, native_decorations,\n discord_rpc, developer_mode, telemetry, personalized_ads,\n json(extra_launch_args) extra_launch_args, json(custom_env_vars) custom_env_vars,\n mc_memory_max, mc_force_fullscreen, mc_game_resolution_x, mc_game_resolution_y, hide_on_process_start,\n hook_pre_launch, hook_wrapper, hook_post_exit, json(sandbox) sandbox,\n custom_dir, prev_custom_dir, migrated, json(feature_flags) feature_flags, toggle_sidebar,\n skipped_update, pending_update_toast_for_version, auto_download_updates,\n\t\t\t\tsync_theme_across_devices, sync_behavior_across_devices, sync_features_across_devices,\n\t\t\t\tshow_files_tab_in_instances, show_worlds_tab_in_instances,\n\t\t\t\tshow_screenshots_tab_in_instances, show_skin_selector_in_sidebar,\n\t\t\t\trefocus_on_game_close, compact_instance_cards, show_play_time, warn_on_unknown_modpacks, skip_non_essential_warnings,\n\t\t\t\tshow_jump_in,\n\t\t\t\talways_show_copy_details,\n\t\t\t\thide_installed_modpacks,\n\t\t\t\tadvanced_filters_collapsed,\n\t\t\t\tdismissed_photosensitivity_filter_warning,\n\t\t\t\tfriends_active_collapsed,\n\t\t\t\tfriends_online_collapsed,\n\t\t\t\tfriends_offline_collapsed,\n\t\t\t\tfriends_pending_collapsed,\n version\n FROM settings\n ", "describe": { "columns": [ { @@ -247,9 +247,15 @@ } }, { - "name": "custom_dir", + "name": "sandbox", "ordinal": 23, "type_info": "Text", + "origin": "Expression" + }, + { + "name": "custom_dir", + "ordinal": 24, + "type_info": "Text", "origin": { "Table": { "table": "settings", @@ -259,7 +265,7 @@ }, { "name": "prev_custom_dir", - "ordinal": 24, + "ordinal": 25, "type_info": "Text", "origin": { "Table": { @@ -270,7 +276,7 @@ }, { "name": "migrated", - "ordinal": 25, + "ordinal": 26, "type_info": "Integer", "origin": { "Table": { @@ -281,13 +287,13 @@ }, { "name": "feature_flags", - "ordinal": 26, + "ordinal": 27, "type_info": "Text", "origin": "Expression" }, { "name": "toggle_sidebar", - "ordinal": 27, + "ordinal": 28, "type_info": "Integer", "origin": { "Table": { @@ -298,7 +304,7 @@ }, { "name": "skipped_update", - "ordinal": 28, + "ordinal": 29, "type_info": "Text", "origin": { "Table": { @@ -309,7 +315,7 @@ }, { "name": "pending_update_toast_for_version", - "ordinal": 29, + "ordinal": 30, "type_info": "Text", "origin": { "Table": { @@ -320,7 +326,7 @@ }, { "name": "auto_download_updates", - "ordinal": 30, + "ordinal": 31, "type_info": "Integer", "origin": { "Table": { @@ -331,7 +337,7 @@ }, { "name": "sync_theme_across_devices", - "ordinal": 31, + "ordinal": 32, "type_info": "Integer", "origin": { "Table": { @@ -342,7 +348,7 @@ }, { "name": "sync_behavior_across_devices", - "ordinal": 32, + "ordinal": 33, "type_info": "Integer", "origin": { "Table": { @@ -353,7 +359,7 @@ }, { "name": "sync_features_across_devices", - "ordinal": 33, + "ordinal": 34, "type_info": "Integer", "origin": { "Table": { @@ -364,7 +370,7 @@ }, { "name": "show_files_tab_in_instances", - "ordinal": 34, + "ordinal": 35, "type_info": "Integer", "origin": { "Table": { @@ -375,7 +381,7 @@ }, { "name": "show_worlds_tab_in_instances", - "ordinal": 35, + "ordinal": 36, "type_info": "Integer", "origin": { "Table": { @@ -386,7 +392,7 @@ }, { "name": "show_screenshots_tab_in_instances", - "ordinal": 36, + "ordinal": 37, "type_info": "Integer", "origin": { "Table": { @@ -397,7 +403,7 @@ }, { "name": "show_skin_selector_in_sidebar", - "ordinal": 37, + "ordinal": 38, "type_info": "Integer", "origin": { "Table": { @@ -408,7 +414,7 @@ }, { "name": "refocus_on_game_close", - "ordinal": 38, + "ordinal": 39, "type_info": "Integer", "origin": { "Table": { @@ -419,7 +425,7 @@ }, { "name": "compact_instance_cards", - "ordinal": 39, + "ordinal": 40, "type_info": "Integer", "origin": { "Table": { @@ -430,7 +436,7 @@ }, { "name": "show_play_time", - "ordinal": 40, + "ordinal": 41, "type_info": "Integer", "origin": { "Table": { @@ -441,7 +447,7 @@ }, { "name": "warn_on_unknown_modpacks", - "ordinal": 41, + "ordinal": 42, "type_info": "Integer", "origin": { "Table": { @@ -452,7 +458,7 @@ }, { "name": "skip_non_essential_warnings", - "ordinal": 42, + "ordinal": 43, "type_info": "Integer", "origin": { "Table": { @@ -463,7 +469,7 @@ }, { "name": "show_jump_in", - "ordinal": 43, + "ordinal": 44, "type_info": "Integer", "origin": { "Table": { @@ -474,7 +480,7 @@ }, { "name": "always_show_copy_details", - "ordinal": 44, + "ordinal": 45, "type_info": "Integer", "origin": { "Table": { @@ -485,7 +491,7 @@ }, { "name": "hide_installed_modpacks", - "ordinal": 45, + "ordinal": 46, "type_info": "Integer", "origin": { "Table": { @@ -496,7 +502,7 @@ }, { "name": "advanced_filters_collapsed", - "ordinal": 46, + "ordinal": 47, "type_info": "Integer", "origin": { "Table": { @@ -507,7 +513,7 @@ }, { "name": "dismissed_photosensitivity_filter_warning", - "ordinal": 47, + "ordinal": 48, "type_info": "Integer", "origin": { "Table": { @@ -518,7 +524,7 @@ }, { "name": "friends_active_collapsed", - "ordinal": 48, + "ordinal": 49, "type_info": "Integer", "origin": { "Table": { @@ -529,7 +535,7 @@ }, { "name": "friends_online_collapsed", - "ordinal": 49, + "ordinal": 50, "type_info": "Integer", "origin": { "Table": { @@ -540,7 +546,7 @@ }, { "name": "friends_offline_collapsed", - "ordinal": 50, + "ordinal": 51, "type_info": "Integer", "origin": { "Table": { @@ -551,7 +557,7 @@ }, { "name": "friends_pending_collapsed", - "ordinal": 51, + "ordinal": 52, "type_info": "Integer", "origin": { "Table": { @@ -562,7 +568,7 @@ }, { "name": "version", - "ordinal": 52, + "ordinal": 53, "type_info": "Integer", "origin": { "Table": { @@ -599,6 +605,7 @@ true, true, true, + null, true, true, false, @@ -631,5 +638,5 @@ false ] }, - "hash": "73280fdb7c56d365237cbda6eafe9b137ebf2cb7af6dcaa7f62ab53f9e359ba1" + "hash": "be6898466740f9675fd569c2bff09f507d79c0445878d3016d69b29ed457869b" } diff --git a/packages/app-lib/Cargo.toml b/packages/app-lib/Cargo.toml index 816d7ee487e..16aabc57a76 100644 --- a/packages/app-lib/Cargo.toml +++ b/packages/app-lib/Cargo.toml @@ -48,8 +48,9 @@ itertools = { workspace = true } json5 = { workspace = true } minecraft-meta-manifest = { workspace = true } modrinth-content-management = { workspace = true } +modrinth-sandbox = { workspace = true } notify = { workspace = true } -notify-debouncer-mini = { workspace = true } +notify-debouncer-full = { workspace = true } p256 = { workspace = true, features = ["ecdsa"] } parking_lot = { workspace = true } paste = { workspace = true } diff --git a/packages/app-lib/migrations/20261116120000_sandbox-settings.sql b/packages/app-lib/migrations/20261116120000_sandbox-settings.sql new file mode 100644 index 00000000000..7d87cc06424 --- /dev/null +++ b/packages/app-lib/migrations/20261116120000_sandbox-settings.sql @@ -0,0 +1,2 @@ +ALTER TABLE settings +ADD COLUMN sandbox JSONB NOT NULL DEFAULT '{}'; diff --git a/packages/app-lib/src/api/instance/run.rs b/packages/app-lib/src/api/instance/run.rs index d5c3f3055aa..7eafa773163 100644 --- a/packages/app-lib/src/api/instance/run.rs +++ b/packages/app-lib/src/api/instance/run.rs @@ -125,6 +125,8 @@ async fn run_credentials( .or(settings.hooks.post_exit) .filter(|hook_command| !hook_command.is_empty()); + let sandbox_settings = + context.launch_overrides.sandbox.apply(settings.sandbox); let memory = context.launch_overrides.memory.unwrap_or(settings.memory); let resolution = context .launch_overrides @@ -280,6 +282,7 @@ async fn run_credentials( &launch_env_args, &mc_set_options, &wrapper, + &sandbox_settings, &memory, &resolution, credentials, diff --git a/packages/app-lib/src/api/instance/synced_options/game_options/locales/mod.rs b/packages/app-lib/src/api/instance/synced_options/game_options/locales/mod.rs index d2c1a9a25ea..42fdc8adc13 100644 --- a/packages/app-lib/src/api/instance/synced_options/game_options/locales/mod.rs +++ b/packages/app-lib/src/api/instance/synced_options/game_options/locales/mod.rs @@ -218,6 +218,21 @@ async fn index_installed_sources(state: &State) -> crate::Result<()> { .await { Ok((document, _)) => document, + Err(error) + if error.chain().any(|cause| { + cause + .downcast_ref::() + .map(|error| error.kind()) + .or_else(|| { + cause + .downcast_ref::() + .map(|error| error.kind()) + }) + == Some(std::io::ErrorKind::NotFound) + }) => + { + continue; + } Err(error) => { tracing::warn!(%error, instance_id = metadata.instance.id, "Game setting locales: options file read failed"); continue; diff --git a/packages/app-lib/src/api/mod.rs b/packages/app-lib/src/api/mod.rs index c0b18051288..f83b5e50a3b 100644 --- a/packages/app-lib/src/api/mod.rs +++ b/packages/app-lib/src/api/mod.rs @@ -33,9 +33,10 @@ pub mod data { InstanceTabVisibility, JavaVersion, LinkedModpackInfo, MemorySettings, ModLoader, ModrinthCredentials, OnboardingChecklist, Organization, OwnerType, ProcessMetadata, Project, ProjectType, ProjectV3, - SearchResult, SearchResults, SearchResultsV3, Settings, - SharedInstanceAttachment, SharedInstanceRole, TeamMember, Theme, User, - UserFriend, Version, WindowSize, + SandboxMode, SandboxOverrides, SandboxSettings, SearchResult, + SearchResults, SearchResultsV3, Settings, SharedInstanceAttachment, + SharedInstanceRole, TeamMember, Theme, User, UserFriend, Version, + WindowSize, }; pub use ariadne::users::UserStatus; pub use modrinth_content_management::{ diff --git a/packages/app-lib/src/api/settings.rs b/packages/app-lib/src/api/settings.rs index 08d2321b9e9..b7cd24a6362 100644 --- a/packages/app-lib/src/api/settings.rs +++ b/packages/app-lib/src/api/settings.rs @@ -3,9 +3,17 @@ pub use crate::state::content_store::StoreUsage; pub use crate::{ State, - state::{Hooks, MemorySettings, Settings, WindowSize}, + state::{ + Hooks, MemorySettings, SandboxMode, SandboxSettings, Settings, + WindowSize, + }, }; +/// Why sandboxing can't be set up on this system, or [`None`] if it's available. +pub async fn sandbox_unavailable_reason() -> crate::Result> { + Ok(State::get().await?.sandbox_env.as_ref().err().cloned()) +} + pub async fn store_usage() -> crate::Result { let state = State::get().await?; state.content_store.usage(&state).await diff --git a/packages/app-lib/src/launcher/args.rs b/packages/app-lib/src/launcher/args.rs index 3906ad26393..e35efffcd9b 100644 --- a/packages/app-lib/src/launcher/args.rs +++ b/packages/app-lib/src/launcher/args.rs @@ -3,47 +3,42 @@ use crate::instance::QuickPlayType; use crate::launcher::library::LibraryExt; use crate::launcher::quick_play_version::QuickPlayServerVersion; use crate::launcher::{QuickPlayVersion, parse_rules}; -use crate::state::Credentials; use crate::{ state::{MemorySettings, WindowSize}, util::{io::IOError, platform::classpath_separator}, }; + use anyhow::Context; use dunce::canonicalize; use itertools::Itertools; -use minecraft_meta_manifest::minecraft::LoggingConfiguration; use minecraft_meta_manifest::{ minecraft::{Argument, ArgumentValue, Library, VersionType}, profile::SidedDataEntry, util::get_path_from_artifact, }; +use modrinth_sandbox::minecraft::JVM_ARGUMENTS; use std::io::{BufRead, BufReader, ErrorKind}; -use std::net::SocketAddr; -use std::path::Path; + +use std::path::{Path, PathBuf}; use uuid::Uuid; // Replaces the space separator with a newline character, as to not split the arguments const TEMPORARY_REPLACE_CHAR: &str = "\n"; +const LAUNCHER_MANAGED_JVM_ARGUMENTS: &[&str] = &[ + "-Dmodrinth.internal.ipc.host", + "-Dmodrinth.internal.ipc.port", +]; + pub fn get_class_paths( libraries_path: &Path, libraries: &[Library], - launcher_class_path: &[&Path], java_arch: &str, minecraft_updated: bool, -) -> crate::Result { - launcher_class_path +) -> crate::Result> { + libraries .iter() - .map(|path| { - Ok(canonicalize(path) - .context(crate::ErrorKind::LauncherError(format!( - "specified class path {} does not exist", - path.display() - )))? - .to_string_lossy() - .to_string()) - }) - .chain(libraries.iter().filter_map(|library| { + .filter_map(|library| { if let Some(rules) = &library.rules && !parse_rules( rules, @@ -59,11 +54,12 @@ pub fn get_class_paths( return None; } - Some(get_lib_path(libraries_path, &library.name, false)) - })) - .process_results(|iter| { - iter.unique().join(classpath_separator(java_arch)) + Some( + get_lib_path(libraries_path, &library.name, false) + .map(PathBuf::from), + ) }) + .process_results(|iter| iter.unique().collect()) } pub fn get_class_paths_jar>( @@ -102,22 +98,14 @@ pub fn get_lib_path( Ok(path.to_string_lossy().to_string()) } -#[allow(clippy::too_many_arguments)] pub fn get_jvm_arguments( arguments: Option<&[Argument]>, - natives_path: &Path, - libraries_path: &Path, - log_configs_path: &Path, - class_paths: &str, - agent_path: &Path, version_name: &str, memory: MemorySettings, custom_args: Vec, java_arch: &str, quick_play_type: &QuickPlayType, quick_play_version: QuickPlayVersion, - log_config: Option<&LoggingConfiguration>, - ipc_addr: SocketAddr, ) -> crate::Result> { let mut parsed_arguments = Vec::new(); @@ -126,56 +114,16 @@ pub fn get_jvm_arguments( args, &mut parsed_arguments, |arg| { - parse_jvm_argument( - arg.to_string(), - natives_path, - libraries_path, - class_paths, - version_name, - java_arch, - ) + Ok(parse_jvm_argument(arg.to_string(), version_name, java_arch)) }, java_arch, quick_play_type, )?; - } else { - parsed_arguments.push(format!( - "-Djava.library.path={}", - canonicalize(natives_path) - .context(crate::ErrorKind::LauncherError(format!( - "specified natives path {} does not exist", - natives_path.display() - )))? - .to_string_lossy() - )); - parsed_arguments.push("-cp".to_string()); - parsed_arguments.push(class_paths.to_string()); + parsed_arguments + .retain(|argument| !is_launcher_managed_jvm_argument(argument)); } parsed_arguments.push(format!("-Xmx{}M", memory.maximum)); - - if let Some(LoggingConfiguration::Log4j2Xml { argument, file }) = log_config - { - let full_path = log_configs_path.join(&file.id); - let full_path = full_path.to_string_lossy(); - parsed_arguments.push(argument.replace("${path}", &full_path)); - } - - parsed_arguments.push(format!( - "-javaagent:{}", - canonicalize(agent_path) - .context(crate::ErrorKind::LauncherError(format!( - "specified java agent path {} does not exist", - agent_path.display() - )))? - .to_string_lossy() - )); - - parsed_arguments - .push(format!("-Dmodrinth.internal.ipc.host={}", ipc_addr.ip())); - parsed_arguments - .push(format!("-Dmodrinth.internal.ipc.port={}", ipc_addr.port())); - parsed_arguments.push(format!( "-Dmodrinth.internal.quickPlay.serverVersion={}", serde_json::to_value(quick_play_version.server)? @@ -192,10 +140,17 @@ pub fn get_jvm_arguments( ]); } - for arg in custom_args { - if !arg.is_empty() { - parsed_arguments.push(arg); + for argument in custom_args { + if argument.is_empty() { + continue; } + if is_launcher_managed_jvm_argument(&argument) { + return Err(crate::ErrorKind::LauncherError(format!( + "Java argument `{argument}` overrides a launcher-managed option" + )) + .into()); + } + parsed_arguments.push(argument); } Ok(parsed_arguments) @@ -203,44 +158,40 @@ pub fn get_jvm_arguments( fn parse_jvm_argument( mut argument: String, - natives_path: &Path, - libraries_path: &Path, - class_paths: &str, version_name: &str, java_arch: &str, -) -> crate::Result { +) -> String { argument.retain(|c| !c.is_whitespace()); - Ok(argument - .replace( - "${natives_directory}", - &canonicalize(natives_path) - .context(crate::ErrorKind::LauncherError(format!( - "specified natives path {} does not exist", - natives_path.display() - )))? - .to_string_lossy(), - ) - .replace( - "${library_directory}", - &canonicalize(libraries_path) - .context(crate::ErrorKind::LauncherError(format!( - "specified libraries path {} does not exist", - libraries_path.display() - )))? - .to_string_lossy(), - ) + argument .replace("${classpath_separator}", classpath_separator(java_arch)) .replace("${launcher_name}", "theseus") .replace("${launcher_version}", env!("CARGO_PKG_VERSION")) .replace("${version_name}", version_name) - .replace("${classpath}", class_paths)) +} + +fn is_launcher_managed_jvm_argument(argument: &str) -> bool { + let argument_name = argument + .find(['=', ':']) + .map_or(argument, |separator| &argument[..separator]); + let argument_name = match argument_name { + "--class-path" | "-classpath" => "-cp", + argument_name => argument_name, + }; + + JVM_ARGUMENTS.contains(&argument_name) + || LAUNCHER_MANAGED_JVM_ARGUMENTS.contains(&argument_name) + || argument.contains("${classpath}") + || argument.contains("${natives_directory}") + || argument.contains("${library_directory}") } #[allow(clippy::too_many_arguments)] -pub async fn get_minecraft_arguments( +pub fn get_minecraft_arguments( arguments: Option<&[Argument]>, legacy_arguments: Option<&str>, - credentials: &Credentials, + access_token: &str, + username: &str, + uuid: Uuid, version: &str, asset_index_name: &str, game_directory: &Path, @@ -251,8 +202,6 @@ pub async fn get_minecraft_arguments( quick_play_type: &QuickPlayType, quick_play_version: QuickPlayVersion, ) -> crate::Result> { - let access_token = credentials.access_token.clone(); - let profile = credentials.maybe_online_profile().await; let mut parsed_arguments = Vec::new(); if let Some(arguments) = arguments { @@ -262,9 +211,9 @@ pub async fn get_minecraft_arguments( |arg| { parse_minecraft_argument( arg, - &access_token, - &profile.name, - profile.id, + access_token, + username, + uuid, version, asset_index_name, game_directory, @@ -281,9 +230,9 @@ pub async fn get_minecraft_arguments( for x in legacy_arguments.split(' ') { parsed_arguments.push(parse_minecraft_argument( &x.replace(' ', TEMPORARY_REPLACE_CHAR), - &access_token, - &profile.name, - profile.id, + access_token, + username, + uuid, version, asset_index_name, game_directory, @@ -338,33 +287,9 @@ fn parse_minecraft_argument( .replace("${user_type}", "msa") .replace("${version_name}", version) .replace("${assets_index_name}", asset_index_name) - .replace( - "${game_directory}", - &canonicalize(game_directory) - .context(crate::ErrorKind::LauncherError(format!( - "specified game directory {} does not exist", - game_directory.display() - )))? - .to_string_lossy(), - ) - .replace( - "${assets_root}", - &canonicalize(assets_directory) - .context(crate::ErrorKind::LauncherError(format!( - "specified assets directory {} does not exist", - assets_directory.display() - )))? - .to_string_lossy(), - ) - .replace( - "${game_assets}", - &canonicalize(assets_directory) - .context(crate::ErrorKind::LauncherError(format!( - "specified assets directory {} does not exist", - assets_directory.display() - )))? - .to_string_lossy(), - ) + .replace("${game_directory}", &game_directory.to_string_lossy()) + .replace("${assets_root}", &assets_directory.to_string_lossy()) + .replace("${game_assets}", &assets_directory.to_string_lossy()) .replace("${version_type}", version_type.as_str()) .replace("${resolution_width}", &resolution.0.to_string()) .replace("${resolution_height}", &resolution.1.to_string()) diff --git a/packages/app-lib/src/launcher/mod.rs b/packages/app-lib/src/launcher/mod.rs index 229bb3703a8..4712c3dc1cd 100644 --- a/packages/app-lib/src/launcher/mod.rs +++ b/packages/app-lib/src/launcher/mod.rs @@ -17,16 +17,17 @@ use crate::server_address::{ServerAddress, parse_server_address}; use crate::state::server_join_log::JoinLogEntry; use crate::state::{ Credentials, DirectoryInfo, InstanceInstallStage, InstanceLaunchContext, - InstanceLink, JavaVersion, MemorySettings, ProcessMetadata, WindowSize, + InstanceLink, JavaVersion, MemorySettings, ProcessMetadata, + SandboxSettings, WindowSize, }; use crate::util::io; use crate::util::rpc::RpcServerBuilder; -use crate::{ErrorKind, State, get_resource_file}; +use crate::{ErrorKind, State}; use anyhow::{Context, bail}; use chrono::Utc; use minecraft_meta_manifest as d; use minecraft_meta_manifest::fabriclike::{LoaderVersion, Manifest}; -use minecraft_meta_manifest::minecraft::{LoggingSide, RuleAction}; +use minecraft_meta_manifest::minecraft::RuleAction; use serde::Deserialize; use sqlx::SqlitePool; use std::future::Future; @@ -38,6 +39,8 @@ mod args; pub(crate) mod hooks; mod library; +mod sandbox; + pub mod download; pub(crate) mod profile; pub mod quick_play_version; @@ -449,343 +452,352 @@ async fn install_minecraft_inner( emit_instance(&instance.id, InstancePayloadType::Edited).await?; let result = Box::pin(async { - let instance_path = - get_instance_full_path(&instance.path, &state.directories)?; - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::ResolvingMinecraft, - None, - phase_details.clone(), - ) - .await?; - } - let (minecraft, version_index) = - resolve_minecraft_manifest(&content_set.game_version, state).await?; - let version = &minecraft.versions[version_index]; - let minecraft_updated = version_index - <= minecraft - .versions - .iter() - .position(|x| x.id == "22w16a") - .unwrap_or(0); - - if content_set.loader != ModLoader::Vanilla - && let Some(reporter) = &reporter - { - reporter - .update( - InstallPhaseId::ResolvingLoader, - None, - phase_details.clone(), - ) - .await?; - } + let instance_path = + get_instance_full_path(&instance.path, &state.directories)?; + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::ResolvingMinecraft, + None, + phase_details.clone(), + ) + .await?; + } + let (minecraft, version_index) = + resolve_minecraft_manifest(&content_set.game_version, state) + .await?; + let version = &minecraft.versions[version_index]; + let minecraft_updated = version_index + <= minecraft + .versions + .iter() + .position(|x| x.id == "22w16a") + .unwrap_or(0); + + if content_set.loader != ModLoader::Vanilla + && let Some(reporter) = &reporter + { + reporter + .update( + InstallPhaseId::ResolvingLoader, + None, + phase_details.clone(), + ) + .await?; + } - let mut loader_version = get_loader_version_from_profile( - &content_set.game_version, - content_set.loader, - content_set.loader_version.as_deref(), - &state.directories, - ) - .await?; + let mut loader_version = get_loader_version_from_profile( + &content_set.game_version, + content_set.loader, + content_set.loader_version.as_deref(), + &state.directories, + ) + .await?; - // If no loader version is selected, try to select the stable version! - if content_set.loader != ModLoader::Vanilla && loader_version.is_none() { - loader_version = get_loader_version_from_profile( - &content_set.game_version, - content_set.loader, - Some("stable"), - &state.directories, - ) - .await?; + // If no loader version is selected, try to select the stable version! + if content_set.loader != ModLoader::Vanilla && loader_version.is_none() + { + loader_version = get_loader_version_from_profile( + &content_set.game_version, + content_set.loader, + Some("stable"), + &state.directories, + ) + .await?; - crate::state::instances::commands::set_applied_content_set_loader_version( + crate::state::instances::commands::set_applied_content_set_loader_version( &instance.id, loader_version.as_ref().map(|x| x.id.as_str()), &state.pool, ) .await?; - } - - let version_jar = loader_version.as_ref().map_or(version.id.to_string(), |it| { - format!("{}-{}", version.id, it.id) - }); - - // Download version info (5) - let mut version_info = download::download_version_info( - state, - version, - loader_version.as_ref(), - Some(repairing), - loading_bar.as_ref(), - reporter.as_ref(), - ) - .await?; - - let key = version_info - .java_version - .as_ref() - .map_or(8, |it| it.major_version); - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::PreparingJava, - Some(InstallProgress { - current: 0, - total: 4, - secondary: None, - }), - InstallPhaseDetails::Java { - major_version: key, - step: InstallJavaStep::Resolving, - }, - ) - .await?; - } - let (java_version, set_java) = if let Some(java_version) = - get_java_version_from_launch_context( - context, - &version_info, - &state.pool, - ) - .await? - { - (std::path::PathBuf::from(java_version.path), false) - } else { - let path = if let Some(reporter) = &reporter { - crate::api::jre::auto_install_java_with_reporter( - key, - reporter.clone(), - ) - .await? - } else { - crate::api::jre::auto_install_java_with_loading(key, true).await? - }; - - (path, true) - }; - - // Test jre version - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::PreparingJava, - Some(InstallProgress { - current: 4, - total: 4, - secondary: None, - }), - InstallPhaseDetails::Java { - major_version: key, - step: InstallJavaStep::Validating, - }, - ) - .await?; - } - let java_version = crate::api::jre::check_jre(java_version.clone()).await?; - - if set_java { - java_version.upsert(&state.pool).await?; - } - - // Download minecraft (5-90) - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::DownloadingMinecraft, - None, - phase_details.clone(), - ) - .await?; - } - download::download_minecraft( - state, - &version_info, - loading_bar.as_ref(), - &java_version.architecture, - repairing, - minecraft_updated, - reporter.clone(), - phase_details.clone(), - ) - .await?; + } - let client_path = state - .directories - .version_dir(&version_jar) - .join(format!("{version_jar}.jar")); - if let Some(processors) = &version_info.processors { - let libraries_dir = state.directories.libraries_dir(); - - if let Some(ref mut data) = version_info.data { - processor_rules! { - data; - "SIDE": - client => "client", - server => ""; - "MINECRAFT_JAR" : - client => client_path.to_string_lossy(), - server => ""; - "MINECRAFT_VERSION": - client => content_set.game_version.clone(), - server => ""; - "ROOT": - client => instance_path.to_string_lossy(), - server => ""; - "LIBRARY_DIR": - client => libraries_dir.to_string_lossy(), - server => ""; - } + let version_jar = loader_version + .as_ref() + .map_or(version.id.to_string(), |it| { + format!("{}-{}", version.id, it.id) + }); + + // Download version info (5) + let mut version_info = download::download_version_info( + state, + version, + loader_version.as_ref(), + Some(repairing), + loading_bar.as_ref(), + reporter.as_ref(), + ) + .await?; - if let Some(loading_bar) = &loading_bar { - emit_loading( - loading_bar, - 0.0, - Some("Running forge processors"), - )?; - } - let total_length = processors.len(); - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::RunningLoaderProcessors, - Some(InstallProgress { - current: 0, - total: total_length as u64, - secondary: None, - }), - phase_details.clone(), - ) - .await?; - } + let key = version_info + .java_version + .as_ref() + .map_or(8, |it| it.major_version); + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::PreparingJava, + Some(InstallProgress { + current: 0, + total: 4, + secondary: None, + }), + InstallPhaseDetails::Java { + major_version: key, + step: InstallJavaStep::Resolving, + }, + ) + .await?; + } + let (java_version, set_java) = if let Some(java_version) = + get_java_version_from_launch_context( + context, + &version_info, + &state.pool, + ) + .await? + { + (std::path::PathBuf::from(java_version.path), false) + } else { + let path = if let Some(reporter) = &reporter { + crate::api::jre::auto_install_java_with_reporter( + key, + reporter.clone(), + ) + .await? + } else { + crate::api::jre::auto_install_java_with_loading(key, true) + .await? + }; + + (path, true) + }; + + // Test jre version + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::PreparingJava, + Some(InstallProgress { + current: 4, + total: 4, + secondary: None, + }), + InstallPhaseDetails::Java { + major_version: key, + step: InstallJavaStep::Validating, + }, + ) + .await?; + } + let java_version = + crate::api::jre::check_jre(java_version.clone()).await?; - // Forge processors (90-100) - for (index, processor) in processors.iter().enumerate() { - if let Some(sides) = &processor.sides - && !sides.contains(&String::from("client")) - { - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::RunningLoaderProcessors, - Some(InstallProgress { - current: (index + 1) as u64, - total: total_length as u64, - secondary: None, - }), - phase_details.clone(), - ) - .await?; - } - continue; - } + if set_java { + java_version.upsert(&state.pool).await?; + } - let cp = { - let mut cp = processor.classpath.clone(); - cp.push(processor.jar.clone()); - cp - }; - - let child = Command::new(&java_version.path) - .arg("-cp") - .arg(args::get_class_paths_jar( - &libraries_dir, - &cp, - &java_version.architecture, - )?) - .arg( - args::get_processor_main_class(args::get_lib_path( - &libraries_dir, - &processor.jar, - false, - )?) - .await? - .ok_or(ErrorKind::LauncherError(format!( - "could not find processor main class for {}", - processor.jar - )))?, - ) - .args(args::get_processor_arguments( - &libraries_dir, - &processor.args, - data, - )?) - .output() - .await - .map_err(|e| IOError::with_path(e, &java_version.path)) - .context(ErrorKind::LauncherError( - "error running processor".to_string(), - ))?; - - if !child.status.success() { - bail!(ErrorKind::LauncherError(format!( - "processor error: {}", - String::from_utf8_lossy(&child.stderr) - ))); - } + // Download minecraft (5-90) + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::DownloadingMinecraft, + None, + phase_details.clone(), + ) + .await?; + } + download::download_minecraft( + state, + &version_info, + loading_bar.as_ref(), + &java_version.architecture, + repairing, + minecraft_updated, + reporter.clone(), + phase_details.clone(), + ) + .await?; - if let Some(loading_bar) = &loading_bar { - emit_loading( - loading_bar, - 30.0 / total_length as f64, - Some(&format!( - "Running forge processor {index}/{total_length}" - )), - )?; - } - if let Some(reporter) = &reporter { - reporter - .update( - InstallPhaseId::RunningLoaderProcessors, - Some(InstallProgress { - current: (index + 1) as u64, - total: total_length as u64, - secondary: None, - }), - phase_details.clone(), - ) - .await?; - } - } - } - } + let client_path = state + .directories + .version_dir(&version_jar) + .join(format!("{version_jar}.jar")); + if let Some(processors) = &version_info.processors { + let libraries_dir = state.directories.libraries_dir(); + + if let Some(ref mut data) = version_info.data { + processor_rules! { + data; + "SIDE": + client => "client", + server => ""; + "MINECRAFT_JAR" : + client => client_path.to_string_lossy(), + server => ""; + "MINECRAFT_VERSION": + client => content_set.game_version.clone(), + server => ""; + "ROOT": + client => instance_path.to_string_lossy(), + server => ""; + "LIBRARY_DIR": + client => libraries_dir.to_string_lossy(), + server => ""; + } + + if let Some(loading_bar) = &loading_bar { + emit_loading( + loading_bar, + 0.0, + Some("Running forge processors"), + )?; + } + let total_length = processors.len(); + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::RunningLoaderProcessors, + Some(InstallProgress { + current: 0, + total: total_length as u64, + secondary: None, + }), + phase_details.clone(), + ) + .await?; + } + + // Forge processors (90-100) + for (index, processor) in processors.iter().enumerate() { + if let Some(sides) = &processor.sides + && !sides.contains(&String::from("client")) + { + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::RunningLoaderProcessors, + Some(InstallProgress { + current: (index + 1) as u64, + total: total_length as u64, + secondary: None, + }), + phase_details.clone(), + ) + .await?; + } + continue; + } + + let cp = { + let mut cp = processor.classpath.clone(); + cp.push(processor.jar.clone()); + cp + }; + + let child = Command::new(&java_version.path) + .arg("-cp") + .arg(args::get_class_paths_jar( + &libraries_dir, + &cp, + &java_version.architecture, + )?) + .arg( + args::get_processor_main_class(args::get_lib_path( + &libraries_dir, + &processor.jar, + false, + )?) + .await? + .ok_or(ErrorKind::LauncherError( + format!( + "could not find processor main class for {}", + processor.jar + ), + ))?, + ) + .args(args::get_processor_arguments( + &libraries_dir, + &processor.args, + data, + )?) + .output() + .await + .map_err(|e| IOError::with_path(e, &java_version.path)) + .context(ErrorKind::LauncherError( + "error running processor".to_string(), + ))?; + + if !child.status.success() { + bail!(ErrorKind::LauncherError(format!( + "processor error: {}", + String::from_utf8_lossy(&child.stderr) + ))); + } + + if let Some(loading_bar) = &loading_bar { + emit_loading( + loading_bar, + 30.0 / total_length as f64, + Some(&format!( + "Running forge processor {index}/{total_length}" + )), + )?; + } + if let Some(reporter) = &reporter { + reporter + .update( + InstallPhaseId::RunningLoaderProcessors, + Some(InstallProgress { + current: (index + 1) as u64, + total: total_length as u64, + secondary: None, + }), + phase_details.clone(), + ) + .await?; + } + } + } + } - let protocol_version = read_protocol_version_from_jar(client_path).await?; + let protocol_version = + read_protocol_version_from_jar(client_path).await?; - crate::state::instances::commands::set_applied_content_set_protocol_version( + crate::state::instances::commands::set_applied_content_set_protocol_version( &instance.id, protocol_version, &state.pool, ) .await?; - if reporter.is_none() { - crate::state::instances::commands::set_instance_install_stage( - &instance.id, - InstanceInstallStage::Installed, - &state.pool, - ) - .await?; - if let Err(error) = - crate::api::instance::reconcile_instance_synced_options( + if reporter.is_none() { + crate::state::instances::commands::set_instance_install_stage( &instance.id, + InstanceInstallStage::Installed, + &state.pool, ) - .await - { - tracing::warn!( - "Failed to reconcile synced options after installing {}: {error}", - instance.id - ); + .await?; + if let Err(error) = + crate::api::instance::reconcile_instance_synced_options( + &instance.id, + ) + .await + { + tracing::warn!( + "Failed to reconcile synced options after installing {}: {error}", + instance.id + ); + } + emit_instance(&instance.id, InstancePayloadType::Edited).await?; + } + if let Some(loading_bar) = &loading_bar { + emit_loading(loading_bar, 1.0, Some("Finished installing"))?; } - emit_instance(&instance.id, InstancePayloadType::Edited).await?; - } - if let Some(loading_bar) = &loading_bar { - emit_loading(loading_bar, 1.0, Some("Finished installing"))?; - } - Ok::<(), crate::Error>(()) + Ok::<(), crate::Error>(()) }) - .await; + .await; if result.is_err() { if let Err(error) = @@ -909,6 +921,7 @@ pub async fn launch_minecraft( env_args: &[(String, String)], mc_set_options: &[(String, String)], wrapper: &Option, + sandbox_settings: &SandboxSettings, memory: &MemorySettings, resolution: &WindowSize, credentials: &Credentials, @@ -939,6 +952,7 @@ pub async fn launch_minecraft( let instance_path = get_instance_full_path(&instance.path, &state.directories) .context("resolving instance path")?; + let assets_path = state.directories.assets_dir(); let (minecraft, version_index) = resolve_minecraft_manifest(&content_set.game_version, state) @@ -1030,22 +1044,18 @@ pub async fn launch_minecraft( .join(format!("{version_jar}.jar")); let args = version_info.arguments.clone().unwrap_or_default(); - let mut command = match wrapper { - Some(hook) => { - let mut cmd = shlex::split(hook) - .ok_or(ErrorKind::LauncherError(format!( - "invalid wrapper command {hook}" - )))? - .into_iter(); - let mut command = Command::new(cmd.next().ok_or( - ErrorKind::LauncherError("empty wrapper command".to_owned()), - )?); - command.args(cmd); - command.arg(&java_version.path); - command - } - None => Command::new(&java_version.path), - }; + let wrapper = wrapper + .as_deref() + .map(|hook| { + shlex::split(hook) + .filter(|parts| !parts.is_empty()) + .ok_or_else(|| { + ErrorKind::LauncherError(format!( + "invalid wrapper command {hook}" + )) + }) + }) + .transpose()?; let env_args = Vec::from(env_args); @@ -1089,6 +1099,8 @@ pub async fn launch_minecraft( io::create_dir_all(&natives_dir).await?; } + io::create_dir_all(instance_path.join("mods")).await?; + let quick_play_version = QuickPlayVersion::find_version(version_index, &minecraft.versions); tracing::debug!( @@ -1126,85 +1138,41 @@ pub async fn launch_minecraft( address.resolve().await?; } - let (main_class_keep_alive, main_class_path) = - get_resource_file!(env "JAVA_JARS_DIR" / "theseus.jar")?; - - let rpc_server = RpcServerBuilder::new().launch().await?; - - command.args( - args::get_jvm_arguments( - args.get(&d::minecraft::ArgumentType::Jvm) - .map(|x| x.as_slice()), - &natives_dir, - &state.directories.libraries_dir(), - &state.directories.log_configs_dir(), - &args::get_class_paths( - &state.directories.libraries_dir(), - version_info.libraries.as_slice(), - &[&main_class_path, &client_path], - &java_version.architecture, - minecraft_updated, - )?, - &main_class_path, - &version_jar, - *memory, - Vec::from(java_args), - &java_version.architecture, - &quick_play_type, - quick_play_version, - version_info - .logging - .as_ref() - .and_then(|x| x.get(&LoggingSide::Client)), - rpc_server.address(), - )? - .into_iter(), - ); - - // The java launcher requires access to java.lang.reflect in order to force access in to - // whatever module the main class is in - if java_version.parsed_version >= 9 { - command.arg("--add-opens=java.base/java.lang.reflect=ALL-UNNAMED"); - } - - // The java launcher code requires internal JDK code in Java 25+ in order to support JEP 512 - if java_version.parsed_version >= 25 { - command.arg("--add-opens=jdk.internal/jdk.internal.misc=ALL-UNNAMED"); - } - - command - .arg("com.modrinth.theseus.MinecraftLaunch") - .arg(version_info.main_class.clone()) - .args( - args::get_minecraft_arguments( - args.get(&d::minecraft::ArgumentType::Game) - .map(|x| x.as_slice()), - version_info.minecraft_arguments.as_deref(), - credentials, - &version.id, - &version_info.asset_index.id, - &instance_path, - &state.directories.assets_dir(), - &version.ty, - *resolution, - &java_version.architecture, - &quick_play_type, - quick_play_version, - ) - .await? - .into_iter(), + let main_class_keep_alive = + modrinth_sandbox::minecraft::create_launcher_temp_dir( + &state.directories.instance_data_dir().join("tmp"), ) - .current_dir(instance_path.clone()); + .map_err(|error| { + crate::ErrorKind::LauncherError(format!( + "Could not create launcher staging directory: {error:#}" + )) + })?; + let main_class_path = main_class_keep_alive.path().join("theseus.jar"); + io::write( + &main_class_path, + include_bytes!(concat!(env!("JAVA_JARS_DIR"), "/theseus.jar")), + ) + .await?; - // CARGO-set DYLD_LIBRARY_PATH breaks Minecraft on macOS during testing on playground - #[cfg(target_os = "macos")] - if std::env::var("CARGO").is_ok() { - command.env_remove("DYLD_FALLBACK_LIBRARY_PATH"); - } - // Java options should be set in instance options (the existence of _JAVA_OPTIONS overwrites them) - command.env_remove("_JAVA_OPTIONS"); + let rpc_server = RpcServerBuilder::new().launch().await?; - command.envs(env_args.iter().cloned()); + let mut classpath = vec![client_path]; + classpath.extend(args::get_class_paths( + &state.directories.libraries_dir(), + version_info.libraries.as_slice(), + &java_version.architecture, + minecraft_updated, + )?); + let jvm_args = args::get_jvm_arguments( + args.get(&d::minecraft::ArgumentType::Jvm) + .map(|x| x.as_slice()), + &version_jar, + *memory, + Vec::from(java_args), + &java_version.architecture, + &quick_play_type, + quick_play_version, + )?; if let Err(error) = crate::api::instance::reconcile_synced_packs(&instance.id).await @@ -1267,6 +1235,71 @@ pub async fn launch_minecraft( ))); } + let sandboxed = sandbox::should_sandbox( + sandbox_settings, + current + .applied_content_set_id + .as_deref() + .unwrap_or(&content_set.id), + &state.pool, + ) + .await?; + if sandboxed && wrapper.is_some() { + bail!(ErrorKind::LauncherError( + "Custom wrapper hooks are not supported for sandboxed launches. Remove the wrapper or turn off sandboxing for this instance." + .to_owned() + )); + } + let sandbox_env = sandbox::select_env(state, sandboxed)?; + tracing::info!(instance_id = %instance.id, sandboxed, "Resolved sandbox for launch"); + + let profile = credentials.maybe_online_profile().await; + let sandbox_session = sandbox::prepare_session( + profile.id, + credentials.access_token.clone(), + sandboxed, + ); + + let game_args = args::get_minecraft_arguments( + args.get(&d::minecraft::ArgumentType::Game) + .map(|x| x.as_slice()), + version_info.minecraft_arguments.as_deref(), + &sandbox_session.access_token, + &profile.name, + profile.id, + &version.id, + &version_info.asset_index.id, + &instance_path, + &assets_path, + &version.ty, + *resolution, + &java_version.architecture, + &quick_play_type, + quick_play_version, + )?; + + let command = sandbox::prepare_command( + sandbox_session, + sandbox::CommandInput { + directories: &state.directories, + java: &java_version, + version_info: &version_info, + version_jar: &version_jar, + java_agent: main_class_path, + classpath, + rpc_address: rpc_server.address(), + instance_path: instance_path.clone(), + jvm_args, + game_args, + granted_paths: if sandboxed { + sandbox::granted_paths(sandbox_settings) + } else { + Vec::new() + }, + }, + &env_args, + )?; + crate::state::instances::commands::set_instance_last_played( &instance.id, Utc::now(), @@ -1308,7 +1341,9 @@ pub async fn launch_minecraft( &instance.id, &instance.path, &instance.name, + &sandbox_env, command, + wrapper, post_exit_hook, env_args, state.directories.instance_logs_dir(&instance.path), diff --git a/packages/app-lib/src/launcher/sandbox.rs b/packages/app-lib/src/launcher/sandbox.rs new file mode 100644 index 00000000000..2b5cff36a16 --- /dev/null +++ b/packages/app-lib/src/launcher/sandbox.rs @@ -0,0 +1,250 @@ +use std::{ + collections::HashMap, + net::SocketAddr, + path::{Path, PathBuf}, + sync::{Arc, LazyLock}, +}; + +use super::profile::ResolvedVersion as VersionInfo; +use crate::state::instances::adapters::sqlite::content_rows; +use crate::state::{ + DirectoryInfo, JavaVersion, SandboxMode, SandboxSettings, State, +}; +use minecraft_meta_manifest::minecraft::{LoggingConfiguration, LoggingSide}; +use modrinth_sandbox::{ + SandboxStdio, + api::{SandboxApiChild, SandboxApiLauncher, SandboxApiService}, + minecraft::{MinecraftCommand, MinecraftLoggingConfig}, +}; +use parking_lot::Mutex; +use sqlx::SqlitePool; +use tokio::sync::oneshot; +use uuid::Uuid; + +const THESEUS_MINECRAFT_LAUNCHER_MAIN_CLASS: &str = + "com.modrinth.theseus.MinecraftLaunch"; +const SANDBOX_API_PORT: u16 = 28881; + +static LOGIN_HANDLER: LazyLock> = + LazyLock::new(Default::default); +static SERVICE: LazyLock = LazyLock::new(|| { + SandboxApiService::new(SANDBOX_API_PORT, LOGIN_HANDLER.clone()) +}); + +#[derive(Default)] +struct SimpleLoginHandler { + sessions: Mutex>>, +} + +impl SandboxApiLauncher for SimpleLoginHandler { + fn login(&self, uuid: Uuid, token: oneshot::Sender>) { + if let Some(access_token) = self.sessions.lock().get(&uuid) { + token.send(access_token.clone()).ok(); + } + } +} + +pub(super) struct Session { + pub access_token: String, + child: Option, +} + +pub(super) fn prepare_session( + uuid: Uuid, + access_token: String, + sandboxed: bool, +) -> Session { + if !sandboxed { + return Session { + access_token, + child: None, + }; + } + + LOGIN_HANDLER + .sessions + .lock() + .insert(uuid, access_token.into()); + let child = SERVICE.clone().start(uuid); + + Session { + access_token: child.get_dummy_access_token().to_string(), + child: Some(child), + } +} + +/// Whether a launch should run in the sandbox under `settings`. +/// +/// In [`SandboxMode::Unrecognized`], an instance is sandboxed when any +/// enabled content entry isn't resolved to a Modrinth project version. +pub(super) async fn should_sandbox( + settings: &SandboxSettings, + content_set_id: &str, + pool: &SqlitePool, +) -> crate::Result { + Ok(match settings.mode { + SandboxMode::Never => false, + SandboxMode::Always => true, + SandboxMode::Unrecognized => { + content_rows::get_content_entries(content_set_id, pool) + .await? + .iter() + .any(|entry| { + entry.enabled + && (entry.project_id.is_none() + || entry.version_id.is_none()) + }) + } + }) +} + +/// Host folders to expose read-write to a sandboxed instance. +pub(super) fn granted_paths(settings: &SandboxSettings) -> Vec { + let mut paths = Vec::new(); + if settings.allow_downloads + && let Some(dir) = dirs::download_dir() + { + paths.push(dir); + } + if settings.allow_documents + && let Some(dir) = dirs::document_dir() + { + paths.push(dir); + } + paths.extend( + settings + .extra_paths + .iter() + .map(|path| path.trim()) + .filter(|path| !path.is_empty()) + .map(PathBuf::from), + ); + paths.retain(|path| { + let exists = path.is_dir(); + if !exists { + tracing::warn!( + "Skipping sandbox folder grant for missing directory {}", + path.display() + ); + } + exists + }); + paths.sort_unstable(); + paths.dedup(); + paths +} + +/// Picks the sandbox environment for a launch, failing if sandboxing was +/// requested but couldn't be set up on this system. +pub(super) fn select_env( + state: &State, + sandboxed: bool, +) -> crate::Result { + if !sandboxed { + return Ok(state.sandbox_env_noop.clone()); + } + + match &state.sandbox_env { + Ok(env) => Ok(env.clone()), + Err(reason) => Err(crate::ErrorKind::LauncherError(format!( + "This instance needs to run in the sandbox, but sandboxing is unavailable on this system: {reason}" + )) + .into()), + } +} + +pub(super) struct CommandInput<'a> { + pub directories: &'a DirectoryInfo, + pub java: &'a JavaVersion, + pub version_info: &'a VersionInfo, + pub version_jar: &'a str, + pub java_agent: PathBuf, + pub classpath: Vec, + pub rpc_address: SocketAddr, + pub instance_path: PathBuf, + pub jvm_args: Vec, + pub game_args: Vec, + pub granted_paths: Vec, +} + +pub(super) fn prepare_command( + session: Session, + input: CommandInput<'_>, + env_args: &[(String, String)], +) -> crate::Result { + let jre_path = Path::new(&input.java.path) + .parent() + .and_then(Path::parent) + .ok_or_else(|| { + crate::ErrorKind::LauncherError(format!( + "Could not determine Java runtime directory from {}", + input.java.path + )) + })? + .to_path_buf(); + + let mut classpath = Vec::with_capacity(input.classpath.len() + 1); + classpath.push(input.java_agent.clone()); + classpath.extend(input.classpath); + + let mut jvm_args = input.jvm_args; + jvm_args.extend([ + format!("-Dmodrinth.internal.ipc.host={}", input.rpc_address.ip()), + format!("-Dmodrinth.internal.ipc.port={}", input.rpc_address.port()), + ]); + + // Theseus needs reflective access to the game's main class across modules. + if input.java.parsed_version >= 9 { + jvm_args.push( + "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED".to_owned(), + ); + } + // Theseus uses internal JDK APIs to support JEP 512 on Java 25+. + if input.java.parsed_version >= 25 { + jvm_args.push( + "--add-opens=jdk.internal/jdk.internal.misc=ALL-UNNAMED".to_owned(), + ); + } + + let mut launcher_args = Vec::with_capacity(input.game_args.len() + 1); + launcher_args.push(input.version_info.main_class.clone().into()); + launcher_args.extend(input.game_args.into_iter().map(Into::into)); + + let logging_config = input + .version_info + .logging + .as_ref() + .and_then(|logging| logging.get(&LoggingSide::Client)) + .map(|logging| match logging { + LoggingConfiguration::Log4j2Xml { argument, file } => { + MinecraftLoggingConfig { + path: input.directories.log_configs_dir().join(&file.id), + argument: argument.clone(), + } + } + }); + + Ok(MinecraftCommand { + sandbox_api_child: session.child, + jre_path, + java_agent: Some(input.java_agent), + classpath, + natives_path: input.directories.version_natives_dir(input.version_jar), + assets_path: input.directories.assets_dir(), + logging_config, + instance_path: input.instance_path, + persistent_dir: input.directories.instance_data_dir(), + granted_paths: input.granted_paths, + jvm_args: jvm_args.into_iter().map(Into::into).collect(), + main_class: THESEUS_MINECRAFT_LAUNCHER_MAIN_CLASS.into(), + main_class_args: launcher_args, + extra_environment: env_args + .iter() + .cloned() + .map(|(key, value)| (key.into(), value.into())) + .collect(), + stdin: SandboxStdio::Null, + stdout: SandboxStdio::Pipe, + stderr: SandboxStdio::Pipe, + }) +} diff --git a/packages/app-lib/src/state/dirs.rs b/packages/app-lib/src/state/dirs.rs index 99f5aaedcb9..6cfb2c7fe86 100644 --- a/packages/app-lib/src/state/dirs.rs +++ b/packages/app-lib/src/state/dirs.rs @@ -10,6 +10,7 @@ use tokio::fs; pub const CACHES_FOLDER_NAME: &str = "caches"; pub const LAUNCHER_LOGS_FOLDER_NAME: &str = "launcher_logs"; pub const INSTANCES_FOLDER_NAME: &str = "profiles"; +pub const INSTANCE_DATA_FOLDER_NAME: &str = "instance-data"; pub const METADATA_FOLDER_NAME: &str = "meta"; pub const SYNCED_OPTIONS_FOLDER_NAME: &str = "synced-options"; pub const STORE_FOLDER_NAME: &str = "store"; @@ -170,6 +171,12 @@ impl DirectoryInfo { self.config_dir.join(INSTANCES_FOLDER_NAME) } + /// Get the persistent directory shared by sandboxed instances. + #[inline] + pub fn instance_data_dir(&self) -> PathBuf { + self.config_dir.join(INSTANCE_DATA_FOLDER_NAME) + } + #[inline] pub fn synced_options_dir(&self) -> PathBuf { self.config_dir.join(SYNCED_OPTIONS_FOLDER_NAME) diff --git a/packages/app-lib/src/state/instances/commands/edit_instance.rs b/packages/app-lib/src/state/instances/commands/edit_instance.rs index 93deef05c1f..4c76f322866 100644 --- a/packages/app-lib/src/state/instances/commands/edit_instance.rs +++ b/packages/app-lib/src/state/instances/commands/edit_instance.rs @@ -6,7 +6,7 @@ use crate::state::instances::{ }; use crate::state::{ Hooks, InstanceInstallStage, LauncherFeatureVersion, MemorySettings, - ModLoader, ReleaseChannel, State, WindowSize, + ModLoader, ReleaseChannel, SandboxOverrides, State, WindowSize, }; use anyhow::bail; use chrono::{DateTime, Utc}; @@ -83,6 +83,7 @@ pub struct InstanceLaunchOverridesPatch { )] pub game_resolution: Option>, pub hooks: Option, + pub sandbox: Option, pub visible_tabs: Option, } @@ -306,6 +307,9 @@ fn apply_launch_overrides_patch( if let Some(hooks) = patch.hooks { overrides.hooks = hooks; } + if let Some(sandbox) = patch.sandbox { + overrides.sandbox = sandbox; + } if let Some(visible_tabs) = patch.visible_tabs { overrides.visible_tabs = visible_tabs; } diff --git a/packages/app-lib/src/state/instances/model/launch.rs b/packages/app-lib/src/state/instances/model/launch.rs index 6b99225f2fe..263f2c23ba5 100644 --- a/packages/app-lib/src/state/instances/model/launch.rs +++ b/packages/app-lib/src/state/instances/model/launch.rs @@ -1,5 +1,6 @@ use crate::state::{ - ContentSet, Hooks, Instance, InstanceLink, MemorySettings, WindowSize, + ContentSet, Hooks, Instance, InstanceLink, MemorySettings, + SandboxOverrides, WindowSize, }; use serde::{Deserialize, Serialize}; @@ -31,6 +32,8 @@ pub struct InstanceLaunchOverrides { pub game_resolution: Option, pub hooks: Hooks, #[serde(default)] + pub sandbox: SandboxOverrides, + #[serde(default)] pub visible_tabs: InstanceTabVisibility, } @@ -49,6 +52,7 @@ impl InstanceLaunchOverrides { wrapper: None, post_exit: None, }, + sandbox: SandboxOverrides::default(), visible_tabs: InstanceTabVisibility::default(), } } @@ -70,6 +74,8 @@ pub(crate) struct InstanceLaunchOverridesData { pub game_resolution: Option, #[serde(default)] pub hooks: Hooks, + #[serde(default, skip_serializing_if = "SandboxOverrides::is_empty")] + pub sandbox: SandboxOverrides, #[serde(default)] pub visible_tabs: InstanceTabVisibility, } @@ -88,6 +94,7 @@ impl InstanceLaunchOverridesData { force_fullscreen: self.force_fullscreen, game_resolution: self.game_resolution, hooks: self.hooks, + sandbox: self.sandbox, visible_tabs: self.visible_tabs, } } @@ -103,6 +110,7 @@ impl From<&InstanceLaunchOverrides> for InstanceLaunchOverridesData { force_fullscreen: overrides.force_fullscreen, game_resolution: overrides.game_resolution, hooks: overrides.hooks.clone(), + sandbox: overrides.sandbox.clone(), visible_tabs: overrides.visible_tabs, } } diff --git a/packages/app-lib/src/state/instances/watcher.rs b/packages/app-lib/src/state/instances/watcher.rs index f7a4fa58ff2..8cfa7658e94 100644 --- a/packages/app-lib/src/state/instances/watcher.rs +++ b/packages/app-lib/src/state/instances/watcher.rs @@ -12,8 +12,8 @@ use notify::{ Config, Event, EventHandler, EventKind, RecommendedWatcher, RecursiveMode, Watcher, WatcherKind, }; -use notify_debouncer_mini::{ - DebounceEventResult, Debouncer, new_debouncer_opt, +use notify_debouncer_full::{ + DebounceEventResult, Debouncer, RecommendedCache, new_debouncer_opt, }; use sqlx::SqlitePool; use std::path::Path; @@ -28,17 +28,16 @@ use tokio::sync::{RwLock, mpsc::channel}; use super::adapters::sqlite::instance_rows; pub struct FileWatcher { - watcher: RwLock>, + watcher: RwLock>, instance_ids: Arc>>, } /// Wraps the platform watcher and drops read-only access events before they /// reach the debouncer. /// -/// The inotify backend reports `IN_OPEN`/`IN_CLOSE_NOWRITE`, and -/// `notify-debouncer-mini` discards event kinds, so without this every read -/// of a watched file (e.g. the locale indexer reading `options.txt`) looks -/// like a change and can re-trigger the reader in a loop. +/// The inotify backend reports `IN_OPEN`/`IN_CLOSE_NOWRITE`. Ignoring these +/// prevents reads (e.g. the locale indexer reading `options.txt`) from looking +/// like changes and re-triggering the reader in a loop. pub struct WriteOnlyWatcher(RecommendedWatcher); fn is_read_only_access(kind: &EventKind) -> bool { @@ -159,12 +158,14 @@ pub async fn init_watcher() -> crate::Result { let instance_ids = Arc::new(RwLock::new(HashMap::::new())); let event_instance_ids = instance_ids.clone(); - let file_watcher = new_debouncer_opt::<_, WriteOnlyWatcher>( - notify_debouncer_mini::Config::default() - .with_timeout(Duration::from_secs_f32(1.0)), + let file_watcher = new_debouncer_opt::<_, WriteOnlyWatcher, _>( + Duration::from_secs_f32(1.0), + None, move |res: DebounceEventResult| { tx.blocking_send(res).ok(); }, + RecommendedCache::new(), + Config::default(), )?; tokio::task::spawn(async move { @@ -192,11 +193,13 @@ pub async fn init_watcher() -> crate::Result { let mut synced_option_files = HashMap::>::new(); - for e in &events { + for (e, event_path) in events.iter().flat_map(|event| { + event.paths.iter().map(move |path| (event, path)) + }) { let mut instance_path = None; let mut found = false; - for component in e.path.components() { + for component in event_path.components() { if found { instance_path = Some(component.as_os_str()); break; @@ -217,8 +220,7 @@ pub async fn init_watcher() -> crate::Result { else { continue; }; - let first_file_name = e - .path + let first_file_name = event_path .components() .skip_while(|x| x.as_os_str() != instance_path) .nth(1) @@ -252,13 +254,15 @@ pub async fn init_watcher() -> crate::Result { crate::api::instance::queue_game_locale_index(); } } - if first_file_name + let is_crash_report = first_file_name .as_ref() .is_some_and(|x| *x == "crash-reports") - && e.path + && event_path .extension() .as_ref() - .is_some_and(|x| *x == "txt") + .is_some_and(|x| *x == "txt"); + if is_crash_report + && matches!(e.kind, EventKind::Create(_)) { crash_task(instance_id, state.pool.clone()); } else if (is_screenshot_event @@ -283,7 +287,7 @@ pub async fn init_watcher() -> crate::Result { } else if first_file_name.as_ref().is_some_and( |x| { *x == "saves" - && e.path + && event_path .file_name() .as_ref() .is_some_and(|x| { @@ -293,17 +297,16 @@ pub async fn init_watcher() -> crate::Result { ) { tracing::info!( "World updated: {}", - e.path.display() + event_path.display() ); - let world = e - .path + let world = event_path .parent() .unwrap() .file_name() .unwrap() .to_string_lossy() .to_string(); - if !e.path.is_file() { + if !event_path.is_file() { let instance_id = instance_id.clone(); let world = world.clone(); let pool = state.pool.clone(); @@ -404,7 +407,7 @@ pub async fn init_watcher() -> crate::Result { }); } } - Err(error) => tracing::warn!("Unable to watch file: {error}"), + Err(error) => tracing::warn!("Unable to watch file: {error:?}"), } } }); @@ -478,10 +481,7 @@ pub(crate) async fn watch_instance_folder( let mut debouncer = watcher.watcher.write().await; for full_path in &to_watch { - if let Err(e) = debouncer - .watcher() - .watch(full_path, RecursiveMode::Recursive) - { + if let Err(e) = debouncer.watch(full_path, RecursiveMode::Recursive) { tracing::error!( "Failed to watch directory for watcher {full_path:?}: {e}" ); @@ -489,9 +489,8 @@ pub(crate) async fn watch_instance_folder( } } - if let Err(e) = debouncer - .watcher() - .watch(&full_instance_path, RecursiveMode::NonRecursive) + if let Err(e) = + debouncer.watch(&full_instance_path, RecursiveMode::NonRecursive) { tracing::error!( "Failed to watch root instance directory for watcher {full_instance_path:?}: {e}" @@ -538,7 +537,7 @@ pub(crate) async fn unwatch_instance_folder( let mut debouncer = watcher.watcher.write().await; for path in watched_paths { - if let Err(error) = debouncer.watcher().unwatch(&path) + if let Err(error) = debouncer.unwatch(&path) && !matches!( error.kind, notify::ErrorKind::WatchNotFound diff --git a/packages/app-lib/src/state/legacy_converter.rs b/packages/app-lib/src/state/legacy_converter.rs index 13901e4ecdf..b2a6a1c3ac7 100644 --- a/packages/app-lib/src/state/legacy_converter.rs +++ b/packages/app-lib/src/state/legacy_converter.rs @@ -11,7 +11,8 @@ use crate::state::{ Credentials, DefaultPage, DependencyType, DeviceToken, DeviceTokenKey, DeviceTokenPair, FileType, Hooks, InstanceInstallStage, LauncherFeatureVersion, MemorySettings, ModrinthCredentials, - ReleaseChannel, TeamMember, Theme, VersionFile, WindowSize, + ReleaseChannel, SandboxOverrides, TeamMember, Theme, VersionFile, + WindowSize, }; use crate::util::fetch::{IoSemaphore, read_json}; use chrono::{DateTime, Utc}; @@ -640,6 +641,7 @@ where force_fullscreen: input.force_fullscreen, game_resolution: input.game_resolution, hooks: input.hooks, + sandbox: SandboxOverrides::default(), visible_tabs: InstanceTabVisibility::default(), }; let launch_overrides_data = serde_json::to_string( diff --git a/packages/app-lib/src/state/mod.rs b/packages/app-lib/src/state/mod.rs index 6f3330ee31d..82ff6d7228e 100644 --- a/packages/app-lib/src/state/mod.rs +++ b/packages/app-lib/src/state/mod.rs @@ -2,6 +2,7 @@ use crate::ErrorKind; use crate::util::fetch::{FetchSemaphore, IoSemaphore}; use anyhow::anyhow; +use modrinth_sandbox::SandboxEnv; use std::sync::atomic::AtomicBool; use std::sync::{Arc, LazyLock}; use tokio::sync::watch::Sender; @@ -125,6 +126,11 @@ pub struct State { pub(crate) pool: SqlitePool, pub(crate) file_watcher: FileWatcher, + /// Created from [`SandboxEnv::new`], or the reason sandboxing is + /// unavailable on this system. + pub sandbox_env: Result, + /// Created from [`SandboxEnv::noop`]. + pub sandbox_env_noop: SandboxEnv, } impl State { @@ -341,6 +347,12 @@ impl State { let process_manager = ProcessManager::new(); + let sandbox_env = SandboxEnv::new().await.map_err(|error| { + tracing::error!("Failed to set up sandboxing: {error:?}"); + format!("{error:#}") + }); + let sandbox_env_noop = SandboxEnv::noop(); + Ok(Arc::new(Self { startup_complete: AtomicBool::new(false), directories, @@ -356,7 +368,8 @@ impl State { restart_after_pending_update: AtomicBool::new(false), pool, file_watcher, - // app_identifier, + sandbox_env, + sandbox_env_noop, })) } } diff --git a/packages/app-lib/src/state/process.rs b/packages/app-lib/src/state/process.rs index ea857479c78..6903c3d5baf 100644 --- a/packages/app-lib/src/state/process.rs +++ b/packages/app-lib/src/state/process.rs @@ -9,6 +9,9 @@ use crate::util::rpc::RpcServer; use anyhow::Context; use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; use dashmap::DashMap; +use modrinth_sandbox::{ + SandboxChild, SandboxEnv, SandboxExitStatus, minecraft::MinecraftCommand, +}; use quick_xml::Reader; use quick_xml::events::Event; use serde::Deserialize; @@ -19,12 +22,12 @@ use std::fmt::Debug; use std::fs::OpenOptions; use std::io::Write; use std::path::{Path, PathBuf}; -use std::process::ExitStatus; use std::sync::{Arc, LazyLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; use tempfile::TempDir; use tokio::io::{AsyncBufReadExt, BufReader}; -use tokio::process::{Child, Command}; +use tokio::process::Command; +use tracing::info; use uuid::Uuid; const LAUNCHER_LOG_PATH: &str = "launcher_log.txt"; @@ -205,7 +208,9 @@ impl ProcessManager { instance_id: &str, instance_path: &str, instance_name: &str, - mut mc_command: Command, + sandbox_env: &SandboxEnv, + mc_command: MinecraftCommand, + wrapper: Option>, post_exit_command: Option, post_exit_env_vars: Vec<(String, String)>, logs_folder: PathBuf, @@ -218,12 +223,9 @@ impl ProcessManager { &RpcServer, ) -> crate::Result<()>, ) -> crate::Result { - mc_command.stdout(std::process::Stdio::piped()); - mc_command.stderr(std::process::Stdio::piped()); - mc_command.stdin(std::process::Stdio::piped()); let executable = mc_command - .as_std() - .get_program() + .jre_path + .join("bin/java") .to_string_lossy() .into_owned(); @@ -257,11 +259,69 @@ impl ProcessManager { writeln!(log_file).map_err(|e| IOError::with_path(e, &log_path))?; } - let mut mc_proc = mc_command.spawn().map_err(IOError::from)?; + let mut command = + modrinth_sandbox::minecraft::setup_minecraft_command(mc_command) + .await + .map_err(|error| anyhow::Error::from_boxed(error.into()))?; + let synced_options_dir = state.directories.synced_options_dir(); + command.ensure_dirs_exist.push(synced_options_dir.clone()); + command.read_write_paths.push(synced_options_dir); + if let Some(mut wrapper) = wrapper { + let wrapper_executable = wrapper.remove(0); + let java = std::mem::replace( + &mut command.executable, + PathBuf::from(wrapper_executable), + ); + let mut args = + Vec::with_capacity(wrapper.len() + 1 + command.args.len()); + args.extend(wrapper.into_iter().map(Into::into)); + args.push(java.into_os_string().into()); + args.append(&mut command.args); + command.args = args; + } + info!("spawning Minecraft process using sandbox {sandbox_env:?}"); + let mut mc_proc = sandbox_env + .spawn(command) + .await + .map_err(|error| anyhow::Error::from_boxed(error.into()))?; let child_pid = mc_proc.id(); - let stdout = mc_proc.stdout.take(); - let stderr = mc_proc.stderr.take(); + let stdout = mc_proc + .stdout + .take() + .map(|reader| { + #[cfg(unix)] + { + tokio::net::unix::pipe::Receiver::from_owned_fd( + reader.into(), + ) + } + #[cfg(windows)] + { + Ok::<_, std::io::Error>( + crate::util::blocking_reader::Blocking::new(reader), + ) + } + }) + .expect("`stdout` is set to `Pipe` so should be available")?; + let stderr = mc_proc + .stderr + .take() + .map(|reader| { + #[cfg(unix)] + { + tokio::net::unix::pipe::Receiver::from_owned_fd( + reader.into(), + ) + } + #[cfg(windows)] + { + Ok::<_, std::io::Error>( + crate::util::blocking_reader::Blocking::new(reader), + ) + } + }) + .expect("`stderr` is set to `Pipe` so should be available")?; let mut process = Process { metadata: ProcessMetadata { @@ -275,6 +335,43 @@ impl ProcessManager { rpc_server, _main_class_keep_alive: main_class_keep_alive, }; + let metadata = process.metadata.clone(); + + { + let log_path = log_path.clone(); + let instance_id = metadata.instance_id.clone(); + let instance_path = metadata.instance_path.clone(); + let pool = state.pool.clone(); + tokio::spawn(async move { + Process::process_output( + &instance_id, + &instance_path, + stdout, + log_path, + xml_logging, + &pool, + ) + .await; + }); + } + + { + let log_path = log_path.clone(); + let instance_id = metadata.instance_id.clone(); + let instance_path = metadata.instance_path.clone(); + let pool = state.pool.clone(); + tokio::spawn(async move { + Process::process_output( + &instance_id, + &instance_path, + stderr, + log_path, + xml_logging, + &pool, + ) + .await; + }); + } let persisted_process = child_pid.map(|pid| { (i64::from(pid), process.metadata.start_time.timestamp()) @@ -309,54 +406,58 @@ impl ProcessManager { } } - if let Err(e) = - post_process_init(&process.metadata, &process.rpc_server).await - { - tracing::error!("Failed to run post-process init: {e}"); - clear_persisted_process(&state.pool, persisted_process).await; - let _ = process.child.kill().await; - return Err(e); - } - - let metadata = process.metadata.clone(); - - if let Some(stdout) = stdout { - let log_path_clone = log_path.clone(); - - let instance_id = metadata.instance_id.clone(); - let instance_path = metadata.instance_path.clone(); - let pool = state.pool.clone(); - tokio::spawn(async move { - Process::process_output( - &instance_id, - &instance_path, - stdout, - log_path_clone, - xml_logging, - &pool, - ) - .await; - }); - } + let rpc_address = process.rpc_server.address(); + info!( + %rpc_address, + log_path = %log_path.display(), + "waiting for Minecraft launcher RPC initialization" + ); - if let Some(stderr) = stderr { - let log_path_clone = log_path.clone(); + let post_process_result = { + let mut child_poll = + tokio::time::interval(Duration::from_millis(100)); + child_poll.set_missed_tick_behavior( + tokio::time::MissedTickBehavior::Skip, + ); + let timeout = tokio::time::sleep(Duration::from_secs(30)); + tokio::pin!(timeout); + let initialization = + post_process_init(&process.metadata, &process.rpc_server); + tokio::pin!(initialization); - let instance_id = metadata.instance_id.clone(); - let instance_path = metadata.instance_path.clone(); - let pool = state.pool.clone(); - tokio::spawn(async move { - Process::process_output( - &instance_id, - &instance_path, - stderr, - log_path_clone, - xml_logging, - &pool, - ) - .await; - }); + loop { + tokio::select! { + result = &mut initialization => break result, + _ = &mut timeout => { + break Err(crate::ErrorKind::LauncherError(format!( + "Timed out waiting for Minecraft launcher initialization at {rpc_address}; see {}", + log_path.display(), + )).into()); + } + // TODO: it's not good that we're polling here. we should use `child.wait()`, + // but that's not cancel-safe (bwrap's isnt cancel safe yet). + _ = child_poll.tick() => { + match process.child.try_wait() { + Ok(Some(status)) => { + break Err(crate::ErrorKind::LauncherError(format!( + "Minecraft launcher exited with {status} before initializing; see {}", + log_path.display(), + )).into()); + } + Ok(None) => {} + Err(error) => break Err(anyhow::Error::from_boxed(error.into())), + } + } + } + } + }; + if let Err(error) = post_process_result { + tracing::error!("Failed to run post-process init: {error}"); + clear_persisted_process(&state.pool, persisted_process).await; + let _ = process.child.kill().await; + return Err(error); } + info!(%rpc_address, "Minecraft launcher RPC initialization completed"); self.processes.insert(process.metadata.uuid, process); @@ -399,9 +500,11 @@ impl ProcessManager { pub fn try_wait( &self, id: Uuid, - ) -> crate::Result>> { + ) -> crate::Result>> { if let Some(mut process) = self.processes.get_mut(&id) { - Ok(Some(process.child.try_wait()?)) + Ok(Some(process.child.try_wait().map_err(|error| { + anyhow::Error::from_boxed(error.into()) + })?)) } else { Ok(None) } @@ -409,14 +512,22 @@ impl ProcessManager { pub async fn wait_for(&self, id: Uuid) -> crate::Result<()> { if let Some(mut process) = self.processes.get_mut(&id) { - process.child.wait().await?; + process + .child + .wait() + .await + .map_err(|error| anyhow::Error::from_boxed(error.into()))?; } Ok(()) } pub async fn kill(&self, id: Uuid) -> crate::Result<()> { if let Some(mut process) = self.processes.get_mut(&id) { - process.child.kill().await?; + process + .child + .kill() + .await + .map_err(|error| anyhow::Error::from_boxed(error.into()))?; } Ok(()) @@ -439,7 +550,7 @@ pub struct ProcessMetadata { #[derive(Debug)] struct Process { metadata: ProcessMetadata, - child: Child, + child: SandboxChild, _main_class_keep_alive: TempDir, rpc_server: RpcServer, } @@ -943,7 +1054,7 @@ impl Process { break; } } else { - mc_exit_status = ExitStatus::default(); + mc_exit_status = SandboxExitStatus::default(); break; } diff --git a/packages/app-lib/src/state/settings.rs b/packages/app-lib/src/state/settings.rs index 08c973893f2..58262e26a93 100644 --- a/packages/app-lib/src/state/settings.rs +++ b/packages/app-lib/src/state/settings.rs @@ -73,6 +73,8 @@ pub struct Settings { #[serde(default)] pub skip_non_essential_warnings: bool, pub hooks: Hooks, + #[serde(default)] + pub sandbox: SandboxSettings, pub custom_dir: Option, pub prev_custom_dir: Option, @@ -121,7 +123,7 @@ impl Settings { discord_rpc, developer_mode, telemetry, personalized_ads, json(extra_launch_args) extra_launch_args, json(custom_env_vars) custom_env_vars, mc_memory_max, mc_force_fullscreen, mc_game_resolution_x, mc_game_resolution_y, hide_on_process_start, - hook_pre_launch, hook_wrapper, hook_post_exit, + hook_pre_launch, hook_wrapper, hook_post_exit, json(sandbox) sandbox, custom_dir, prev_custom_dir, migrated, json(feature_flags) feature_flags, toggle_sidebar, skipped_update, pending_update_toast_for_version, auto_download_updates, sync_theme_across_devices, sync_behavior_across_devices, sync_features_across_devices, @@ -199,6 +201,11 @@ impl Settings { wrapper: res.hook_wrapper, post_exit: res.hook_post_exit, }, + sandbox: res + .sandbox + .as_ref() + .and_then(|x| serde_json::from_str(x).ok()) + .unwrap_or_default(), custom_dir: res.custom_dir, prev_custom_dir: res.prev_custom_dir, migrated: res.migrated == 1, @@ -236,6 +243,7 @@ impl Settings { let extra_launch_args = serde_json::to_string(&self.extra_launch_args)?; let custom_env_vars = serde_json::to_string(&self.custom_env_vars)?; let feature_flags = serde_json::to_string(&self.feature_flags)?; + let sandbox = serde_json::to_string(&self.sandbox)?; let version = self.version as i64; sqlx::query!( @@ -303,7 +311,8 @@ impl Settings { friends_active_collapsed = $50, friends_online_collapsed = $51, friends_offline_collapsed = $52, - friends_pending_collapsed = $53 + friends_pending_collapsed = $53, + sandbox = jsonb($54) ", max_concurrent_writes, max_concurrent_downloads, @@ -358,6 +367,7 @@ impl Settings { self.friends_online_collapsed, self.friends_offline_collapsed, self.friends_pending_collapsed, + sandbox, ) .execute(exec) .await?; @@ -489,6 +499,75 @@ pub struct Hooks { pub post_exit: Option, } +/// When to run instances inside the sandbox +#[derive( + Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq, +)] +#[serde(rename_all = "snake_case")] +pub enum SandboxMode { + Never, + #[default] + Unrecognized, + Always, +} + +/// Sandbox mode and the extra access granted to sandboxed instances +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(default)] +pub struct SandboxSettings { + pub mode: SandboxMode, + pub allow_network: bool, + pub allow_downloads: bool, + pub allow_documents: bool, + pub extra_paths: Vec, +} + +/// Per-instance sandbox overrides; [`None`] fields use the app defaults +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +#[serde(default)] +pub struct SandboxOverrides { + pub mode: Option, + pub allow_network: Option, + pub allow_downloads: Option, + pub allow_documents: Option, + pub extra_paths: Option>, +} + +impl SandboxOverrides { + pub fn is_empty(&self) -> bool { + *self == Self::default() + } + + pub fn apply(&self, defaults: SandboxSettings) -> SandboxSettings { + SandboxSettings { + mode: self.mode.unwrap_or(defaults.mode), + allow_network: self.allow_network.unwrap_or(defaults.allow_network), + allow_downloads: self + .allow_downloads + .unwrap_or(defaults.allow_downloads), + allow_documents: self + .allow_documents + .unwrap_or(defaults.allow_documents), + extra_paths: self + .extra_paths + .clone() + .unwrap_or(defaults.extra_paths), + } + } +} + +impl Default for SandboxSettings { + fn default() -> Self { + Self { + mode: SandboxMode::default(), + allow_network: true, + allow_downloads: true, + allow_documents: false, + extra_paths: Vec::new(), + } + } +} + /// Opening window to start with #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub enum DefaultPage { diff --git a/packages/app-lib/src/util/blocking_reader.rs b/packages/app-lib/src/util/blocking_reader.rs new file mode 100644 index 00000000000..abf9d37d9d0 --- /dev/null +++ b/packages/app-lib/src/util/blocking_reader.rs @@ -0,0 +1,171 @@ +// Adapted from https://docs.rs/crate/tokio/1.26.0/source/src/io/blocking.rs + +use std::{ + io::Read, + pin::Pin, + task::{Context, Poll, ready}, +}; + +use tokio::{ + io::{AsyncRead, ReadBuf}, + task::JoinHandle, +}; + +/// `T` should not implement _both_ Read and Write. +#[derive(Debug)] +pub(crate) struct Blocking { + inner: Option, + state: State, +} + +#[derive(Debug)] +pub(crate) struct Buf { + buf: Vec, + pos: usize, +} + +pub(crate) const MAX_BUF: usize = 2 * 1024 * 1024; + +#[derive(Debug)] +enum State { + Idle(Option), + Busy(JoinHandle<(std::io::Result, Buf, T)>), +} + +impl Blocking { + pub(crate) fn new(inner: T) -> Blocking { + Blocking { + inner: Some(inner), + state: State::Idle(Some(Buf::with_capacity(0))), + } + } +} + +impl AsyncRead for Blocking +where + T: Read + Unpin + Send + 'static, +{ + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + dst: &mut ReadBuf<'_>, + ) -> Poll> { + loop { + match self.state { + State::Idle(ref mut buf_cell) => { + let mut buf = buf_cell.take().unwrap(); + + if !buf.is_empty() { + buf.copy_to(dst); + *buf_cell = Some(buf); + return Poll::Ready(Ok(())); + } + + buf.ensure_capacity_for(dst); + let mut inner = self.inner.take().unwrap(); + + self.state = + State::Busy(tokio::task::spawn_blocking(move || { + let res = buf.read_from(&mut inner); + (res, buf, inner) + })); + } + State::Busy(ref mut rx) => { + let (res, mut buf, inner) = ready!(Pin::new(rx).poll(cx))?; + self.inner = Some(inner); + + match res { + Ok(_) => { + buf.copy_to(dst); + self.state = State::Idle(Some(buf)); + return Poll::Ready(Ok(())); + } + Err(e) => { + assert!(buf.is_empty()); + + self.state = State::Idle(Some(buf)); + return Poll::Ready(Err(e)); + } + } + } + } + } + } +} + +/// Repeats operations that are interrupted. +macro_rules! uninterruptibly { + ($e:expr) => {{ + loop { + match $e { + Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {} + res => break res, + } + } + }}; +} + +impl Buf { + pub(crate) fn with_capacity(n: usize) -> Buf { + Buf { + buf: Vec::with_capacity(n), + pos: 0, + } + } + + pub(crate) fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub(crate) fn len(&self) -> usize { + self.buf.len() - self.pos + } + + pub(crate) fn copy_to(&mut self, dst: &mut ReadBuf<'_>) -> usize { + let n = std::cmp::min(self.len(), dst.remaining()); + dst.put_slice(&self.bytes()[..n]); + self.pos += n; + + if self.pos == self.buf.len() { + self.buf.truncate(0); + self.pos = 0; + } + + n + } + + pub(crate) fn bytes(&self) -> &[u8] { + &self.buf[self.pos..] + } + + pub(crate) fn ensure_capacity_for(&mut self, bytes: &ReadBuf<'_>) { + assert!(self.is_empty()); + + let len = std::cmp::min(bytes.remaining(), MAX_BUF); + + if self.buf.len() < len { + self.buf.reserve(len - self.buf.len()); + } + + unsafe { + self.buf.set_len(len); + } + } + + pub(crate) fn read_from( + &mut self, + rd: &mut T, + ) -> std::io::Result { + let res = uninterruptibly!(rd.read(&mut self.buf)); + + if let Ok(n) = res { + self.buf.truncate(n); + } else { + self.buf.clear(); + } + + assert_eq!(self.pos, 0); + + res + } +} diff --git a/packages/app-lib/src/util/mod.rs b/packages/app-lib/src/util/mod.rs index 1962d6c47f5..d0b71c55fbb 100644 --- a/packages/app-lib/src/util/mod.rs +++ b/packages/app-lib/src/util/mod.rs @@ -1,4 +1,6 @@ //! Theseus utility functions +#[cfg(windows)] +pub(crate) mod blocking_reader; pub(crate) mod content_hash; pub mod fetch; pub mod io; diff --git a/packages/app-lib/src/util/rpc.rs b/packages/app-lib/src/util/rpc.rs index e891e146728..918b9500b23 100644 --- a/packages/app-lib/src/util/rpc.rs +++ b/packages/app-lib/src/util/rpc.rs @@ -48,6 +48,7 @@ impl RpcServerBuilder { .await .context("binding rpc server socket")?; let address = socket.local_addr()?; + tracing::info!(%address, "Minecraft launcher RPC server listening"); let (message_sender, message_receiver) = mpsc::unbounded_channel(); let waiting_responses = Arc::new(Mutex::new(HashMap::new())); @@ -132,7 +133,7 @@ impl RpcServer { bail!("rpc connection closed while sending"); } - tracing::debug!("Waiting on result for {id}"); + tracing::debug!(%id, %method, "waiting for Minecraft launcher RPC response"); let Ok(result) = recv.await else { self.waiting_responses.lock().unwrap().remove(&id); bail!("rpc connection closed while waiting for response"); @@ -157,7 +158,8 @@ struct RunningRpcServer { impl RunningRpcServer { async fn run(&mut self, listener: TcpListener) -> Result<()> { - let (socket, _) = listener.accept().await?; + let (socket, peer_address) = listener.accept().await?; + tracing::info!(%peer_address, "Minecraft launcher RPC client connected"); drop(listener); let mut socket = LinesCodec::new().framed(socket); diff --git a/packages/modrinth-sandbox-agent/.gitignore b/packages/modrinth-sandbox-agent/.gitignore new file mode 100644 index 00000000000..2fd9ef51c11 --- /dev/null +++ b/packages/modrinth-sandbox-agent/.gitignore @@ -0,0 +1,3 @@ +.gradle/ +build/ +.idea/ diff --git a/packages/modrinth-sandbox-agent/SandboxAgent.jar b/packages/modrinth-sandbox-agent/SandboxAgent.jar new file mode 100644 index 00000000000..5272c19faa8 Binary files /dev/null and b/packages/modrinth-sandbox-agent/SandboxAgent.jar differ diff --git a/packages/modrinth-sandbox-agent/build.gradle b/packages/modrinth-sandbox-agent/build.gradle new file mode 100644 index 00000000000..357826b3ab4 --- /dev/null +++ b/packages/modrinth-sandbox-agent/build.gradle @@ -0,0 +1,52 @@ +buildscript { + repositories { + mavenCentral() + gradlePluginPortal() + } + dependencies { + classpath("com.gradleup.shadow:com.gradleup.shadow.gradle.plugin:8.3.0") + } +} + +plugins { + id "java" + id "com.gradleup.shadow" version "8.3.0" +} + +group = "com.modrinth" +version = "1.0.0" + +base { + archivesName.set("SandboxAgent") +} + +repositories { + mavenCentral() +} + +dependencies { + shadow(implementation("org.ow2.asm:asm:9.10.1")) + shadow(implementation("org.ow2.asm:asm-tree:9.10.1")) + shadow(implementation("com.google.code.gson:gson:2.14.0")) + compileOnly("org.lwjgl:lwjgl-sdl:3.4.3") + compileOnly("org.lwjgl:lwjgl-nfd:3.4.3") +} + +shadowJar { + configurations = [project.configurations.shadow] + relocate("org.objectweb.asm", "com.modrinth.sandboxagent.org.objectweb.asm") + relocate("com.google", "com.modrinth.sandboxagent.com.google") +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(8)) + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +tasks.jar { + dependsOn(shadowJar) + manifest { + attributes["Premain-Class"] = "com.modrinth.sandboxagent.SandboxAgent" + } +} diff --git a/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.jar b/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..f8e1ee3125f Binary files /dev/null and b/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.properties b/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..37f853b1c84 --- /dev/null +++ b/packages/modrinth-sandbox-agent/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/modrinth-sandbox-agent/gradlew b/packages/modrinth-sandbox-agent/gradlew new file mode 100755 index 00000000000..adff685a034 --- /dev/null +++ b/packages/modrinth-sandbox-agent/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/modrinth-sandbox-agent/gradlew.bat b/packages/modrinth-sandbox-agent/gradlew.bat new file mode 100644 index 00000000000..c4bdd3ab8e3 --- /dev/null +++ b/packages/modrinth-sandbox-agent/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/modrinth-sandbox-agent/obfuscation/generate.py b/packages/modrinth-sandbox-agent/obfuscation/generate.py new file mode 100755 index 00000000000..b0c9f32ddb4 --- /dev/null +++ b/packages/modrinth-sandbox-agent/obfuscation/generate.py @@ -0,0 +1,37 @@ +#!/bin/python3 + +import os +import tarfile +from compression import zstd + +method = input("Intermediary method name: ") + +if not method.startswith("method_"): + print("Expected method to start with method_") + exit(1) + +data = [] + +# The archive is compressed with `zstd --long=31`, so the decompressor must allow a 2 GiB window +mappings_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mappings.tar.zst") +zstd_options = {zstd.DecompressionParameter.window_log_max: 31} +with zstd.ZstdFile(mappings_path, options=zstd_options) as compressed, tarfile.open(fileobj=compressed, mode="r|") as mappings: + for member in mappings: + filename = member.name + if not member.isfile() or not filename.endswith(".tiny"): + continue + contents = mappings.extractfile(member).read().decode("utf-8") + for line in contents.splitlines(): + split = line.strip().split("\t") + if len(split) != 5: + continue + if split[0] == "METHOD" and split[4] == method: + name = filename[:-5] + data.append(name + "," + split[1] + "," + split[3] + "," + split[2]) + +data.sort() + +with open(method+".csv", "w") as f: + for line in data: + f.write(line) + f.write('\n') diff --git a/packages/modrinth-sandbox-agent/obfuscation/licenses/Fabric-LICENSE b/packages/modrinth-sandbox-agent/obfuscation/licenses/Fabric-LICENSE new file mode 100644 index 00000000000..1625c179360 --- /dev/null +++ b/packages/modrinth-sandbox-agent/obfuscation/licenses/Fabric-LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. \ No newline at end of file diff --git a/packages/modrinth-sandbox-agent/obfuscation/licenses/LegacyFabric-LICENSE b/packages/modrinth-sandbox-agent/obfuscation/licenses/LegacyFabric-LICENSE new file mode 100644 index 00000000000..1625c179360 --- /dev/null +++ b/packages/modrinth-sandbox-agent/obfuscation/licenses/LegacyFabric-LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. \ No newline at end of file diff --git a/packages/modrinth-sandbox-agent/obfuscation/licenses/README.md b/packages/modrinth-sandbox-agent/obfuscation/licenses/README.md new file mode 100644 index 00000000000..79bf42d2755 --- /dev/null +++ b/packages/modrinth-sandbox-agent/obfuscation/licenses/README.md @@ -0,0 +1,7 @@ +The 1.14+ files in mappings.tar.zst are released under Creative Commons Zero v1.0 Universal via https://github.com/FabricMC/intermediary/ + +See Fabric-LICENSE for more details + +The 1.13 and below files in mappings.tar.zst are released under Creative Commons Zero v1.0 Universal via https://github.com/Legacy-Fabric/Legacy-Intermediaries/ + +See LegacyFabric-LICENSE for more details \ No newline at end of file diff --git a/packages/modrinth-sandbox-agent/obfuscation/mappings.tar.zst b/packages/modrinth-sandbox-agent/obfuscation/mappings.tar.zst new file mode 100644 index 00000000000..dc7c48dd0b3 Binary files /dev/null and b/packages/modrinth-sandbox-agent/obfuscation/mappings.tar.zst differ diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/MinecraftVersionInfo.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/MinecraftVersionInfo.java new file mode 100644 index 00000000000..e57bc1269db --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/MinecraftVersionInfo.java @@ -0,0 +1,46 @@ +package com.modrinth.sandboxagent; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +public class MinecraftVersionInfo { + + private static final Gson GSON = new Gson(); + + public String id = null; + public String name = null; + public int dataVersion = 0; + + public MinecraftVersionInfo(String json) { + if (json == null) { + return; + } + + JsonObject minecraftVersion = GSON.fromJson(json, JsonObject.class); + if (minecraftVersion == null) { + return; + } + + JsonElement id = minecraftVersion.get("id"); + if (id instanceof JsonPrimitive) { + this.id = id.getAsString(); + } + + JsonElement name = minecraftVersion.get("name"); + if (name instanceof JsonPrimitive) { + this.name = name.getAsString(); + } + + JsonElement dataVersion = minecraftVersion.get("world_version"); + if (dataVersion instanceof JsonPrimitive) { + this.dataVersion = dataVersion.getAsInt(); + } + } + + public boolean isObfuscated() { + return this.dataVersion < 4764; // Java Edition 26.1 Snapshot 1 + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxAgent.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxAgent.java new file mode 100644 index 00000000000..3c411111625 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxAgent.java @@ -0,0 +1,67 @@ +package com.modrinth.sandboxagent; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.instrument.Instrumentation; +import java.nio.charset.StandardCharsets; + +import com.modrinth.sandboxagent.transformation.*; +import com.modrinth.sandboxagent.transformer.TransformerMap; + +public class SandboxAgent { + public static void premain(String agentArgs, Instrumentation inst) { + instrument(inst); + } + + private static void instrument(Instrumentation inst) { + TransformerMap transformerMap = new TransformerMap(); + + String minecraftVersionJson = readResourceToString("/version.json"); + MinecraftVersionInfo minecraftVersionInfo = new MinecraftVersionInfo(minecraftVersionJson); + + if (System.getProperty("modrinth.sandboxagent.transform.openuri", "").equals("true")) { + // Replaces Util$OS#openUri with sandbox api call + OpenUriTransformation.register(transformerMap, minecraftVersionInfo); + } + if (System.getProperty("modrinth.sandboxagent.transform.dragdrop", "").equals("true")) { + // Requests access to certain files outside the sandbox when drag-dropping + DropFileTransformation.register(transformerMap, minecraftVersionInfo); + } + if (System.getProperty("modrinth.sandboxagent.transform.filedialog", "").equals("true")) { + // Transform various file dialog APIs (SDL, NFD, TFD) to use our api instead + FileDialogTransformation.register(transformerMap); + } + if (System.getProperty("modrinth.sandboxagent.transform.auth", "").equals("true")) { + // Replaces realms url generation to point to sandbox api + RealmsTransformation.register(transformerMap, minecraftVersionInfo); + // Modifies auth code on older versions of Minecraft to use our proxy + AuthTransformation.register(transformerMap, minecraftVersionInfo); + } + + inst.addTransformer(transformerMap); + } + + public static String readResourceToString(String file) { + try (InputStream is = SandboxAgent.class.getResourceAsStream(file)) { + if (is == null) { + return null; + } + return readInputStreamToString(is); + } catch (IOException ignored) {} + return null; + } + + public static String readInputStreamToString(InputStream is) throws IOException { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + byte[] chunk = new byte[8192]; + int read; + while ((read = is.read(chunk)) != -1) { + baos.write(chunk, 0, read); + } + return new String(baos.toByteArray(), StandardCharsets.UTF_8); + } + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxApi.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxApi.java new file mode 100644 index 00000000000..d46e4e07ae3 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/SandboxApi.java @@ -0,0 +1,154 @@ +package com.modrinth.sandboxagent; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +public class SandboxApi { + + private static SandboxApi sandboxApi = null; + + private final String sandboxApiAuthorization; + private final String baseUrl; + + public SandboxApi(String secret, int port) { + this.sandboxApiAuthorization = "Bearer " + secret; + this.baseUrl = "http://127.0.0.1:" + port; + } + + public static SandboxApi getOrInit() { + if (sandboxApi != null) { + return sandboxApi; + } + String secret = System.getProperty("modrinth.sandboxagent.secret", ""); + if (secret.isEmpty()) { + throw new RuntimeException("Missing -Dmodrinth.sandboxagent.secret argument"); + } + String portStr = System.getProperty("modrinth.sandboxagent.port", ""); + if (portStr.isEmpty()) { + throw new RuntimeException("Missing -Dmodrinth.sandboxagent.port argument"); + } + int port = Integer.parseInt(portStr); + + sandboxApi = new SandboxApi(secret, port); + return sandboxApi; + } + + public String getBaseUrl() { + return this.baseUrl; + } + + public void openUri(URI uri) { + HttpURLConnection conn = null; + try { + String encodedUri = URLEncoder.encode(uri.toString(), StandardCharsets.UTF_8.toString()); + conn = (HttpURLConnection) new URL(this.baseUrl + "/sandboxapi/open-uri?uri="+encodedUri).openConnection(); + conn.setRequestProperty("Authorization", this.sandboxApiAuthorization); + conn.setRequestMethod("POST"); + int responseCode = conn.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) { + System.err.println("Unable to use sandboxapi openUri, got error code " + responseCode); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.disconnect(); + } + } + } + + public Path tryRequestAccess(Path originalPath) { + HttpURLConnection conn = null; + try { + String encodedPath = URLEncoder.encode(originalPath.toString(), StandardCharsets.UTF_8.toString()); + conn = (HttpURLConnection) new URL(this.baseUrl + "/sandboxapi/request-access?path="+encodedPath).openConnection(); + conn.setRequestProperty("Authorization", this.sandboxApiAuthorization); + conn.setRequestMethod("GET"); + int responseCode = conn.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) { + System.err.println("Unable to use sandboxapi requestAccess, got error code " + responseCode); + return originalPath; + } + return Paths.get(SandboxAgent.readInputStreamToString(conn.getInputStream())); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.disconnect(); + } + } + return originalPath; + } + + public List openFileDialog(String title, String acceptLabel, boolean save, boolean multiple, boolean directory, List filters, String defaultLocation) { + HttpURLConnection conn = null; + try { + StringBuilder url = new StringBuilder(this.baseUrl); + url.append("/sandboxapi/open-file-dialog"); + + AtomicBoolean first = new AtomicBoolean(true); + if (title != null) { + addQueryArg(url, first, "title", title); + } + if (acceptLabel != null) { + addQueryArg(url, first, "accept_label", acceptLabel); + } + addQueryArg(url, first, "save", Boolean.toString(save)); + addQueryArg(url, first, "multiple", Boolean.toString(multiple)); + addQueryArg(url, first, "directory", Boolean.toString(directory)); + if (filters != null) { + for (String filter : filters) { + addQueryArg(url, first, "filter", filter); + } + } + if (defaultLocation != null) { + addQueryArg(url, first, "default_location", defaultLocation); + } + + conn = (HttpURLConnection) new URL(url.toString()).openConnection(); + conn.setRequestProperty("Authorization", this.sandboxApiAuthorization); + conn.setRequestMethod("GET"); + int responseCode = conn.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) { + System.err.println("Unable to use sandboxapi openFileDialog, got error code " + responseCode); + return null; + } + + List paths = new ArrayList<>(); + String result = SandboxAgent.readInputStreamToString(conn.getInputStream()); + for (String line : result.split("\n")) { + String path = line.trim(); + if (!path.isEmpty()) { + paths.add(Paths.get(path)); + } + } + return paths; + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.disconnect(); + } + } + return null; + } + + private static void addQueryArg(StringBuilder url, AtomicBoolean first, String key, String value) throws UnsupportedEncodingException { + if (first.compareAndSet(true, false)) { + url.append('?'); + } else { + url.append('&'); + } + url.append(URLEncoder.encode(key, StandardCharsets.UTF_8.toString())); + url.append('='); + url.append(URLEncoder.encode(value, StandardCharsets.UTF_8.toString())); + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/NFDFileDialog.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/NFDFileDialog.java new file mode 100644 index 00000000000..1ab4685d788 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/NFDFileDialog.java @@ -0,0 +1,259 @@ +package com.modrinth.sandboxagent.implementation; + +import com.modrinth.sandboxagent.SandboxApi; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.nfd.*; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class NFDFileDialog { + + private static final Set overridenAllocations = ConcurrentHashMap.newKeySet(); + private static final Map> overriddenPathSets = new ConcurrentHashMap<>(); + private static final Map overriddenEnums = new ConcurrentHashMap<>(); + + private static final class PathSetCursor { + private final List paths; + private int next = 0; + + private PathSetCursor(List paths) { + this.paths = paths; + } + } + + private static long allocatePath(String path) { + long allocation = MemoryUtil.memAddress(MemoryUtil.memUTF8(path)); + overridenAllocations.add(allocation); + return allocation; + } + + public static boolean handleNfdFreeBuffer(ByteBuffer path) { + return path != null && handleNfdFreeLong(MemoryUtil.memAddress(path)); + } + + public static boolean handleNfdFreeLong(long path) { + if (overridenAllocations.remove(path)) { + MemoryUtil.nmemFree(path); + return true; + } + return false; + } + + public static OptionalInt handlePathSetGetCount(long pathSet, IntBuffer count) { + List paths = overriddenPathSets.get(pathSet); + if (paths == null) { + return OptionalInt.empty(); + } + count.put(count.position(), paths.size()); + return OptionalInt.of(NativeFileDialog.NFD_OKAY); + } + + public static OptionalInt handlePathSetGetCount(long pathSet, int[] count) { + List paths = overriddenPathSets.get(pathSet); + if (paths == null) { + return OptionalInt.empty(); + } + count[0] = paths.size(); + return OptionalInt.of(NativeFileDialog.NFD_OKAY); + } + + public static OptionalInt handlePathSetGetPath(long pathSet, int index, PointerBuffer outPath) { + List paths = overriddenPathSets.get(pathSet); + if (paths == null) { + return OptionalInt.empty(); + } + if (index < 0 || index >= paths.size()) { + return OptionalInt.of(NativeFileDialog.NFD_ERROR); + } + outPath.put(outPath.position(), allocatePath(paths.get(index))); + return OptionalInt.of(NativeFileDialog.NFD_OKAY); + } + + public static OptionalInt handlePathSetGetEnum(long pathSet, NFDPathSetEnum outEnumerator) { + List paths = overriddenPathSets.get(pathSet); + if (paths == null) { + return OptionalInt.empty(); + } + long cursor = MemoryUtil.nmemAllocChecked(1); + overriddenEnums.put(cursor, new PathSetCursor(paths)); + MemoryUtil.memPutAddress(outEnumerator.address(), cursor); + return OptionalInt.of(NativeFileDialog.NFD_OKAY); + } + + public static OptionalInt handlePathSetEnumNext(NFDPathSetEnum enumerator, PointerBuffer outPath) { + if (enumerator == null) { + return OptionalInt.empty(); + } + PathSetCursor cursor = overriddenEnums.get(MemoryUtil.memGetAddress(enumerator.address())); + if (cursor == null) { + return OptionalInt.empty(); + } + synchronized (cursor) { + if (cursor.next < cursor.paths.size()) { + outPath.put(outPath.position(), allocatePath(cursor.paths.get(cursor.next++))); + } else { + outPath.put(outPath.position(), MemoryUtil.NULL); + } + } + return OptionalInt.of(NativeFileDialog.NFD_OKAY); + } + + public static boolean handlePathSetFreeEnum(NFDPathSetEnum enumerator) { + if (enumerator == null) { + return false; + } + long cursor = MemoryUtil.memGetAddress(enumerator.address()); + if (overriddenEnums.remove(cursor) != null) { + MemoryUtil.nmemFree(cursor); + MemoryUtil.memPutAddress(enumerator.address(), MemoryUtil.NULL); + return true; + } + return false; + } + + public static boolean handlePathSetFree(long pathSet) { + if (overriddenPathSets.remove(pathSet) != null) { + MemoryUtil.nmemFree(pathSet); + return true; + } + return false; + } + + public static int handleNfd(PointerBuffer outPath, NFDFilterItem.Buffer filterList, CharSequence defaultPath, boolean save, boolean multiple, boolean directory) { + System.out.println("Using launcher SandboxApi to handle file dialog"); + + String locationString = defaultPath == null ? null : defaultPath.toString(); + + List filters = new ArrayList<>(); + if (filterList != null) { + for (NFDFilterItem item : filterList) { + for (String individualPattern : item.specString().split("[;,]")) { + individualPattern = individualPattern.trim(); + if (individualPattern.isEmpty()) { + continue; + } + + String[] parts = individualPattern.split("\\."); + String extension = parts[parts.length - 1]; + + String name = item.nameString(); + filters.add(extension + "," + name); + } + } + } + + List paths = SandboxApi.getOrInit().openFileDialog(null, null, save, multiple, + directory, filters, locationString); + + if (paths == null) { + return NativeFileDialog.NFD_ERROR; + } else if (paths.isEmpty()) { + return NativeFileDialog.NFD_CANCEL; + } else if (multiple) { + List pathStrings = new ArrayList<>(paths.size()); + for (Path path : paths) { + pathStrings.add(path.toString()); + } + long pathSet = MemoryUtil.nmemAllocChecked(1); + overriddenPathSets.put(pathSet, pathStrings); + outPath.put(outPath.position(), pathSet); + return NativeFileDialog.NFD_OKAY; + } else { + outPath.put(outPath.position(), allocatePath(paths.get(0).toString())); + return NativeFileDialog.NFD_OKAY; + } + } + + public static int handleNfdOpen(PointerBuffer outPath, NFDFilterItem.Buffer filterList, ByteBuffer defaultPath) { + return handleNfd(outPath, filterList, MemoryUtil.memUTF8Safe(defaultPath), false, false, false); + } + + public static int handleNfdOpen(PointerBuffer outPath, NFDFilterItem.Buffer filterList, CharSequence defaultPath) { + return handleNfd(outPath, filterList, defaultPath, false, false, false); + } + + public static int handleNfdOpen(PointerBuffer outPath, NFDOpenDialogArgs args) { + return handleNfd(outPath, args.filterList(), args.defaultPathString(), false, false, false); + } + + public static int handleNfdOpenMultiple(PointerBuffer outPath, NFDFilterItem.Buffer filterList, ByteBuffer defaultPath) { + return handleNfd(outPath, filterList, MemoryUtil.memUTF8Safe(defaultPath), false, true, false); + } + + public static int handleNfdOpenMultiple(PointerBuffer outPath, NFDFilterItem.Buffer filterList, CharSequence defaultPath) { + return handleNfd(outPath, filterList, defaultPath, false, true, false); + } + + public static int handleNfdOpenMultiple(PointerBuffer outPath, NFDOpenDialogArgs args) { + return handleNfd(outPath, args.filterList(), args.defaultPathString(), false, true, false); + } + + private static String makeDefaultPathFromFolderAndName(CharSequence defaultFolder, CharSequence defaultName) { + StringBuilder path = new StringBuilder(); + if (defaultFolder != null) { + path.append(defaultFolder); + } else { + path.append(System.getProperty("user.dir", ".")); + } + + if (!path.toString().endsWith(File.separator)) { + path.append(File.separatorChar); + } + + if (defaultName != null) { + path.append(defaultName); + } + + return path.toString(); + } + + public static int handleNfdSave(PointerBuffer outPath, NFDFilterItem.Buffer filterList, ByteBuffer defaultFolder, ByteBuffer defaultName) { + String defaultPath = makeDefaultPathFromFolderAndName(MemoryUtil.memUTF8Safe(defaultFolder), MemoryUtil.memUTF8Safe(defaultName)); + return handleNfd(outPath, filterList, defaultPath, true, false, false); + } + + public static int handleNfdSave(PointerBuffer outPath, NFDFilterItem.Buffer filterList, CharSequence defaultFolder, CharSequence defaultName) { + String defaultPath = makeDefaultPathFromFolderAndName(defaultFolder, defaultName); + return handleNfd(outPath, filterList, defaultPath, true, false, false); + } + + public static int handleNfdSave(PointerBuffer outPath, NFDSaveDialogArgs args) { + String defaultPath = makeDefaultPathFromFolderAndName(args.defaultPathString(), args.defaultNameString()); + return handleNfd(outPath, args.filterList(), defaultPath, true, false, false); + } + + public static int handleNfdFolder(PointerBuffer outPath, ByteBuffer defaultPath) { + return handleNfd(outPath, null, MemoryUtil.memUTF8Safe(defaultPath), false, false, true); + } + + public static int handleNfdFolder(PointerBuffer outPath, CharSequence defaultPath) { + return handleNfd(outPath, null, defaultPath, false, false, true); + } + + public static int handleNfdFolder(PointerBuffer outPath, NFDPickFolderArgs args) { + return handleNfd(outPath, null, args.defaultPathString(), false, false, true); + } + + public static int handleNfdFolderMultiple(PointerBuffer outPath, ByteBuffer defaultPath) { + return handleNfd(outPath, null, MemoryUtil.memUTF8Safe(defaultPath), false, true, true); + } + + public static int handleNfdFolderMultiple(PointerBuffer outPath, CharSequence defaultPath) { + return handleNfd(outPath, null, defaultPath, false, true, true); + } + + public static int handleNfdFolderMultiple(PointerBuffer outPath, NFDPickFolderArgs args) { + return handleNfd(outPath, null, args.defaultPathString(), false, true, true); + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/SDLFileDialog.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/SDLFileDialog.java new file mode 100644 index 00000000000..8d70155a5af --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/SDLFileDialog.java @@ -0,0 +1,122 @@ +package com.modrinth.sandboxagent.implementation; + +import com.modrinth.sandboxagent.SandboxApi; +import org.lwjgl.PointerBuffer; +import org.lwjgl.sdl.*; +import org.lwjgl.system.Callback; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class SDLFileDialog { + + public static void handleSdlOpen(long callback, long userdata, long window, long filters, int nfilters, long default_location, boolean allow_many) { + int props = SDLProperties.SDL_CreateProperties(); + + SDLProperties.SDL_SetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_FILTERS_POINTER, filters); + SDLProperties.SDL_SetNumberProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER, nfilters); + SDLProperties.SDL_SetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_WINDOW_POINTER, window); + SDLProperties.SDL_SetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_LOCATION_STRING, MemoryUtil.memUTF8Safe(default_location)); + SDLProperties.SDL_SetBooleanProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_MANY_BOOLEAN, allow_many); + + handleSdlWithProperties(SDLDialog.SDL_FILEDIALOG_OPENFILE, callback, userdata, props); + + SDLProperties.SDL_DestroyProperties(props); + } + + public static void handleSdlSave(long callback, long userdata, long window, long filters, int nfilters, long default_location) { + int props = SDLProperties.SDL_CreateProperties(); + + SDLProperties.SDL_SetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_FILTERS_POINTER, filters); + SDLProperties.SDL_SetNumberProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER, nfilters); + SDLProperties.SDL_SetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_WINDOW_POINTER, window); + SDLProperties.SDL_SetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_LOCATION_STRING, MemoryUtil.memUTF8Safe(default_location)); + + handleSdlWithProperties(SDLDialog.SDL_FILEDIALOG_SAVEFILE, callback, userdata, props); + + SDLProperties.SDL_DestroyProperties(props); + } + + public static void handleSdlFolder(long callback, long userdata, long window, long default_location, boolean allow_many) { + int props = SDLProperties.SDL_CreateProperties(); + + SDLProperties.SDL_SetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_WINDOW_POINTER, window); + SDLProperties.SDL_SetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_LOCATION_STRING, MemoryUtil.memUTF8Safe(default_location)); + SDLProperties.SDL_SetBooleanProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_MANY_BOOLEAN, allow_many); + + handleSdlWithProperties(SDLDialog.SDL_FILEDIALOG_OPENFOLDER, callback, userdata, props); + + SDLProperties.SDL_DestroyProperties(props); + } + + public static void handleSdlWithProperties(int type, long callback, long userdata, int props) { + System.out.println("Using launcher SandboxApi to handle file dialog"); + + boolean save = type == SDLDialog.SDL_FILEDIALOG_SAVEFILE; + boolean multiple = SDLProperties.SDL_GetBooleanProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_MANY_BOOLEAN, false); + boolean directory = type == SDLDialog.SDL_FILEDIALOG_OPENFOLDER; + + long filtersPtr = SDLProperties.SDL_GetPointerProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_FILTERS_POINTER, 0); + long nfilters = SDLProperties.SDL_GetNumberProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER, 0); + + List filters = new ArrayList<>((int) Math.min(32, nfilters)); + if (filtersPtr != 0 && nfilters > 0) { + for (long i = 0; i < Math.min(32, nfilters); i++) { + long struct = filtersPtr + SDL_DialogFileFilter.SIZEOF * i; + + String pattern = SDL_DialogFileFilter.npatternString(struct); + for (String individualPattern : pattern.split("[;,]")) { + individualPattern = individualPattern.trim(); + if (individualPattern.isEmpty()) { + continue; + } + + String[] parts = individualPattern.split("\\."); + String extension = parts[parts.length - 1]; + + String name = SDL_DialogFileFilter.nnameString(struct); + filters.add(extension + "," + name); + } + } + } + + String locationString = SDLProperties.SDL_GetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_LOCATION_STRING, null); + String titleString = SDLProperties.SDL_GetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_TITLE_STRING, null); + String acceptString = SDLProperties.SDL_GetStringProperty(props, SDLDialog.SDL_PROP_FILE_DIALOG_ACCEPT_STRING, null); + + CompletableFuture.runAsync(() -> { + List paths = SandboxApi.getOrInit().openFileDialog(titleString, acceptString, save, multiple, + directory, filters, locationString); + if (paths == null) { + SDLError.SDL_SetError("Failed to use launcher SandboxApi to create file dialog"); + SDL_DialogFileCallbackI dialogFileCallback = Callback.getSafe(callback); + if (dialogFileCallback == null) { + throw new RuntimeException("Failed to get SDL_DialogFileCallbackI from callback ptr"); + } + dialogFileCallback.invoke(userdata, MemoryUtil.NULL, -1); + } else { + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer pointerBuffer = stack.callocPointer(paths.size() + 1); + + for (int i = 0; i < paths.size(); i++) { + Path path = paths.get(i); + ByteBuffer encoded = stack.UTF8(path.toString(), true); + pointerBuffer.put(i, encoded); + } + + SDL_DialogFileCallbackI dialogFileCallback = Callback.getSafe(callback); + if (dialogFileCallback == null) { + throw new RuntimeException("Failed to get SDL_DialogFileCallbackI from callback ptr"); + } + dialogFileCallback.invoke(userdata, MemoryUtil.memAddress(pointerBuffer), -1); + } + } + }); + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/TinyFileDialog.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/TinyFileDialog.java new file mode 100644 index 00000000000..bf814b23f3d --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/implementation/TinyFileDialog.java @@ -0,0 +1,83 @@ +package com.modrinth.sandboxagent.implementation; + +import com.modrinth.sandboxagent.SandboxApi; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +public class TinyFileDialog { + + private static final String MULTIPLE_SEPARATOR = "|"; + + private static String handleTinyfd(CharSequence title, CharSequence defaultPath, PointerBuffer filterPatterns, CharSequence filterDescription, boolean save, boolean multiple, boolean directory) { + System.out.println("Using launcher SandboxApi to handle file dialog"); + + List filters = new ArrayList<>(); + if (filterPatterns != null) { + String name = filterDescription == null ? null : filterDescription.toString(); + for (int i = filterPatterns.position(); i < filterPatterns.limit(); i++) { + String pattern = MemoryUtil.memUTF8Safe(filterPatterns.get(i)); + if (pattern == null) { + continue; + } + + for (String individualPattern : pattern.split("[;,\\s]")) { + int dot = individualPattern.lastIndexOf('.'); + String extension = individualPattern.substring(dot + 1).trim(); + if (extension.isEmpty() || extension.contains("*")) { + continue; + } + + filters.add(extension + "," + (name == null ? individualPattern.trim() : name)); + } + } + } + + List paths = SandboxApi.getOrInit().openFileDialog( + title == null ? null : title.toString(), null, save, multiple, directory, filters, + defaultPath == null ? null : defaultPath.toString()); + + if (paths == null || paths.isEmpty()) { + return null; + } + + StringBuilder result = new StringBuilder(paths.get(0).toString()); + if (multiple) { + for (int i = 1; i < paths.size(); i++) { + result.append(MULTIPLE_SEPARATOR).append(paths.get(i)); + } + } + return result.toString(); + } + + public static String handleTinyfdOpen(ByteBuffer title, ByteBuffer defaultPathAndFile, PointerBuffer filterPatterns, ByteBuffer singleFilterDescription, boolean allowMultipleSelects) { + return handleTinyfd(MemoryUtil.memUTF8Safe(title), MemoryUtil.memUTF8Safe(defaultPathAndFile), filterPatterns, + MemoryUtil.memUTF8Safe(singleFilterDescription), false, allowMultipleSelects, false); + } + + public static String handleTinyfdOpen(CharSequence title, CharSequence defaultPathAndFile, PointerBuffer filterPatterns, CharSequence singleFilterDescription, boolean allowMultipleSelects) { + return handleTinyfd(title, defaultPathAndFile, filterPatterns, singleFilterDescription, false, allowMultipleSelects, false); + } + + public static String handleTinyfdSave(ByteBuffer title, ByteBuffer defaultPathAndFile, PointerBuffer filterPatterns, ByteBuffer singleFilterDescription) { + return handleTinyfd(MemoryUtil.memUTF8Safe(title), MemoryUtil.memUTF8Safe(defaultPathAndFile), filterPatterns, + MemoryUtil.memUTF8Safe(singleFilterDescription), true, false, false); + } + + public static String handleTinyfdSave(CharSequence title, CharSequence defaultPathAndFile, PointerBuffer filterPatterns, CharSequence singleFilterDescription) { + return handleTinyfd(title, defaultPathAndFile, filterPatterns, singleFilterDescription, true, false, false); + } + + public static String handleTinyfdFolder(ByteBuffer title, ByteBuffer defaultPath) { + return handleTinyfd(MemoryUtil.memUTF8Safe(title), MemoryUtil.memUTF8Safe(defaultPath), null, null, false, false, true); + } + + public static String handleTinyfdFolder(CharSequence title, CharSequence defaultPath) { + return handleTinyfd(title, defaultPath, null, null, false, false, true); + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/AuthTransformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/AuthTransformation.java new file mode 100644 index 00000000000..3140f185b39 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/AuthTransformation.java @@ -0,0 +1,47 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.MinecraftVersionInfo; +import com.modrinth.sandboxagent.transformer.TransformerMap; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +import java.util.ListIterator; + +public class AuthTransformation { + + public static void register(TransformerMap transformerMap, MinecraftVersionInfo minecraftVersionInfo) { + // Transform authlib 1.x + transformerMap.registerMethod("com/mojang/authlib/HttpAuthenticationService", "constantURL", "(Ljava/lang/String;)Ljava/net/URL;", AuthTransformation::transform); + } + + private static boolean transform(ListIterator it, boolean isStatic) { + it.add(new VarInsnNode(Opcodes.ALOAD, isStatic ? 0 : 1)); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/modrinth/sandboxagent/transformation/AuthTransformation", + "modifyConstantUrl", "(Ljava/lang/String;)Ljava/lang/String;")); + it.add(new VarInsnNode(Opcodes.ASTORE, isStatic ? 0 : 1)); + return true; + } + + public static String modifyConstantUrl(String url) { + url = replaceFromProperty(url, "https://authserver.mojang.com/", "minecraft.api.auth.host"); + url = replaceFromProperty(url, "https://api.mojang.com/", "minecraft.api.account.host"); + url = replaceFromProperty(url, "https://sessionserver.mojang.com/", "minecraft.api.session.host"); + url = replaceFromProperty(url, "https://api.minecraftservices.com/", "minecraft.api.services.host"); + + return url; + } + + private static String replaceFromProperty(String url, String baseUrl, String property) { + if (url.startsWith(baseUrl)) { + String customAuthHost = System.getProperty(property); + if (customAuthHost != null) { + if (!customAuthHost.endsWith("/")) { + customAuthHost += "/"; + } + return customAuthHost + url.substring(baseUrl.length()); + } + } + return url; + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/DropFileTransformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/DropFileTransformation.java new file mode 100644 index 00000000000..8370834d804 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/DropFileTransformation.java @@ -0,0 +1,109 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.MinecraftVersionInfo; +import com.modrinth.sandboxagent.SandboxApi; +import com.modrinth.sandboxagent.transformer.TransformerMap; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; +import java.util.concurrent.CompletableFuture; + +public class DropFileTransformation { + + public static void register(TransformerMap transformerMap, MinecraftVersionInfo minecraftVersionInfo) { + String[] descs = new String[]{"(JLjava/util/List;)V", "(JLjava/util/List;I)V"}; + for (String desc : descs) { + // Mojang + transformerMap.registerMethod("net/minecraft/client/MouseHandler", "onDrop", desc, DropFileTransformation::transform); + + // Intermediary + transformerMap.registerMethod("net/minecraft/class_312", "method_29616", desc, DropFileTransformation::transform); + // SRG + transformerMap.registerMethod("net/minecraft/src/C_3397_", "m_91539_", desc, DropFileTransformation::transform); + // Old MCP (Intermediary) + transformerMap.registerMethod("net/minecraft/client/MouseHelper", "func_238228_a_", desc, DropFileTransformation::transform); + // Old MCP (Unobfuscated) + transformerMap.registerMethod("net/minecraft/client/MouseHelper", "addPacksToScreen", desc, DropFileTransformation::transform); + } + + Transformation.registerObfuscated(transformerMap, DropFileTransformation::transform, + minecraftVersionInfo, "/com/modrinth/sandboxagent/method_29616.csv"); + } + + private static boolean transform(ListIterator it, boolean isStatic) { + it.add(new VarInsnNode(Opcodes.ALOAD, isStatic ? 2 : 3)); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/modrinth/sandboxagent/transformation/DropFileTransformation", + "accessPaths", "(Ljava/util/List;)Ljava/util/List;")); + it.add(new VarInsnNode(Opcodes.ASTORE, isStatic ? 2 : 3)); + return true; + } + + public static List accessPaths(List list) { + if (list.isEmpty()) { + return list; + } + + boolean changed = false; + List> futureList = new ArrayList<>(); + + SandboxApi sandboxApi = SandboxApi.getOrInit(); + + for (Object o : list) { + Path path; + Class srcType; + + if (o instanceof Path) { + path = (Path) o; + srcType = Path.class; + } else if (o instanceof File) { + path = ((File) o).toPath(); + srcType = File.class; + } else if (o instanceof String) { + path = Paths.get((String) o); + srcType = String.class; + } else { + futureList.add(CompletableFuture.completedFuture(o)); + continue; + } + + if (!Files.isReadable(path)) { + futureList.add(CompletableFuture.supplyAsync(() -> sandboxApi.tryRequestAccess(path)) + .thenApply(newPath -> { + if (srcType == Path.class) { + return newPath; + } else if (srcType == File.class) { + return newPath.toFile(); + } else if (srcType == String.class) { + return newPath.toString(); + } else { + return null; + } + })); + changed = true; + } else { + futureList.add(CompletableFuture.completedFuture(o)); + } + } + + if (!changed) { + return list; + } + + List newList = new ArrayList<>(); + for (CompletableFuture future : futureList) { + Object o = future.join(); + if (o != null) { + newList.add(o); + } + } + return newList; + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/FileDialogTransformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/FileDialogTransformation.java new file mode 100644 index 00000000000..a118124388f --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/FileDialogTransformation.java @@ -0,0 +1,72 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.implementation.NFDFileDialog; +import com.modrinth.sandboxagent.implementation.SDLFileDialog; +import com.modrinth.sandboxagent.implementation.TinyFileDialog; +import com.modrinth.sandboxagent.transformer.TransformerMap; + +public class FileDialogTransformation { + + public static void register(TransformerMap transformerMap) { + // SDL + String sdl = "org/lwjgl/sdl/SDLDialog"; + Transformation.registerOverwrite(transformerMap, sdl, "nSDL_ShowOpenFileDialog", "(JJJJIJZ)V", SDLFileDialog.class, "handleSdlOpen"); + Transformation.registerOverwrite(transformerMap, sdl, "nSDL_ShowSaveFileDialog", "(JJJJIJ)V", SDLFileDialog.class, "handleSdlSave"); + Transformation.registerOverwrite(transformerMap, sdl, "nSDL_ShowOpenFolderDialog", "(JJJJZ)V", SDLFileDialog.class, "handleSdlFolder"); + Transformation.registerOverwrite(transformerMap, sdl, "nSDL_ShowFileDialogWithProperties", "(IJJI)V", SDLFileDialog.class, "handleSdlWithProperties"); + + // NFD (Native File Dialogs) + String nfd = "org/lwjgl/util/nfd/NativeFileDialog"; + String pointerBuffer = "Lorg/lwjgl/PointerBuffer;"; + String filterList = "Lorg/lwjgl/util/nfd/NFDFilterItem$Buffer;"; + String byteBuffer = "Ljava/nio/ByteBuffer;"; + String charSequence = "Ljava/lang/CharSequence;"; + String pathSetEnum = "Lorg/lwjgl/util/nfd/NFDPathSetEnum;"; + + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_FreePath", "(" + byteBuffer + ")V", NFDFileDialog.class, "handleNfdFreeBuffer"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_FreePath", "(J)V", NFDFileDialog.class, "handleNfdFreeLong"); + + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialog", "(" + pointerBuffer + filterList + byteBuffer + ")I", NFDFileDialog.class, "handleNfdOpen"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialog", "(" + pointerBuffer + filterList + charSequence + ")I", NFDFileDialog.class, "handleNfdOpen"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialog_With", "(" + pointerBuffer + "Lorg/lwjgl/util/nfd/NFDOpenDialogArgs;)I", NFDFileDialog.class, "handleNfdOpen"); + + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialogMultiple", "(" + pointerBuffer + filterList + byteBuffer + ")I", NFDFileDialog.class, "handleNfdOpenMultiple"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialogMultiple", "(" + pointerBuffer + filterList + charSequence + ")I", NFDFileDialog.class, "handleNfdOpenMultiple"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_OpenDialogMultiple_With", "(" + pointerBuffer + "Lorg/lwjgl/util/nfd/NFDOpenDialogArgs;)I", NFDFileDialog.class, "handleNfdOpenMultiple"); + + Transformation.registerOverwrite(transformerMap, nfd, "NFD_SaveDialog", "(" + pointerBuffer + filterList + byteBuffer + byteBuffer + ")I", NFDFileDialog.class, "handleNfdSave"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_SaveDialog", "(" + pointerBuffer + filterList + charSequence + charSequence + ")I", NFDFileDialog.class, "handleNfdSave"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_SaveDialog_With", "(" + pointerBuffer + "Lorg/lwjgl/util/nfd/NFDSaveDialogArgs;)I", NFDFileDialog.class, "handleNfdSave"); + + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolder", "(" + pointerBuffer + byteBuffer + ")I", NFDFileDialog.class, "handleNfdFolder"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolder", "(" + pointerBuffer + charSequence + ")I", NFDFileDialog.class, "handleNfdFolder"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolder_With", "(" + pointerBuffer + "Lorg/lwjgl/util/nfd/NFDPickFolderArgs;)I", NFDFileDialog.class, "handleNfdFolder"); + + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolderMultiple", "(" + pointerBuffer + byteBuffer + ")I", NFDFileDialog.class, "handleNfdFolderMultiple"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolderMultiple", "(" + pointerBuffer + charSequence + ")I", NFDFileDialog.class, "handleNfdFolderMultiple"); + Transformation.registerOverwrite(transformerMap, nfd, "NFD_PickFolderMultiple_With", "(" + pointerBuffer + "Lorg/lwjgl/util/nfd/NFDPickFolderArgs;)I", NFDFileDialog.class, "handleNfdFolderMultiple"); + + // NFD path sets, returned by the "Multiple" dialogs + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_GetCount", "(JLjava/nio/IntBuffer;)I", NFDFileDialog.class, "handlePathSetGetCount"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_GetCount", "(J[I)I", NFDFileDialog.class, "handlePathSetGetCount"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_GetPath", "(JI" + pointerBuffer + ")I", NFDFileDialog.class, "handlePathSetGetPath"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_GetEnum", "(J" + pathSetEnum + ")I", NFDFileDialog.class, "handlePathSetGetEnum"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_EnumNext", "(" + pathSetEnum + pointerBuffer + ")I", NFDFileDialog.class, "handlePathSetEnumNext"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_FreePath", "(" + byteBuffer + ")V", NFDFileDialog.class, "handleNfdFreeBuffer"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_FreePath", "(J)V", NFDFileDialog.class, "handleNfdFreeLong"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_FreeEnum", "(" + pathSetEnum + ")V", NFDFileDialog.class, "handlePathSetFreeEnum"); + Transformation.registerOverwriteConditional(transformerMap, nfd, "NFD_PathSet_Free", "(J)V", NFDFileDialog.class, "handlePathSetFree"); + + // TFD (Tiny File Dialogs) + String tfd = "org/lwjgl/util/tinyfd/TinyFileDialogs"; + String string = "Ljava/lang/String;"; + + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_openFileDialog", "(" + byteBuffer + byteBuffer + pointerBuffer + byteBuffer + "Z)" + string, TinyFileDialog.class, "handleTinyfdOpen"); + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_openFileDialog", "(" + charSequence + charSequence + pointerBuffer + charSequence + "Z)" + string, TinyFileDialog.class, "handleTinyfdOpen"); + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_saveFileDialog", "(" + byteBuffer + byteBuffer + pointerBuffer + byteBuffer + ")" + string, TinyFileDialog.class, "handleTinyfdSave"); + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_saveFileDialog", "(" + charSequence + charSequence + pointerBuffer + charSequence + ")" + string, TinyFileDialog.class, "handleTinyfdSave"); + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_selectFolderDialog", "(" + byteBuffer + byteBuffer + ")" + string, TinyFileDialog.class, "handleTinyfdFolder"); + Transformation.registerOverwrite(transformerMap, tfd, "tinyfd_selectFolderDialog", "(" + charSequence + charSequence + ")" + string, TinyFileDialog.class, "handleTinyfdFolder"); + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/OpenUriTransformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/OpenUriTransformation.java new file mode 100644 index 00000000000..63e331ccf27 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/OpenUriTransformation.java @@ -0,0 +1,67 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.MinecraftVersionInfo; +import com.modrinth.sandboxagent.SandboxApi; +import com.modrinth.sandboxagent.transformer.TransformerMap; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +import java.net.URI; +import java.util.ListIterator; +import java.util.concurrent.CompletableFuture; + +public class OpenUriTransformation { + + public static void register(TransformerMap transformerMap, MinecraftVersionInfo minecraftVersionInfo) { + // Mojang (26.3+) + transformerMap.registerMethod("com/mojang/blaze3d/Blaze3D", "openUri", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Mojang (1.21.11+) + transformerMap.registerMethod("net/minecraft/util/Util$OS", "openUri", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Mojang (before 1.21.11) + transformerMap.registerMethod("net/minecraft/Util$OS", "openUri", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Intermediary + transformerMap.registerMethod("net/minecraft/class_156$class_158", "method_673", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // SRG + transformerMap.registerMethod("net/minecraft/src/C_5322_$C_5330_", "m_137648_", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Intermediary, 1.14+) + transformerMap.registerMethod("net/minecraft/util/Util$OS", "func_195642_a", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Unobfuscated, 1.14+) + transformerMap.registerMethod("net/minecraft/util/Util$OS", "openURI", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Intermediary, 1.13) + transformerMap.registerMethod("net/minecraft/util/Util$EnumOS", "func_195642_a", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Unobfuscated, 1.13) + transformerMap.registerMethod("net/minecraft/util/Util$EnumOS", "openURI", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Intermediary, before 1.13) + transformerMap.registerMethod("net/minecraft/client/gui/GuiScreen", "func_175282_a", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + // Old MCP (Unobfuscated, before 1.13) + transformerMap.registerMethod("net/minecraft/client/gui/GuiScreen", "openWebLink", "(Ljava/net/URI;)V", OpenUriTransformation::transform); + + // Util$OS#openUri + Transformation.registerObfuscated(transformerMap, OpenUriTransformation::transform, + minecraftVersionInfo, "/com/modrinth/sandboxagent/method_673.csv"); + // Screen#openUri (before 1.13) + Transformation.registerObfuscated(transformerMap, OpenUriTransformation::transform, + minecraftVersionInfo, "/com/modrinth/sandboxagent/method_2221.csv"); + } + + private static boolean transform(ListIterator it, boolean isStatic) { + final LabelNode after = new LabelNode(); + it.add(new VarInsnNode(Opcodes.ALOAD, isStatic ? 0 : 1)); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/modrinth/sandboxagent/transformation/OpenUriTransformation", + "openUri", "(Ljava/net/URI;)Z")); + it.add(new JumpInsnNode(Opcodes.IFEQ, after)); // If false, jump to after to skip early return + it.add(new InsnNode(Opcodes.RETURN)); + it.add(after); + return true; + } + + public static boolean openUri(URI uri) { + String scheme = uri.getScheme(); + if ("http".equals(scheme) || "https".equals(scheme) || "file".equals(scheme) || "steam".equals(scheme)) { + CompletableFuture.runAsync(() -> SandboxApi.getOrInit().openUri(uri)); + return true; + } + return false; + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/RealmsTransformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/RealmsTransformation.java new file mode 100644 index 00000000000..1b7c48ed596 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/RealmsTransformation.java @@ -0,0 +1,62 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.MinecraftVersionInfo; +import com.modrinth.sandboxagent.SandboxApi; +import com.modrinth.sandboxagent.transformer.TransformerMap; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +import java.util.ListIterator; + +public class RealmsTransformation { + + public static void register(TransformerMap transformerMap, MinecraftVersionInfo minecraftVersionInfo) { + String[] descs = new String[]{ + "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", + "(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String;" + }; + + for (String desc : descs) { + // Mojang + transformerMap.registerMethod("com/mojang/realmsclient/client/RealmsClient", "url", desc, RealmsTransformation::transform); + // Intermediary + transformerMap.registerMethod("net/minecraft/class_4341", "method_21007", desc, RealmsTransformation::transform); + // Intermediary (new) + transformerMap.registerMethod("net/minecraft/class_4341", "method_68464", desc, RealmsTransformation::transform); + // SRG + transformerMap.registerMethod("net/minecraft/src/C_3223_", "m_87203_", desc, RealmsTransformation::transform); + // Old MCP (Intermediary) + transformerMap.registerMethod("com/mojang/realmsclient/client/RealmsClient", "func_224907_b", desc, RealmsTransformation::transform); + } + + // Note: Prior to 1.14, realms was a separate unobfuscated jar. Thus, the Mojang mapping + // will apply to 1.13 and below instead of the obfuscated mappings below (method_68464) + + Transformation.registerObfuscated(transformerMap, RealmsTransformation::transform, + minecraftVersionInfo, "/com/modrinth/sandboxagent/method_21007.csv"); + Transformation.registerObfuscated(transformerMap, RealmsTransformation::transform, + minecraftVersionInfo, "/com/modrinth/sandboxagent/method_68464.csv"); + } + + private static boolean transform(ListIterator it, boolean isStatic) { + final LabelNode after = new LabelNode(); + it.add(new VarInsnNode(Opcodes.ALOAD, isStatic ? 0 : 1)); + it.add(new VarInsnNode(Opcodes.ALOAD, isStatic ? 1 : 2)); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/modrinth/sandboxagent/transformation/RealmsTransformation", + "createUrl", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")); + it.add(new InsnNode(Opcodes.DUP)); + it.add(new JumpInsnNode(Opcodes.IFNULL, after)); // If null, jump to after to skip early return + it.add(new InsnNode(Opcodes.ARETURN)); + it.add(after); + return true; + } + + public static String createUrl(String path, String query) { + String url = SandboxApi.getOrInit().getBaseUrl() + "/sandboxrealms/" + path; + if (query != null) { + url += "?" + query; + } + return url; + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/Transformation.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/Transformation.java new file mode 100644 index 00000000000..bef495d5b08 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformation/Transformation.java @@ -0,0 +1,146 @@ +package com.modrinth.sandboxagent.transformation; + +import com.modrinth.sandboxagent.MinecraftVersionInfo; +import com.modrinth.sandboxagent.SandboxAgent; +import com.modrinth.sandboxagent.transformer.MethodTransformer; +import com.modrinth.sandboxagent.transformer.TransformerMap; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +public class Transformation { + + public static void registerObfuscated(TransformerMap transformerMap, MethodTransformer transformer, MinecraftVersionInfo minecraftVersionInfo, String mappings) { + if (!minecraftVersionInfo.isObfuscated()) { + return; + } + + String csv = SandboxAgent.readResourceToString(mappings); + if (csv == null) { + System.err.println("Missing " + mappings); + return; + } + int start = 0; + while (true) { + int lineEnd = csv.indexOf('\n', start); + int column1End = csv.indexOf(',', start); + if (column1End < 0) { + break; + } else if (lineEnd >= 0 && column1End > lineEnd) { + continue; + } + + String sub = csv.substring(start, column1End); + if (sub.equals(minecraftVersionInfo.id) || sub.equals(minecraftVersionInfo.name)) { + registerObfuscatedEntry(transformerMap, transformer, csv, column1End, lineEnd); + } + + if (lineEnd < 0) { + break; + } + start = lineEnd+1; + } + } + + private static void registerObfuscatedEntry(TransformerMap transformerMap, MethodTransformer transformer, String csv, int column1End, int lineEnd) { + int column2End = csv.indexOf(',', column1End+1); + int column3End = csv.indexOf(',', column2End+1); + int column4End = csv.indexOf(',', column3End+1); + if (lineEnd >= 0) { + if (column2End > lineEnd) { + return; + } + if (column3End > lineEnd) { + return; + } + if (column4End > lineEnd) { + column4End = lineEnd; + } + } + if (column2End < 0 || column3End < 0 || column4End < 0) { + return; + } + + String className = csv.substring(column1End+1, column2End); + String method = csv.substring(column2End+1, column3End); + String desc = csv.substring(column3End+1, column4End); + + transformerMap.registerMethod(className, method, desc, transformer); + } + + // Register a method to be unconditionally overwritten by a static handler with the same descriptor + public static void registerOverwrite(TransformerMap transformerMap, String className, String method, String descriptor, Class owner, String handlerName) { + transformerMap.registerMethod(className, method, descriptor, (it, isStatic) -> { + overwrite(it, isStatic, owner, handlerName, descriptor); + return true; + }); + } + + // Register a method to be conditionally overwritten, see overwriteConditional for the handler's return type + public static void registerOverwriteConditional(TransformerMap transformerMap, String className, String method, String descriptor, Class owner, String handlerName) { + transformerMap.registerMethod(className, method, descriptor, (it, isStatic) -> { + overwriteConditional(it, isStatic, owner, handlerName, descriptor); + return true; + }); + } + + // Unconditionally overwrite method by inserting an early return + public static void overwrite(ListIterator it, boolean isStatic, Class owner, String name, String descriptor) { + Type methodType = Type.getMethodType(descriptor); + String ownerName = owner.getName().replace('.', '/'); + + loadArguments(it, isStatic, methodType); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ownerName, name, descriptor)); + it.add(new InsnNode(methodType.getReturnType().getOpcode(Opcodes.IRETURN))); + } + + // Conditionally overwrite method by inserting an early return depending on the handler's result + // void methods: the handler returns a boolean, true to return early + // int methods: the handler returns an OptionalInt, present to return early with that value + public static void overwriteConditional(ListIterator it, boolean isStatic, Class owner, String name, String descriptor) { + Type methodType = Type.getMethodType(descriptor); + Type returnType = methodType.getReturnType(); + String ownerName = owner.getName().replace('.', '/'); + final LabelNode after = new LabelNode(); + + if (returnType == Type.VOID_TYPE) { + String handlerDescriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, methodType.getArgumentTypes()); + + loadArguments(it, isStatic, methodType); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ownerName, name, handlerDescriptor)); + it.add(new JumpInsnNode(Opcodes.IFEQ, after)); + it.add(new InsnNode(Opcodes.RETURN)); + } else if (returnType == Type.INT_TYPE) { + String optionalInt = "java/util/OptionalInt"; + String handlerDescriptor = Type.getMethodDescriptor(Type.getObjectType(optionalInt), methodType.getArgumentTypes()); + final LabelNode empty = new LabelNode(); + + loadArguments(it, isStatic, methodType); + it.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ownerName, name, handlerDescriptor)); + it.add(new InsnNode(Opcodes.DUP)); + it.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, optionalInt, "isPresent", "()Z")); + it.add(new JumpInsnNode(Opcodes.IFEQ, empty)); + it.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, optionalInt, "getAsInt", "()I")); + it.add(new InsnNode(Opcodes.IRETURN)); + it.add(empty); + it.add(new InsnNode(Opcodes.POP)); + } else { + throw new RuntimeException("overwriteConditional can only be used with void or int methods"); + } + + it.add(after); + } + + private static void loadArguments(ListIterator it, boolean isStatic, Type methodType) { + int index = isStatic ? 0 : 1; + for (Type argumentType : methodType.getArgumentTypes()) { + it.add(new VarInsnNode(argumentType.getOpcode(Opcodes.ILOAD), index)); + index += argumentType.getSize(); + } + } + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/MethodTransformer.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/MethodTransformer.java new file mode 100644 index 00000000000..77e51b6de42 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/MethodTransformer.java @@ -0,0 +1,11 @@ +package com.modrinth.sandboxagent.transformer; + +import org.objectweb.asm.tree.AbstractInsnNode; + +import java.util.ListIterator; + +public interface MethodTransformer { + + boolean transformMethod(ListIterator it, boolean isStatic); + +} diff --git a/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/TransformerMap.java b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/TransformerMap.java new file mode 100644 index 00000000000..aa09dc238ae --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/java/com/modrinth/sandboxagent/transformer/TransformerMap.java @@ -0,0 +1,65 @@ +package com.modrinth.sandboxagent.transformer; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +import java.lang.instrument.ClassFileTransformer; +import java.security.ProtectionDomain; +import java.util.HashMap; + +public class TransformerMap implements ClassFileTransformer { + + private final HashMap>> transformers = new HashMap<>(); + + public void registerMethod(String className, String method, String desc, MethodTransformer transformer) { + HashMap> byMethod = transformers.computeIfAbsent(className, k -> new HashMap<>()); + HashMap byDesc = byMethod.computeIfAbsent(method, k -> new HashMap<>()); + byDesc.put(desc, transformer); + } + + @Override + public byte[] transform(ClassLoader classLoader, String className, Class clazz, ProtectionDomain protectionDomain, byte[] classBytes) { + HashMap> byMethod = transformers.get(className); + if (byMethod == null) { + return null; + } + + final ClassNode classNode = new ClassNode(); + ClassReader reader = new ClassReader(classBytes); + reader.accept(classNode, 0); + + try { + boolean modified = false; + for (MethodNode method : classNode.methods) { + HashMap byDesc = byMethod.get(method.name); + if (byDesc == null) { + continue; + } + + MethodTransformer transformer = byDesc.get(method.desc); + if (transformer == null) { + continue; + } + + boolean isStatic = (method.access & Opcodes.ACC_STATIC) != 0; + + modified |= transformer.transformMethod(method.instructions.iterator(), isStatic); + } + + if (!modified) { + return null; + } + + ClassWriter classWriter = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + classNode.accept(classWriter); + return classWriter.toByteArray(); + } catch (Throwable t) { + System.out.println("Exception while transforming " + className); + t.printStackTrace(); + return null; + } + } +} diff --git a/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_21007.csv b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_21007.csv new file mode 100644 index 00000000000..eecd37a9514 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_21007.csv @@ -0,0 +1,409 @@ +1.14.4,cvm,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre1,cvh,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre2,cvj,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre3,cvk,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre4,cvm,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre5,cvm,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre6,cvm,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14.4-pre7,cvm,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14_combat-0,cvn,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.14_combat-3,cvo,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre1,cyt,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre2,cyu,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre3,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre4,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre5,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre6,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15-pre7,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15.1,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15.1-pre1,cyv,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15.2,cyy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15.2-pre1,cyy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15.2-pre2,cyy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.15_combat-1,cyx,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre1,dhw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre2,dhw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre3,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre4,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre5,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre6,dib,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre7,dib,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-pre8,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16-rc1,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.1,dia,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2-pre1,dfv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2-pre2,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2-pre3,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2-rc1,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.2-rc2,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.3,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.3-rc1,dfy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.4,dgb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.4-pre1,dga,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.4-pre2,dgb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.4-rc1,dgb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.5,dgb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16.5-rc1,dgb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.16_combat-3,dga,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-pre1,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-pre2,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-pre3,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-pre4,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-pre5,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-rc1,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17-rc2,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1-pre1,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1-pre2,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1-pre3,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1-rc1,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.17.1-rc2,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre1,dsl,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre2,dsm,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre3,dsw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre4,dsw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre5,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre6,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre7,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-pre8,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-rc1,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-rc2,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-rc3,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18-rc4,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.1,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.1-pre1,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.1-rc1,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.1-rc2,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.1-rc3,dsy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.2,dub,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.2-pre1,dua,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.2-pre2,dua,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.2-pre3,dub,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18.2-rc1,dub,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-1,dqx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-2,dqx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-3,dqz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-4,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-5,dra,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-6,drd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.18_experimental-snapshot-7,drd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19,eai,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-pre1,eaf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-pre2,eah,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-pre3,eah,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-pre4,eah,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-pre5,eai,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-rc1,eai,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19-rc2,eai,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1,ebf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre1,eaj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre2,eak,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre3,eal,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre4,eas,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre5,eba,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-pre6,ebd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-rc1,eak,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-rc2,ebd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.1-rc3,ebf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.2,ebf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.2-rc1,ebf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.2-rc2,ebf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3,ees,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-pre1,eeq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-pre2,ees,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-pre3,eer,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-rc1,ees,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-rc2,ees,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.3-rc3,ees,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4,eht,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-pre1,ehr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-pre2,ehr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-pre3,ehr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-pre4,eht,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-rc1,eht,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-rc2,eht,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19.4-rc3,eht,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.19_deep_dark_experimental_snapshot-1,dur,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20,eiz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre1,eir,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre2,eir,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre3,eis,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre4,eis,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre5,eit,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre6,eiu,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-pre7,eiz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20-rc1,eiz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.1,eiz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.1-rc1,eiz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-pre1,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-pre2,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-pre3,emh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-pre4,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-rc1,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.2-rc2,emf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3-pre1,eqp,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3-pre2,eqq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3-pre3,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3-pre4,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.3-rc1,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.4,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.4-rc1,eqr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5,fap,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-pre1,faj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-pre2,fam,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-pre3,fan,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-pre4,fao,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-rc1,fap,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-rc2,fap,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.5-rc3,fap,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.6,faq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.20.6-rc1,faq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21-pre1,fbw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21-pre2,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21-pre3,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21-pre4,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21-rc1,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.1,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.1-rc1,fby,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.10,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.10-rc1,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-pre1,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-pre2,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-pre3,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-pre4,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-pre5,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-rc1,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-rc2,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.11-rc3,fzz,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.2,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-pre1,fhg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-pre2,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-pre3,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-pre4,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-pre5,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-rc1,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.2-rc2,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.3,fhi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4,fgl,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-pre1,fgj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-pre2,fgk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-pre3,fgk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-rc1,fgk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-rc2,fgk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.4-rc3,fgl,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.5-pre1,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.5-pre2,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.5-pre3,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.5-rc1,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.5-rc2,flq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6-pre1,foo,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6-pre2,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6-pre3,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6-pre4,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.6-rc1,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.7,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.7-rc1,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.7-rc2,fop,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.8,foq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.8-rc1,foq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9-pre1,fuo,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9-pre2,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9-pre3,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9-pre4,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +1.21.9-rc1,fun,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +19w34a,cwy,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w35a,cxa,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w36a,cxh,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w37a,cxh,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w38a,cxt,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w38b,cxt,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w39a,cyd,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w40a,cyc,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w41a,cyl,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w42a,cym,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w44a,cyn,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w45a,cyn,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w45b,cyn,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w46a,cys,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +19w46b,cys,b,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1_15_combat-6,cza,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1_16_combat-0,dga,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w06a,dah,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w07a,dbx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w08a,dbx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w09a,dcd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w10a,ddi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w11a,ddn,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w12a,ddy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w13a,dep,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w13b,dep,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w14a,dez,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w14infinite,dhd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w15a,dfo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w16a,dgg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w17a,dgv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w18a,dhc,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w19a,dhf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w20a,dha,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w20b,dha,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w21a,dgs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w22a,dhi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w27a,dil,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w28a,din,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w29a,dfs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w30a,dfr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w45a,dij,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w46a,dji,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w48a,djl,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w49a,dkp,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +20w51a,dle,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w03a,dlm,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w05a,dmg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w05b,dmg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w06a,dmk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w07a,dmo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w08a,dnj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w08b,dnj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w10a,doa,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w11a,dol,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w13a,dpv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w14a,dpx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w15a,dpy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w16a,dqb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w17a,dqd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w18a,dqd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w19a,dqg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w20a,dqj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w37a,dri,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w38a,dsa,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w39a,dsn,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w40a,dsv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w41a,drx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w42a,dsb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w43a,dsm,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +21w44a,dsk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w03a,dte,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w05a,dtf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w06a,dtm,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w07a,dts,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w11a,dvy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w12a,dws,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w13a,dxd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w13oneblockatatime,dum,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w14a,dxu,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w15a,dxw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w16a,dyh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w16b,dyh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w17a,dyo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w18a,dze,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w19a,dzq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w24a,eai,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w42a,eds,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w43a,edr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w44a,edz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w45a,eeh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +22w46a,eep,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w03a,efg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w04a,ega,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w05a,egc,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w06a,egp,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w07a,ehq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w12a,ehy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w13a,ehz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w13a_or_b,emy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w13a_or_b_original,emy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w14a,eic,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w16a,eig,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w17a,eij,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w18a,eil,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w31a,elx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w32a,elw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w33a,elv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w35a,ema,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w40a,elz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w41a,emx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w42a,eoa,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w43a,eom,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w43b,eom,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w44a,eor,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w45a,ept,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w46a,eqj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w51a,era,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +23w51b,era,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w03a,esq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w03b,esq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w04a,esx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w05a,ett,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w05b,ett,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w06a,eup,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w07a,eur,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w09a,ewy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w10a,exh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w11a,eyd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w12a,eyn,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w13a,ezi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w14a,ezk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w14potato,fbs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w14potato_original,fbs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w18a,faw,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w19a,fbc,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w19b,fbc,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w20a,fbe,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w21a,fbs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w21b,fbs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w33a,fdk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w34a,fdu,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w35a,fdy,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w36a,fej,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w37a,fer,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w38a,ffa,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w39a,ffh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w40a,fhb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w44a,fhb,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w45a,fgk,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +24w46a,fgi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w02a,fhh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w03a,fie,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w04a,fjg,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w05a,fjs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w06a,fjz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w07a,fko,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w08a,fkt,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w09a,fmd,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w09b,fmd,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w10a,fmf,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w14craftmine,fpq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w15a,fmh,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w16a,fmi,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w17a,fmj,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w18a,fmt,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w19a,fmt,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w20a,fon,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w21a,foq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w31a,fpx,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w32a,fqh,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w33a,fqn,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w34a,fqs,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w34b,fqs,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w35a,ftd,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w36a,ftq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w36b,ftq,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w37a,fui,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w41a,fwr,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w42a,fxm,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w43a,fxo,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w44a,fyh,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w45a,fyr,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; +25w46a,fyv,a,(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String; diff --git a/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_2221.csv b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_2221.csv new file mode 100644 index 00000000000..83de86ec6d1 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_2221.csv @@ -0,0 +1,230 @@ +1.10,bft,a,(Ljava/net/URI;)V +1.10-pre1,bfu,a,(Ljava/net/URI;)V +1.10-pre2,bft,a,(Ljava/net/URI;)V +1.10.1,bft,a,(Ljava/net/URI;)V +1.10.2,bft,a,(Ljava/net/URI;)V +1.11,bhm,a,(Ljava/net/URI;)V +1.11-pre1,bhm,a,(Ljava/net/URI;)V +1.11.1,bho,a,(Ljava/net/URI;)V +1.11.2,bho,a,(Ljava/net/URI;)V +1.12,bli,a,(Ljava/net/URI;)V +1.12-pre1,bld,a,(Ljava/net/URI;)V +1.12-pre2,ble,a,(Ljava/net/URI;)V +1.12-pre3,blh,a,(Ljava/net/URI;)V +1.12-pre3-1316,blh,a,(Ljava/net/URI;)V +1.12-pre4,blh,a,(Ljava/net/URI;)V +1.12-pre5,blh,a,(Ljava/net/URI;)V +1.12-pre6,bli,a,(Ljava/net/URI;)V +1.12-pre7,bli,a,(Ljava/net/URI;)V +1.12.1,blk,a,(Ljava/net/URI;)V +1.12.1-pre1,blk,a,(Ljava/net/URI;)V +1.12.2,blk,a,(Ljava/net/URI;)V +1.12.2-pre1,blk,a,(Ljava/net/URI;)V +1.12.2-pre2,blk,a,(Ljava/net/URI;)V +1.13,cjs,a,(Ljava/net/URI;)V +1.13-pre1,cmh,a,(Ljava/net/URI;)V +1.13-pre10,cjq,a,(Ljava/net/URI;)V +1.13-pre2,cmk,a,(Ljava/net/URI;)V +1.13-pre3,cmt,a,(Ljava/net/URI;)V +1.13-pre4,cnd,a,(Ljava/net/URI;)V +1.13-pre5,cig,a,(Ljava/net/URI;)V +1.13-pre6,cix,a,(Ljava/net/URI;)V +1.13-pre7,cjf,a,(Ljava/net/URI;)V +1.13-pre8,cjp,a,(Ljava/net/URI;)V +1.13-pre9,cjp,a,(Ljava/net/URI;)V +1.13.1,ckc,a,(Ljava/net/URI;)V +1.13.1-pre1,ckc,a,(Ljava/net/URI;)V +1.13.1-pre2,ckc,a,(Ljava/net/URI;)V +1.13.2,ckd,a,(Ljava/net/URI;)V +1.13.2-pre1,ckd,a,(Ljava/net/URI;)V +1.13.2-pre2,ckd,a,(Ljava/net/URI;)V +1.8.2,axv,a,(Ljava/net/URI;)V +1.8.2-pre5,axv,a,(Ljava/net/URI;)V +1.8.2-pre6,axv,a,(Ljava/net/URI;)V +1.8.2-pre7,axv,a,(Ljava/net/URI;)V +1.8.3,axv,a,(Ljava/net/URI;)V +1.8.4,axu,a,(Ljava/net/URI;)V +1.8.5,axu,a,(Ljava/net/URI;)V +1.8.6,axu,a,(Ljava/net/URI;)V +1.8.7,axu,a,(Ljava/net/URI;)V +1.8.8,axu,a,(Ljava/net/URI;)V +1.8.9,axu,a,(Ljava/net/URI;)V +1.9,bfb,a,(Ljava/net/URI;)V +1.9-pre1,bfa,a,(Ljava/net/URI;)V +1.9-pre2,bfa,a,(Ljava/net/URI;)V +1.9-pre3,bfb,a,(Ljava/net/URI;)V +1.9-pre4,bfb,a,(Ljava/net/URI;)V +1.9.1,bey,a,(Ljava/net/URI;)V +1.9.1-pre1,bey,a,(Ljava/net/URI;)V +1.9.1-pre2,bey,a,(Ljava/net/URI;)V +1.9.1-pre3,bey,a,(Ljava/net/URI;)V +1.9.2,bey,a,(Ljava/net/URI;)V +1.9.3,bez,a,(Ljava/net/URI;)V +1.9.3-pre1,bey,a,(Ljava/net/URI;)V +1.9.3-pre2,bez,a,(Ljava/net/URI;)V +1.9.3-pre3,bez,a,(Ljava/net/URI;)V +1.9.4,bez,a,(Ljava/net/URI;)V +1.RV-Pre1,bey,a,(Ljava/net/URI;)V +15w14a,axy,a,(Ljava/net/URI;)V +15w31a,azu,a,(Ljava/net/URI;)V +15w31b,azu,a,(Ljava/net/URI;)V +15w31c,azv,a,(Ljava/net/URI;)V +15w32a,bar,a,(Ljava/net/URI;)V +15w32b,bax,a,(Ljava/net/URI;)V +15w32c,bax,a,(Ljava/net/URI;)V +15w33a,bbj,a,(Ljava/net/URI;)V +15w33b,bbj,a,(Ljava/net/URI;)V +15w33c,bbo,a,(Ljava/net/URI;)V +15w34a,bbs,a,(Ljava/net/URI;)V +15w34b,bbs,a,(Ljava/net/URI;)V +15w34c,bby,a,(Ljava/net/URI;)V +15w34d,bby,a,(Ljava/net/URI;)V +15w35a,bbx,a,(Ljava/net/URI;)V +15w35b,bbx,a,(Ljava/net/URI;)V +15w35c,bbx,a,(Ljava/net/URI;)V +15w35d,bbx,a,(Ljava/net/URI;)V +15w35e,bcb,a,(Ljava/net/URI;)V +15w36a,bce,a,(Ljava/net/URI;)V +15w36b,bce,a,(Ljava/net/URI;)V +15w36c,bce,a,(Ljava/net/URI;)V +15w36d,bce,a,(Ljava/net/URI;)V +15w37a,bcn,a,(Ljava/net/URI;)V +15w38a,bcr,a,(Ljava/net/URI;)V +15w38b,bcr,a,(Ljava/net/URI;)V +15w39a,bcr,a,(Ljava/net/URI;)V +15w39b,bcr,a,(Ljava/net/URI;)V +15w39c,bcr,a,(Ljava/net/URI;)V +15w40a,bcr,a,(Ljava/net/URI;)V +15w40b,bcs,a,(Ljava/net/URI;)V +15w41a,bcr,a,(Ljava/net/URI;)V +15w41b,bcr,a,(Ljava/net/URI;)V +15w42a,bcw,a,(Ljava/net/URI;)V +15w43a,bec,a,(Ljava/net/URI;)V +15w43b,beh,a,(Ljava/net/URI;)V +15w43c,bel,a,(Ljava/net/URI;)V +15w44a,beq,a,(Ljava/net/URI;)V +15w44b,bes,a,(Ljava/net/URI;)V +15w45a,bep,a,(Ljava/net/URI;)V +15w46a,beo,a,(Ljava/net/URI;)V +15w47a,bep,a,(Ljava/net/URI;)V +15w47b,bep,a,(Ljava/net/URI;)V +15w47c,bep,a,(Ljava/net/URI;)V +15w49a,bep,a,(Ljava/net/URI;)V +15w49b,bep,a,(Ljava/net/URI;)V +15w50a,beq,a,(Ljava/net/URI;)V +15w51a,ber,a,(Ljava/net/URI;)V +15w51b,ber,a,(Ljava/net/URI;)V +16w02a,bey,a,(Ljava/net/URI;)V +16w03a,bey,a,(Ljava/net/URI;)V +16w04a,bfa,a,(Ljava/net/URI;)V +16w05a,bez,a,(Ljava/net/URI;)V +16w05b,bey,a,(Ljava/net/URI;)V +16w06a,bez,a,(Ljava/net/URI;)V +16w07a,bfa,a,(Ljava/net/URI;)V +16w07b,bfa,a,(Ljava/net/URI;)V +16w14a,bey,a,(Ljava/net/URI;)V +16w15a,bey,a,(Ljava/net/URI;)V +16w15b,bey,a,(Ljava/net/URI;)V +16w20a,bfp,a,(Ljava/net/URI;)V +16w21a,bfs,a,(Ljava/net/URI;)V +16w21b,bfs,a,(Ljava/net/URI;)V +16w32a,bgk,a,(Ljava/net/URI;)V +16w32b,bgk,a,(Ljava/net/URI;)V +16w33a,bgk,a,(Ljava/net/URI;)V +16w35a,bgk,a,(Ljava/net/URI;)V +16w36a,bgm,a,(Ljava/net/URI;)V +16w38a,bgn,a,(Ljava/net/URI;)V +16w39a,bhh,a,(Ljava/net/URI;)V +16w39b,bhk,a,(Ljava/net/URI;)V +16w39c,bhk,a,(Ljava/net/URI;)V +16w40a,bhj,a,(Ljava/net/URI;)V +16w41a,bhj,a,(Ljava/net/URI;)V +16w42a,bhj,a,(Ljava/net/URI;)V +16w43a,bhj,a,(Ljava/net/URI;)V +16w44a,bhl,a,(Ljava/net/URI;)V +16w50a,bho,a,(Ljava/net/URI;)V +17w06a,bhr,a,(Ljava/net/URI;)V +17w13a,bjm,a,(Ljava/net/URI;)V +17w13b,bjn,a,(Ljava/net/URI;)V +17w14a,bju,a,(Ljava/net/URI;)V +17w15a,bjx,a,(Ljava/net/URI;)V +17w16a,bki,a,(Ljava/net/URI;)V +17w16b,bkj,a,(Ljava/net/URI;)V +17w17a,bkl,a,(Ljava/net/URI;)V +17w17b,bkm,a,(Ljava/net/URI;)V +17w18a,bkq,a,(Ljava/net/URI;)V +17w18b,bkv,a,(Ljava/net/URI;)V +17w31a,blk,a,(Ljava/net/URI;)V +17w43a,bna,a,(Ljava/net/URI;)V +17w43b,bna,a,(Ljava/net/URI;)V +17w45a,boc,a,(Ljava/net/URI;)V +17w45b,boi,a,(Ljava/net/URI;)V +17w46a,bov,a,(Ljava/net/URI;)V +17w47a,bqa,a,(Ljava/net/URI;)V +17w47b,bqb,a,(Ljava/net/URI;)V +17w48a,bqg,a,(Ljava/net/URI;)V +17w49a,bqo,a,(Ljava/net/URI;)V +17w49b,bqq,a,(Ljava/net/URI;)V +17w50a,bqv,a,(Ljava/net/URI;)V +18w01a,brm,a,(Ljava/net/URI;)V +18w02a,brs,a,(Ljava/net/URI;)V +18w03a,brs,a,(Ljava/net/URI;)V +18w03b,brs,a,(Ljava/net/URI;)V +18w05a,brw,a,(Ljava/net/URI;)V +18w06a,cao,a,(Ljava/net/URI;)V +18w07a,cbk,a,(Ljava/net/URI;)V +18w07b,cau,a,(Ljava/net/URI;)V +18w07c,cau,a,(Ljava/net/URI;)V +18w08a,cbk,a,(Ljava/net/URI;)V +18w08b,cbq,a,(Ljava/net/URI;)V +18w09a,cbx,a,(Ljava/net/URI;)V +18w10a,ccj,a,(Ljava/net/URI;)V +18w10b,ccj,a,(Ljava/net/URI;)V +18w10c,ccq,a,(Ljava/net/URI;)V +18w10d,cda,a,(Ljava/net/URI;)V +18w11a,cdf,a,(Ljava/net/URI;)V +18w14a,cdh,a,(Ljava/net/URI;)V +18w14b,cdm,a,(Ljava/net/URI;)V +18w15a,ceg,a,(Ljava/net/URI;)V +18w16a,cex,a,(Ljava/net/URI;)V +18w19a,cjn,a,(Ljava/net/URI;)V +18w19b,clh,a,(Ljava/net/URI;)V +18w20a,cll,a,(Ljava/net/URI;)V +18w20b,clk,a,(Ljava/net/URI;)V +18w20c,clm,a,(Ljava/net/URI;)V +18w21a,cmd,a,(Ljava/net/URI;)V +18w21b,cmd,a,(Ljava/net/URI;)V +18w22a,cme,a,(Ljava/net/URI;)V +18w22b,cmf,a,(Ljava/net/URI;)V +18w22c,cmf,a,(Ljava/net/URI;)V +18w30a,cju,a,(Ljava/net/URI;)V +18w30b,cjv,a,(Ljava/net/URI;)V +18w31a,cka,a,(Ljava/net/URI;)V +18w32a,cka,a,(Ljava/net/URI;)V +18w33a,ckb,a,(Ljava/net/URI;)V +18w43a,cns,a,(Ljava/net/URI;)V +18w43b,cns,a,(Ljava/net/URI;)V +18w43c,cnt,a,(Ljava/net/URI;)V +18w44a,cpt,a,(Ljava/net/URI;)V +18w45a,cqc,a,(Ljava/net/URI;)V +18w46a,crc,a,(Ljava/net/URI;)V +18w47a,crq,a,(Ljava/net/URI;)V +18w47b,cri,a,(Ljava/net/URI;)V +18w48a,csb,a,(Ljava/net/URI;)V +18w48b,csb,a,(Ljava/net/URI;)V +18w49a,csl,a,(Ljava/net/URI;)V +18w50a,ctp,a,(Ljava/net/URI;)V +19w02a,cug,a,(Ljava/net/URI;)V +19w03a,cul,a,(Ljava/net/URI;)V +19w03b,cul,a,(Ljava/net/URI;)V +19w03c,cul,a,(Ljava/net/URI;)V +19w04a,cuf,a,(Ljava/net/URI;)V +19w04b,cuf,a,(Ljava/net/URI;)V +19w05a,cuk,a,(Ljava/net/URI;)V +19w06a,cun,a,(Ljava/net/URI;)V +19w07a,cut,a,(Ljava/net/URI;)V +19w08a,cvi,a,(Ljava/net/URI;)V +19w08b,cvj,a,(Ljava/net/URI;)V +19w09a,cvj,a,(Ljava/net/URI;)V +19w11a,cyh,a,(Ljava/net/URI;)V +19w11b,cyg,a,(Ljava/net/URI;)V diff --git a/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_29616.csv b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_29616.csv new file mode 100644 index 00000000000..0b802453d59 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_29616.csv @@ -0,0 +1,349 @@ +1.16,dly,a,(JLjava/util/List;)V +1.16-pre1,dlu,a,(JLjava/util/List;)V +1.16-pre2,dlu,a,(JLjava/util/List;)V +1.16-pre3,dly,a,(JLjava/util/List;)V +1.16-pre4,dly,a,(JLjava/util/List;)V +1.16-pre5,dly,a,(JLjava/util/List;)V +1.16-pre6,dlz,a,(JLjava/util/List;)V +1.16-pre7,dlz,a,(JLjava/util/List;)V +1.16-pre8,dly,a,(JLjava/util/List;)V +1.16-rc1,dly,a,(JLjava/util/List;)V +1.16.1,dly,a,(JLjava/util/List;)V +1.16.2,djx,a,(JLjava/util/List;)V +1.16.2-pre1,dju,a,(JLjava/util/List;)V +1.16.2-pre2,djx,a,(JLjava/util/List;)V +1.16.2-pre3,djx,a,(JLjava/util/List;)V +1.16.2-rc1,djx,a,(JLjava/util/List;)V +1.16.2-rc2,djx,a,(JLjava/util/List;)V +1.16.3,djx,a,(JLjava/util/List;)V +1.16.3-rc1,djx,a,(JLjava/util/List;)V +1.16.4,dka,a,(JLjava/util/List;)V +1.16.4-pre1,djz,a,(JLjava/util/List;)V +1.16.4-pre2,dka,a,(JLjava/util/List;)V +1.16.4-rc1,dka,a,(JLjava/util/List;)V +1.16.5,dka,a,(JLjava/util/List;)V +1.16.5-rc1,dka,a,(JLjava/util/List;)V +1.16_combat-3,djz,a,(JLjava/util/List;)V +1.17,dvp,a,(JLjava/util/List;)V +1.17-pre1,dvp,a,(JLjava/util/List;)V +1.17-pre2,dvp,a,(JLjava/util/List;)V +1.17-pre3,dvp,a,(JLjava/util/List;)V +1.17-pre4,dvp,a,(JLjava/util/List;)V +1.17-pre5,dvp,a,(JLjava/util/List;)V +1.17-rc1,dvp,a,(JLjava/util/List;)V +1.17-rc2,dvp,a,(JLjava/util/List;)V +1.17.1,dvq,a,(JLjava/util/List;)V +1.17.1-pre1,dvq,a,(JLjava/util/List;)V +1.17.1-pre2,dvq,a,(JLjava/util/List;)V +1.17.1-pre3,dvq,a,(JLjava/util/List;)V +1.17.1-rc1,dvq,a,(JLjava/util/List;)V +1.17.1-rc2,dvq,a,(JLjava/util/List;)V +1.18,dxp,a,(JLjava/util/List;)V +1.18-pre1,dxc,a,(JLjava/util/List;)V +1.18-pre2,dxd,a,(JLjava/util/List;)V +1.18-pre3,dxn,a,(JLjava/util/List;)V +1.18-pre4,dxn,a,(JLjava/util/List;)V +1.18-pre5,dxp,a,(JLjava/util/List;)V +1.18-pre6,dxp,a,(JLjava/util/List;)V +1.18-pre7,dxp,a,(JLjava/util/List;)V +1.18-pre8,dxp,a,(JLjava/util/List;)V +1.18-rc1,dxp,a,(JLjava/util/List;)V +1.18-rc2,dxp,a,(JLjava/util/List;)V +1.18-rc3,dxp,a,(JLjava/util/List;)V +1.18-rc4,dxp,a,(JLjava/util/List;)V +1.18.1,dxp,a,(JLjava/util/List;)V +1.18.1-pre1,dxp,a,(JLjava/util/List;)V +1.18.1-rc1,dxp,a,(JLjava/util/List;)V +1.18.1-rc2,dxp,a,(JLjava/util/List;)V +1.18.1-rc3,dxp,a,(JLjava/util/List;)V +1.18.2,dys,a,(JLjava/util/List;)V +1.18.2-pre1,dyr,a,(JLjava/util/List;)V +1.18.2-pre2,dyr,a,(JLjava/util/List;)V +1.18.2-pre3,dys,a,(JLjava/util/List;)V +1.18.2-rc1,dys,a,(JLjava/util/List;)V +1.18_experimental-snapshot-1,dvn,a,(JLjava/util/List;)V +1.18_experimental-snapshot-2,dvn,a,(JLjava/util/List;)V +1.18_experimental-snapshot-3,dvp,a,(JLjava/util/List;)V +1.18_experimental-snapshot-4,dvq,a,(JLjava/util/List;)V +1.18_experimental-snapshot-5,dvq,a,(JLjava/util/List;)V +1.18_experimental-snapshot-6,dvt,a,(JLjava/util/List;)V +1.18_experimental-snapshot-7,dvt,a,(JLjava/util/List;)V +1.19,eew,a,(JLjava/util/List;)V +1.19-pre1,eet,a,(JLjava/util/List;)V +1.19-pre2,eev,a,(JLjava/util/List;)V +1.19-pre3,eev,a,(JLjava/util/List;)V +1.19-pre4,eev,a,(JLjava/util/List;)V +1.19-pre5,eew,a,(JLjava/util/List;)V +1.19-rc1,eew,a,(JLjava/util/List;)V +1.19-rc2,eew,a,(JLjava/util/List;)V +1.19.1,efv,a,(JLjava/util/List;)V +1.19.1-pre1,eex,a,(JLjava/util/List;)V +1.19.1-pre2,efa,a,(JLjava/util/List;)V +1.19.1-pre3,efb,a,(JLjava/util/List;)V +1.19.1-pre4,efi,a,(JLjava/util/List;)V +1.19.1-pre5,efq,a,(JLjava/util/List;)V +1.19.1-pre6,eft,a,(JLjava/util/List;)V +1.19.1-rc1,eey,a,(JLjava/util/List;)V +1.19.1-rc2,eft,a,(JLjava/util/List;)V +1.19.1-rc3,efv,a,(JLjava/util/List;)V +1.19.2,efv,a,(JLjava/util/List;)V +1.19.2-rc1,efv,a,(JLjava/util/List;)V +1.19.2-rc2,efv,a,(JLjava/util/List;)V +1.19.3,ejg,a,(JLjava/util/List;)V +1.19.3-pre1,ejf,a,(JLjava/util/List;)V +1.19.3-pre2,ejh,a,(JLjava/util/List;)V +1.19.3-pre3,ejg,a,(JLjava/util/List;)V +1.19.3-rc1,ejg,a,(JLjava/util/List;)V +1.19.3-rc2,ejg,a,(JLjava/util/List;)V +1.19.3-rc3,ejg,a,(JLjava/util/List;)V +1.19.4,emi,a,(JLjava/util/List;)V +1.19.4-pre1,emg,a,(JLjava/util/List;)V +1.19.4-pre2,emg,a,(JLjava/util/List;)V +1.19.4-pre3,emg,a,(JLjava/util/List;)V +1.19.4-pre4,emi,a,(JLjava/util/List;)V +1.19.4-rc1,emi,a,(JLjava/util/List;)V +1.19.4-rc2,emi,a,(JLjava/util/List;)V +1.19.4-rc3,emi,a,(JLjava/util/List;)V +1.19_deep_dark_experimental_snapshot-1,dzi,a,(JLjava/util/List;)V +1.20,eno,a,(JLjava/util/List;)V +1.20-pre1,eng,a,(JLjava/util/List;)V +1.20-pre2,eng,a,(JLjava/util/List;)V +1.20-pre3,enh,a,(JLjava/util/List;)V +1.20-pre4,enh,a,(JLjava/util/List;)V +1.20-pre5,eni,a,(JLjava/util/List;)V +1.20-pre6,enj,a,(JLjava/util/List;)V +1.20-pre7,eno,a,(JLjava/util/List;)V +1.20-rc1,eno,a,(JLjava/util/List;)V +1.20.1,eno,a,(JLjava/util/List;)V +1.20.1-rc1,eno,a,(JLjava/util/List;)V +1.20.2,eqw,a,(JLjava/util/List;)V +1.20.2-pre1,eqw,a,(JLjava/util/List;)V +1.20.2-pre2,eqw,a,(JLjava/util/List;)V +1.20.2-pre3,eqy,a,(JLjava/util/List;)V +1.20.2-pre4,eqw,a,(JLjava/util/List;)V +1.20.2-rc1,eqw,a,(JLjava/util/List;)V +1.20.2-rc2,eqw,a,(JLjava/util/List;)V +1.20.3,evj,a,(JLjava/util/List;)V +1.20.3-pre1,evh,a,(JLjava/util/List;)V +1.20.3-pre2,evi,a,(JLjava/util/List;)V +1.20.3-pre3,evj,a,(JLjava/util/List;)V +1.20.3-pre4,evj,a,(JLjava/util/List;)V +1.20.3-rc1,evj,a,(JLjava/util/List;)V +1.20.4,evj,a,(JLjava/util/List;)V +1.20.4-rc1,evj,a,(JLjava/util/List;)V +1.20.5,ffh,a,(JLjava/util/List;)V +1.20.5-pre1,ffb,a,(JLjava/util/List;)V +1.20.5-pre2,ffe,a,(JLjava/util/List;)V +1.20.5-pre3,fff,a,(JLjava/util/List;)V +1.20.5-pre4,ffg,a,(JLjava/util/List;)V +1.20.5-rc1,ffh,a,(JLjava/util/List;)V +1.20.5-rc2,ffh,a,(JLjava/util/List;)V +1.20.5-rc3,ffh,a,(JLjava/util/List;)V +1.20.6,ffi,a,(JLjava/util/List;)V +1.20.6-rc1,ffi,a,(JLjava/util/List;)V +1.21,fgp,a,(JLjava/util/List;I)V +1.21-pre1,fgn,a,(JLjava/util/List;I)V +1.21-pre2,fgp,a,(JLjava/util/List;I)V +1.21-pre3,fgp,a,(JLjava/util/List;I)V +1.21-pre4,fgp,a,(JLjava/util/List;I)V +1.21-rc1,fgp,a,(JLjava/util/List;I)V +1.21.1,fgp,a,(JLjava/util/List;I)V +1.21.1-rc1,fgp,a,(JLjava/util/List;I)V +1.21.10,gaa,a,(JLjava/util/List;I)V +1.21.10-rc1,gaa,a,(JLjava/util/List;I)V +1.21.11,gfk,a,(JLjava/util/List;I)V +1.21.11-pre1,gfk,a,(JLjava/util/List;I)V +1.21.11-pre2,gfk,a,(JLjava/util/List;I)V +1.21.11-pre3,gfk,a,(JLjava/util/List;I)V +1.21.11-pre4,gfk,a,(JLjava/util/List;I)V +1.21.11-pre5,gfk,a,(JLjava/util/List;I)V +1.21.11-rc1,gfk,a,(JLjava/util/List;I)V +1.21.11-rc2,gfk,a,(JLjava/util/List;I)V +1.21.11-rc3,gfk,a,(JLjava/util/List;I)V +1.21.2,fmg,a,(JLjava/util/List;I)V +1.21.2-pre1,fmf,a,(JLjava/util/List;I)V +1.21.2-pre2,fmg,a,(JLjava/util/List;I)V +1.21.2-pre3,fmg,a,(JLjava/util/List;I)V +1.21.2-pre4,fmg,a,(JLjava/util/List;I)V +1.21.2-pre5,fmg,a,(JLjava/util/List;I)V +1.21.2-rc1,fmg,a,(JLjava/util/List;I)V +1.21.2-rc2,fmg,a,(JLjava/util/List;I)V +1.21.3,fmh,a,(JLjava/util/List;I)V +1.21.4,fll,a,(JLjava/util/List;I)V +1.21.4-pre1,flj,a,(JLjava/util/List;I)V +1.21.4-pre2,flk,a,(JLjava/util/List;I)V +1.21.4-pre3,flk,a,(JLjava/util/List;I)V +1.21.4-rc1,flk,a,(JLjava/util/List;I)V +1.21.4-rc2,flk,a,(JLjava/util/List;I)V +1.21.4-rc3,fll,a,(JLjava/util/List;I)V +1.21.5,fqr,a,(JLjava/util/List;I)V +1.21.5-pre1,fqr,a,(JLjava/util/List;I)V +1.21.5-pre2,fqr,a,(JLjava/util/List;I)V +1.21.5-pre3,fqr,a,(JLjava/util/List;I)V +1.21.5-rc1,fqr,a,(JLjava/util/List;I)V +1.21.5-rc2,fqr,a,(JLjava/util/List;I)V +1.21.6,fue,a,(JLjava/util/List;I)V +1.21.6-pre1,fud,a,(JLjava/util/List;I)V +1.21.6-pre2,fue,a,(JLjava/util/List;I)V +1.21.6-pre3,fue,a,(JLjava/util/List;I)V +1.21.6-pre4,fue,a,(JLjava/util/List;I)V +1.21.6-rc1,fue,a,(JLjava/util/List;I)V +1.21.7,fue,a,(JLjava/util/List;I)V +1.21.7-rc1,fue,a,(JLjava/util/List;I)V +1.21.7-rc2,fue,a,(JLjava/util/List;I)V +1.21.8,fuf,a,(JLjava/util/List;I)V +1.21.8-rc1,fuf,a,(JLjava/util/List;I)V +1.21.9,gaa,a,(JLjava/util/List;I)V +1.21.9-pre1,gab,a,(JLjava/util/List;I)V +1.21.9-pre2,gaa,a,(JLjava/util/List;I)V +1.21.9-pre3,gaa,a,(JLjava/util/List;I)V +1.21.9-pre4,gaa,a,(JLjava/util/List;I)V +1.21.9-rc1,gaa,a,(JLjava/util/List;I)V +1_16_combat-0,djy,a,(JLjava/util/List;)V +20w27a,dmj,a,(JLjava/util/List;)V +20w28a,dml,a,(JLjava/util/List;)V +20w29a,djq,a,(JLjava/util/List;)V +20w30a,djp,a,(JLjava/util/List;)V +20w45a,dmi,a,(JLjava/util/List;)V +20w46a,dnj,a,(JLjava/util/List;)V +20w48a,dnm,a,(JLjava/util/List;)V +20w49a,doq,a,(JLjava/util/List;)V +20w51a,dpf,a,(JLjava/util/List;)V +21w03a,dpr,a,(JLjava/util/List;)V +21w05a,dql,a,(JLjava/util/List;)V +21w05b,dql,a,(JLjava/util/List;)V +21w06a,dqp,a,(JLjava/util/List;)V +21w07a,dqt,a,(JLjava/util/List;)V +21w08a,dro,a,(JLjava/util/List;)V +21w08b,dro,a,(JLjava/util/List;)V +21w10a,dsf,a,(JLjava/util/List;)V +21w11a,dsq,a,(JLjava/util/List;)V +21w13a,dul,a,(JLjava/util/List;)V +21w14a,dun,a,(JLjava/util/List;)V +21w15a,duo,a,(JLjava/util/List;)V +21w16a,dur,a,(JLjava/util/List;)V +21w17a,dut,a,(JLjava/util/List;)V +21w18a,dut,a,(JLjava/util/List;)V +21w19a,duw,a,(JLjava/util/List;)V +21w20a,duz,a,(JLjava/util/List;)V +21w37a,dvy,a,(JLjava/util/List;)V +21w38a,dwr,a,(JLjava/util/List;)V +21w39a,dxe,a,(JLjava/util/List;)V +21w40a,dxm,a,(JLjava/util/List;)V +21w41a,dwo,a,(JLjava/util/List;)V +21w42a,dws,a,(JLjava/util/List;)V +21w43a,dxd,a,(JLjava/util/List;)V +21w44a,dxb,a,(JLjava/util/List;)V +22w03a,dxv,a,(JLjava/util/List;)V +22w05a,dxw,a,(JLjava/util/List;)V +22w06a,dyd,a,(JLjava/util/List;)V +22w07a,dyj,a,(JLjava/util/List;)V +22w11a,ean,a,(JLjava/util/List;)V +22w12a,ebg,a,(JLjava/util/List;)V +22w13a,ebr,a,(JLjava/util/List;)V +22w13oneblockatatime,dzd,a,(JLjava/util/List;)V +22w14a,eci,a,(JLjava/util/List;)V +22w15a,eck,a,(JLjava/util/List;)V +22w16a,ecv,a,(JLjava/util/List;)V +22w16b,ecv,a,(JLjava/util/List;)V +22w17a,edc,a,(JLjava/util/List;)V +22w18a,eds,a,(JLjava/util/List;)V +22w19a,eee,a,(JLjava/util/List;)V +22w24a,eex,a,(JLjava/util/List;)V +22w42a,eii,a,(JLjava/util/List;)V +22w43a,eih,a,(JLjava/util/List;)V +22w44a,eip,a,(JLjava/util/List;)V +22w45a,eix,a,(JLjava/util/List;)V +22w46a,eje,a,(JLjava/util/List;)V +23w03a,eju,a,(JLjava/util/List;)V +23w04a,eko,a,(JLjava/util/List;)V +23w05a,ekq,a,(JLjava/util/List;)V +23w06a,elc,a,(JLjava/util/List;)V +23w07a,emd,a,(JLjava/util/List;)V +23w12a,emn,a,(JLjava/util/List;)V +23w13a,emo,a,(JLjava/util/List;)V +23w13a_or_b,ern,a,(JLjava/util/List;)V +23w13a_or_b_original,ern,a,(JLjava/util/List;)V +23w14a,emr,a,(JLjava/util/List;)V +23w16a,emv,a,(JLjava/util/List;)V +23w17a,emy,a,(JLjava/util/List;)V +23w18a,ena,a,(JLjava/util/List;)V +23w31a,eqo,a,(JLjava/util/List;)V +23w32a,eqn,a,(JLjava/util/List;)V +23w33a,eqm,a,(JLjava/util/List;)V +23w35a,eqr,a,(JLjava/util/List;)V +23w40a,eqq,a,(JLjava/util/List;)V +23w41a,erp,a,(JLjava/util/List;)V +23w42a,ess,a,(JLjava/util/List;)V +23w43a,ete,a,(JLjava/util/List;)V +23w43b,ete,a,(JLjava/util/List;)V +23w44a,etj,a,(JLjava/util/List;)V +23w45a,eul,a,(JLjava/util/List;)V +23w46a,evb,a,(JLjava/util/List;)V +23w51a,evs,a,(JLjava/util/List;)V +23w51b,evs,a,(JLjava/util/List;)V +24w03a,exi,a,(JLjava/util/List;)V +24w03b,exi,a,(JLjava/util/List;)V +24w04a,exp,a,(JLjava/util/List;)V +24w05a,eyl,a,(JLjava/util/List;)V +24w05b,eyl,a,(JLjava/util/List;)V +24w06a,ezh,a,(JLjava/util/List;)V +24w07a,ezj,a,(JLjava/util/List;)V +24w09a,fbq,a,(JLjava/util/List;)V +24w10a,fbz,a,(JLjava/util/List;)V +24w11a,fcv,a,(JLjava/util/List;)V +24w12a,fdf,a,(JLjava/util/List;)V +24w13a,fea,a,(JLjava/util/List;)V +24w14a,fec,a,(JLjava/util/List;)V +24w14potato,fgk,a,(JLjava/util/List;)V +24w14potato_original,fgk,a,(JLjava/util/List;)V +24w18a,ffo,a,(JLjava/util/List;)V +24w19a,ffu,a,(JLjava/util/List;)V +24w19b,ffu,a,(JLjava/util/List;)V +24w20a,ffx,a,(JLjava/util/List;)V +24w21a,fgj,a,(JLjava/util/List;I)V +24w21b,fgj,a,(JLjava/util/List;I)V +24w33a,fic,a,(JLjava/util/List;I)V +24w34a,fim,a,(JLjava/util/List;I)V +24w35a,fiq,a,(JLjava/util/List;I)V +24w36a,fjb,a,(JLjava/util/List;I)V +24w37a,fjj,a,(JLjava/util/List;I)V +24w38a,fjy,a,(JLjava/util/List;I)V +24w39a,fkf,a,(JLjava/util/List;I)V +24w40a,fma,a,(JLjava/util/List;I)V +24w44a,fma,a,(JLjava/util/List;I)V +24w45a,flk,a,(JLjava/util/List;I)V +24w46a,fli,a,(JLjava/util/List;I)V +25w02a,fmh,a,(JLjava/util/List;I)V +25w03a,fne,a,(JLjava/util/List;I)V +25w04a,fog,a,(JLjava/util/List;I)V +25w05a,fot,a,(JLjava/util/List;I)V +25w06a,fpa,a,(JLjava/util/List;I)V +25w07a,fpp,a,(JLjava/util/List;I)V +25w08a,fpu,a,(JLjava/util/List;I)V +25w09a,fre,a,(JLjava/util/List;I)V +25w09b,fre,a,(JLjava/util/List;I)V +25w10a,frg,a,(JLjava/util/List;I)V +25w14craftmine,fuq,a,(JLjava/util/List;I)V +25w15a,fri,a,(JLjava/util/List;I)V +25w16a,frj,a,(JLjava/util/List;I)V +25w17a,frx,a,(JLjava/util/List;I)V +25w18a,fsh,a,(JLjava/util/List;I)V +25w19a,fsh,a,(JLjava/util/List;I)V +25w20a,fuc,a,(JLjava/util/List;I)V +25w21a,fuf,a,(JLjava/util/List;I)V +25w31a,fvl,a,(JLjava/util/List;I)V +25w32a,fvv,a,(JLjava/util/List;I)V +25w33a,fwb,a,(JLjava/util/List;I)V +25w34a,fwf,a,(JLjava/util/List;I)V +25w34b,fwf,a,(JLjava/util/List;I)V +25w35a,fyq,a,(JLjava/util/List;I)V +25w36a,fzd,a,(JLjava/util/List;I)V +25w36b,fzd,a,(JLjava/util/List;I)V +25w37a,fzv,a,(JLjava/util/List;I)V +25w41a,gcd,a,(JLjava/util/List;I)V +25w42a,gcy,a,(JLjava/util/List;I)V +25w43a,gda,a,(JLjava/util/List;I)V +25w44a,gdt,a,(JLjava/util/List;I)V +25w45a,ged,a,(JLjava/util/List;I)V +25w46a,geg,a,(JLjava/util/List;I)V diff --git a/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_673.csv b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_673.csv new file mode 100644 index 00000000000..b526d92d212 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_673.csv @@ -0,0 +1,526 @@ +1.13,k$a,a,(Ljava/net/URI;)V +1.13-pre1,k$a,a,(Ljava/net/URI;)V +1.13-pre10,k$a,a,(Ljava/net/URI;)V +1.13-pre2,k$a,a,(Ljava/net/URI;)V +1.13-pre3,k$a,a,(Ljava/net/URI;)V +1.13-pre4,k$a,a,(Ljava/net/URI;)V +1.13-pre5,k$a,a,(Ljava/net/URI;)V +1.13-pre6,k$a,a,(Ljava/net/URI;)V +1.13-pre7,k$a,a,(Ljava/net/URI;)V +1.13-pre8,k$a,a,(Ljava/net/URI;)V +1.13-pre9,k$a,a,(Ljava/net/URI;)V +1.13.1,k$b,a,(Ljava/net/URI;)V +1.13.1-pre1,k$b,a,(Ljava/net/URI;)V +1.13.1-pre2,k$b,a,(Ljava/net/URI;)V +1.13.2,k$b,a,(Ljava/net/URI;)V +1.13.2-pre1,k$b,a,(Ljava/net/URI;)V +1.13.2-pre2,k$b,a,(Ljava/net/URI;)V +1.14 Pre-Release 1,p$b,a,(Ljava/net/URI;)V +1.14 Pre-Release 2,p$b,a,(Ljava/net/URI;)V +1.14 Pre-Release 3,p$b,a,(Ljava/net/URI;)V +1.14 Pre-Release 4,p$b,a,(Ljava/net/URI;)V +1.14 Pre-Release 5,p$b,a,(Ljava/net/URI;)V +1.14,p$b,a,(Ljava/net/URI;)V +1.14.1 Pre-Release 1,p$b,a,(Ljava/net/URI;)V +1.14.1 Pre-Release 2,p$b,a,(Ljava/net/URI;)V +1.14.1,p$b,a,(Ljava/net/URI;)V +1.14.2 Pre-Release 1,p$b,a,(Ljava/net/URI;)V +1.14.2 Pre-Release 2,p$b,a,(Ljava/net/URI;)V +1.14.2 Pre-Release 3,p$b,a,(Ljava/net/URI;)V +1.14.2 Pre-Release 4,p$b,a,(Ljava/net/URI;)V +1.14.2,p$b,a,(Ljava/net/URI;)V +1.14.3,p$b,a,(Ljava/net/URI;)V +1.14.3-pre1,p$b,a,(Ljava/net/URI;)V +1.14.3-pre2,p$b,a,(Ljava/net/URI;)V +1.14.3-pre3,p$b,a,(Ljava/net/URI;)V +1.14.3-pre4,p$b,a,(Ljava/net/URI;)V +1.14.4,p$b,a,(Ljava/net/URI;)V +1.14.4-pre1,p$b,a,(Ljava/net/URI;)V +1.14.4-pre2,p$b,a,(Ljava/net/URI;)V +1.14.4-pre3,p$b,a,(Ljava/net/URI;)V +1.14.4-pre4,p$b,a,(Ljava/net/URI;)V +1.14.4-pre5,p$b,a,(Ljava/net/URI;)V +1.14.4-pre6,p$b,a,(Ljava/net/URI;)V +1.14.4-pre7,p$b,a,(Ljava/net/URI;)V +1.14_combat-0,p$b,a,(Ljava/net/URI;)V +1.14_combat-212796,p$b,a,(Ljava/net/URI;)V +1.14_combat-3,p$b,a,(Ljava/net/URI;)V +1.15,t$b,a,(Ljava/net/URI;)V +1.15-pre1,t$b,a,(Ljava/net/URI;)V +1.15-pre2,t$b,a,(Ljava/net/URI;)V +1.15-pre3,t$b,a,(Ljava/net/URI;)V +1.15-pre4,t$b,a,(Ljava/net/URI;)V +1.15-pre5,t$b,a,(Ljava/net/URI;)V +1.15-pre6,t$b,a,(Ljava/net/URI;)V +1.15-pre7,t$b,a,(Ljava/net/URI;)V +1.15.1,t$b,a,(Ljava/net/URI;)V +1.15.1-pre1,t$b,a,(Ljava/net/URI;)V +1.15.2,t$b,a,(Ljava/net/URI;)V +1.15.2-pre1,t$b,a,(Ljava/net/URI;)V +1.15.2-pre2,t$b,a,(Ljava/net/URI;)V +1.15_combat-1,t$b,a,(Ljava/net/URI;)V +1.16,v$b,a,(Ljava/net/URI;)V +1.16-pre1,v$b,a,(Ljava/net/URI;)V +1.16-pre2,v$b,a,(Ljava/net/URI;)V +1.16-pre3,v$b,a,(Ljava/net/URI;)V +1.16-pre4,v$b,a,(Ljava/net/URI;)V +1.16-pre5,v$b,a,(Ljava/net/URI;)V +1.16-pre6,v$b,a,(Ljava/net/URI;)V +1.16-pre7,v$b,a,(Ljava/net/URI;)V +1.16-pre8,v$b,a,(Ljava/net/URI;)V +1.16-rc1,v$b,a,(Ljava/net/URI;)V +1.16.1,v$b,a,(Ljava/net/URI;)V +1.16.2,x$b,a,(Ljava/net/URI;)V +1.16.2-pre1,x$b,a,(Ljava/net/URI;)V +1.16.2-pre2,x$b,a,(Ljava/net/URI;)V +1.16.2-pre3,x$b,a,(Ljava/net/URI;)V +1.16.2-rc1,x$b,a,(Ljava/net/URI;)V +1.16.2-rc2,x$b,a,(Ljava/net/URI;)V +1.16.3,x$b,a,(Ljava/net/URI;)V +1.16.3-rc1,x$b,a,(Ljava/net/URI;)V +1.16.4,x$b,a,(Ljava/net/URI;)V +1.16.4-pre1,x$b,a,(Ljava/net/URI;)V +1.16.4-pre2,x$b,a,(Ljava/net/URI;)V +1.16.4-rc1,x$b,a,(Ljava/net/URI;)V +1.16.5,x$b,a,(Ljava/net/URI;)V +1.16.5-rc1,x$b,a,(Ljava/net/URI;)V +1.16_combat-3,x$b,a,(Ljava/net/URI;)V +1.17,ad$b,a,(Ljava/net/URI;)V +1.17-pre1,ad$b,a,(Ljava/net/URI;)V +1.17-pre2,ad$b,a,(Ljava/net/URI;)V +1.17-pre3,ad$b,a,(Ljava/net/URI;)V +1.17-pre4,ad$b,a,(Ljava/net/URI;)V +1.17-pre5,ad$b,a,(Ljava/net/URI;)V +1.17-rc1,ad$b,a,(Ljava/net/URI;)V +1.17-rc2,ad$b,a,(Ljava/net/URI;)V +1.17.1,ad$b,a,(Ljava/net/URI;)V +1.17.1-pre1,ad$b,a,(Ljava/net/URI;)V +1.17.1-pre2,ad$b,a,(Ljava/net/URI;)V +1.17.1-pre3,ad$b,a,(Ljava/net/URI;)V +1.17.1-rc1,ad$b,a,(Ljava/net/URI;)V +1.17.1-rc2,ad$b,a,(Ljava/net/URI;)V +1.18,ad$b,a,(Ljava/net/URI;)V +1.18-pre1,ad$b,a,(Ljava/net/URI;)V +1.18-pre2,ad$b,a,(Ljava/net/URI;)V +1.18-pre3,ad$b,a,(Ljava/net/URI;)V +1.18-pre4,ad$b,a,(Ljava/net/URI;)V +1.18-pre5,ad$b,a,(Ljava/net/URI;)V +1.18-pre6,ad$b,a,(Ljava/net/URI;)V +1.18-pre7,ad$b,a,(Ljava/net/URI;)V +1.18-pre8,ad$b,a,(Ljava/net/URI;)V +1.18-rc1,ad$b,a,(Ljava/net/URI;)V +1.18-rc2,ad$b,a,(Ljava/net/URI;)V +1.18-rc3,ad$b,a,(Ljava/net/URI;)V +1.18-rc4,ad$b,a,(Ljava/net/URI;)V +1.18.1,ad$b,a,(Ljava/net/URI;)V +1.18.1-pre1,ad$b,a,(Ljava/net/URI;)V +1.18.1-rc1,ad$b,a,(Ljava/net/URI;)V +1.18.1-rc2,ad$b,a,(Ljava/net/URI;)V +1.18.1-rc3,ad$b,a,(Ljava/net/URI;)V +1.18.2,ad$b,a,(Ljava/net/URI;)V +1.18.2-pre1,ad$b,a,(Ljava/net/URI;)V +1.18.2-pre2,ad$b,a,(Ljava/net/URI;)V +1.18.2-pre3,ad$b,a,(Ljava/net/URI;)V +1.18.2-rc1,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-1,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-2,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-3,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-4,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-5,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-6,ad$b,a,(Ljava/net/URI;)V +1.18_experimental-snapshot-7,ad$b,a,(Ljava/net/URI;)V +1.19,ad$b,a,(Ljava/net/URI;)V +1.19-pre1,ad$b,a,(Ljava/net/URI;)V +1.19-pre2,ad$b,a,(Ljava/net/URI;)V +1.19-pre3,ad$b,a,(Ljava/net/URI;)V +1.19-pre4,ad$b,a,(Ljava/net/URI;)V +1.19-pre5,ad$b,a,(Ljava/net/URI;)V +1.19-rc1,ad$b,a,(Ljava/net/URI;)V +1.19-rc2,ad$b,a,(Ljava/net/URI;)V +1.19.1,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre1,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre2,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre3,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre4,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre5,ad$b,a,(Ljava/net/URI;)V +1.19.1-pre6,ad$b,a,(Ljava/net/URI;)V +1.19.1-rc1,ad$b,a,(Ljava/net/URI;)V +1.19.1-rc2,ad$b,a,(Ljava/net/URI;)V +1.19.1-rc3,ad$b,a,(Ljava/net/URI;)V +1.19.2,ad$b,a,(Ljava/net/URI;)V +1.19.2-rc1,ad$b,a,(Ljava/net/URI;)V +1.19.2-rc2,ad$b,a,(Ljava/net/URI;)V +1.19.3,aa$b,a,(Ljava/net/URI;)V +1.19.3-pre1,aa$b,a,(Ljava/net/URI;)V +1.19.3-pre2,aa$b,a,(Ljava/net/URI;)V +1.19.3-pre3,aa$b,a,(Ljava/net/URI;)V +1.19.3-rc1,aa$b,a,(Ljava/net/URI;)V +1.19.3-rc2,aa$b,a,(Ljava/net/URI;)V +1.19.3-rc3,aa$b,a,(Ljava/net/URI;)V +1.19.4,ac$b,a,(Ljava/net/URI;)V +1.19.4-pre1,ab$b,a,(Ljava/net/URI;)V +1.19.4-pre2,ab$b,a,(Ljava/net/URI;)V +1.19.4-pre3,ab$b,a,(Ljava/net/URI;)V +1.19.4-pre4,ac$b,a,(Ljava/net/URI;)V +1.19.4-rc1,ac$b,a,(Ljava/net/URI;)V +1.19.4-rc2,ac$b,a,(Ljava/net/URI;)V +1.19.4-rc3,ac$b,a,(Ljava/net/URI;)V +1.19_deep_dark_experimental_snapshot-1,ad$b,a,(Ljava/net/URI;)V +1.20,ac$b,a,(Ljava/net/URI;)V +1.20-pre1,ac$b,a,(Ljava/net/URI;)V +1.20-pre2,ac$b,a,(Ljava/net/URI;)V +1.20-pre3,ac$b,a,(Ljava/net/URI;)V +1.20-pre4,ac$b,a,(Ljava/net/URI;)V +1.20-pre5,ac$b,a,(Ljava/net/URI;)V +1.20-pre6,ac$b,a,(Ljava/net/URI;)V +1.20-pre7,ac$b,a,(Ljava/net/URI;)V +1.20-rc1,ac$b,a,(Ljava/net/URI;)V +1.20.1,ac$b,a,(Ljava/net/URI;)V +1.20.1-rc1,ac$b,a,(Ljava/net/URI;)V +1.20.2,ac$b,a,(Ljava/net/URI;)V +1.20.2-pre1,ac$b,a,(Ljava/net/URI;)V +1.20.2-pre2,ac$b,a,(Ljava/net/URI;)V +1.20.2-pre3,ac$b,a,(Ljava/net/URI;)V +1.20.2-pre4,ac$b,a,(Ljava/net/URI;)V +1.20.2-rc1,ac$b,a,(Ljava/net/URI;)V +1.20.2-rc2,ac$b,a,(Ljava/net/URI;)V +1.20.3,ac$a,a,(Ljava/net/URI;)V +1.20.3-pre1,ac$a,a,(Ljava/net/URI;)V +1.20.3-pre2,ac$a,a,(Ljava/net/URI;)V +1.20.3-pre3,ac$a,a,(Ljava/net/URI;)V +1.20.3-pre4,ac$a,a,(Ljava/net/URI;)V +1.20.3-rc1,ac$a,a,(Ljava/net/URI;)V +1.20.4,ac$a,a,(Ljava/net/URI;)V +1.20.4-rc1,ac$a,a,(Ljava/net/URI;)V +1.20.5,ac$a,a,(Ljava/net/URI;)V +1.20.5-pre1,ac$a,a,(Ljava/net/URI;)V +1.20.5-pre2,ac$a,a,(Ljava/net/URI;)V +1.20.5-pre3,ac$a,a,(Ljava/net/URI;)V +1.20.5-pre4,ac$a,a,(Ljava/net/URI;)V +1.20.5-rc1,ac$a,a,(Ljava/net/URI;)V +1.20.5-rc2,ac$a,a,(Ljava/net/URI;)V +1.20.5-rc3,ac$a,a,(Ljava/net/URI;)V +1.20.6,ac$a,a,(Ljava/net/URI;)V +1.20.6-rc1,ac$a,a,(Ljava/net/URI;)V +1.21,ad$a,a,(Ljava/net/URI;)V +1.21-pre1,ad$a,a,(Ljava/net/URI;)V +1.21-pre2,ad$a,a,(Ljava/net/URI;)V +1.21-pre3,ad$a,a,(Ljava/net/URI;)V +1.21-pre4,ad$a,a,(Ljava/net/URI;)V +1.21-rc1,ad$a,a,(Ljava/net/URI;)V +1.21.1,ad$a,a,(Ljava/net/URI;)V +1.21.1-rc1,ad$a,a,(Ljava/net/URI;)V +1.21.10,ag$a,a,(Ljava/net/URI;)V +1.21.10-rc1,ag$a,a,(Ljava/net/URI;)V +1.21.11,bhs$a,a,(Ljava/net/URI;)V +1.21.11-pre1,bhs$a,a,(Ljava/net/URI;)V +1.21.11-pre2,bhs$a,a,(Ljava/net/URI;)V +1.21.11-pre3,bhs$a,a,(Ljava/net/URI;)V +1.21.11-pre4,bhs$a,a,(Ljava/net/URI;)V +1.21.11-pre5,bhs$a,a,(Ljava/net/URI;)V +1.21.11-rc1,bhs$a,a,(Ljava/net/URI;)V +1.21.11-rc2,bhs$a,a,(Ljava/net/URI;)V +1.21.11-rc3,bhs$a,a,(Ljava/net/URI;)V +1.21.2,ae$a,a,(Ljava/net/URI;)V +1.21.2-pre1,ae$a,a,(Ljava/net/URI;)V +1.21.2-pre2,ae$a,a,(Ljava/net/URI;)V +1.21.2-pre3,ae$a,a,(Ljava/net/URI;)V +1.21.2-pre4,ae$a,a,(Ljava/net/URI;)V +1.21.2-pre5,ae$a,a,(Ljava/net/URI;)V +1.21.2-rc1,ae$a,a,(Ljava/net/URI;)V +1.21.2-rc2,ae$a,a,(Ljava/net/URI;)V +1.21.3,ae$a,a,(Ljava/net/URI;)V +1.21.4,af$a,a,(Ljava/net/URI;)V +1.21.4-pre1,af$a,a,(Ljava/net/URI;)V +1.21.4-pre2,af$a,a,(Ljava/net/URI;)V +1.21.4-pre3,af$a,a,(Ljava/net/URI;)V +1.21.4-rc1,af$a,a,(Ljava/net/URI;)V +1.21.4-rc2,af$a,a,(Ljava/net/URI;)V +1.21.4-rc3,af$a,a,(Ljava/net/URI;)V +1.21.5,ag$a,a,(Ljava/net/URI;)V +1.21.5-pre1,ag$a,a,(Ljava/net/URI;)V +1.21.5-pre2,ag$a,a,(Ljava/net/URI;)V +1.21.5-pre3,ag$a,a,(Ljava/net/URI;)V +1.21.5-rc1,ag$a,a,(Ljava/net/URI;)V +1.21.5-rc2,ag$a,a,(Ljava/net/URI;)V +1.21.6,ag$a,a,(Ljava/net/URI;)V +1.21.6-pre1,ag$a,a,(Ljava/net/URI;)V +1.21.6-pre2,ag$a,a,(Ljava/net/URI;)V +1.21.6-pre3,ag$a,a,(Ljava/net/URI;)V +1.21.6-pre4,ag$a,a,(Ljava/net/URI;)V +1.21.6-rc1,ag$a,a,(Ljava/net/URI;)V +1.21.7,ag$a,a,(Ljava/net/URI;)V +1.21.7-rc1,ag$a,a,(Ljava/net/URI;)V +1.21.7-rc2,ag$a,a,(Ljava/net/URI;)V +1.21.8,ag$a,a,(Ljava/net/URI;)V +1.21.8-rc1,ag$a,a,(Ljava/net/URI;)V +1.21.9,ag$a,a,(Ljava/net/URI;)V +1.21.9-pre1,ag$a,a,(Ljava/net/URI;)V +1.21.9-pre2,ag$a,a,(Ljava/net/URI;)V +1.21.9-pre3,ag$a,a,(Ljava/net/URI;)V +1.21.9-pre4,ag$a,a,(Ljava/net/URI;)V +1.21.9-rc1,ag$a,a,(Ljava/net/URI;)V +17w43a,h$a,a,(Ljava/net/URI;)V +17w43b,h$a,a,(Ljava/net/URI;)V +17w45a,h$a,a,(Ljava/net/URI;)V +17w45b,h$a,a,(Ljava/net/URI;)V +17w46a,h$a,a,(Ljava/net/URI;)V +17w47a,h$a,a,(Ljava/net/URI;)V +17w47b,h$a,a,(Ljava/net/URI;)V +17w48a,h$a,a,(Ljava/net/URI;)V +17w49a,i$a,a,(Ljava/net/URI;)V +17w49b,i$a,a,(Ljava/net/URI;)V +17w50a,i$a,a,(Ljava/net/URI;)V +18w01a,i$a,a,(Ljava/net/URI;)V +18w02a,i$a,a,(Ljava/net/URI;)V +18w03a,i$a,a,(Ljava/net/URI;)V +18w03b,i$a,a,(Ljava/net/URI;)V +18w05a,i$a,a,(Ljava/net/URI;)V +18w06a,k$a,a,(Ljava/net/URI;)V +18w07a,k$a,a,(Ljava/net/URI;)V +18w07b,k$a,a,(Ljava/net/URI;)V +18w07c,k$a,a,(Ljava/net/URI;)V +18w08a,k$a,a,(Ljava/net/URI;)V +18w08b,k$a,a,(Ljava/net/URI;)V +18w09a,k$a,a,(Ljava/net/URI;)V +18w10a,k$a,a,(Ljava/net/URI;)V +18w10b,k$a,a,(Ljava/net/URI;)V +18w10c,k$a,a,(Ljava/net/URI;)V +18w10d,k$a,a,(Ljava/net/URI;)V +18w11a,k$a,a,(Ljava/net/URI;)V +18w14a,k$a,a,(Ljava/net/URI;)V +18w14b,k$a,a,(Ljava/net/URI;)V +18w15a,k$a,a,(Ljava/net/URI;)V +18w16a,k$a,a,(Ljava/net/URI;)V +18w19a,k$a,a,(Ljava/net/URI;)V +18w19b,k$a,a,(Ljava/net/URI;)V +18w20a,k$a,a,(Ljava/net/URI;)V +18w20b,k$a,a,(Ljava/net/URI;)V +18w20c,k$a,a,(Ljava/net/URI;)V +18w21a,k$a,a,(Ljava/net/URI;)V +18w21b,k$a,a,(Ljava/net/URI;)V +18w22a,k$a,a,(Ljava/net/URI;)V +18w22b,k$a,a,(Ljava/net/URI;)V +18w22c,k$a,a,(Ljava/net/URI;)V +18w30a,k$b,a,(Ljava/net/URI;)V +18w30b,k$b,a,(Ljava/net/URI;)V +18w31a,k$b,a,(Ljava/net/URI;)V +18w32a,k$b,a,(Ljava/net/URI;)V +18w33a,k$b,a,(Ljava/net/URI;)V +18w43a,k$b,a,(Ljava/net/URI;)V +18w43b,k$b,a,(Ljava/net/URI;)V +18w43c,k$b,a,(Ljava/net/URI;)V +18w44a,k$b,a,(Ljava/net/URI;)V +18w45a,l$b,a,(Ljava/net/URI;)V +18w46a,l$b,a,(Ljava/net/URI;)V +18w47a,l$b,a,(Ljava/net/URI;)V +18w47b,m$b,a,(Ljava/net/URI;)V +18w48a,m$b,a,(Ljava/net/URI;)V +18w48b,m$b,a,(Ljava/net/URI;)V +18w49a,m$b,a,(Ljava/net/URI;)V +18w50a,m$b,a,(Ljava/net/URI;)V +19w02a,m$b,a,(Ljava/net/URI;)V +19w03a,m$b,a,(Ljava/net/URI;)V +19w03b,m$b,a,(Ljava/net/URI;)V +19w03c,m$b,a,(Ljava/net/URI;)V +19w04a,m$b,a,(Ljava/net/URI;)V +19w04b,m$b,a,(Ljava/net/URI;)V +19w05a,m$b,a,(Ljava/net/URI;)V +19w06a,m$b,a,(Ljava/net/URI;)V +19w07a,m$b,a,(Ljava/net/URI;)V +19w08a,m$b,a,(Ljava/net/URI;)V +19w08b,m$b,a,(Ljava/net/URI;)V +19w09a,m$b,a,(Ljava/net/URI;)V +19w11a,o$b,a,(Ljava/net/URI;)V +19w11b,o$b,a,(Ljava/net/URI;)V +19w12a,p$b,a,(Ljava/net/URI;)V +19w12b,p$b,a,(Ljava/net/URI;)V +19w13a,p$b,a,(Ljava/net/URI;)V +19w13b,p$b,a,(Ljava/net/URI;)V +19w14a,p$b,a,(Ljava/net/URI;)V +19w14b,p$b,a,(Ljava/net/URI;)V +19w34a,p$b,a,(Ljava/net/URI;)V +19w35a,p$b,a,(Ljava/net/URI;)V +19w36a,p$b,a,(Ljava/net/URI;)V +19w37a,p$b,a,(Ljava/net/URI;)V +19w38a,p$b,a,(Ljava/net/URI;)V +19w38b,p$b,a,(Ljava/net/URI;)V +19w39a,t$b,a,(Ljava/net/URI;)V +19w40a,t$b,a,(Ljava/net/URI;)V +19w41a,t$b,a,(Ljava/net/URI;)V +19w42a,t$b,a,(Ljava/net/URI;)V +19w44a,t$b,a,(Ljava/net/URI;)V +19w45a,t$b,a,(Ljava/net/URI;)V +19w45b,t$b,a,(Ljava/net/URI;)V +19w46a,t$b,a,(Ljava/net/URI;)V +19w46b,t$b,a,(Ljava/net/URI;)V +1_15_combat-6,t$b,a,(Ljava/net/URI;)V +1_16_combat-0,x$b,a,(Ljava/net/URI;)V +20w06a,t$b,a,(Ljava/net/URI;)V +20w07a,t$b,a,(Ljava/net/URI;)V +20w08a,t$b,a,(Ljava/net/URI;)V +20w09a,t$b,a,(Ljava/net/URI;)V +20w10a,t$b,a,(Ljava/net/URI;)V +20w11a,t$b,a,(Ljava/net/URI;)V +20w12a,t$b,a,(Ljava/net/URI;)V +20w13a,v$b,a,(Ljava/net/URI;)V +20w13b,v$b,a,(Ljava/net/URI;)V +20w14a,v$b,a,(Ljava/net/URI;)V +20w14infinite,v$b,a,(Ljava/net/URI;)V +20w15a,v$b,a,(Ljava/net/URI;)V +20w16a,v$b,a,(Ljava/net/URI;)V +20w17a,v$b,a,(Ljava/net/URI;)V +20w18a,v$b,a,(Ljava/net/URI;)V +20w19a,v$b,a,(Ljava/net/URI;)V +20w20a,v$b,a,(Ljava/net/URI;)V +20w20b,v$b,a,(Ljava/net/URI;)V +20w21a,v$b,a,(Ljava/net/URI;)V +20w22a,v$b,a,(Ljava/net/URI;)V +20w27a,v$b,a,(Ljava/net/URI;)V +20w28a,x$b,a,(Ljava/net/URI;)V +20w29a,x$b,a,(Ljava/net/URI;)V +20w30a,x$b,a,(Ljava/net/URI;)V +20w45a,x$b,a,(Ljava/net/URI;)V +20w46a,x$b,a,(Ljava/net/URI;)V +20w48a,x$b,a,(Ljava/net/URI;)V +20w49a,x$b,a,(Ljava/net/URI;)V +20w51a,x$b,a,(Ljava/net/URI;)V +21w03a,x$b,a,(Ljava/net/URI;)V +21w05a,x$b,a,(Ljava/net/URI;)V +21w05b,x$b,a,(Ljava/net/URI;)V +21w06a,x$b,a,(Ljava/net/URI;)V +21w07a,x$b,a,(Ljava/net/URI;)V +21w08a,x$b,a,(Ljava/net/URI;)V +21w08b,x$b,a,(Ljava/net/URI;)V +21w10a,x$b,a,(Ljava/net/URI;)V +21w11a,x$b,a,(Ljava/net/URI;)V +21w13a,ac$b,a,(Ljava/net/URI;)V +21w14a,ac$b,a,(Ljava/net/URI;)V +21w15a,ac$b,a,(Ljava/net/URI;)V +21w16a,ac$b,a,(Ljava/net/URI;)V +21w17a,ac$b,a,(Ljava/net/URI;)V +21w18a,ac$b,a,(Ljava/net/URI;)V +21w19a,ac$b,a,(Ljava/net/URI;)V +21w20a,ac$b,a,(Ljava/net/URI;)V +21w37a,ad$b,a,(Ljava/net/URI;)V +21w38a,ad$b,a,(Ljava/net/URI;)V +21w39a,ad$b,a,(Ljava/net/URI;)V +21w40a,ad$b,a,(Ljava/net/URI;)V +21w41a,ad$b,a,(Ljava/net/URI;)V +21w42a,ad$b,a,(Ljava/net/URI;)V +21w43a,ad$b,a,(Ljava/net/URI;)V +21w44a,ad$b,a,(Ljava/net/URI;)V +22w03a,ad$b,a,(Ljava/net/URI;)V +22w05a,ad$b,a,(Ljava/net/URI;)V +22w06a,ad$b,a,(Ljava/net/URI;)V +22w07a,ad$b,a,(Ljava/net/URI;)V +22w11a,ad$b,a,(Ljava/net/URI;)V +22w12a,ad$b,a,(Ljava/net/URI;)V +22w13a,ad$b,a,(Ljava/net/URI;)V +22w13oneblockatatime,ad$b,a,(Ljava/net/URI;)V +22w14a,ad$b,a,(Ljava/net/URI;)V +22w15a,ad$b,a,(Ljava/net/URI;)V +22w16a,ad$b,a,(Ljava/net/URI;)V +22w16b,ad$b,a,(Ljava/net/URI;)V +22w17a,ad$b,a,(Ljava/net/URI;)V +22w18a,ad$b,a,(Ljava/net/URI;)V +22w19a,ad$b,a,(Ljava/net/URI;)V +22w24a,ad$b,a,(Ljava/net/URI;)V +22w42a,ad$b,a,(Ljava/net/URI;)V +22w43a,aa$b,a,(Ljava/net/URI;)V +22w44a,aa$b,a,(Ljava/net/URI;)V +22w45a,aa$b,a,(Ljava/net/URI;)V +22w46a,aa$b,a,(Ljava/net/URI;)V +23w03a,aa$b,a,(Ljava/net/URI;)V +23w04a,aa$b,a,(Ljava/net/URI;)V +23w05a,aa$b,a,(Ljava/net/URI;)V +23w06a,ab$b,a,(Ljava/net/URI;)V +23w07a,ab$b,a,(Ljava/net/URI;)V +23w12a,ac$b,a,(Ljava/net/URI;)V +23w13a,ac$b,a,(Ljava/net/URI;)V +23w13a_or_b,ac$b,a,(Ljava/net/URI;)V +23w13a_or_b_original,ac$b,a,(Ljava/net/URI;)V +23w14a,ac$b,a,(Ljava/net/URI;)V +23w16a,ac$b,a,(Ljava/net/URI;)V +23w17a,ac$b,a,(Ljava/net/URI;)V +23w18a,ac$b,a,(Ljava/net/URI;)V +23w31a,ac$b,a,(Ljava/net/URI;)V +23w32a,ac$b,a,(Ljava/net/URI;)V +23w33a,ac$b,a,(Ljava/net/URI;)V +23w35a,ac$b,a,(Ljava/net/URI;)V +23w40a,ac$a,a,(Ljava/net/URI;)V +23w41a,ac$a,a,(Ljava/net/URI;)V +23w42a,ac$a,a,(Ljava/net/URI;)V +23w43a,ac$a,a,(Ljava/net/URI;)V +23w43b,ac$a,a,(Ljava/net/URI;)V +23w44a,ac$a,a,(Ljava/net/URI;)V +23w45a,ac$a,a,(Ljava/net/URI;)V +23w46a,ac$a,a,(Ljava/net/URI;)V +23w51a,ac$a,a,(Ljava/net/URI;)V +23w51b,ac$a,a,(Ljava/net/URI;)V +24w03a,ac$a,a,(Ljava/net/URI;)V +24w03b,ac$a,a,(Ljava/net/URI;)V +24w04a,ac$a,a,(Ljava/net/URI;)V +24w05a,ac$a,a,(Ljava/net/URI;)V +24w05b,ac$a,a,(Ljava/net/URI;)V +24w06a,ac$a,a,(Ljava/net/URI;)V +24w07a,ac$a,a,(Ljava/net/URI;)V +24w09a,ac$a,a,(Ljava/net/URI;)V +24w10a,ac$a,a,(Ljava/net/URI;)V +24w11a,ac$a,a,(Ljava/net/URI;)V +24w12a,ac$a,a,(Ljava/net/URI;)V +24w13a,ac$a,a,(Ljava/net/URI;)V +24w14a,ac$a,a,(Ljava/net/URI;)V +24w14potato,ad$a,a,(Ljava/net/URI;)V +24w14potato_original,ad$a,a,(Ljava/net/URI;)V +24w18a,ac$a,a,(Ljava/net/URI;)V +24w19a,ac$a,a,(Ljava/net/URI;)V +24w19b,ac$a,a,(Ljava/net/URI;)V +24w20a,ac$a,a,(Ljava/net/URI;)V +24w21a,ad$a,a,(Ljava/net/URI;)V +24w21b,ad$a,a,(Ljava/net/URI;)V +24w33a,ad$a,a,(Ljava/net/URI;)V +24w34a,ad$a,a,(Ljava/net/URI;)V +24w35a,ad$a,a,(Ljava/net/URI;)V +24w36a,ad$a,a,(Ljava/net/URI;)V +24w37a,ae$a,a,(Ljava/net/URI;)V +24w38a,ae$a,a,(Ljava/net/URI;)V +24w39a,ae$a,a,(Ljava/net/URI;)V +24w40a,ae$a,a,(Ljava/net/URI;)V +24w44a,ae$a,a,(Ljava/net/URI;)V +24w45a,af$a,a,(Ljava/net/URI;)V +24w46a,af$a,a,(Ljava/net/URI;)V +25w02a,af$a,a,(Ljava/net/URI;)V +25w03a,af$a,a,(Ljava/net/URI;)V +25w04a,af$a,a,(Ljava/net/URI;)V +25w05a,af$a,a,(Ljava/net/URI;)V +25w06a,af$a,a,(Ljava/net/URI;)V +25w07a,ag$a,a,(Ljava/net/URI;)V +25w08a,ag$a,a,(Ljava/net/URI;)V +25w09a,ag$a,a,(Ljava/net/URI;)V +25w09b,ag$a,a,(Ljava/net/URI;)V +25w10a,ag$a,a,(Ljava/net/URI;)V +25w14craftmine,ag$a,a,(Ljava/net/URI;)V +25w15a,ag$a,a,(Ljava/net/URI;)V +25w16a,ag$a,a,(Ljava/net/URI;)V +25w17a,ag$a,a,(Ljava/net/URI;)V +25w18a,ag$a,a,(Ljava/net/URI;)V +25w19a,ag$a,a,(Ljava/net/URI;)V +25w20a,ag$a,a,(Ljava/net/URI;)V +25w21a,ag$a,a,(Ljava/net/URI;)V +25w31a,ag$a,a,(Ljava/net/URI;)V +25w32a,ag$a,a,(Ljava/net/URI;)V +25w33a,ag$a,a,(Ljava/net/URI;)V +25w34a,ag$a,a,(Ljava/net/URI;)V +25w34b,ag$a,a,(Ljava/net/URI;)V +25w35a,ag$a,a,(Ljava/net/URI;)V +25w36a,ag$a,a,(Ljava/net/URI;)V +25w36b,ag$a,a,(Ljava/net/URI;)V +25w37a,ag$a,a,(Ljava/net/URI;)V +25w41a,ag$a,a,(Ljava/net/URI;)V +25w42a,ag$a,a,(Ljava/net/URI;)V +25w43a,ag$a,a,(Ljava/net/URI;)V +25w44a,ac$a,a,(Ljava/net/URI;)V +25w45a,bhr$a,a,(Ljava/net/URI;)V +25w46a,bhs$a,a,(Ljava/net/URI;)V +3D Shareware v1.34,p$b,a,(Ljava/net/URI;)V diff --git a/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_68464.csv b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_68464.csv new file mode 100644 index 00000000000..38bed5aee51 --- /dev/null +++ b/packages/modrinth-sandbox-agent/src/main/resources/com/modrinth/sandboxagent/method_68464.csv @@ -0,0 +1,60 @@ +1.21.10,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.10-rc1,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-pre1,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-pre2,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-pre3,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-pre4,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-pre5,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-rc1,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-rc2,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.11-rc3,fzz,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5-pre1,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5-pre2,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5-pre3,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5-rc1,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.5-rc2,flq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6-pre1,foo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6-pre2,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6-pre3,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6-pre4,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.6-rc1,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.7,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.7-rc1,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.7-rc2,fop,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.8,foq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.8-rc1,foq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9-pre1,fuo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9-pre2,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9-pre3,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9-pre4,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +1.21.9-rc1,fun,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w09a,fmd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w09b,fmd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w10a,fmf,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w14craftmine,fpq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w15a,fmh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w16a,fmi,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w17a,fmj,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w18a,fmt,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w19a,fmt,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w20a,fon,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w21a,foq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w31a,fpx,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w32a,fqh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w33a,fqn,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w34a,fqs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w34b,fqs,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w35a,ftd,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w36a,ftq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w36b,ftq,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w37a,fui,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w41a,fwr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w42a,fxm,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w43a,fxo,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w44a,fyh,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w45a,fyr,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; +25w46a,fyv,a,(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; diff --git a/packages/modrinth-sandbox/Cargo.toml b/packages/modrinth-sandbox/Cargo.toml new file mode 100644 index 00000000000..ae067a4bcbc --- /dev/null +++ b/packages/modrinth-sandbox/Cargo.toml @@ -0,0 +1,73 @@ +[package] +name = "modrinth-sandbox" +version = "0.1.0" +edition.workspace = true +readme = "README.md" + +[lib] +crate-type = ["rlib", "cdylib", "staticlib"] + +[dependencies] +tempfile = { workspace = true } +tracing = { workspace = true } +tokio = { workspace = true, features = ["fs", "io-util", "macros", "net", "process", "rt", "sync"] } +eyre = { workspace = true } +async-trait = { workspace = true } +bitflags = { workspace = true, features = ["serde"] } +derive_more = { workspace = true, features = ["debug"] } +uuid = { workspace = true, features = ["v7"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +zbus = { workspace = true } +enum_dispatch = { workspace = true } +futures = { workspace = true } +rand = { workspace = true } +libc = { workspace = true } +infer = { workspace = true } +parking_lot = { workspace = true } +reqwest = { workspace = true } +url = { workspace = true } +httparse = { workspace = true } +open = { workspace = true } +urlencoding = { workspace = true } +sha1 = { workspace = true } +hex = { workspace = true } +indexmap = { workspace = true } +async_zip = { workspace = true, features = [ + "bzip2", + "chrono", + "deflate", + "deflate64", + "tokio-fs", + "zstd", +] } + +[dev-dependencies] +tokio = { workspace = true, features = ["full"] } +tracing-subscriber = { workspace = true, features = ["chrono", "env-filter"] } +clap = { workspace = true, features = ["derive"] } + +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +ashpd = { workspace = true } +libseccomp = { workspace = true } +directories = { workspace = true } +fuser = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +objc2-app-kit = { workspace = true } +objc2-foundation = { workspace = true } +objc2-uniform-type-identifiers = { workspace = true } +dispatch2 = { workspace = true } +block2 = { workspace = true } + +[target.'cfg(target_os = "windows")'.dependencies] +windows = { workspace = true, features = ["Win32_System_Memory", "Win32_UI_Shell_Common"] } +scopeguard = { workspace = true } +winreg = { workspace = true } +serde_json = { workspace = true } + +[lints] +workspace = true diff --git a/packages/modrinth-sandbox/README.md b/packages/modrinth-sandbox/README.md new file mode 100644 index 00000000000..fffbf6efb31 --- /dev/null +++ b/packages/modrinth-sandbox/README.md @@ -0,0 +1,81 @@ +Library for sandboxing Minecraft instances for modded game launchers + +```rs +use eyre::{Context, Result}; +use modrinth_sandbox::{minecraft::MinecraftCommand, SandboxEnv, SandboxOutput}; + +#[tokio::main] +async fn main() -> Result<()> { + // Handle sandbox setup when this executable is launched as a helper. + if modrinth_sandbox::helper::run_default()? { + return Ok(()); + } + + // Create the sandbox. + let sandbox_env = SandboxEnv::new() + .await + .wrap_err("creating sandbox environment")?; + let command = MinecraftCommand { + jre_path: "/path/to/the/jre".into(), + classpath: vec!["/path/to/minecraft.jar".into()], + instance_path: "/path/to/instance".into(), + persistent_dir: "/path/to/instance-data".into(), + // etc. + }; + + // Spawn Minecraft. + let command = modrinth_sandbox::minecraft::setup_minecraft_command(command) + .await + .wrap_err("creating Minecraft sandbox command")?; + let mut minecraft_process = sandbox_env + .spawn(command) + .await + .wrap_err("running Minecraft")?; + // Minecraft is now running in a sandbox. + + // Wait for the user to close the game. + minecraft_process.wait().await?; + Ok(()) +} +``` + +The goal of this crate is to make it stupid simple to run a Minecraft instance inside a sandbox _the right way_. Sandboxing isolates the game process from the user's real machine, so that mods and other game code is unable to access sensitive user resources, like browser cookies or login tokens; this prevents malicious mods from reading such information, or performing other sensitive actions. + +Sandboxing aims to be minimally invasive to the game, so most mods should continue working fine. This means we generally do not restrict access to the network, microphone, controller, or other hardware. Mods which read files outside of the instance directory may require changes to work properly. + +# Architecture + +We use OS-specific primitives to perform sandboxing, that is: +- Windows [AppContainers] +- MacOS [Seatbelt] and `sandbox-exec` +- Linux + - In Flatpak: [`flatpak-spawn`] + - Outside of Flatpak: [Bubblewrap] + +Each platform has its own specific capabilities, but we abstract over that using the `SandboxCommand`, which is a platform-independent way to configure: +- What command you want to run in a sandbox +- What capabilities you allow inside the sandbox +- What files are exposed inside the sandbox + +The general flow of spawning a sandboxed process is: + +- Call `helper::run_default` + + This handles sandbox setup when the application is relaunched as a helper process. If it returns `true`, exit without continuing normal application startup. + +- Create a `SandboxEnv` + + This ensures that we have the right dependencies to actually perform sandboxing. On most platforms this should always be successful, but on Linux we may be missing `bwrap` - this is our chance to inform the user that they're missing dependencies. + +- Create a `SandboxCommand` + + This sets up the sandboxing configuration and describes what we actually want to run. + +- Run `SandboxEnv::spawn` + + This starts the sandboxed process, and gives us back a `SandboxChild`, which we can use to wait for process termination, or kill the process, or anything else we need to do. + +[AppContainers]: https://learn.microsoft.com/en-us/windows/win32/secauthz/appcontainer-isolation +[Seatbelt]: https://theapplewiki.com/wiki/Dev:Seatbelt +[`flatpak-spawn`]: https://www.man7.org/linux/man-pages/man1/flatpak-spawn.1.html +[Bubblewrap]: https://github.com/containers/bubblewrap diff --git a/packages/modrinth-sandbox/cbindgen.toml b/packages/modrinth-sandbox/cbindgen.toml new file mode 100644 index 00000000000..3c31cdd6407 --- /dev/null +++ b/packages/modrinth-sandbox/cbindgen.toml @@ -0,0 +1,14 @@ +language = "C" +include_guard = "MODRINTH_SANDBOX_H" +pragma_once = true +cpp_compat = true +usize_is_size_t = true +documentation = true +autogen_warning = "/* Generated by cbindgen. Do not edit manually. */" + +[parse] +parse_deps = false + +[export] +item_types = ["constants", "structs", "opaque", "functions", "typedefs"] +exclude = ["sandbox_init_with_parameters", "sandbox_free_error", "JVM_ARGUMENTS"] diff --git a/packages/modrinth-sandbox/examples/run.c b/packages/modrinth-sandbox/examples/run.c new file mode 100644 index 00000000000..bb0fc04a7cf --- /dev/null +++ b/packages/modrinth-sandbox/examples/run.c @@ -0,0 +1,136 @@ +/* + * Arguments and paths must be UTF-8. Unlike run.rs, output is inherited + * directly instead of being forwarded with a "child:" prefix. + + */ +#include "modrinth_sandbox.h" + +#include +#include +#include + +static ModrinthSandboxString string_view(const char *value) +{ + return (ModrinthSandboxString){value, strlen(value)}; +} + +static void report_error(const char *operation) +{ + const char *message = NULL; + size_t length = 0; + modrinth_sandbox_get_last_error(&message, &length); + fprintf(stderr, "%s: ", operation); + if (length != 0) { + fwrite(message, 1, length, stderr); + } + fputc('\n', stderr); +} + +int main(int argc, char **argv) +{ + bool handled = false; + if (!modrinth_sandbox_helper_run_default(&handled)) { + report_error("Running sandbox helper"); + return EXIT_FAILURE; + } + if (handled) { + return EXIT_SUCCESS; + } + + int result = EXIT_FAILURE; + ModrinthSandboxEnv *env = NULL; + ModrinthSandboxCommand *command = NULL; + ModrinthSandboxChild *child = NULL; + ModrinthSandboxExitStatus status = {0}; + ModrinthSandboxCommandView view = {0}; + ModrinthSandboxString *read_paths = calloc((size_t)argc, sizeof(*read_paths)); + ModrinthSandboxString *write_paths = calloc((size_t)argc, sizeof(*write_paths)); + ModrinthSandboxString *args = calloc((size_t)argc, sizeof(*args)); + if (!read_paths || !write_paths || !args) { + fprintf(stderr, "Allocating command arguments failed.\n"); + goto cleanup; + } + + view.read_only_paths.ptr = read_paths; + view.read_write_paths.ptr = write_paths; + view.args.ptr = args; + int index = 1; + for (; index < argc; ++index) { + const char *option = argv[index]; + if (strcmp(option, "--") == 0) { + ++index; + break; + } + if (option[0] != '-') { + break; + } + if (strcmp(option, "--read") != 0 && strcmp(option, "--write") != 0 && strcmp(option, "--cwd") != 0) { + goto usage; + } + if (++index == argc) { + goto usage; + } + ModrinthSandboxString path = string_view(argv[index]); + if (strcmp(option, "--read") == 0) { + read_paths[view.read_only_paths.len++] = path; + } else if (strcmp(option, "--write") == 0) { + write_paths[view.read_write_paths.len++] = path; + } else { + view.working_directory = (ModrinthSandboxStringOption){path.ptr, path.len}; + } + } + if (index == argc) { + goto usage; + } + view.executable = string_view(argv[index++]); + for (; index < argc; ++index) { + args[view.args.len++] = string_view(argv[index]); + } + view.allow_network = true; + view.die_with_parent = true; + view.child_stdin = MODRINTH_SANDBOX_STDIO_NULL; + view.child_stdout = MODRINTH_SANDBOX_STDIO_INHERIT; + view.child_stderr = MODRINTH_SANDBOX_STDIO_INHERIT; + view.app_container_name = string_view("ModrinthMinecraftSandbox"); + view.app_container_description = string_view("Sandbox for Minecraft instances created by modrinth-sandbox"); + + if (!modrinth_sandbox_create_env(&env)) { + report_error("Creating sandbox environment"); + goto cleanup; + } + if (!modrinth_sandbox_prepare_command(view, &command)) { + report_error("Preparing sandbox command"); + goto cleanup; + } + /* Spawn consumes the command and clears its handle, even on failure. */ + if (!modrinth_sandbox_spawn(env, &command, &child)) { + report_error("Spawning sandboxed process"); + goto cleanup; + } + if (!modrinth_sandbox_child_wait(child, &status)) { + report_error("Waiting for sandboxed process"); + modrinth_sandbox_child_kill(child); + goto cleanup; + } + if (!status.success) { + if (status.has_code) { + fprintf(stderr, "Sandboxed process exited with code %" PRId32 ".\n", status.code); + } else { + fprintf(stderr, "Sandboxed process terminated without an exit code.\n"); + } + goto cleanup; + } + result = EXIT_SUCCESS; + goto cleanup; + +usage: + fprintf(stderr, "Usage: %s [--read PATH] [--write PATH] [--cwd PATH] [--] EXECUTABLE [ARGS...]\n", argv[0]); +cleanup: + modrinth_sandbox_child_free(child); + modrinth_sandbox_command_free(command); + modrinth_sandbox_env_free(env); + free(args); + free(write_paths); + free(read_paths); + return result; +} diff --git a/packages/modrinth-sandbox/examples/run.rs b/packages/modrinth-sandbox/examples/run.rs new file mode 100644 index 00000000000..7341e6eebab --- /dev/null +++ b/packages/modrinth-sandbox/examples/run.rs @@ -0,0 +1,115 @@ +use std::{ + collections::{BTreeMap, BTreeSet}, + ffi::OsString, + io::{BufRead, BufReader, PipeReader, Write}, + path::PathBuf, +}; + +use eyre::{Result, WrapErr, ensure}; +use modrinth_sandbox::{SandboxArg, SandboxCommand, SandboxEnv, SandboxStdio}; +use tracing::info; + +#[derive(Debug, clap::Parser)] +struct Cli { + #[arg(long, value_name = "PATH")] + read: Vec, + #[arg(long, value_name = "PATH")] + write: Vec, + #[arg(long, value_name = "PATH")] + cwd: Option, + executable: PathBuf, + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, +} + +#[tokio::main] +async fn main() -> Result<()> { + if modrinth_sandbox::helper::run_default()? { + return Ok(()); + } + let cli = ::parse(); + tracing_subscriber::fmt().init(); + + let env = SandboxEnv::new() + .await + .wrap_err("creating sandbox environment")?; + info!("using environment {env:?}"); + + let mut child = env + .spawn(SandboxCommand { + executable: cli.executable, + args: cli.args.into_iter().map(SandboxArg::from).collect(), + ensure_dirs_exist: Vec::new(), + read_only_paths: cli.read, + read_write_paths: cli.write, + working_directory: cli.cwd, + passthrough_environment: BTreeSet::new(), + extra_environment: BTreeMap::new(), + allow_network: true, + is_jvm: false, + die_with_parent: true, + stdin: SandboxStdio::Null, + stdout: SandboxStdio::Pipe, + stderr: SandboxStdio::Pipe, + app_container_name: "ModrinthMinecraftSandbox".into(), + app_container_description: + "Sandbox for Minecraft instances created by modrinth-sandbox" + .into(), + on_start: Vec::new(), + on_finish: Vec::new(), + }) + .await + .wrap_err("spawning process in sandbox")?; + + let stdout = forward_pipe( + child.stdout.take().expect("we set `stdout` to `Pipe`"), + || std::io::stdout().lock(), + ); + let stderr = forward_pipe( + child.stderr.take().expect("we set `stderr` to `Pipe`"), + || std::io::stderr().lock(), + ); + + let status = child + .wait() + .await + .wrap_err("waiting for process in sandbox")?; + + stdout + .await + .wrap_err("joining stdout reader task")? + .wrap_err("forwarding sandboxed process stdout")?; + stderr + .await + .wrap_err("joining stderr reader task")? + .wrap_err("forwarding sandboxed process stderr")?; + + ensure!(status.success(), "sandboxed process exited with {status}"); + + Ok(()) +} + +fn forward_pipe( + pipe: PipeReader, + make_output: fn() -> W, +) -> tokio::task::JoinHandle> +where + W: Write + 'static, +{ + tokio::task::spawn_blocking(move || { + let mut output = make_output(); + let mut reader = BufReader::new(pipe); + let mut line = String::new(); + + while reader.read_line(&mut line)? != 0 { + write!(output, "child: {line}")?; + if !line.ends_with('\n') { + writeln!(output)?; + } + output.flush()?; + line.clear(); + } + + Ok(()) + }) +} diff --git a/packages/modrinth-sandbox/justfile b/packages/modrinth-sandbox/justfile new file mode 100644 index 00000000000..838e010b400 --- /dev/null +++ b/packages/modrinth-sandbox/justfile @@ -0,0 +1,23 @@ +set working-directory := "../.." +set positional-arguments + +sandbox := "packages/modrinth-sandbox" +output := "target/modrinth-sandbox-example" +cc := env("CC", "cc") +rpath := if os() == "macos" { "@loader_path" } else { "$ORIGIN" } + +# Show available recipes. +default: + @just --list --justfile {{sandbox}}/justfile + +# Compile the C example against the shared library (Linux/macOS). +compile-c: + cargo build --release -p modrinth-sandbox --target-dir {{output}} + {{cc}} -std=c11 -Wall -Wextra -Werror -pedantic \ + -I {{sandbox}} {{sandbox}}/examples/run.c \ + -L {{output}}/release -lmodrinth_sandbox -Wl,-rpath,'{{rpath}}' \ + -o {{output}}/release/sandbox-run-c + +# Compile and run, forwarding options, the executable, and its arguments. +run-c *args: compile-c + {{output}}/release/sandbox-run-c "$@" diff --git a/packages/modrinth-sandbox/modrinth_sandbox.h b/packages/modrinth-sandbox/modrinth_sandbox.h new file mode 100644 index 00000000000..631322cf6c0 --- /dev/null +++ b/packages/modrinth-sandbox/modrinth_sandbox.h @@ -0,0 +1,419 @@ +#ifndef MODRINTH_SANDBOX_H +#define MODRINTH_SANDBOX_H + +#pragma once + +/* Generated by cbindgen. Do not edit manually. */ + +#include +#include +#include +#include +#include + +#define MODRINTH_SANDBOX_STDIO_NULL 0 + +#define MODRINTH_SANDBOX_STDIO_INHERIT 1 + +#define MODRINTH_SANDBOX_STDIO_PIPE 2 + +typedef struct ModrinthSandboxChild ModrinthSandboxChild; + +typedef struct ModrinthSandboxCommand ModrinthSandboxCommand; + +typedef struct ModrinthSandboxEnv ModrinthSandboxEnv; + +typedef struct ModrinthSandboxPipeReader ModrinthSandboxPipeReader; + +typedef struct ModrinthSandboxPipeWriter ModrinthSandboxPipeWriter; + +/** + * C representation of a sandboxed child's exit status. + * + * If `exited` is false, the other fields have no meaning. If `has_code` is + * false, the process terminated without an exit code, such as from a signal. + */ +typedef struct ModrinthSandboxExitStatus { + bool exited; + bool success; + bool has_code; + int32_t code; +} ModrinthSandboxExitStatus; + +/** + * A borrowed UTF-8 string. `len` counts bytes; no trailing NUL is required. + */ +typedef struct ModrinthSandboxString { + const char *ptr; + size_t len; +} ModrinthSandboxString; + +typedef struct ModrinthSandboxStringSlice { + const struct ModrinthSandboxString *ptr; + size_t len; +} ModrinthSandboxStringSlice; + +/** + * An optional borrowed UTF-8 string. `len` counts bytes; no trailing NUL is + * required. A null pointer with zero length represents an absent string. + */ +typedef struct ModrinthSandboxStringOption { + const char *ptr; + size_t len; +} ModrinthSandboxStringOption; + +typedef struct ModrinthSandboxStringPairsSlice { + const struct ModrinthSandboxString *key_ptr; + size_t key_len; + const struct ModrinthSandboxString *value_ptr; + size_t value_len; +} ModrinthSandboxStringPairsSlice; + +typedef struct ModrinthSandboxCommandView { + struct ModrinthSandboxString executable; + struct ModrinthSandboxStringSlice args; + struct ModrinthSandboxStringSlice ensure_dirs_exist; + struct ModrinthSandboxStringSlice read_only_paths; + struct ModrinthSandboxStringSlice read_write_paths; + struct ModrinthSandboxStringOption working_directory; + struct ModrinthSandboxStringSlice passthrough_environment; + struct ModrinthSandboxStringPairsSlice extra_environment; + bool allow_network; + bool is_jvm; + bool die_with_parent; + uint32_t child_stdin; + uint32_t child_stdout; + uint32_t child_stderr; + struct ModrinthSandboxString app_container_name; + struct ModrinthSandboxString app_container_description; +} ModrinthSandboxCommandView; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Returns the child's platform process ID, or zero when no stable process ID + * is available for this backend or the child has already exited. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`]. `out_id` must be properly + * aligned and valid for writing one `u32`. Neither pointer may be concurrently + * accessed for the duration of this call. + */ +bool modrinth_sandbox_child_id(const struct ModrinthSandboxChild *child, uint32_t *out_id); + +/** + * Attempts to collect the child's exit status without blocking. + * + * On success, `out_status.exited` is false when the child is still running. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. `out_status` must be properly aligned and + * valid for writing one [`ModrinthSandboxExitStatus`]. + */ +bool modrinth_sandbox_child_try_wait(struct ModrinthSandboxChild *child, + struct ModrinthSandboxExitStatus *out_status); + +/** + * Blocks until the child exits and writes its exit status. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. `out_status` must be properly aligned and + * valid for writing one [`ModrinthSandboxExitStatus`]. + */ +bool modrinth_sandbox_child_wait(struct ModrinthSandboxChild *child, + struct ModrinthSandboxExitStatus *out_status); + +/** + * Forces the child process to exit. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. + */ +bool modrinth_sandbox_child_kill(struct ModrinthSandboxChild *child); + +/** + * Takes ownership of the child's standard-input pipe. + * + * On success, `*out_stdin` is null if stdin was not configured as a pipe or + * was already taken. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. `out_stdin` must be properly aligned and + * valid for writing a `*mut ModrinthSandboxPipeWriter`, and must not contain an + * owned handle. + */ +bool modrinth_sandbox_child_take_stdin(struct ModrinthSandboxChild *child, + struct ModrinthSandboxPipeWriter **out_stdin); + +/** + * Takes ownership of the child's standard-output pipe. + * + * On success, `*out_stdout` is null if stdout was not configured as a pipe or + * was already taken. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. `out_stdout` must be properly aligned and + * valid for writing a `*mut ModrinthSandboxPipeReader`, and must not contain an + * owned handle. + */ +bool modrinth_sandbox_child_take_stdout(struct ModrinthSandboxChild *child, + struct ModrinthSandboxPipeReader **out_stdout); + +/** + * Takes ownership of the child's standard-error pipe. + * + * On success, `*out_stderr` is null if stderr was not configured as a pipe or + * was already taken. + * + * # Safety + * + * `child` must point to a live child returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible + * for the duration of this call. `out_stderr` must be properly aligned and + * valid for writing a `*mut ModrinthSandboxPipeReader`, and must not contain an + * owned handle. + */ +bool modrinth_sandbox_child_take_stderr(struct ModrinthSandboxChild *child, + struct ModrinthSandboxPipeReader **out_stderr); + +/** + * Reads up to `buffer_len` bytes from a child output pipe. + * + * A successful read of zero bytes indicates end-of-file. A null `buffer` is + * permitted only when `buffer_len` is zero. + * + * # Safety + * + * `reader` must point to a live reader returned by a child pipe accessor and + * be exclusively accessible for the duration of this call. If `buffer_len` is + * nonzero, `buffer` must be valid for writes of `buffer_len` bytes and may not + * alias `reader` or `out_read`. `out_read` must be properly aligned and valid + * for writing one `size_t`. + */ +bool modrinth_sandbox_pipe_reader_read(struct ModrinthSandboxPipeReader *reader, + uint8_t *buffer, + size_t buffer_len, + size_t *out_read); + +/** + * Writes up to `buffer_len` bytes to a child input pipe. + * + * A null `buffer` is permitted only when `buffer_len` is zero. + * + * # Safety + * + * `writer` must point to a live writer returned by + * [`modrinth_sandbox_child_take_stdin`] and be exclusively accessible for the + * duration of this call. If `buffer_len` is nonzero, `buffer` must be valid for + * reads of `buffer_len` bytes and may not alias `writer` or `out_written`. + * `out_written` must be properly aligned and valid for writing one `size_t`. + */ +bool modrinth_sandbox_pipe_writer_write(struct ModrinthSandboxPipeWriter *writer, + const uint8_t *buffer, + size_t buffer_len, + size_t *out_written); + +/** + * Flushes a child input pipe. + * + * # Safety + * + * `writer` must point to a live writer returned by + * [`modrinth_sandbox_child_take_stdin`] and be exclusively accessible for the + * duration of this call. + */ +bool modrinth_sandbox_pipe_writer_flush(struct ModrinthSandboxPipeWriter *writer); + +/** + * Frees a child output pipe reader. + * + * # Safety + * + * `reader` must be null or a pointer returned by a child pipe accessor that + * has not already been freed. + */ +void modrinth_sandbox_pipe_reader_free(struct ModrinthSandboxPipeReader *reader); + +/** + * Frees a child input pipe writer, closing the child's standard input. + * + * # Safety + * + * `writer` must be null or a pointer returned by + * [`modrinth_sandbox_child_take_stdin`] that has not already been freed. + */ +void modrinth_sandbox_pipe_writer_free(struct ModrinthSandboxPipeWriter *writer); + +/** + * Frees a child returned by [`crate::ffi::modrinth_sandbox_spawn`]. + * + * # Safety + * + * `child` must be null or a pointer returned by + * [`crate::ffi::env::modrinth_sandbox_spawn`] that has not already been freed. + */ +void modrinth_sandbox_child_free(struct ModrinthSandboxChild *child); + +/** + * Copies a borrowed C command view into a Rust-owned sandbox command. + * + * Stdio values use `0` for null, `1` for inherit, and `2` for pipe. + * + * # Safety + * + * Every pointer reachable through `command_view` must uphold its string or + * slice type's safety contract for the duration of this call. If `out_command` + * is non-null, it must be properly aligned and valid for writing a + * `*mut ModrinthSandboxCommand`, and must not contain an owned handle. + */ +bool modrinth_sandbox_prepare_command(struct ModrinthSandboxCommandView command_view, + struct ModrinthSandboxCommand **out_command); + +/** + * Frees a command returned by [`modrinth_sandbox_prepare_command`]. + * + * # Safety + * + * `command` must be null or a pointer returned by + * [`modrinth_sandbox_prepare_command`] that has not already been freed. + */ +void modrinth_sandbox_command_free(struct ModrinthSandboxCommand *command); + +/** + * Creates a sandbox environment and returns an opaque, Rust-owned handle. + * + * # Safety + * + * If `out_env` is non-null, it must be properly aligned and valid for writing + * a `*mut ModrinthSandboxEnv`. It must not currently contain an owned handle. + */ +bool modrinth_sandbox_create_env(struct ModrinthSandboxEnv **out_env); + +/** + * Creates an environment that launches processes without sandboxing. + * + * This applies no filesystem or network isolation. Sandbox-specific options, + * including `die_with_parent`, are not enforced. Use [`modrinth_sandbox_spawn`] + * to launch processes and [`modrinth_sandbox_env_free`] to release the handle. + * + * # Safety + * + * If `out_env` is non-null, it must be properly aligned and valid for writing + * a `*mut ModrinthSandboxEnv`. It must not currently contain an owned handle. + */ +bool modrinth_sandbox_create_noop_env(struct ModrinthSandboxEnv **out_env); + +/** + * Frees a sandbox or no-op environment. + * + * Children spawned through the environment remain usable after the environment + * is freed because they retain the runtime needed for asynchronous operations. + * + * # Safety + * + * `env` must be null or a pointer returned by + * [`modrinth_sandbox_create_env`] or [`modrinth_sandbox_create_noop_env`] + * that has not already been freed. + */ +void modrinth_sandbox_env_free(struct ModrinthSandboxEnv *env); + +/** + * Spawns a sandboxed child and consumes `*command`. + * + * Once a non-null command handle has been validated, `*command` is set to + * null and the command is consumed whether spawning succeeds or fails. + * + * # Safety + * + * `env` must point to a live environment returned by + * [`modrinth_sandbox_create_env`] or [`modrinth_sandbox_create_noop_env`] + * and must not be freed for the duration of + * this call. `command` must point to valid, writable pointer storage, and a + * non-null `*command` must be a uniquely owned handle returned by + * [`crate::ffi::modrinth_sandbox_prepare_command`]. If `out_child` is + * non-null, it must be properly aligned and valid for writing a + * `*mut ModrinthSandboxChild`, and must not contain an owned handle. + */ +bool modrinth_sandbox_spawn(const struct ModrinthSandboxEnv *env, + struct ModrinthSandboxCommand **command, + struct ModrinthSandboxChild **out_child); + +/** + * Handles a sandbox helper invocation for the default helper command. + * + * Call this near the beginning of the executable, before parsing application + * arguments or creating a sandbox environment. On success, `out_handled` is + * true when a helper invocation was handled; the caller should then exit + * successfully without continuing application initialization. Otherwise, + * normal application startup should continue. + * + * Returns false on failure and sets the last FFI error. A non-null + * `out_handled` is initialized to false before running the helper. + * + * # Safety + * + * If `out_handled` is non-null, it must be properly aligned and valid for + * writing one `bool`, and must not be concurrently accessed during this call. + */ +bool modrinth_sandbox_helper_run_default(bool *out_handled); + +/** + * Handles a sandbox helper invocation using the provided UTF-8 arguments. + * + * The argument list must not include the executable name or + * `--modrinth-sandbox-helper` argument. On success, `out_handled` is true + * when a helper invocation was handled; the caller should then exit + * successfully without continuing application initialization. + * + * Returns false on failure and sets the last FFI error. A non-null + * `out_handled` is initialized to false before converting arguments or + * running the helper. A null argument pointer with zero length is allowed. + * + * # Safety + * + * Every pointer reachable through `args` must uphold + * [`ModrinthSandboxStringSlice::try_to_owned`]'s safety contract for the + * duration of this call. If `out_handled` is non-null, it must be properly + * aligned and valid for writing one `bool`, and must not be concurrently + * accessed during this call or overlap the argument storage. + */ +bool modrinth_sandbox_helper_run_with_args(struct ModrinthSandboxStringSlice args, + bool *out_handled); + +/** + * Returns the most recent FFI error message. + * + * The returned message is not null-terminated and remains valid until the + * next FFI operation that updates the last error. + * + * # Safety + * + * `out_message` and `out_message_len` must be valid, properly aligned, + * writable pointers. + */ +void modrinth_sandbox_get_last_error(const char **out_message, size_t *out_message_len); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif /* MODRINTH_SANDBOX_H */ diff --git a/packages/modrinth-sandbox/src/api/desktop/launch_file.rs b/packages/modrinth-sandbox/src/api/desktop/launch_file.rs new file mode 100644 index 00000000000..34e079bf87c --- /dev/null +++ b/packages/modrinth-sandbox/src/api/desktop/launch_file.rs @@ -0,0 +1,84 @@ +use std::path::PathBuf; + +pub async fn launch_file_safe(path: PathBuf) { + let Some(extension) = path.extension() else { + return; + }; + + // Ensure extension matches files we allow (images, video, audio) + match extension.to_ascii_lowercase().as_encoded_bytes() { + // Image formats + b"jpg" | b"jpeg" | b"png" | b"gif" | b"webp" | b"cr2" | b"tif" + | b"tiff" | b"bmp" => {} + // Video formats + b"mp4" | b"m4v" | b"mkv" | b"webm" | b"mov" | b"avi" | b"mpg" => {} + // Audio formats + b"mid" | b"mp3" | b"m4a" | b"ogg" | b"flac" | b"wav" | b"amr" + | b"aac" | b"aiff" => {} + // Refuse to open other formats + _ => { + return; + } + } + + // On Linux, file opening is typically determined by the mime type rather than extension + // Therefore, for security reasons, we need to copy the file to a safe place before we check the mime type + // of the file. This is to prevent a TOCTOU exploit where the program could replace the file + // with a malicious executable after we check the mime. + #[cfg(target_os = "linux")] + let path = { + let mut new_path = + std::env::temp_dir().join(uuid::Uuid::now_v7().to_string()); + new_path.set_extension(extension); + if tokio::fs::copy(&path, &new_path).await.is_err() { + return; + } + new_path + }; + + // Ensure mime type is image, video or audio + let Ok(Some(file_type)) = infer::get_from_path(&path) else { + return; + }; + let matcher_type = file_type.matcher_type(); + if !matches!( + matcher_type, + infer::MatcherType::Image + | infer::MatcherType::Video + | infer::MatcherType::Audio + ) { + return; + } + + launch_file(path).await +} + +async fn launch_file(path: PathBuf) { + #[cfg(target_os = "macos")] + { + let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace(); + if let Some(path) = objc2_foundation::NSURL::from_file_path(&path) { + workspace.openURL(&path); + return; + } + } + + #[cfg(target_os = "linux")] + { + let Ok(file) = std::fs::File::open(&path) else { + return; + }; + let result = ashpd::desktop::open_uri::OpenFileRequest::default() + .send_file(&std::os::fd::AsFd::as_fd(&file)) + .await; + if let Err(err) = result { + tracing::error!("SandboxAPI failed to send OpenFile: {err}"); + } else { + return; + } + } + + if let Err(err) = open::that_detached(path) { + tracing::error!("SandboxAPI failed to open file: {err}"); + } +} diff --git a/packages/modrinth-sandbox/src/api/desktop/mod.rs b/packages/modrinth-sandbox/src/api/desktop/mod.rs new file mode 100644 index 00000000000..b6c882f3923 --- /dev/null +++ b/packages/modrinth-sandbox/src/api/desktop/mod.rs @@ -0,0 +1,11 @@ +mod open_url; +pub use open_url::*; + +mod open_dir; +pub use open_dir::*; + +mod launch_file; +pub use launch_file::*; + +mod open_file_dialog; +pub use open_file_dialog::*; diff --git a/packages/modrinth-sandbox/src/api/desktop/open_dir.rs b/packages/modrinth-sandbox/src/api/desktop/open_dir.rs new file mode 100644 index 00000000000..3e0a4f9e139 --- /dev/null +++ b/packages/modrinth-sandbox/src/api/desktop/open_dir.rs @@ -0,0 +1,61 @@ +use std::path::PathBuf; + +pub async fn open_dir(path: PathBuf) { + // We have to be very careful here, using something like open::that(path) will work, + // however it opens us up to a TOCTOU exploit where the folder's path is replaced by an executable file. + // Therefore, we use platform specific operations that are designed to specifically open a folder + #[cfg(target_os = "macos")] + { + let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace(); + let path = + objc2_foundation::NSString::from_str(&path.to_string_lossy()); + workspace.selectFile_inFileViewerRootedAtPath(None, &path); + } + #[cfg(target_os = "windows")] + { + // ShellExecuteExW requires COM to be initialized, which the spawn thread has done + let result = crate::backend::run_on_spawn_thread(move || { + use std::os::windows::ffi::OsStrExt; + use windows::Win32::UI::Shell::SHELLEXECUTEINFOW; + + let folder = path + .as_os_str() + .encode_wide() + .chain([0]) + .collect::>(); + + let mut sei: SHELLEXECUTEINFOW = SHELLEXECUTEINFOW::default(); + sei.cbSize = std::mem::size_of::() as _; + sei.fMask = windows::Win32::UI::Shell::SEE_MASK_DEFAULT; + sei.lpVerb = windows::core::w!("explore"); + sei.lpFile = windows::core::PCWSTR(folder.as_ptr()); + sei.nShow = + windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL.0; + + unsafe { windows::Win32::UI::Shell::ShellExecuteExW(&mut sei) } + }) + .await; + + match result { + Ok(Ok(())) => {} + Ok(Err(err)) => tracing::error!( + "SandboxAPI failed to ShellExecuteExW with explore verb: {err}" + ), + Err(err) => tracing::error!( + "SandboxAPI failed to run ShellExecuteExW on spawn thread: {err}" + ), + } + } + #[cfg(target_os = "linux")] + { + let Ok(directory) = std::fs::File::open(path) else { + return; + }; + let result = ashpd::desktop::open_uri::OpenDirectoryRequest::default() + .send(&std::os::fd::AsFd::as_fd(&directory)) + .await; + if let Err(err) = result { + tracing::error!("SandboxAPI failed to send OpenDirectory: {err}"); + } + } +} diff --git a/packages/modrinth-sandbox/src/api/desktop/open_file_dialog.rs b/packages/modrinth-sandbox/src/api/desktop/open_file_dialog.rs new file mode 100644 index 00000000000..0ffbe23fc85 --- /dev/null +++ b/packages/modrinth-sandbox/src/api/desktop/open_file_dialog.rs @@ -0,0 +1,599 @@ +use std::path::PathBuf; + +#[cfg(any(target_os = "linux", target_os = "windows"))] +use eyre::Context; +use eyre::eyre; + +pub struct OpenFileDialogFilter { + #[cfg_attr(target_os = "macos", allow(unused))] + pub user_friendly_name: String, + pub extension: String, +} + +#[derive(Default)] +pub struct OpenFileDialogArgs { + /// Title of the dialog window + pub title: Option, + /// Label for the accept button + pub accept_label: Option, + /// Whether the dialog should be a save dialog instead of an open dialog + pub save: bool, + /// Whether multiple files can be selected + pub multiple: bool, + /// Whether folders should be selected instead of files + pub directory: bool, + /// List of filters to apply + pub filters: Vec, + /// Default path (may be folder or file) + pub default_location: Option, +} + +pub async fn open_file_dialog( + args: OpenFileDialogArgs, +) -> eyre::Result> { + #[cfg(target_os = "macos")] + { + open_file_dialog_macos(args).await + } + #[cfg(target_os = "linux")] + { + open_file_dialog_linux(args).await + } + #[cfg(target_os = "windows")] + { + open_file_dialog_windows(args).await + } + #[cfg(not(any( + target_os = "macos", + target_os = "linux", + target_os = "windows" + )))] + { + drop(args); + Err(eyre::eyre!("unsupported platform for file dialog")) + } +} + +fn split_default_location( + default_location: &std::path::Path, +) -> (Option, Option) { + let bytes = default_location.as_os_str().as_encoded_bytes(); + let has_trailing_separator = + bytes.ends_with(b"/") || (cfg!(windows) && bytes.ends_with(b"\\")); + if has_trailing_separator || default_location.is_dir() { + (Some(default_location.to_path_buf()), None) + } else { + ( + default_location + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .map(std::path::Path::to_path_buf), + default_location + .file_name() + .map(std::ffi::OsStr::to_os_string), + ) + } +} + +#[cfg(target_os = "macos")] +pub async fn open_file_dialog_macos( + args: OpenFileDialogArgs, +) -> eyre::Result> { + let (result_sender, result_receiver) = + tokio::sync::oneshot::channel::>>(); + + dispatch2::run_on_main(move |mtm| { + if !objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning() { + _ = result_sender.send(Err(eyre!( + "cannot open file dialog in headless environment" + ))); + return; + } + + let panel = if args.save { + objc2_app_kit::NSSavePanel::new(mtm) + } else { + let Ok(panel) = objc2_app_kit::NSOpenPanel::new(mtm) + .downcast::() + else { + _ = result_sender.send(Err(eyre!( + "couldn't cast NSOpenPanel to NSSavePanel" + ))); + return; + }; + panel + }; + + if let Some(title) = &args.title { + let title = objc2_foundation::NSString::from_str(title); + panel.setTitle(Some(&title)); + } + if let Some(accept_label) = &args.accept_label { + let title = objc2_foundation::NSString::from_str(accept_label); + panel.setPrompt(Some(&title)); + } + + if let Some(open_panel) = + panel.downcast_ref::() + && !args.save + { + open_panel.setAllowsMultipleSelection(args.multiple); + open_panel.setCanChooseDirectories(args.directory); + open_panel.setCanChooseFiles(!args.directory); + } + + // For consistent behaviour with other platforms + panel.setAllowsOtherFileTypes(true); + + // Filters + if !args.filters.is_empty() { + let filters = args.filters.iter().filter_map(|filter| { + let extension = objc2_foundation::NSString::from_str(&filter.extension); + objc2_uniform_type_identifiers::UTType::typeWithFilenameExtension(&extension) + }).collect::>(); + let filters = + filters.iter().map(|uttype| &**uttype).collect::>(); + if !filters.is_empty() { + let array = objc2_foundation::NSArray::from_slice(&filters); + panel.setAllowedContentTypes(&array); + } + if args.save { + panel.setShowsContentTypes(filters.len() >= 2); + } + } + + // Default location + if let Some(default_location) = &args.default_location { + let (folder, file_name) = split_default_location(default_location); + if let Some(folder) = folder { + let folder = objc2_foundation::NSString::from_str( + &folder.to_string_lossy(), + ); + let url = objc2_foundation::NSURL::fileURLWithPath_isDirectory( + &folder, true, + ); + panel.setDirectoryURL(Some(&url)); + } + if let Some(file_name) = file_name { + let name_field = objc2_foundation::NSString::from_str( + &file_name.to_string_lossy(), + ); + panel.setNameFieldStringValue(&name_field); + } + } + + let retained_panel = panel.clone(); + let sender = std::cell::Cell::new(Some(result_sender)); + let closure = move |response: objc2_app_kit::NSModalResponse| { + let Some(result_sender) = sender.take() else { + return; + }; + if response != objc2_app_kit::NSModalResponseOK { + _ = result_sender.send(Ok(Vec::new())); + return; + } + + let urls = if args.multiple + && let Some(open_panel) = + retained_panel.downcast_ref::() + { + open_panel.URLs().iter().collect::>() + } else if let Some(url) = retained_panel.URL() { + vec![url] + } else { + vec![] + }; + + let mut paths = Vec::new(); + for url in urls { + if !url.isFileURL() { + _ = result_sender.send(Err(eyre!( + "panel returned a url which was not a file:// url" + ))); + return; + } + let Some(path) = url.to_file_path() else { + _ = result_sender.send(Err(eyre!( + "failed to convert url into file path" + ))); + return; + }; + paths.push(path); + } + + _ = result_sender.send(Ok(paths)); + }; + + let block = block2::RcBlock::new(closure); + panel.beginWithCompletionHandler(&block); + }); + + result_receiver.await + .map_err(|_| eyre!("channel closed unexpectedly while waiting for file dialog result")) + .flatten() +} + +#[cfg(target_os = "linux")] +pub async fn open_file_dialog_linux( + args: OpenFileDialogArgs, +) -> eyre::Result> { + use ashpd::desktop::{ResponseError, file_chooser::SelectedFiles}; + + let filters = linux_file_filters(&args.filters); + let (folder, file_name) = match &args.default_location { + Some(default_location) => split_default_location(default_location), + None => (None, None), + }; + + let request = if args.save { + let file_name = file_name.as_ref().map(|name| name.to_string_lossy()); + SelectedFiles::save_file() + .title(args.title.as_deref()) + .accept_label(args.accept_label.as_deref()) + .modal(true) + .current_name(file_name.as_deref()) + .current_folder::<&std::path::Path>(folder.as_deref()) + .wrap_err("setting default folder")? + .filters(filters) + .send() + .await + } else { + SelectedFiles::open_file() + .title(args.title.as_deref()) + .accept_label(args.accept_label.as_deref()) + .modal(true) + .multiple(args.multiple) + .directory(args.directory) + .current_folder::<&std::path::Path>(folder.as_deref()) + .wrap_err("setting default folder")? + .filters(if args.directory { Vec::new() } else { filters }) + .send() + .await + } + .wrap_err("sending FileChooser portal request")?; + + let selected = match request.response() { + Ok(selected) => selected, + Err(ashpd::Error::Response(ResponseError::Cancelled)) => { + return Ok(Vec::new()); + } + Err(err) => { + return Err( + eyre!(err).wrap_err("FileChooser portal request failed") + ); + } + }; + + let mut paths = Vec::with_capacity(selected.uris().len()); + for uri in selected.uris() { + if uri.scheme() != "file" { + return Err(eyre!( + "portal returned a url which was not a file:// url" + )); + } + let path = uri + .to_file_path() + .map_err(|_| eyre!("failed to convert url into file path"))?; + paths.push(path); + } + + if !args.multiple { + paths.truncate(1); + } + + Ok(paths) +} + +#[cfg(target_os = "linux")] +fn linux_file_filters( + filters: &[OpenFileDialogFilter], +) -> Vec { + use ashpd::desktop::file_chooser::FileFilter; + + let mut grouped: Vec<(&str, Vec)> = Vec::new(); + for filter in filters { + let extension = filter.extension.trim().trim_start_matches('.'); + if extension.is_empty() { + continue; + } + let glob = case_insensitive_extension_glob(extension); + let label = filter.user_friendly_name.as_str(); + match grouped.iter_mut().find(|(existing, _)| *existing == label) { + Some((_, globs)) => { + if !globs.contains(&glob) { + globs.push(glob); + } + } + None => grouped.push((label, vec![glob])), + } + } + + if grouped.is_empty() { + return Vec::new(); + } + + let mut portal_filters = grouped + .into_iter() + .map(|(label, globs)| { + globs + .iter() + .fold(FileFilter::new(label), |filter, glob| filter.glob(glob)) + }) + .collect::>(); + portal_filters.push(FileFilter::new("All files").glob("*")); + portal_filters +} + +/// Portal globs are case-sensitive, so `png` becomes `*.[pP][nN][gG]`. +#[cfg(target_os = "linux")] +fn case_insensitive_extension_glob(extension: &str) -> String { + let mut glob = String::from("*."); + for c in extension.chars() { + let lower = c.to_ascii_lowercase(); + let upper = c.to_ascii_uppercase(); + if lower != upper { + glob.push('['); + glob.push(lower); + glob.push(upper); + glob.push(']'); + } else if matches!(c, '*' | '?' | '[' | ']') { + glob.push('['); + glob.push(c); + glob.push(']'); + } else { + glob.push(c); + } + } + glob +} + +#[cfg(target_os = "windows")] +pub async fn open_file_dialog_windows( + args: OpenFileDialogArgs, +) -> eyre::Result> { + let (result_sender, result_receiver) = + tokio::sync::oneshot::channel::>>(); + + std::thread::Builder::new() + .name("Modrinth Sandbox File Dialog".to_string()) + .spawn(move || { + _ = result_sender.send(show_windows_file_dialog(&args)); + }) + .wrap_err("spawning file dialog thread")?; + + result_receiver.await.map_err(|_| { + eyre!( + "channel closed unexpectedly while waiting for file dialog result" + ) + })? +} + +#[cfg(target_os = "windows")] +fn show_windows_file_dialog( + args: &OpenFileDialogArgs, +) -> eyre::Result> { + use windows::{ + Win32::{ + Foundation::ERROR_CANCELLED, + System::Com::{ + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, + COINIT_DISABLE_OLE1DDE, CoCreateInstance, CoInitializeEx, + CoUninitialize, + }, + UI::Shell::{ + Common::COMDLG_FILTERSPEC, FOS_ALLOWMULTISELECT, + FOS_FILEMUSTEXIST, FOS_FORCEFILESYSTEM, FOS_NOCHANGEDIR, + FOS_OVERWRITEPROMPT, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS, + FileOpenDialog, FileSaveDialog, IFileDialog, IFileOpenDialog, + IFileSaveDialog, IShellItem, SHCreateItemFromParsingName, + }, + }, + core::{HRESULT, Interface, PCWSTR}, + }; + + unsafe { + CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) + } + .ok() + .map_err(com_error("initializing COM"))?; + + scopeguard::defer! { + unsafe { CoUninitialize() }; + } + + let (dialog, open_dialog): (IFileDialog, Option) = + if args.save { + let dialog: IFileSaveDialog = unsafe { + CoCreateInstance(&FileSaveDialog, None, CLSCTX_INPROC_SERVER) + } + .map_err(com_error("creating FileSaveDialog"))?; + ( + dialog.cast().map_err(com_error("casting FileSaveDialog"))?, + None, + ) + } else { + let dialog: IFileOpenDialog = unsafe { + CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER) + } + .map_err(com_error("creating FileOpenDialog"))?; + ( + dialog.cast().map_err(com_error("casting FileOpenDialog"))?, + Some(dialog), + ) + }; + + let mut options = unsafe { dialog.GetOptions() } + .map_err(com_error("getting dialog options"))? + | FOS_FORCEFILESYSTEM + | FOS_NOCHANGEDIR + | FOS_PATHMUSTEXIST; + if args.save { + options |= FOS_OVERWRITEPROMPT; + } else { + options |= FOS_FILEMUSTEXIST; + if args.multiple { + options |= FOS_ALLOWMULTISELECT; + } + if args.directory { + options |= FOS_PICKFOLDERS; + } + } + unsafe { dialog.SetOptions(options) } + .map_err(com_error("setting dialog options"))?; + + if let Some(title) = &args.title { + let title = to_wide(title); + unsafe { dialog.SetTitle(PCWSTR(title.as_ptr())) } + .map_err(com_error("setting dialog title"))?; + } + if let Some(accept_label) = &args.accept_label { + let accept_label = to_wide(accept_label); + unsafe { dialog.SetOkButtonLabel(PCWSTR(accept_label.as_ptr())) } + .map_err(com_error("setting dialog accept label"))?; + } + + // The wide strings must outlive the call to Show + let filters = if args.directory { + Vec::new() + } else { + windows_file_filters(&args.filters) + }; + if !filters.is_empty() { + let filter_specs = filters + .iter() + .map(|(name, spec)| COMDLG_FILTERSPEC { + pszName: PCWSTR(name.as_ptr()), + pszSpec: PCWSTR(spec.as_ptr()), + }) + .collect::>(); + unsafe { dialog.SetFileTypes(&filter_specs) } + .map_err(com_error("setting dialog file types"))?; + } + if args.save + && let Some(extension) = args + .filters + .iter() + .map(|filter| filter.extension.trim().trim_start_matches('.')) + .find(|extension| is_valid_windows_extension(extension)) + { + let extension = to_wide(extension); + unsafe { dialog.SetDefaultExtension(PCWSTR(extension.as_ptr())) } + .map_err(com_error("setting dialog default extension"))?; + } + + if let Some(default_location) = &args.default_location { + let (folder, file_name) = split_default_location(default_location); + if let Some(folder) = folder { + let folder = to_wide(folder.as_os_str()); + let folder_item: windows::core::Result = unsafe { + SHCreateItemFromParsingName(PCWSTR(folder.as_ptr()), None) + }; + if let Ok(folder_item) = folder_item { + _ = unsafe { dialog.SetFolder(&folder_item) }; + } + } + if let Some(file_name) = file_name { + let file_name = to_wide(file_name.as_os_str()); + unsafe { dialog.SetFileName(PCWSTR(file_name.as_ptr())) } + .map_err(com_error("setting dialog file name"))?; + } + } + + if let Err(err) = unsafe { dialog.Show(None) } { + if err.code() == HRESULT::from_win32(ERROR_CANCELLED.0) { + return Ok(Vec::new()); + } + return Err(com_error("showing file dialog")(err)); + } + + let mut paths = Vec::new(); + if let Some(open_dialog) = &open_dialog + && args.multiple + { + let items = unsafe { open_dialog.GetResults() } + .map_err(com_error("getting dialog results"))?; + let count = unsafe { items.GetCount() } + .map_err(com_error("getting result count"))?; + for index in 0..count { + let item = unsafe { items.GetItemAt(index) } + .map_err(com_error("getting dialog result"))?; + paths.push(windows_shell_item_path(&item)?); + } + } else { + let item = unsafe { dialog.GetResult() } + .map_err(com_error("getting dialog result"))?; + paths.push(windows_shell_item_path(&item)?); + } + + Ok(paths) +} + +#[cfg(target_os = "windows")] +fn com_error( + context: &'static str, +) -> impl FnOnce(windows::core::Error) -> eyre::Report { + move |err| eyre!("{err}").wrap_err(context) +} + +#[cfg(target_os = "windows")] +fn is_valid_windows_extension(extension: &str) -> bool { + !extension.is_empty() && !extension.contains(['*', '?', ';', '\0']) +} + +#[cfg(target_os = "windows")] +fn windows_shell_item_path( + item: &windows::Win32::UI::Shell::IShellItem, +) -> eyre::Result { + use std::os::windows::ffi::OsStringExt; + use windows::Win32::{ + System::Com::CoTaskMemFree, UI::Shell::SIGDN_FILESYSPATH, + }; + + let name = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH) } + .map_err(com_error("getting file system path of dialog result"))?; + let path = std::ffi::OsString::from_wide(unsafe { name.as_wide() }); + unsafe { CoTaskMemFree(Some(name.0 as *const _)) }; + Ok(PathBuf::from(path)) +} + +/// Groups extensions by label into `(name, "*.a;*.b")` pairs as +/// null-terminated wide strings, followed by an "All files" entry. +#[cfg(target_os = "windows")] +fn windows_file_filters( + filters: &[OpenFileDialogFilter], +) -> Vec<(Vec, Vec)> { + let mut grouped: Vec<(&str, Vec)> = Vec::new(); + for filter in filters { + let extension = filter.extension.trim().trim_start_matches('.'); + if !is_valid_windows_extension(&extension) { + continue; + } + let pattern = format!("*.{extension}"); + let label = filter.user_friendly_name.as_str(); + match grouped.iter_mut().find(|(existing, _)| *existing == label) { + Some((_, patterns)) => { + if !patterns.contains(&pattern) { + patterns.push(pattern); + } + } + None => grouped.push((label, vec![pattern])), + } + } + + if grouped.is_empty() { + return Vec::new(); + } + + let mut specs = grouped + .into_iter() + .map(|(label, patterns)| (to_wide(label), to_wide(patterns.join(";")))) + .collect::>(); + specs.push((to_wide("All files"), to_wide("*.*"))); + specs +} + +#[cfg(target_os = "windows")] +fn to_wide(value: impl AsRef) -> Vec { + use std::os::windows::ffi::OsStrExt; + value.as_ref().encode_wide().chain([0]).collect() +} diff --git a/packages/modrinth-sandbox/src/api/desktop/open_url.rs b/packages/modrinth-sandbox/src/api/desktop/open_url.rs new file mode 100644 index 00000000000..1d849f14229 --- /dev/null +++ b/packages/modrinth-sandbox/src/api/desktop/open_url.rs @@ -0,0 +1,31 @@ +use url::Url; + +pub async fn open_url(url: Url) { + assert!(matches!(url.scheme(), "http" | "https" | "steam")); + + #[cfg(target_os = "linux")] + { + let result = ashpd::desktop::open_uri::OpenFileRequest::default() + .send_uri(&url) + .await; + if let Err(err) = result { + tracing::error!("SandboxAPI failed to send OpenURI: {err}"); + } else { + return; + } + } + + #[cfg(target_os = "macos")] + { + let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace(); + let nsstring = objc2_foundation::NSString::from_str(url.as_str()); + if let Some(path) = objc2_foundation::NSURL::URLWithString(&nsstring) { + workspace.openURL(&path); + return; + } + } + + if let Err(err) = open::that_detached(url.as_str()) { + tracing::error!("SandboxAPI failed to open url: {err}"); + } +} diff --git a/packages/modrinth-sandbox/src/api/mod.rs b/packages/modrinth-sandbox/src/api/mod.rs new file mode 100644 index 00000000000..114b5af1358 --- /dev/null +++ b/packages/modrinth-sandbox/src/api/mod.rs @@ -0,0 +1,4 @@ +pub(super) mod desktop; +mod service; + +pub use service::*; diff --git a/packages/modrinth-sandbox/src/api/service.rs b/packages/modrinth-sandbox/src/api/service.rs new file mode 100644 index 00000000000..c9b5ff0100d --- /dev/null +++ b/packages/modrinth-sandbox/src/api/service.rs @@ -0,0 +1,1310 @@ +use std::{ + collections::HashMap, + ffi::OsStr, + io::ErrorKind, + net::{IpAddr, Ipv4Addr, SocketAddr}, + path::{Path, PathBuf}, + str::FromStr, + sync::{ + Arc, + atomic::{AtomicBool, AtomicU32, Ordering}, + }, + time::Duration, +}; + +use futures::StreamExt; +use parking_lot::Mutex; +use rand::{RngExt, distr::Alphanumeric}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; +use serde::{Deserialize, Serialize}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, + time::Instant, +}; +use tracing::{error, info, warn}; +use url::Url; +use uuid::Uuid; + +use crate::{ + ExposedPath, SandboxHandle, + api::desktop::{OpenFileDialogArgs, OpenFileDialogFilter}, +}; + +const DEFAULT_SESSION_JOIN: &str = + "https://sessionserver.mojang.com/session/minecraft/join"; + +#[derive(Default)] +pub struct DiscoveredEndpoints { + custom_session_join: Option, + replace_authorization_header: HashMap, Url>, +} + +// todo(boris): idk how this will look in ffi, probably going to be a bit of a pain so feel free +// to adjust as much as you want +pub trait SandboxApiLauncher: Send + Sync { + /// Retrieve the session token for a given account + fn login(&self, uuid: Uuid, token: tokio::sync::oneshot::Sender>); +} + +/// Contains info required for the game to communicate with the sandbox api +/// Dropping this handle will result in the child being unregistered +/// Dropping all handles will result in the localhost server being stopped until the next call to start +#[derive(Clone)] +pub struct SandboxApiChild(Arc); + +pub struct SandboxApiChildInner { + dummy_access_token: Arc, + secret: Arc, + port: u16, + notify: Arc, + child_count: Arc, + inner: Arc>, +} + +impl std::fmt::Debug for SandboxApiChild { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SandboxApiChild").finish() + } +} + +impl SandboxApiChild { + pub fn get_dummy_access_token(&self) -> Arc { + self.0.dummy_access_token.clone() + } + + pub fn get_secret(&self) -> Arc { + self.0.secret.clone() + } + + pub fn get_port(&self) -> u16 { + self.0.port + } + + pub fn set_sandbox_handle(&self, sandbox_handle: crate::SandboxHandle) { + if let Some(child) = self + .0 + .inner + .lock() + .children_by_secret + .get_mut(&self.0.secret) + { + child.handle = Some(sandbox_handle); + } + } +} + +impl Drop for SandboxApiChildInner { + fn drop(&mut self) { + { + let mut inner = self.inner.lock(); + inner.children_by_secret.remove(&self.secret); + inner.dummy_access_tokens.remove(&self.dummy_access_token); + } + + self.child_count.fetch_sub(1, Ordering::SeqCst); + self.notify.notify_one(); + } +} + +#[derive(Clone)] +pub struct SandboxApiService { + port: u16, + notify: Arc, + child_count: Arc, + http_client: reqwest::Client, + launcher_api: Arc, + inner: Arc>, +} + +#[derive(Default, Clone, Debug)] +struct ServiceChildState { + handle: Option, + disallow_request_access: Arc, +} + +#[derive(Default)] +struct SandboxApiServiceInner { + reuse_buffer: Option>, + discovered_endpoints: DiscoveredEndpoints, + children_by_secret: HashMap, ServiceChildState>, + dummy_access_tokens: HashMap, Uuid>, + running_server: bool, +} + +impl SandboxApiService { + pub fn new(port: u16, launcher_api: Arc) -> Self { + Self::new_with_client(port, launcher_api, reqwest::Client::default()) + } + + pub fn new_with_client( + port: u16, + launcher_api: Arc, + http_client: reqwest::Client, + ) -> Self { + Self { + port, + notify: Arc::default(), + child_count: Arc::default(), + http_client, + launcher_api, + inner: Arc::default(), + } + } + + pub fn start(self, account_uuid: Uuid) -> SandboxApiChild { + // Create dummy access token + let mut dummy_access_token = String::from("SandboxAccessToken_"); + for c in rand::rng() + .sample_iter(Alphanumeric) + .take(32) + .map(char::from) + { + dummy_access_token.push(c); + } + let dummy_access_token: Arc = dummy_access_token.into(); + + // Create secret + let secret = rand::rng() + .sample_iter(Alphanumeric) + .take(32) + .map(char::from) + .collect::(); + let secret: Arc = secret.into(); + + // Run localhost server if it isn't already running + self.child_count.fetch_add(1, Ordering::SeqCst); + tokio::task::spawn(self.clone().run_localhost_server()); + + { + let mut inner = self.inner.lock(); + inner + .children_by_secret + .insert(secret.clone(), ServiceChildState::default()); + inner + .dummy_access_tokens + .insert(dummy_access_token.clone(), account_uuid); + } + + SandboxApiChild(Arc::new(SandboxApiChildInner { + dummy_access_token, + secret, + port: self.port, + notify: self.notify.clone(), + child_count: self.child_count.clone(), + inner: self.inner, + })) + } + + async fn run_localhost_server(self) { + let inner = self.inner.clone(); + { + let mut inner = inner.lock(); + if inner.running_server { + return; + } + inner.running_server = true; + } + + if let Err(err) = self.run_localhost_server_inner().await { + error!("error running sandboxapi service: {err}"); + + let mut inner = inner.lock(); + inner.running_server = false; + } + } + + async fn run_localhost_server_inner(self) -> std::io::Result<()> { + let socket_addr = + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), self.port); + info!("starting sandboxapi service on {}", socket_addr); + let listener = tokio::net::TcpListener::bind(socket_addr).await?; + + loop { + let notify = self.notify.clone().notified_owned(); + let notified = tokio::select! { + res = listener.accept() => { + match res { + Ok((stream, _)) => { + tokio::task::spawn(self.clone().handle_incoming(stream)); + } + Err(err) => { + // Errors are usually temporary, so keep the server running + warn!("sandboxapi service failed to accept connection: {err}"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + false + }, + _ = notify => true, + }; + + if notified { + let mut inner = self.inner.lock(); + if self.child_count.load(Ordering::SeqCst) == 0 { + // Close the listener before clearing the flag so a server started + // after this point doesn't fail to bind because the port is still in use + drop(listener); + inner.running_server = false; + return Ok(()); + } + } + } + } + + async fn handle_incoming(self, stream: TcpStream) -> std::io::Result<()> { + let mut buf = self + .inner + .lock() + .reuse_buffer + .take() + .unwrap_or_else(|| vec![0_u8; 1024]); + let res = self + .clone() + .handle_incoming_with_buffer(stream, &mut buf) + .await; + match &mut self.inner.lock().reuse_buffer { + Some(old) => { + if old.len() < buf.len() { + *old = buf; + } + } + v => *v = Some(buf), + } + res + } + + async fn handle_incoming_with_buffer( + self, + mut stream: TcpStream, + buf: &mut Vec, + ) -> std::io::Result<()> { + let deadline = Instant::now() + Duration::from_secs(5); + + let mut read = 0; + 'read_loop: loop { + if read == buf.len() { + if buf.len() >= 1048576 { + return Err(ErrorKind::OutOfMemory.into()); + } + buf.resize(buf.len() * 2, 0); + } + + let n = tokio::select! { + n = stream.read(&mut buf[read..]) => n?, + _ = tokio::time::sleep_until(deadline) => { + return Err(ErrorKind::TimedOut.into()); + } + }; + read += n; + + if read == 0 { + return Ok(()); + } + + let mut headers = [httparse::EMPTY_HEADER; 32]; + let mut request = httparse::Request::new(&mut headers); + let Ok(parsed) = request.parse(&buf[..read]) else { + return Err(ErrorKind::InvalidData.into()); + }; + + let httparse::Status::Complete(body_offset) = parsed else { + if n == 0 { + return Err(ErrorKind::InvalidData.into()); + } else { + continue; + } + }; + + // Make sure we're read enough content according to Content-Length + if n > 0 { + for header in request.headers.iter() { + if !header.name.eq_ignore_ascii_case("Content-Length") { + continue; + } + let Ok(content_length_str) = str::from_utf8(header.value) + else { + break; + }; + let Ok(content_length) = + content_length_str.parse::() + else { + break; + }; + let received_length = read - body_offset; + if received_length < content_length { + continue 'read_loop; + } + break; + } + } + + self.handle_request(request, &buf[body_offset..read], stream) + .await; + return Ok(()); + } + } + + async fn handle_request( + self, + request: httparse::Request<'_, '_>, + body: &[u8], + mut stream: TcpStream, + ) { + let Some(path) = request.path else { + RequestStatus::NotFound.write(stream).await; + return; + }; + let (path, params) = path.split_once('?').unwrap_or((path, "")); + let params_or_none = if params.is_empty() { + None + } else { + Some(params) + }; + + // We check for this authorization header in order to prevent other applications + // on the system from interacting with our API. This isn't strictly necessary, but + // is good practice + let child_state = if path.starts_with("/sandboxapi/") { + match self.clone().check_authorization_secret(&request) { + Ok(child_state) => Some(child_state), + Err(error_status) => { + error_status.write(stream).await; + return; + } + } + } else { + None + }; + + if let Some(realms_path) = path.strip_prefix("/sandboxrealms/") { + if let Ok(mut url) = Url::parse(&format!( + "https://pc.realms.minecraft.net/{realms_path}" + )) { + url.set_query(params_or_none); + self.proxy_with_replacement( + &request, + body.to_vec(), + url, + stream, + ) + .await; + } + return; + } + + match path { + "/sandboxapi/open-uri" => { + if request.method != Some("POST") { + RequestStatus::MethodNotAllowed.write(stream).await; + return; + } + let status = self.handle_request_open_uri(params).await; + status.write(stream).await; + } + "/sandboxapi/request-access" => { + if request.method != Some("GET") { + RequestStatus::MethodNotAllowed.write(stream).await; + return; + } + match self + .handle_request_request_access(params, child_state) + .await + { + Ok(path) => { + write_text_response(stream, &path.to_string_lossy()) + .await + } + Err(error_status) => error_status.write(stream).await, + }; + } + "/sandboxapi/open-file-dialog" => { + if request.method != Some("GET") { + RequestStatus::MethodNotAllowed.write(stream).await; + return; + } + match self + .handle_request_open_file_dialog(params, child_state) + .await + { + Ok(paths) => { + let mut response = String::new(); + for path in paths { + if !response.is_empty() { + response.push('\n'); + } + response.push_str(&path.to_string_lossy()); + } + write_text_response(stream, &response).await + } + Err(error_status) => error_status.write(stream).await, + }; + } + "/sandboxauth/session/session/minecraft/join" => { + // Need special handling for the join request since it puts the + // access token in the body instead of in the Authorization header + // like all other requests + let Ok(mut join_request) = + serde_json::from_slice::(body) + else { + RequestStatus::BadRequest.write(stream).await; + return; + }; + + let real_uuid = self + .inner + .lock() + .dummy_access_tokens + .get(&join_request.access_token) + .copied(); + if let Some(real_uuid) = real_uuid { + if real_uuid != join_request.selected_profile { + RequestStatus::Unauthorized.write(stream).await; + return; + } + + let (sender, receiver) = tokio::sync::oneshot::channel(); + self.launcher_api.login(real_uuid, sender); + let Ok(real_token) = receiver.await else { + RequestStatus::Unauthorized.write(stream).await; + return; + }; + join_request.access_token = real_token; + } + + let Ok(new_body) = serde_json::to_vec(&join_request) else { + RequestStatus::InternalServerError.write(stream).await; + return; + }; + + let to = self + .inner + .lock() + .discovered_endpoints + .custom_session_join + .clone() + .or_else(|| Url::parse(DEFAULT_SESSION_JOIN).ok()); + + let Some(mut to) = to else { + RequestStatus::InternalServerError.write(stream).await; + return; + }; + + to.set_query(params_or_none); + self.proxy_with_replacement(&request, new_body, to, stream) + .await; + } + "/sandboxauth/discovery" => { + let Ok(discovery) = self.http_client.get("https://discovery.minecraftservices.com/minecraft/client").send().await else { + RequestStatus::InternalServerError.write(stream).await; + return; + }; + + let mut discovery_result = match discovery + .json::() + .await + { + Ok(discovery_result) => discovery_result, + Err(err) => { + error!("failed to get discovery: {:?}", err); + RequestStatus::InternalServerError.write(stream).await; + return; + } + }; + + discovery_result.environment = Some("sandboxauth".into()); + for (service_name, endpoints) in + &mut discovery_result.discovery.services + { + for (endpoint_name, endpoint) in &mut endpoints.endpoints { + let Some(old_uri) = &endpoint.uri else { + continue; + }; + if old_uri.contains('{') && old_uri.contains('}') { + // Skip URIs with path replacements for now, currently these are only + // used for profile/skin lookups which are unauthenticated anyways + continue; + } + let Ok(old_url) = Url::parse(old_uri) else { + continue; + }; + if !old_url.has_host() { + continue; + } + + // Custom behaviour for session join since it puts the access token in the + // body instead of the Authorization header + if &**service_name == "session" + && &**endpoint_name == "join" + { + // Update custom_session_join + self.inner + .lock() + .discovered_endpoints + .custom_session_join = + if &**old_uri == DEFAULT_SESSION_JOIN { + None + } else { + Some(old_url) + }; + + // Override join with our custom endpoint + *endpoint = MinecraftEndpoint { + uri: Some(format!("http://127.0.0.1:{}/sandboxauth/session/session/minecraft/join", self.port).into()), + valid_uris: None, + other_values: HashMap::default() + }; + } else { + // Create new endpoint string + let new_endpoint_path: Arc = format!("/sandboxauth/discovered-service/{service_name}/{endpoint_name}").into(); + let new_endpoint: Arc = format!( + "http://127.0.0.1:{}{}", + self.port, new_endpoint_path + ) + .into(); + + self.inner + .lock() + .discovered_endpoints + .replace_authorization_header + .insert(new_endpoint_path.clone(), old_url); + + *endpoint = MinecraftEndpoint { + uri: Some(new_endpoint), + valid_uris: None, + other_values: HashMap::default(), + }; + } + } + } + + if write_json_response(&mut stream, &discovery_result) + .await + .is_err() + { + RequestStatus::InternalServerError.write(stream).await; + } + } + _ => { + if let Some(session_path) = + path.strip_prefix("/sandboxauth/session/") + { + // Proxy minecraft.api.session.host requests + let Ok(mut to) = Url::parse(&format!( + "https://sessionserver.mojang.com/{session_path}" + )) else { + RequestStatus::BadRequest.write(stream).await; + return; + }; + to.set_query(params_or_none); + self.proxy_with_replacement( + &request, + body.to_vec(), + to, + stream, + ) + .await; + return; + } else if let Some(service_path) = + path.strip_prefix("/sandboxauth/services/") + { + // Proxy minecraft.api.services.host requests + let Ok(mut to) = Url::parse(&format!( + "https://api.minecraftservices.com/{service_path}" + )) else { + RequestStatus::BadRequest.write(stream).await; + return; + }; + to.set_query(params_or_none); + self.proxy_with_replacement( + &request, + body.to_vec(), + to, + stream, + ) + .await; + return; + } else if path.starts_with("/sandboxauth/discovered-service") { + // Arbitrary service discovered through discovery.minecraftservices.com (26.3+) + let to = self + .inner + .lock() + .discovered_endpoints + .replace_authorization_header + .get(path) + .cloned(); + if let Some(mut to) = to { + to.set_query(params_or_none); + self.proxy_with_replacement( + &request, + body.to_vec(), + to, + stream, + ) + .await; + return; + } + } + RequestStatus::NotFound.write(stream).await; + } + } + } + + async fn proxy_with_replacement( + self, + request: &httparse::Request<'_, '_>, + body: Vec, + to: Url, + mut stream: TcpStream, + ) { + let headers = match self.create_headers_with_replacement(request).await + { + Ok(headers) => headers, + Err(status) => { + status.write(stream).await; + return; + } + }; + + let method = request + .method + .and_then(|method| { + reqwest::Method::from_bytes(method.as_bytes()).ok() + }) + .unwrap_or(reqwest::Method::GET); + + let response = self + .http_client + .request(method.clone(), to.clone()) + .headers(headers) + .body(body) + .send() + .await; + + let response = match response { + Ok(response) => response, + Err(err) => { + tracing::error!( + "Sandbox service was unable to send request to upstream {to}: {err}" + ); + RequestStatus::InternalServerError.write(stream).await; + return; + } + }; + + let status = response.status(); + + let mut builder = Vec::from("HTTP/1.1 "); + builder.extend_from_slice(response.status().as_str().as_bytes()); + if let Some(canonical_reason) = response.status().canonical_reason() { + builder.push(b' '); + builder.extend_from_slice(canonical_reason.as_bytes()); + } + builder.extend_from_slice(b"\r\n"); + + let no_body = status.is_informational() + || status == reqwest::StatusCode::NO_CONTENT + || status == reqwest::StatusCode::NOT_MODIFIED; + let override_content_length = + !no_body && method != reqwest::Method::HEAD; + + let connection_listed_headers: Vec = response + .headers() + .get_all(reqwest::header::CONNECTION) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .map(|name| name.trim().to_ascii_lowercase()) + .filter(|name| !name.is_empty()) + .collect(); + + for (name, value) in response.headers() { + let lowercase_name = name.as_str().trim().to_ascii_lowercase(); + if is_hop_by_hop_header(lowercase_name.as_str()) + || connection_listed_headers + .iter() + .any(|listed| listed == lowercase_name.as_str()) + { + continue; + } + if override_content_length + && name.as_str().eq_ignore_ascii_case("content-length") + { + continue; + } + builder.extend_from_slice(name.as_str().as_bytes()); + builder.extend_from_slice(b": "); + builder.extend_from_slice(value.as_bytes()); + builder.extend_from_slice(b"\r\n"); + } + + let content = match response.bytes().await { + Ok(content) => content, + Err(err) => { + tracing::error!( + "Sandbox service was unable to read upstream response from {to}: {err}" + ); + RequestStatus::InternalServerError.write(stream).await; + return; + } + }; + + if override_content_length { + builder.extend_from_slice( + format!("Content-Length: {}\r\n", content.len()).as_bytes(), + ); + } + builder.extend_from_slice(b"Connection: close\r\n\r\n"); + builder.extend_from_slice(&content); + + _ = stream.write_all(&builder).await; + _ = stream.shutdown().await; + } + + async fn create_headers_with_replacement( + &self, + request: &httparse::Request<'_, '_>, + ) -> Result { + let mut headers = HeaderMap::new(); + + for old_header in request.headers.iter() { + if is_hop_by_hop_header(&old_header.name.to_ascii_lowercase()) { + continue; + } + if old_header.name.eq_ignore_ascii_case("Host") + || old_header.name.eq_ignore_ascii_case("Content-Length") + || old_header.name.eq_ignore_ascii_case("Connection") + { + // Reqwest will automatically set these headers + continue; + } + // Access token authorization header + if old_header.name.eq_ignore_ascii_case("Authorization") + && let Some(bearer) = old_header.value.strip_prefix(b"Bearer") + && let Ok(bearer) = str::from_utf8(bearer) + { + let access_token = bearer.trim_ascii_start(); + let real_uuid = self + .inner + .lock() + .dummy_access_tokens + .get(access_token) + .copied(); + + if let Some(real_uuid) = real_uuid { + let (sender, receiver) = tokio::sync::oneshot::channel(); + self.launcher_api.login(real_uuid, sender); + let Ok(real_token) = receiver.await else { + return Err(RequestStatus::Unauthorized); + }; + + if let Ok(header_value) = + HeaderValue::from_str(&format!("Bearer {real_token}")) + { + headers.insert("Authorization", header_value); + } + continue; + } + } + // Realms cookie header + if old_header.name.eq_ignore_ascii_case("Cookie") + && let Ok(cookie) = str::from_utf8(old_header.value) + { + let mut new_cookie = String::new(); + let mut first = true; + for element in cookie.split(';') { + if first { + first = false; + } else { + new_cookie.push(';'); + } + + // Auth cookie is `sid=token:access:uuid` + if let Some((key, value)) = element.split_once('=') + && key == "sid" + && let Some(right) = value.strip_prefix("token:") + && let Some((token, uuid_str)) = right.split_once(':') + && let Ok(uuid) = Uuid::from_str(uuid_str) + { + let real_uuid = self + .inner + .lock() + .dummy_access_tokens + .get(token) + .copied(); + if let Some(real_uuid) = real_uuid + && real_uuid == uuid + { + let (sender, receiver) = + tokio::sync::oneshot::channel(); + self.launcher_api.login(real_uuid, sender); + let Ok(real_token) = receiver.await else { + return Err(RequestStatus::Unauthorized); + }; + + new_cookie.push_str("sid=token:"); + new_cookie.push_str(&real_token); + new_cookie.push(':'); + new_cookie.push_str(uuid_str); + continue; + } + } + new_cookie.push_str(element); + } + + if let Ok(header_value) = HeaderValue::from_str(&new_cookie) { + headers.insert("Cookie", header_value); + } + continue; + } + if let Ok(header_name) = HeaderName::from_str(old_header.name) + && let Ok(header_value) = + HeaderValue::from_bytes(old_header.value) + { + headers.append(header_name, header_value); + } + } + + Ok(headers) + } + + fn check_authorization_secret( + self, + request: &httparse::Request<'_, '_>, + ) -> Result { + for header in request.headers.iter() { + if header.name == "Authorization" { + let Some(token) = + header.value.trim_ascii_start().strip_prefix(b"Bearer") + else { + return Err(RequestStatus::Forbidden); + }; + let Ok(token) = str::from_utf8(token) else { + return Err(RequestStatus::BadRequest); + }; + if let Some(child) = self + .inner + .lock() + .children_by_secret + .get(token.trim_ascii_start()) + { + return Ok(child.clone()); + } else { + return Err(RequestStatus::Forbidden); + } + } + } + Err(RequestStatus::Unauthorized) + } + + async fn handle_request_open_uri(self, params: &str) -> RequestStatus { + let mut uri = None; + for (key, value) in + params.split("&").filter_map(|arg| arg.split_once('=')) + { + if key == "uri" { + uri = Some(value); + } else { + warn!("unrecognized option for open-uri: {key}"); + } + } + + let Some(encoded) = uri else { + return RequestStatus::BadRequest; + }; + + let encoded = encoded.replace("+", "%20"); + let Ok(decoded) = urlencoding::decode(&encoded) else { + return RequestStatus::BadRequest; + }; + + let Ok(url) = url::Url::parse(&decoded) else { + return RequestStatus::BadRequest; + }; + + if matches!(url.scheme(), "http" | "https" | "steam") { + if url.scheme() == "steam" { + let allowed = match url.host_str() { + Some("forceinputappid") => true, + Some("open") | Some("close") => url.path() == "/keyboard", + _ => false, + }; + if !allowed { + return RequestStatus::Forbidden; + } + } + + tokio::task::spawn(super::desktop::open_url(url)); + RequestStatus::OK + } else if url.scheme() == "file" && url.host_str().is_none() { + let Ok(path) = url.to_file_path() else { + return RequestStatus::BadRequest; + }; + if let Ok(path) = path.canonicalize() { + if path.is_dir() { + tokio::task::spawn(super::desktop::open_dir(path)); + } else { + tokio::task::spawn(super::desktop::launch_file_safe(path)); + } + }; + // If the path doesn't exist, do nothing. This prevents enumeration of existing files + RequestStatus::OK + } else { + RequestStatus::Forbidden + } + } + + async fn handle_request_request_access( + self, + params: &str, + child_state: Option, + ) -> Result { + let Some(child_state) = child_state else { + return Err(RequestStatus::InternalServerError); + }; + + if child_state.disallow_request_access.load(Ordering::SeqCst) { + return Err(RequestStatus::Unauthorized); + } + + let Some(sandbox_handle) = child_state.handle else { + return Err(RequestStatus::InternalServerError); + }; + + let mut path = None; + for (key, value) in + params.split("&").filter_map(|arg| arg.split_once('=')) + { + if key == "path" { + path = Some(value); + } else { + warn!("unrecognized option for request-access: {key}"); + } + } + + let Some(encoded) = path else { + return Err(RequestStatus::BadRequest); + }; + + let encoded = encoded.replace("+", "%20"); + let Ok(decoded) = urlencoding::decode(&encoded) else { + return Err(RequestStatus::BadRequest); + }; + + let path = Path::new(&*decoded); + info!( + path = %path.display(), + "got request to access dropped file" + ); + if !path.exists() { + // This API should only be used for DnD file paths + // Therefore, it should only ever be called for files that actually exist + // If we're receiving a request for a file that doesn't exist, it's possible + // that a malicious program is attempting to enumerate files on the computer + // To prevent this, we return Unauthorized and block the process from further requests + warn!( + path = %path.display(), + "rejecting dropped-file access because the path doesn't exist" + ); + child_state + .disallow_request_access + .store(true, Ordering::SeqCst); + return Err(RequestStatus::Unauthorized); + } + + // We only allow certain zip file formats (resourcepacks, mods, shaders, etc.) + let Ok(archive) = + async_zip::tokio::read::fs::ZipFileReader::new(path).await + else { + warn!( + path = %path.display(), + "rejecting dropped-file access because the file is not a readable ZIP archive" + ); + return Err(RequestStatus::InternalServerError); + }; + + let mut allow = false; + let is_zip = path.extension() == Some(OsStr::new("zip")); + for entry in archive.file().entries() { + let Ok(filename) = entry.filename().as_str() else { + continue; + }; + let filename = filename.strip_prefix('/').unwrap_or(filename); + let is_content_file = match filename { + "pack.mcmeta" => true, // Resourcepack/datapack + "mcmod.info" => true, // Old forge mod + "fabric.mod.json" => true, // Fabric mod + "META-INF/mods.toml" => true, // New forge mod + "META-INF/neoforge.mods.toml" => true, // Neoforge mod + "META-INF/jarjar/metadata.json" => true, // Forge jarjar + "modrinth.index.json" => true, // Mrpack + "metaData.json" => path.extension() == Some(OsStr::new("mcpr")), // Replaymod replay + _ => { + let is_shaderpack = + filename.starts_with("shaders/") && is_zip; + let is_flashback_replay = + filename.ends_with(".flashback") && is_zip; + is_shaderpack || is_flashback_replay + } + }; + if is_content_file { + allow = true; + break; + } + } + + if !allow { + warn!( + path = %path.display(), + "rejecting dropped-file access because this content type is not allowed" + ); + return Err(RequestStatus::Unauthorized); + } + + info!( + path = %path.display(), + "dropped file passed content validation" + ); + match sandbox_handle.expose_path(path, false) { + Ok(ExposedPath::Direct) => { + info!( + path = %path.display(), + "granted sandbox direct access to dropped file" + ); + Ok(path.to_path_buf()) + } + Ok(ExposedPath::Proxied(proxied)) => { + info!( + path = %path.display(), + exposed_path = %proxied.display(), + "granted sandbox proxied access to dropped file" + ); + Ok(proxied) + } + Err(err) => { + error!("unable to expose path to sandbox: {err:#}"); + Err(RequestStatus::InternalServerError) + } + } + } + + async fn handle_request_open_file_dialog( + self, + params: &str, + child_state: Option, + ) -> Result, RequestStatus> { + let Some(child_state) = child_state else { + return Err(RequestStatus::InternalServerError); + }; + + let Some(sandbox_handle) = child_state.handle else { + return Err(RequestStatus::InternalServerError); + }; + + let mut open_args = OpenFileDialogArgs::default(); + + for (key, value) in + params.split("&").filter_map(|arg| arg.split_once('=')) + { + let value = value.replace("+", "%20"); + let Ok(value) = urlencoding::decode(&value) else { + return Err(RequestStatus::BadRequest); + }; + + match key { + "title" => { + open_args.title = Some(value.to_string()); + } + "accept_label" => { + open_args.accept_label = Some(value.to_string()); + } + "save" => { + open_args.save = value + .parse::() + .map_err(|_| RequestStatus::BadRequest)?; + } + "multiple" => { + open_args.multiple = value + .parse::() + .map_err(|_| RequestStatus::BadRequest)?; + } + "directory" => { + open_args.directory = value + .parse::() + .map_err(|_| RequestStatus::BadRequest)?; + } + "filter" => { + let (extension, friendly) = + value.split_once(',').unwrap_or((&*value, &*value)); + open_args.filters.push(OpenFileDialogFilter { + user_friendly_name: friendly.to_string(), + extension: extension.to_string(), + }); + } + "default_location" => { + open_args.default_location = Some(PathBuf::from(&*value)); + } + _ => { + warn!("unrecognized option for open-file-dialog: {key}"); + } + } + } + + let mut paths = match super::desktop::open_file_dialog(open_args).await + { + Ok(paths) => paths, + Err(err) => { + error!("failed to open file dialog: {err:#}"); + return Err(RequestStatus::InternalServerError); + } + }; + + for path in &mut paths { + if !sandbox_handle.is_path_writeable(path) { + match sandbox_handle.expose_path(path, true) { + Ok(ExposedPath::Direct) => {} + Ok(ExposedPath::Proxied(proxied)) => { + *path = proxied; + } + Err(err) => { + error!("unable to expose path to sandbox: {err:#}"); + return Err(RequestStatus::InternalServerError); + } + } + } + } + + Ok(paths) + } +} + +#[derive(Debug, Serialize, Deserialize)] +struct MinecraftDiscoveryResult { + #[serde(skip_serializing_if = "skip_if_none")] + environment: Option>, + discovery: MinecraftDiscovery, + + #[serde(flatten)] + other_values: HashMap, serde_json::Value>, +} + +#[derive(Debug, Serialize, Deserialize)] +struct MinecraftDiscovery { + #[serde(skip_serializing_if = "skip_if_none")] + product: Option>, + #[serde(flatten)] + services: HashMap, MinecraftEndpoints>, +} + +#[derive(Debug, Serialize, Deserialize)] +struct MinecraftEndpoints { + endpoints: HashMap, MinecraftEndpoint>, + + #[serde(flatten)] + other_values: HashMap, serde_json::Value>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct MinecraftEndpoint { + #[serde(skip_serializing_if = "skip_if_none")] + uri: Option>, + #[serde(skip_serializing_if = "skip_if_none")] + valid_uris: Option]>>, + + #[serde(flatten)] + other_values: HashMap, serde_json::Value>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct MinecraftJoinRequest { + access_token: Arc, + selected_profile: Uuid, + server_id: Arc, +} + +pub fn skip_if_none(value: &Option) -> bool { + value.is_none() +} + +#[derive(Clone, Copy)] +enum RequestStatus { + OK, + BadRequest, + Unauthorized, + Forbidden, + NotFound, + MethodNotAllowed, + InternalServerError, +} + +pub async fn write_json_response( + stream: &mut TcpStream, + t: &T, +) -> serde_json::Result<()> { + let raw = serde_json::to_string(t)?; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + raw.len(), + raw + ); + _ = stream.write_all(response.as_bytes()).await; + _ = stream.shutdown().await; + Ok(()) +} + +fn is_hop_by_hop_header(lowercase_name: &str) -> bool { + const HOP_BY_HOP_HEADERS: &[&str] = &[ + "connection", + "keep-alive", + "proxy-connection", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade", + ]; + HOP_BY_HOP_HEADERS.contains(&lowercase_name) +} + +pub async fn write_text_response(mut stream: TcpStream, t: &str) { + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + t.len(), + t + ); + _ = stream.write_all(response.as_bytes()).await; + _ = stream.shutdown().await; +} + +impl RequestStatus { + pub async fn write(self, mut stream: TcpStream) { + let response = match self { + RequestStatus::OK => { + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::BadRequest => { + "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::Unauthorized => { + "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::Forbidden => { + "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::NotFound => { + "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::MethodNotAllowed => { + "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + RequestStatus::InternalServerError => { + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + } + }; + _ = stream.write_all(response.as_bytes()).await; + _ = stream.shutdown().await; + } +} diff --git a/packages/modrinth-sandbox/src/backend/bubblewrap.rs b/packages/modrinth-sandbox/src/backend/bubblewrap.rs new file mode 100644 index 00000000000..e6545fc898c --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/bubblewrap.rs @@ -0,0 +1,1356 @@ +use std::{ + borrow::Cow, + collections::BTreeMap, + ffi::{CStr, CString, OsStr, OsString}, + os::fd::{AsRawFd, OwnedFd}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use async_trait::async_trait; +use derive_more::Debug; +use eyre::{OptionExt, Result, WrapErr, bail, eyre}; +use libseccomp::{ + ScmpAction, ScmpArgCompare, ScmpCompareOp, ScmpFilterContext, ScmpSyscall, +}; +use parking_lot::Mutex; +use uuid::Uuid; + +use crate::{ + ExposedPath, SandboxStdio, + backend::{ + Backend, SandboxChild, SandboxChildOp, SandboxCommand, SandboxEnv, + SandboxHandleOp, + linux::{WritableMemoryFile, find_command}, + pathset::{PathSet, ReadWritePathSet}, + unix::UnixChild, + }, + file_sharing::FileSharing, + util::SandboxArg, +}; + +#[derive(Debug)] +pub struct Bubblewrap; + +#[async_trait] +impl Backend for Bubblewrap { + async fn init( + _make_helper: crate::helper::MakeHelper, + ) -> Result> { + init().await.map(|env| Box::new(env) as Box) + } +} + +async fn init() -> Result { + let bwrap = find_command("bwrap") + .await + .wrap_err("searching for `bwrap` executable")?; + let xdg_dbus_proxy = find_command("xdg-dbus-proxy") + .await + .wrap_err("searching for `xdg-dbus-proxy` executable")?; + let dev_null = + super::unix::open_dev_null().wrap_err("opening /dev/null")?; + Ok(BubblewrapEnv { + bwrap, + xdg_dbus_proxy, + dev_null, + }) +} + +#[derive(Debug, Clone)] +#[debug("BubblewrapEnv")] +pub struct BubblewrapEnv { + bwrap: PathBuf, + xdg_dbus_proxy: PathBuf, + dev_null: libc::c_int, +} + +#[async_trait] +impl SandboxEnv for BubblewrapEnv { + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result { + super::linux::ensure_valid_command(&command).await?; + let env = self.clone(); + crate::backend::run_on_spawn_thread(move || spawn(&env, command)) + .await? + } +} + +const DEV_BINDS: &[&str] = &[ + // Graphics + "/dev/dri", + "/dev/udmabuf", + // Graphics (mali) + "/dev/mali", + "/dev/mali0", + "/dev/umplock", + // Graphics (adreno) + "/dev/kgsl-3d0", + "/dev/ion", + // System info + "/dev/disk/by-uuid", + "/dev/dm", + "/dev/loop", + "/dev/mapper", + "/dev/ram", + // NT Sync Primitives (Wine) + "/dev/ntsync", + // Raw ALSA + "/dev/snd", + // AMD Compute + "/dev/kfd", +]; + +const SYSTEM_FILES_RO: &[&str] = &[ + "/bin", + "/sbin", + "/usr", + "/lib", + "/lib32", + "/lib64", + "/etc/alternatives", + "/etc/resolv.conf", + "/run/systemd/resolve", + "/usr/share/ca-certificates", + "/etc/ca-certificates", + "/etc/ssl", + "/etc/pki", + "/etc/pkcs11", + "/etc/hosts", + "/etc/ld.so.cache", + "/etc/ld.so.conf.d", + "/etc/localtime", + "/etc/os-release", + "/etc/machine-id", + "/etc/timezone", + "/etc/fonts", + "/sys/block", + "/sys/bus", + "/sys/class", + "/sys/dev", + "/sys/devices", + "/sys/firmware/devicetree/base/model", + "/proc/apm", + "/proc/acpi", + "/etc/glvnd", + "/etc/vulkan", + "/etc/alsa", + "/etc/egl", + "/etc/static/egl", + "/nix/store", + // NVIDIA kernel module state (needed for driver init in user ns) + "/sys/module/nvidia", + "/sys/module/nvidia_drm", + "/sys/module/nvidia_modeset", + "/sys/module/nvidia_uvm", +]; + +const FAKE_FLATPAK_APP_NAME: &'static str = + "com.modrinth.sandbox.ModrinthSandbox"; + +#[derive(Default)] +struct BubblewrapCommandBuilder { + arguments: Vec, + read: PathSet, + write: PathSet, + symlinks: BTreeMap, +} + +enum BindBehaviour { + Device, + FollowRead, + FollowWrite, + NoFollowRead, + NoFollowWrite, +} + +impl BubblewrapCommandBuilder { + pub fn push(&mut self, arg: impl Into) { + self.arguments.push(arg.into()); + } + + pub fn create_dir( + &mut self, + path: impl Into, + permissions: u32, + ) { + self.push("--perms"); + self.push(format!("{permissions:o}")); + self.push("--dir"); + self.push(path); + } + + /// Bind every intermediate symlink returning the final path + fn bind_links(&mut self, path: &Path) -> std::io::Result { + const MAX_HOPS: u8 = 40; + + fn push_components( + path: &Path, + components: &mut Vec, + ) -> std::io::Result<()> { + for component in path.components().rev() { + match component { + std::path::Component::Prefix(_) => { + return Err(std::io::ErrorKind::InvalidFilename.into()); + } + std::path::Component::RootDir + | std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + components.push(OsStr::new("..").to_os_string()); + } + std::path::Component::Normal(os_str) => { + components.push(os_str.to_os_string()); + } + } + } + Ok(()) + } + + let mut components = Vec::new(); + push_components(path, &mut components)?; + + let mut resolved = PathBuf::from("/"); + let mut hops = 0; + + while let Some(component) = components.pop() { + if component == ".." { + resolved.pop(); + continue; + } + resolved.push(component); + + if let Ok(link) = std::fs::read_link(&resolved) { + hops += 1; + if hops > MAX_HOPS { + return Err(std::io::ErrorKind::TooManyLinks.into()); + } + if !self.read.contains(resolved.clone()) + && !self.write.contains(resolved.clone()) + { + self.symlinks.insert(resolved.clone(), link.clone()); + } + if link.is_absolute() { + resolved = PathBuf::from("/"); + } else { + resolved.pop(); + } + push_components(&link, &mut components)?; + } + } + + Ok(resolved) + } + + pub fn bind_if_exists( + &mut self, + bind_behaviour: BindBehaviour, + path: &Path, + ) { + let Ok(path) = std::path::absolute(path) else { + return; + }; + match bind_behaviour { + BindBehaviour::FollowRead => { + if let Ok(target) = self.bind_links(&path) { + if target.parent().is_none() { + return; + } + self.read.insert(target); + } + } + BindBehaviour::FollowWrite => { + if let Ok(target) = self.bind_links(&path) { + if target.parent().is_none() { + return; + } + self.write.insert(target); + } + } + BindBehaviour::Device => { + self.push("--dev-bind-try"); + self.push(path.clone()); + self.push(path); + } + BindBehaviour::NoFollowRead => { + let Some(parent) = path.parent() else { + return; + }; + let Some(filename) = path.file_name() else { + return; + }; + let Ok(real_parent) = self.bind_links(parent) else { + return; + }; + let path = real_parent.join(filename); + if let Ok(src) = std::fs::read_link(&path) { + self.symlinks.insert(path, src); + } else { + self.read.insert(path); + } + } + BindBehaviour::NoFollowWrite => { + let Some(parent) = path.parent() else { + return; + }; + let Some(filename) = path.file_name() else { + return; + }; + let Ok(real_parent) = self.bind_links(parent) else { + return; + }; + let path = real_parent.join(filename); + if let Ok(src) = std::fs::read_link(&path) { + self.symlinks.insert(path, src); + } else { + self.write.insert(path); + } + } + } + } + + pub fn finish(mut self) -> (Vec, ReadWritePathSet) { + let mut read_write_path_set = ReadWritePathSet::default(); + + for (symlink_dest, symlink_src) in std::mem::take(&mut self.symlinks) { + if self.read.contains(symlink_dest.clone()) + || self.write.contains(symlink_dest.clone()) + { + continue; + } + + self.push("--symlink"); + self.push(symlink_src); + self.push(symlink_dest); + } + + for read_path in std::mem::take(&mut self.read).iter() { + read_write_path_set.insert_readable(read_path.clone()); + + self.push("--ro-bind-try"); + self.push(read_path.clone()); + self.push(read_path.clone()); + } + + for write_path in std::mem::take(&mut self.write).iter() { + read_write_path_set.insert_writeable(write_path.clone()); + + self.push("--bind-try"); + self.push(write_path.clone()); + self.push(write_path.clone()); + } + + (self.arguments, read_write_path_set) + } +} + +fn spawn( + env: &BubblewrapEnv, + mut command: SandboxCommand, +) -> Result { + let mut builder = BubblewrapCommandBuilder::default(); + + let Some(directories) = directories::BaseDirs::new() else { + return Err(eyre!("unable to determine base directories")); + }; + + let mut environment = command.take_environment(); + + let xdg_runtime_dir = directories + .runtime_dir() + .ok_or_eyre("XDG_RUNTIME_DIR is not set")?; + + let file_sharing_mountpoint = xdg_runtime_dir + .join(format!("modrinth-file-sharing-{}", Uuid::now_v7())); + let file_sharing = match crate::file_sharing::mount( + file_sharing_mountpoint.clone(), + ) { + Ok(file_sharing) => Some(file_sharing), + Err(err) => { + tracing::warn!( + "Unable to start file sharing, some features may be unavailable: {}", + err + ); + None + } + }; + + // Namespaces + builder.push("--unshare-all"); + if command.allow_network { + builder.push("--share-net"); + } + + // Detach from the controlling terminal so TIOCSTI can't inject input into it (CVE-2017-5226) + builder.push("--new-session"); + + // Special filesystems + builder.push("--proc"); + builder.push("/proc"); + + builder.push("--dev"); + builder.push("/dev"); + + builder.push("--tmpfs"); + builder.push("/tmp"); + // set sticky bit on the tmp dir + // required for some mods which do weird stuff like Waylandcraft; + // it spawns xwayland-satellite, which spawns X11, which expects + // the temp dir to have the sticky bit set for safety. + builder.push("--chmod"); + builder.push("1777"); + builder.push("/tmp"); + + builder.create_dir("/tmp/.X11-unix", 0o1777); + + // Other arguments + if command.die_with_parent { + builder.push("--die-with-parent"); + } + if let Some(path) = command.working_directory.clone() { + builder.push("--chdir"); + builder.push(path); + } + + // Binds + for dev_bind in DEV_BINDS { + builder.bind_if_exists(BindBehaviour::Device, Path::new(*dev_bind)); + } + if let Ok(read_dir) = std::fs::read_dir("/dev") { + for entry in read_dir { + let Ok(entry) = entry else { + break; + }; + let path = entry.path(); + let Some(file_name) = path.file_name() else { + continue; + }; + if file_name.as_encoded_bytes().starts_with(b"nvidia") { + builder.bind_if_exists(BindBehaviour::Device, &path); + } + } + } + + for file_ro in SYSTEM_FILES_RO { + builder.bind_if_exists(BindBehaviour::FollowRead, Path::new(*file_ro)); + } + + // Bind everything in $PATH + if let Some(path) = std::env::var_os("PATH") { + for path in std::env::split_paths(&path) { + builder.bind_if_exists(BindBehaviour::FollowRead, &path); + } + } + + // Bind files in xdg runtime dir + builder.create_dir(xdg_runtime_dir.to_path_buf(), 0o700); + + let wayland_display_path = xdg_runtime_dir.join( + std::env::var_os("WAYLAND_DISPLAY") + .as_deref() + .unwrap_or(OsStr::new("wayland-0")), + ); + builder.bind_if_exists(BindBehaviour::FollowRead, &wayland_display_path); + + let pipewire_path = xdg_runtime_dir.join("pipewire-0"); + builder.bind_if_exists(BindBehaviour::FollowRead, &pipewire_path); + + // Set up flatpak document portal + let document_portal_path = xdg_runtime_dir.join("doc"); + let mut document_portal_path_by_app = document_portal_path.join("by-app"); + document_portal_path_by_app.push(FAKE_FLATPAK_APP_NAME); + _ = std::fs::create_dir_all(&document_portal_path_by_app); + + builder.push("--bind"); + builder.push(document_portal_path_by_app); + builder.push("/run/flatpak/doc"); + + builder.push("--symlink"); + builder.push("/run/flatpak/doc"); + builder.push(document_portal_path); + + let pulse_path = xdg_runtime_dir.join("pulse"); + builder.create_dir(pulse_path.clone(), 0o700); + + // Bind our file-sharing + if file_sharing.is_some() { + // We could bind it to $XDG_RUNTIME_DIR/modrinth-file-sharing, but it's + // simpler just to bind it to the real location on disk + builder.bind_if_exists( + BindBehaviour::NoFollowWrite, + &file_sharing_mountpoint, + ); + } + + if let Some(pulse_server) = std::env::var_os("PULSE_SERVER") { + if let Some(pulse_server_path) = + pulse_server.as_encoded_bytes().strip_prefix(b"unix:") + { + let pulse_server_path = unsafe { + OsStr::from_encoded_bytes_unchecked(pulse_server_path) + }; + builder.bind_if_exists( + BindBehaviour::FollowRead, + Path::new(pulse_server_path), + ); + } + } else { + let pulse_server_path = pulse_path.join("native"); + builder.bind_if_exists(BindBehaviour::FollowRead, &pulse_server_path); + + let mut pulse_server = OsString::from("unix:"); + pulse_server.push(pulse_server_path); + environment.insert("PULSE_SERVER".into(), pulse_server.into()); + } + + // Bind a bunch of pulse audio stuff + let pulse_config_dir = directories.config_dir().join("pulse"); + builder.bind_if_exists(BindBehaviour::FollowRead, &pulse_config_dir); + let pulse_home_config_dir = directories.home_dir().join(".pulse"); + builder.bind_if_exists(BindBehaviour::FollowRead, &pulse_home_config_dir); + let asound_home_config_dir = directories.home_dir().join(".asoundrc"); + builder.bind_if_exists(BindBehaviour::FollowRead, &asound_home_config_dir); + + builder.bind_if_exists(BindBehaviour::FollowWrite, Path::new("/run/pulse")); + + if let Some(pulse_clientconfig) = std::env::var_os("PULSE_CLIENTCONFIG") { + builder.bind_if_exists( + BindBehaviour::FollowRead, + Path::new(&pulse_clientconfig), + ); + } + + // Bind X11 sockets/xauthority + let display_index = std::env::var_os("DISPLAY") + .and_then(parse_x11_display_index) + .unwrap_or(0); + + builder.bind_if_exists( + BindBehaviour::FollowRead, + Path::new(&format!("/tmp/.X11-unix/X{display_index}")), + ); + if let Some(xauthority) = std::env::var_os("XAUTHORITY") { + builder + .bind_if_exists(BindBehaviour::FollowRead, Path::new(&xauthority)); + } else { + builder.bind_if_exists( + BindBehaviour::FollowRead, + &directories.home_dir().join(".Xauthority"), + ); + } + + // Bind executable + builder.bind_if_exists(BindBehaviour::FollowRead, &command.executable); + + for path in &command.ensure_dirs_exist { + std::fs::create_dir_all(path) + .wrap_err_with(|| eyre!("creating directory {path:?}"))?; + } + + // Bind custom paths + // Read-only directories can contain a read-write, but not vice-versa. So we bind read then write + let path_set = command.take_paths()?; + for path in path_set.iter_read_only() { + builder.bind_if_exists(BindBehaviour::NoFollowRead, path); + } + for path in path_set.iter_read_write() { + builder.bind_if_exists(BindBehaviour::NoFollowWrite, path); + } + + let (mut arguments, path_set) = builder.finish(); + + let flatpak_instances_dir = xdg_runtime_dir.join(".flatpak"); + let mut instance_id = rand::random::() & 0x7FFFFFFF; + let mut instance_dir = flatpak_instances_dir.join(instance_id.to_string()); + _ = std::fs::create_dir_all(&flatpak_instances_dir); + for attempt in 0..=100 { + if std::fs::create_dir(&instance_dir).is_ok() { + break; + } + + if attempt == 100 { + return Err(eyre!( + "Unable to find unique instance-id for .flatpak-info" + )); + } else { + instance_id = rand::random::() & 0x7FFFFFFF; + instance_dir = flatpak_instances_dir.join(instance_id.to_string()); + } + } + + // Set up /.flatpak-info + let flatpak_info = format!( + " +[Application] +name={FAKE_FLATPAK_APP_NAME} + +[Instance] +instance-id={instance_id} +\0" + ); + let flatpak_info: CString = + CString::from_vec_with_nul(flatpak_info.into_bytes())?; + let flatpak_info_fd1 = + WritableMemoryFile::open(c"modrinth-sandbox-bwrap-flatpak-info1")?; + let flatpak_info_fd1 = flatpak_info_fd1.write(flatpak_info.as_c_str())?; + let flatpak_info_fd2 = + WritableMemoryFile::open(c"modrinth-sandbox-bwrap-flatpak-info2")?; + let flatpak_info_fd2 = flatpak_info_fd2.write(flatpak_info.as_c_str())?; + + arguments.push("--file".into()); + arguments.push(format!("{}", flatpak_info_fd1.as_raw_fd()).into()); + arguments.push("/.flatpak-info".into()); + arguments.push("--ro-bind-data".into()); + arguments.push(format!("{}", flatpak_info_fd2.as_raw_fd()).into()); + arguments.push("/.flatpak-info".into()); + + // Set up $XDG_RUNTIME_DIR/.flatpak/{instance_id}/bwrapinfo.json + let bwrapinfo = instance_dir.join("bwrapinfo.json"); + let bwrapinfo_fd: OwnedFd = std::fs::File::create(bwrapinfo)?.into(); + arguments.push("--info-fd".into()); + arguments.push(format!("{}", bwrapinfo_fd.as_raw_fd()).into()); + + // Set up xdg-dbus-proxy + let dbus_proxy_result = + start_dbus_proxy(env, xdg_runtime_dir, &flatpak_info); + let dbus_proxy = match dbus_proxy_result { + Ok(dbus_proxy) => { + arguments.push("--bind".into()); + arguments.push(dbus_proxy.proxy_session_path.clone().into()); + let mapped_bus_dir = xdg_runtime_dir.join("bus"); + arguments.push(mapped_bus_dir.clone().into()); + + let mut dbus_session_bus_address = OsString::new(); + dbus_session_bus_address.push("unix:path="); + dbus_session_bus_address.push(mapped_bus_dir); + + environment.insert( + "DBUS_SESSION_BUS_ADDRESS".into(), + dbus_session_bus_address.into(), + ); + + Some(dbus_proxy) + } + Err(err) => { + tracing::warn!( + "Unable to start dbus proxy, some functionality may be broken: {err}" + ); + None + } + }; + + // Set up seccomp filtering + let seccomp_fd = create_seccomp_filter()?; + arguments.push("--seccomp".into()); + arguments.push(format!("{}", seccomp_fd.as_raw_fd()).into()); + + arguments.push("--".into()); + arguments.push(command.executable.into()); + for arg in command.args { + arguments.push(arg.into()); + } + + let (pipes, child) = super::unix::spawn( + env.bwrap.clone().into(), + arguments, + environment, + command.stdin, + command.stdout, + command.stderr, + command.working_directory, + vec![flatpak_info_fd1, flatpak_info_fd2, bwrapinfo_fd, seccomp_fd], + env.dev_null, + false, + command.die_with_parent, + ) + .wrap_err("spawning child")?; + + let mut child = crate::SandboxChild { + stdin: pipes.stdin, + stdout: pipes.stdout, + stderr: pipes.stderr, + imp: SandboxChild::Bubblewrap(BubblewrapChild { + child, + instance_dir, + _dbus_proxy: dbus_proxy, + }), + handle: super::SandboxHandle::Bubblewrap(BubblewrapSandboxHandle { + file_sharing, + path_set: Arc::new(path_set), + }), + on_finish: command.on_finish, + }; + + for on_start in command.on_start { + (on_start)(&mut child); + } + + Ok(child) +} + +/// Parse `:{display}.{screen}` into the display index +fn parse_x11_display_index(display: OsString) -> Option { + let display_bytes = display.as_encoded_bytes(); + if display_bytes.len() < 2 || display_bytes[0] != b':' { + return None; + } + + let mut index = 0; + for display_byte in &display_bytes[1..] { + if *display_byte == b'.' { + return Some(index); + } + index = index.checked_mul(10)?; + if *display_byte >= b'0' && *display_byte <= b'9' { + index = index.checked_add((*display_byte - b'0') as u32)?; + } else { + return None; + } + } + Some(index) +} + +#[derive(Debug)] +pub(crate) struct BubblewrapChild { + child: UnixChild, + instance_dir: PathBuf, + _dbus_proxy: Option, +} + +impl Drop for BubblewrapChild { + fn drop(&mut self) { + _ = std::fs::remove_dir_all(&self.instance_dir); + } +} + +#[async_trait] +impl SandboxChildOp for BubblewrapChild { + fn id(&self) -> Option { + self.child.id() + } + + fn try_wait(&mut self) -> Result> { + self.child.try_wait() + } + + async fn wait(&mut self) -> Result { + self.child.wait().await + } + + async fn kill(&mut self) -> Result<()> { + self.child.kill().await + } +} + +#[derive(Clone, Debug)] +pub struct BubblewrapSandboxHandle { + file_sharing: Option, + path_set: Arc, +} + +impl SandboxHandleOp for BubblewrapSandboxHandle { + fn expose_path( + &self, + path: &Path, + allow_write: bool, + ) -> eyre::Result { + let can_access = if allow_write { + self.is_path_writeable(path) + } else { + self.is_path_readable(path) + }; + if can_access { + return Ok(ExposedPath::Direct); + } + let Some(file_sharing) = &self.file_sharing else { + bail!( + "file cannot be shared because file sharing filesystem failed to start" + ); + }; + + let proxied_path = file_sharing.add(path.to_path_buf(), allow_write)?; + Ok(ExposedPath::Proxied(proxied_path)) + } + + fn is_path_readable(&self, path: &Path) -> bool { + self.path_set.can_read(path.to_path_buf()) + } + + fn is_path_writeable(&self, path: &Path) -> bool { + self.path_set.can_write(path.to_path_buf()) + } +} + +#[derive(Debug)] +struct DbusProxy { + proxy_session_path: PathBuf, + _keep_alive_read_fd: OwnedFd, +} + +impl Drop for DbusProxy { + fn drop(&mut self) { + _ = std::fs::remove_file(&self.proxy_session_path); + } +} + +fn start_dbus_proxy( + env: &BubblewrapEnv, + runtime_dir: &Path, + flatpak_info: &CStr, +) -> Result { + const DBUS_ADDRESS_ENV: &str = "DBUS_SESSION_BUS_ADDRESS"; + + let (keep_alive_read_fd, keep_alive_write_fd) = super::linux::open_pipe()?; + + let session_bus_address = std::env::var_os(DBUS_ADDRESS_ENV) + .ok_or_else(|| eyre!("reading `{DBUS_ADDRESS_ENV}`"))?; + + let mut builder = BubblewrapCommandBuilder::default(); + + builder.push("--new-session"); + + let proxy_session_path = runtime_dir.join(format!( + "modrinth-xdg-dbus-proxy-session-{}", + Uuid::now_v7() + )); + + builder.bind_if_exists(BindBehaviour::FollowRead, Path::new("/usr")); + builder.bind_if_exists(BindBehaviour::FollowRead, Path::new("/lib64")); + builder.bind_if_exists(BindBehaviour::FollowRead, Path::new("/nix/store")); + builder.bind_if_exists(BindBehaviour::FollowWrite, &runtime_dir); + + let (mut arguments, path_set) = builder.finish(); + + let flatpak_info_fd1 = + WritableMemoryFile::open(c"modrinth-sandbox-proxy-flatpak-info1") + .wrap_err("creating flatpak-info memory file 1")?; + let flatpak_info_fd1 = flatpak_info_fd1 + .write(flatpak_info) + .wrap_err("writing to flatpak-info memory file 1")?; + let flatpak_info_fd2 = + WritableMemoryFile::open(c"modrinth-sandbox-proxy-flatpak-info2") + .wrap_err("creating flatpak-info memory file 2")?; + let flatpak_info_fd2 = flatpak_info_fd2 + .write(flatpak_info) + .wrap_err("writing to flatpak-info memory file 2")?; + + arguments.push("--file".into()); + arguments.push(format!("{}", flatpak_info_fd1.as_raw_fd()).into()); + arguments.push("/.flatpak-info".into()); + arguments.push("--ro-bind-data".into()); + arguments.push(format!("{}", flatpak_info_fd2.as_raw_fd()).into()); + arguments.push("/.flatpak-info".into()); + + arguments.push("--".into()); + arguments.push(env.xdg_dbus_proxy.clone().into()); + arguments.push(session_bus_address.into()); + arguments.push(proxy_session_path.clone().into()); + arguments.push(format!("--fd={}", keep_alive_write_fd.as_raw_fd()).into()); + arguments.push("--filter".into()); + arguments.push("--talk=com.feralinteractive.GameMode".into()); + arguments.push( + "--call=com.feralinteractive.GameMode=/com/feralinteractive/GameMode" + .into(), + ); + arguments.push("--talk=org.kde.StatusNotifierWatcher".into()); + arguments.push( + "--call=org.kde.StatusNotifierWatcher=/StatusNotifierWatcher".into(), + ); + arguments.push("--talk=org.freedesktop.Notifications".into()); + arguments.push( + "--call=org.freedesktop.Notifications=/org/freedesktop/Notifications" + .into(), + ); + arguments.push("--talk=org.freedesktop.portal.*".into()); + arguments.push("--call=org.freedesktop.portal.Desktop=org.freedesktop.portal.Settings.Read@/org/freedesktop/portal/desktop".into()); + arguments.push("--broadcast=org.freedesktop.portal.Desktop=org.freedesktop.portal.Settings.SettingChanged@/org/freedesktop/portal/desktop".into()); + arguments.push("--talk=org.mpris.MediaPlayer2.*".into()); + + let mut environment = BTreeMap::default(); + for (arg, value) in std::env::vars_os() { + environment.insert(arg.into(), value.into()); + } + + super::unix::spawn( + env.bwrap.clone().into(), + arguments, + environment, + SandboxStdio::Null, + SandboxStdio::Null, + SandboxStdio::Null, + Some(runtime_dir.to_path_buf()), + vec![flatpak_info_fd1, flatpak_info_fd2, keep_alive_write_fd], + env.dev_null, + true, + false, + ) + .wrap_err("spawning dbus proxy child")?; + + // Wait for proxy to start by reading from fd + let mut buf = 0 as libc::c_char; + unsafe { + let start = std::time::Instant::now(); + if libc::read( + keep_alive_read_fd.as_raw_fd(), + &raw mut buf as *mut libc::c_char as *mut _, + 1, + ) != 1 + { + return Err(eyre!("syncing with xdg-dbus-proxy")); + } + tracing::info!("xdg-dbus-proxy took {:.1?} to start", start.elapsed()); + } + + eyre::Ok(DbusProxy { + proxy_session_path, + _keep_alive_read_fd: keep_alive_read_fd, + }) +} + +// Syscall allowlist copied from https://github.com/moby/profiles/blob/fa50b7287199d1c781284d1a34d1395a62e57f1e/seccomp/default.json +// Licensed as Apache 2.0 (https://github.com/moby/profiles/blob/fa50b7287199d1c781284d1a34d1395a62e57f1e/LICENSE) +const ALLOWED_SYSCALLS: &[&str] = &[ + "accept", + "accept4", + "access", + "adjtimex", + "alarm", + "bind", + "brk", + "cachestat", + "capget", + "capset", + "chdir", + "chmod", + "chown", + "chown32", + "clock_adjtime", + "clock_adjtime64", + "clock_getres", + "clock_getres_time64", + "clock_gettime", + "clock_gettime64", + "clock_nanosleep", + "clock_nanosleep_time64", + "close", + "close_range", + "connect", + "copy_file_range", + "creat", + "dup", + "dup2", + "dup3", + "epoll_create", + "epoll_create1", + "epoll_ctl", + "epoll_ctl_old", + "epoll_pwait", + "epoll_pwait2", + "epoll_wait", + "epoll_wait_old", + "eventfd", + "eventfd2", + "execve", + "execveat", + "exit", + "exit_group", + "faccessat", + "faccessat2", + "fadvise64", + "fadvise64_64", + "fallocate", + "fanotify_mark", + "fchdir", + "fchmod", + "fchmodat", + "fchmodat2", + "fchown", + "fchown32", + "fchownat", + "fcntl", + "fcntl64", + "fdatasync", + "fgetxattr", + "flistxattr", + "flock", + "fork", + "fremovexattr", + "fsetxattr", + "fstat", + "fstat64", + "fstatat64", + "fstatfs", + "fstatfs64", + "fsync", + "ftruncate", + "ftruncate64", + "futex", + "futex_requeue", + "futex_time64", + "futex_wait", + "futex_waitv", + "futex_wake", + "futimesat", + "getcpu", + "getcwd", + "getdents", + "getdents64", + "getegid", + "getegid32", + "geteuid", + "geteuid32", + "getgid", + "getgid32", + "getgroups", + "getgroups32", + "getitimer", + "getpeername", + "getpgid", + "getpgrp", + "getpid", + "getppid", + "getpriority", + "getrandom", + "getresgid", + "getresgid32", + "getresuid", + "getresuid32", + "getrlimit", + "get_robust_list", + "getrusage", + "getsid", + "getsockname", + "getsockopt", + "get_thread_area", + "gettid", + "gettimeofday", + "getuid", + "getuid32", + "getxattr", + "getxattrat", + "inotify_add_watch", + "inotify_init", + "inotify_init1", + "inotify_rm_watch", + "io_cancel", + "ioctl", + "io_destroy", + "io_getevents", + "io_pgetevents", + "io_pgetevents_time64", + "ioprio_get", + "ioprio_set", + "io_setup", + "io_submit", + "ipc", + "kill", + "landlock_add_rule", + "landlock_create_ruleset", + "landlock_restrict_self", + "lchown", + "lchown32", + "lgetxattr", + "link", + "linkat", + "listen", + "listmount", + "listxattr", + "listxattrat", + "llistxattr", + "_llseek", + "lremovexattr", + "lseek", + "lsetxattr", + "lstat", + "lstat64", + "madvise", + "map_shadow_stack", + "membarrier", + "memfd_create", + "memfd_secret", + "mincore", + "mkdir", + "mkdirat", + "mknod", + "mknodat", + "mlock", + "mlock2", + "mlockall", + "mmap", + "mmap2", + "mprotect", + "mq_getsetattr", + "mq_notify", + "mq_open", + "mq_timedreceive", + "mq_timedreceive_time64", + "mq_timedsend", + "mq_timedsend_time64", + "mq_unlink", + "mremap", + "mseal", + "msgctl", + "msgget", + "msgrcv", + "msgsnd", + "msync", + "munlock", + "munlockall", + "munmap", + "name_to_handle_at", + "nanosleep", + "newfstatat", + "_newselect", + "open", + "openat", + "openat2", + "pause", + "pidfd_open", + "pidfd_send_signal", + "pipe", + "pipe2", + "pkey_alloc", + "pkey_free", + "pkey_mprotect", + "poll", + "ppoll", + "ppoll_time64", + "prctl", + "pread64", + "preadv", + "preadv2", + "prlimit64", + "process_mrelease", + "pselect6", + "pselect6_time64", + "pwrite64", + "pwritev", + "pwritev2", + "read", + "readahead", + "readlink", + "readlinkat", + "readv", + "recv", + "recvfrom", + "recvmmsg", + "recvmmsg_time64", + "recvmsg", + "remap_file_pages", + "removexattr", + "removexattrat", + "rename", + "renameat", + "renameat2", + "restart_syscall", + "riscv_hwprobe", + "rmdir", + "rseq", + "rt_sigaction", + "rt_sigpending", + "rt_sigprocmask", + "rt_sigqueueinfo", + "rt_sigreturn", + "rt_sigsuspend", + "rt_sigtimedwait", + "rt_sigtimedwait_time64", + "rt_tgsigqueueinfo", + "sched_getaffinity", + "sched_getattr", + "sched_getparam", + "sched_get_priority_max", + "sched_get_priority_min", + "sched_getscheduler", + "sched_rr_get_interval", + "sched_rr_get_interval_time64", + "sched_setaffinity", + "sched_setattr", + "sched_setparam", + "sched_setscheduler", + "sched_yield", + "seccomp", + "select", + "semctl", + "semget", + "semop", + "semtimedop", + "semtimedop_time64", + "send", + "sendfile", + "sendfile64", + "sendmmsg", + "sendmsg", + "sendto", + "setfsgid", + "setfsgid32", + "setfsuid", + "setfsuid32", + "setgid", + "setgid32", + "setgroups", + "setgroups32", + "setitimer", + "setpgid", + "setpriority", + "setregid", + "setregid32", + "setresgid", + "setresgid32", + "setresuid", + "setresuid32", + "setreuid", + "setreuid32", + "setrlimit", + "set_robust_list", + "setsid", + "setsockopt", + "set_thread_area", + "set_tid_address", + "setuid", + "setuid32", + "setxattr", + "setxattrat", + "shmat", + "shmctl", + "shmdt", + "shmget", + "shutdown", + "sigaltstack", + "signalfd", + "signalfd4", + "sigprocmask", + "sigreturn", + "socketcall", + "socketpair", + "splice", + "stat", + "stat64", + "statfs", + "statfs64", + "statmount", + "statx", + "symlink", + "symlinkat", + "sync", + "sync_file_range", + "syncfs", + "sysinfo", + "tee", + "tgkill", + "time", + "timer_create", + "timer_delete", + "timer_getoverrun", + "timer_gettime", + "timer_gettime64", + "timer_settime", + "timer_settime64", + "timerfd_create", + "timerfd_gettime", + "timerfd_gettime64", + "timerfd_settime", + "timerfd_settime64", + "times", + "tkill", + "truncate", + "truncate64", + "ugetrlimit", + "umask", + "uname", + "unlink", + "unlinkat", + "uretprobe", + "utime", + "utimensat", + "utimensat_time64", + "utimes", + "vfork", + "vmsplice", + "wait4", + "waitid", + "waitpid", + "write", + "writev", + #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] + "arch_prctl", +]; + +fn create_seccomp_filter() -> Result { + // We could cache the fd and dup, but I'm worried that this might allow the child + // to modify the memfd even when it is sealed, so we just recreate the bpf memfd from scratch + + let Ok(mut filter) = ScmpFilterContext::new(ScmpAction::Errno(libc::EPERM)) + else { + return Err(eyre!("unable to init seccomp filter context")); + }; + + for syscall in ALLOWED_SYSCALLS { + let Ok(syscall) = ScmpSyscall::from_name(syscall) else { + continue; + }; + _ = filter.add_rule(ScmpAction::Allow, syscall); + } + if let Ok(syscall) = ScmpSyscall::from_name("clone") { + let disallowed_clones = libc::CLONE_NEWNS + | libc::CLONE_NEWUTS + | libc::CLONE_NEWIPC + | libc::CLONE_NEWUSER + | libc::CLONE_NEWPID + | libc::CLONE_NEWNET + | libc::CLONE_NEWCGROUP; + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new( + 0, + ScmpCompareOp::MaskedEqual(disallowed_clones as u64), + 0, + )], + ); + } + if let Ok(syscall) = ScmpSyscall::from_name("clone3") { + _ = filter.add_rule(ScmpAction::Errno(libc::ENOSYS), syscall); + } + if let Ok(syscall) = ScmpSyscall::from_name("socket") { + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new( + 0, + ScmpCompareOp::NotEqual, + libc::AF_VSOCK as u64, + )], + ); + } + if let Ok(syscall) = ScmpSyscall::from_name("personality") { + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new(0, ScmpCompareOp::Equal, 0x0)], + ); + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new(0, ScmpCompareOp::Equal, 0x8)], + ); + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new(0, ScmpCompareOp::Equal, 0x20000)], + ); + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new(0, ScmpCompareOp::Equal, 0x20008)], + ); + _ = filter.add_rule_conditional( + ScmpAction::Allow, + syscall, + &[ScmpArgCompare::new(0, ScmpCompareOp::Equal, 0xffffffff)], + ); + } + let fd = WritableMemoryFile::open(c"modrinth-sandbox-seccomp-bpf")?; + let fd = fd.write_filter(filter)?; + Ok(fd) +} diff --git a/packages/modrinth-sandbox/src/backend/flatpak/dbus.rs b/packages/modrinth-sandbox/src/backend/flatpak/dbus.rs new file mode 100644 index 00000000000..f93cfd8c52c --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/flatpak/dbus.rs @@ -0,0 +1,282 @@ +#![allow(dead_code, reason = "kept for completeness' sake")] + +use std::collections::BTreeMap; + +use zbus::{ + Fd, OwnedFd, Signature, + zvariant::{SerializeDict, Type}, +}; + +pub use imp::{SpawnExitedStream, SpawnStartedStream}; + +bitflags::bitflags! { + /// Controls how the Flatpak portal creates and manages a process. + /// + /// These flags are passed directly to the `flags` argument of the + /// `org.freedesktop.portal.Flatpak.Spawn` method. Unknown flag bits cause + /// the portal call to fail. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct SpawnFlags: u32 { + /// Clears the inherited environment before applying the variables in + /// the `envs` argument. + const CLEAR_ENV = 1 << 0; + /// Runs the latest installed version of the calling Flatpak app instead + /// of the version currently running. + const LATEST_VERSION = 1 << 1; + /// Creates a new, more restrictive subsandbox, equivalent to the + /// sandboxing performed by `flatpak run --sandbox`. + const SANDBOX = 1 << 2; + /// Creates the process without network access by giving it a separate + /// network namespace. + /// + /// This also separates its loopback interface from the caller, so it + /// must not be used when the child needs loopback IPC with the caller. + const NO_NETWORK = 1 << 3; + /// Terminates the spawned sandbox when the calling D-Bus connection + /// disappears from the session bus. + const WATCH_BUS = 1 << 4; + /// Makes the sandbox's process IDs visible in the caller's PID namespace. + /// + /// This requires [`Supports::EXPOSE_PIDS`] and is only supported when + /// Flatpak uses user namespaces rather than a setuid sandbox helper. + const EXPOSE_PIDS = 1 << 5; + /// Requests a `SpawnStarted` signal after the process inside the new + /// sandbox has started. + /// + /// This requires Flatpak portal interface version 4 or newer. + const NOTIFY_START = 1 << 6; + /// Shares process IDs in both directions between the caller and the new + /// sandbox. + /// + /// This is broader than [`SpawnFlags::EXPOSE_PIDS`], requires PID + /// exposure support, and requires Flatpak portal interface version 5 or + /// newer. + const SHARE_PIDS = 1 << 7; + /// Mounts an empty directory at `/app` in the new sandbox. + /// + /// The caller's app files remain available below `/run/parent/app`. + /// This flag is mutually exclusive with the `app-fd` spawn option and + /// requires Flatpak portal interface version 6 or newer. + const EMPTY_APP = 1 << 8; + } + + /// Features supported by the running Flatpak portal implementation. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct Supports: u32 { + /// The portal supports [`SpawnFlags::EXPOSE_PIDS`]. On interface version + /// 5 or newer, this also indicates support for [`SpawnFlags::SHARE_PIDS`]. + const EXPOSE_PIDS = 1 << 0; + } + + /// Capabilities selectively granted to a process created as a subsandbox. + /// + /// These flags are encoded in [`SpawnOptions::sandbox_flags`]. They only + /// apply when [`SpawnFlags::SANDBOX`] is set and cannot grant access that the + /// calling Flatpak does not already have. + #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] + pub struct SandboxFlags: u32 { + /// Shares the caller's X11 and Wayland display access with the sandbox. + const SHARE_DISPLAY = 1 << 0; + /// Shares the caller's PulseAudio sound access with the sandbox. + const SHARE_SOUND = 1 << 1; + /// Shares the caller's GPU access with the sandbox. + const SHARE_GPU = 1 << 2; + /// Grants access to a filtered session D-Bus connection. + const SESSION_BUS = 1 << 3; + /// Grants access to the accessibility D-Bus connection. + const ACCESSIBILITY_BUS = 1 << 4; + /// Grants access to input devices. + const INPUT_DEVICES = 1 << 5; + /// Grants access to USB devices. + const USB_DEVICES = 1 << 6; + /// Grants access to hardware virtualization through KVM. + const KVM = 1 << 7; + /// Grants access to shared memory provided by the caller's sandbox. + const SHARED_MEMORY = 1 << 8; + /// Grants access to all devices available to the caller. + /// + /// This is substantially broader than the individual device flags and + /// should only be used when narrowly scoped grants are insufficient. + const ALL_DEVICES = 1 << 9; + } +} + +impl Type for SandboxFlags { + const SIGNATURE: &'static Signature = ::SIGNATURE; +} + +/// Optional settings for [`FlatpakPortalProxy::spawn`]. +/// +/// This serializes as the extensible D-Bus dictionary `a{sv}` expected by the +/// Flatpak portal. Fields set to [`None`] are omitted from the dictionary. +/// Unknown dictionary keys are ignored by the portal, unlike unknown bits in +/// [`SpawnFlags`], which cause the spawn request to fail. +#[derive(Debug, Default, SerializeDict, Type)] +#[zvariant(signature = "dict")] +pub struct SpawnOptions { + /// Capabilities granted to the new subsandbox. + /// + /// This corresponds to the `sandbox-flags` option and only applies when + /// [`SpawnFlags::SANDBOX`] is set. + #[zvariant(rename = "sandbox-flags")] + pub sandbox_flags: Option, + /// Read-write entries from the caller's Flatpak sandbox directory to expose. + /// + /// Each entry must be a single filename inside + /// `~/.var/app//sandbox`. Absolute paths and subdirectories are not + /// accepted. Use [`SpawnOptions::sandbox_expose_fd`] for arbitrary paths. + #[zvariant(rename = "sandbox-expose")] + pub sandbox_expose: Option>, + /// Read-only entries from the caller's Flatpak sandbox directory to expose. + /// + /// Each entry must be a single filename inside + /// `~/.var/app//sandbox`. Absolute paths and subdirectories are not + /// accepted. Use [`SpawnOptions::sandbox_expose_fd_ro`] for arbitrary paths. + #[zvariant(rename = "sandbox-expose-ro")] + pub sandbox_expose_ro: Option>, + /// Paths exposed read-write, identified by owned file descriptors. + /// + /// Each descriptor must have been opened with `O_PATH | O_NOFOLLOW` and + /// must not refer to a symbolic link. A path is writable only when the + /// caller already has write access to it. This option requires Flatpak + /// portal interface version 3 or newer. + #[zvariant(rename = "sandbox-expose-fd")] + pub sandbox_expose_fd: Option>, + /// Paths exposed read-only, identified by owned file descriptors. + /// + /// Each descriptor must have been opened with `O_PATH | O_NOFOLLOW` and + /// must not refer to a symbolic link. This option requires Flatpak portal + /// interface version 3 or newer. + #[zvariant(rename = "sandbox-expose-fd-ro")] + pub sandbox_expose_fd_ro: Option>, + /// Environment variables removed from the spawned process. + /// + /// This corresponds to the `unset-env` option and requires Flatpak portal + /// interface version 5 or newer. + #[zvariant(rename = "unset-env")] + pub unset_env: Option>, + /// Directory to mount as `/usr` in the new sandbox. + /// + /// The descriptor must have been opened with `O_PATH | O_NOFOLLOW` and + /// must not refer to a symbolic link. The caller's original runtime remains + /// available under `/run/parent/usr`. This option requires Flatpak portal + /// interface version 6 or newer. + #[zvariant(rename = "usr-fd")] + pub usr_fd: Option, + /// Directory to mount as `/app` in the new sandbox. + /// + /// The descriptor must have been opened with `O_PATH | O_NOFOLLOW` and + /// must not refer to a symbolic link. The caller's original app remains + /// available under `/run/parent/app`. This option is mutually exclusive + /// with [`SpawnFlags::EMPTY_APP`] and requires Flatpak portal interface + /// version 6 or newer. + #[zvariant(rename = "app-fd")] + pub app_fd: Option, + /// D-Bus names the sandbox may own on the accessibility bus. + /// + /// Each name must use the caller's application ID as its prefix. This only + /// applies when [`SandboxFlags::ACCESSIBILITY_BUS`] is set and requires + /// Flatpak portal interface version 7 or newer. + #[zvariant(rename = "sandbox-a11y-own-names")] + pub sandbox_a11y_own_names: Option>, +} + +#[derive(Debug, Clone)] +pub struct FlatpakPortalProxy<'p> { + inner: imp::FlatpakPortalProxy<'p>, +} + +impl<'p> FlatpakPortalProxy<'p> { + pub async fn new(conn: &zbus::Connection) -> zbus::Result { + imp::FlatpakPortalProxy::new(conn) + .await + .map(|inner| Self { inner }) + } + + pub async fn version(&self) -> zbus::Result { + self.inner.version().await + } + + pub async fn supports(&self) -> zbus::Result { + self.inner.supports().await.map(Supports::from_bits_retain) + } + + pub async fn spawn( + &self, + cwd_path: &[u8], + argv: &[Vec], + fds: &BTreeMap>, + envs: &BTreeMap, + flags: SpawnFlags, + options: &SpawnOptions, + ) -> zbus::Result { + self.inner + .spawn(cwd_path, argv, fds, envs, flags.bits(), options) + .await + } + + pub async fn spawn_signal( + &self, + pid: u32, + signal: u32, + to_process_group: bool, + ) -> zbus::Result<()> { + self.inner.spawn_signal(pid, signal, to_process_group).await + } + + pub async fn receive_spawn_started( + &self, + ) -> zbus::Result { + self.inner.receive_spawn_started().await + } + + pub async fn receive_spawn_exited( + &self, + ) -> zbus::Result { + self.inner.receive_spawn_exited().await + } +} + +mod imp { + use std::collections::BTreeMap; + + use zbus::Fd; + + use super::SpawnOptions; + + #[zbus::proxy( + interface = "org.freedesktop.portal.Flatpak", + default_service = "org.freedesktop.portal.Flatpak", + default_path = "/org/freedesktop/portal/Flatpak" + )] + pub trait FlatpakPortal { + #[zbus(property, name = "version")] + fn version(&self) -> zbus::Result; + + #[zbus(property, name = "supports")] + fn supports(&self) -> zbus::Result; + + fn spawn( + &self, + cwd_path: &[u8], + argv: &[Vec], + fds: &BTreeMap>, + envs: &BTreeMap, + flags: u32, + options: &SpawnOptions, + ) -> zbus::Result; + + fn spawn_signal( + &self, + pid: u32, + signal: u32, + to_process_group: bool, + ) -> zbus::Result<()>; + + #[zbus(signal)] + fn spawn_started(&self, pid: u32, relpid: u32) -> zbus::Result<()>; + + #[zbus(signal)] + fn spawn_exited(&self, pid: u32, exit_status: u32) -> zbus::Result<()>; + } +} diff --git a/packages/modrinth-sandbox/src/backend/flatpak/mod.rs b/packages/modrinth-sandbox/src/backend/flatpak/mod.rs new file mode 100644 index 00000000000..38a88c31e7c --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/flatpak/mod.rs @@ -0,0 +1,445 @@ +use std::{ + collections::BTreeMap, + io::ErrorKind, + os::{ + fd::{AsFd, OwnedFd}, + unix::ffi::OsStringExt, + }, + sync::Arc, +}; + +use async_trait::async_trait; +use derive_more::Debug; +use eyre::{Context, OptionExt, Result, bail, ensure, eyre}; +use futures::{StreamExt, TryStreamExt, stream::FuturesUnordered}; +use libc::SIGKILL; +use tokio::{fs, sync::oneshot}; +use tracing::error; +use zbus::Fd; + +use crate::{ + SandboxCommand, SandboxExitStatus, SandboxStdio, + backend::{ + Backend, SandboxChild, SandboxChildOp, SandboxEnv, + flatpak::dbus::{SandboxFlags, SpawnFlags, SpawnOptions}, + pathset::ReadWritePathSet, + unix, + }, +}; + +mod dbus; + +#[derive(Debug)] +pub struct Flatpak; + +#[async_trait] +impl Backend for Flatpak { + async fn init( + _make_helper: crate::helper::MakeHelper, + ) -> Result> { + init().await.map(|env| Box::new(env) as Box) + } +} + +async fn init() -> Result { + let session_bus = zbus::Connection::session() + .await + .wrap_err("connecting to session bus")?; + let flatpak_portal = dbus::FlatpakPortalProxy::new(&session_bus) + .await + .context("connecting to Flatpak portal")?; + Ok(FlatpakEnv { flatpak_portal }) +} + +#[derive(Debug)] +#[debug("FlatpakEnv")] +pub struct FlatpakEnv { + flatpak_portal: dbus::FlatpakPortalProxy<'static>, +} + +#[async_trait] +impl SandboxEnv for FlatpakEnv { + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result { + super::linux::ensure_valid_command(&command).await?; + spawn(self, command).await + } +} + +async fn spawn( + env: &FlatpakEnv, + mut command: SandboxCommand, +) -> Result { + let envs = command + .take_environment() + .into_iter() + .map(|(key, val)| { + let key = key.into_os_string().into_string().map_err(|key| { + eyre!("environment variable {key:?} has non-UTF-8 key") + })?; + let val = val.into_os_string().into_string().map_err(|_| { + eyre!("environment variable value for key {key:?} has non-UTF-8 value") + })?; + eyre::Ok((key, val)) + }) + .collect::>>()?; + + let path_set = command.take_paths()?; + + let cwd_path = match command.working_directory { + Some(path) => nul_terminate( + path.into_os_string().into_vec(), + "working directory", + )?, + None => vec![0], + }; + + let mut argv = Vec::with_capacity(command.args.len() + 1); + argv.push(nul_terminate( + command.executable.into_os_string().into_vec(), + "executable path", + )?); + for arg in command.args { + argv.push(nul_terminate( + arg.into_os_string().into_vec(), + "process argument", + )?); + } + + let mut fds = BTreeMap::new(); + + let inherited = std::io::stdin(); + let stdin = { + let (fd, write) = match command.stdin { + SandboxStdio::Null => open_dev_null() + .map(OwnedFd::from) + .map(Fd::Owned) + .map(|fd| (fd, None)) + .wrap_err("creating /dev/null fd")?, + SandboxStdio::Inherit => { + let fd = Fd::Borrowed(inherited.as_fd()); + (fd, None) + } + SandboxStdio::Pipe => { + let (read, write) = + std::io::pipe().wrap_err("creating child stdin pipe")?; + (OwnedFd::from(read).into(), Some(write)) + } + }; + + fds.insert(libc::STDIN_FILENO as u32, fd); + write + }; + + let inherited = std::io::stdout(); + let stdout = { + let (fd, read) = match command.stdout { + SandboxStdio::Null => open_dev_null() + .map(OwnedFd::from) + .map(Fd::Owned) + .map(|fd| (fd, None)) + .wrap_err("creating /dev/null fd")?, + SandboxStdio::Inherit => { + let fd = Fd::Borrowed(inherited.as_fd()); + (fd, None) + } + SandboxStdio::Pipe => { + let (read, write) = + std::io::pipe().wrap_err("creating child stdout pipe")?; + (OwnedFd::from(write).into(), Some(read)) + } + }; + + fds.insert(libc::STDOUT_FILENO as u32, fd); + read + }; + + let inherited = std::io::stderr(); + let stderr = { + let (fd, read) = match command.stderr { + SandboxStdio::Null => open_dev_null() + .map(OwnedFd::from) + .map(Fd::Owned) + .map(|fd| (fd, None)) + .wrap_err("creating /dev/null fd")?, + SandboxStdio::Inherit => { + let fd = Fd::Borrowed(inherited.as_fd()); + (fd, None) + } + SandboxStdio::Pipe => { + let (read, write) = + std::io::pipe().wrap_err("creating child stderr pipe")?; + (OwnedFd::from(write).into(), Some(read)) + } + }; + + fds.insert(libc::STDERR_FILENO as u32, fd); + read + }; + + let mut flags = SpawnFlags::CLEAR_ENV + | SpawnFlags::SANDBOX + | SpawnFlags::WATCH_BUS + | SpawnFlags::EMPTY_APP; + if !command.allow_network { + flags |= SpawnFlags::NO_NETWORK; + } + + for path in &command.ensure_dirs_exist { + fs::create_dir_all(path) + .await + .wrap_err_with(|| eyre!("creating directory {path:?}"))?; + } + + let sandbox_expose_fd = path_set + .iter_read_write() + .map(|path| async move { + let file_result = fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_PATH | libc::O_NOFOLLOW) + .open(&path) + .await; + if let Err(err) = &file_result + && err.kind() == ErrorKind::NotFound + { + return eyre::Ok(None); + } + let file = file_result + .wrap_err_with(|| eyre!("opening file {path:?} for writing"))?; + let file = file.into_std().await; + let fd = OwnedFd::from(file); + let fd = zbus::OwnedFd::from(fd); + eyre::Ok(Some(fd)) + }) + .collect::>() + .filter_map(|i| async move { i.transpose() }) + .try_collect::>() + .await?; + + let sandbox_expose_fd_ro = path_set + .iter_read_only() + .map(|path| async move { + let file_result = fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_PATH | libc::O_NOFOLLOW) + .open(&path) + .await; + if let Err(err) = &file_result + && err.kind() == ErrorKind::NotFound + { + return eyre::Ok(None); + } + let file = file_result + .wrap_err_with(|| eyre!("opening file {path:?} for reading"))?; + let file = file.into_std().await; + let fd = OwnedFd::from(file); + let fd = zbus::OwnedFd::from(fd); + eyre::Ok(Some(fd)) + }) + .collect::>() + .filter_map(|i| async move { i.transpose() }) + .try_collect::>() + .await?; + + let options = SpawnOptions { + sandbox_flags: Some( + SandboxFlags::SHARE_DISPLAY + | SandboxFlags::SHARE_SOUND + | SandboxFlags::SHARE_GPU + | SandboxFlags::SESSION_BUS + | SandboxFlags::INPUT_DEVICES, + ), + sandbox_expose_fd: Some(sandbox_expose_fd), + sandbox_expose_fd_ro: Some(sandbox_expose_fd_ro), + ..Default::default() + }; + + // make the spawn_exited stream first... + let mut spawn_exited = env + .flatpak_portal + .receive_spawn_exited() + .await + .context("creating SpawnExited stream")?; + + let flatpak_pid = env + .flatpak_portal + .spawn(&cwd_path, &argv, &fds, &envs, flags, &options) + .await + .wrap_err("spawning child process through Flatpak portal")?; + + // ...because otherwise we can have a race condition here. + // if we spawn the process, and it exits very quickly, then flatpak + // sends a SpawnExited signal *now*, before we've started the task which + // forwards exits to `tx_exited`. + // to counteract this, we make the stream *first*, then we can receive + // messages which were made after we spawned but before the forwarder task + // first ran. + + let (tx_exited, rx_exited) = oneshot::channel(); + // this is the forwarder task. + // + // why do we make a new task on every spawn(), instead of having a single + // long-living task in the `FlatpakEnv` which sends on a channel? + // + // using a broadcast channel, we are forced to have a bounded capacity, and + // there's always a risk of a receiver channel lagging and we skip an exited + // signal. this is bad, because we must be able to *reliably* receive + // SpawnExited signals, and never drop any. + // and we can't use an mpsc here, because we don't have a single consumer, + // we have many (breaking the "sc" part of "mpsc"). + tokio::spawn(async move { + while let Some(exited) = spawn_exited.next().await { + let exited = match exited.args() { + Ok(args) => args, + Err(err) => { + // this is very much less than ideal since we're potentially dropping + // the exit signal for our process, but I'm not sure what to do here, + // short of panicking the whole app. + error!( + "failed to receive SpawnExited signal, skipping: {err:?}" + ); + return; + } + }; + + if exited.pid == flatpak_pid { + let exit_status = exited.exit_status as libc::c_int; + tx_exited + .send(SandboxExitStatus { + imp: unix::UnixSandboxExitStatus(exit_status), + }) + .ok(); + return; + } + } + }); + + let mut child = crate::SandboxChild { + stdin, + stdout, + stderr, + on_finish: command.on_finish, + handle: super::SandboxHandle::Flatpak(FlatpakSandboxHandle { + path_set: Arc::new(path_set), + }), + imp: SandboxChild::Flatpak(FlatpakChild { + flatpak_pid, + flatpak_portal: env.flatpak_portal.clone(), + rx_exited: Some(rx_exited), + exit_status: None, + }), + }; + + for on_start in command.on_start { + (on_start)(&mut child); + } + + Ok(child) +} + +fn nul_terminate(mut value: Vec, description: &str) -> Result> { + ensure!( + !value.contains(&0), + "{description} contains an embedded NUL byte" + ); + value.push(0); + Ok(value) +} + +fn open_dev_null() -> Result { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/null") + .wrap_err("opening /dev/null") +} + +/// Flatpak does not support granting additional filesystem access after spawn. +#[derive(Clone, Debug)] +pub struct FlatpakSandboxHandle { + path_set: Arc, +} + +impl super::SandboxHandleOp for FlatpakSandboxHandle { + fn expose_path( + &self, + _path: &std::path::Path, + _allow_write: bool, + ) -> Result { + bail!( + "exposing additional paths to a running Flatpak sandbox is unsupported" + ) + } + + fn is_path_readable(&self, path: &std::path::Path) -> bool { + self.path_set.can_read(path.to_path_buf()) + } + + fn is_path_writeable(&self, path: &std::path::Path) -> bool { + self.path_set.can_write(path.to_path_buf()) + } +} + +#[derive(Debug)] +pub struct FlatpakChild { + /// Flatpak's opaque process ID for this child - *not* a Unix process ID. + flatpak_pid: u32, + flatpak_portal: dbus::FlatpakPortalProxy<'static>, + rx_exited: Option>, + exit_status: Option, +} + +#[async_trait] +impl SandboxChildOp for FlatpakChild { + fn id(&self) -> Option { + // TODO: can we get some kind of persistent id here? not sure + None + } + + fn try_wait(&mut self) -> Result> { + if let Some(exit_status) = self.exit_status { + return Ok(Some(exit_status)); + } + + let rx_exited = self + .rx_exited + .as_mut() + .ok_or_eyre("missing exit status receiver")?; + match rx_exited.try_recv() { + Ok(exit_status) => { + self.rx_exited = None; + self.exit_status = Some(exit_status); + Ok(Some(exit_status)) + } + Err(oneshot::error::TryRecvError::Empty) => Ok(None), + Err(oneshot::error::TryRecvError::Closed) => { + bail!("channel closed") + } + } + } + + async fn wait(&mut self) -> Result { + if let Some(exit_status) = self.exit_status { + return Ok(exit_status); + } + + let exit_status = self + .rx_exited + .as_mut() + .ok_or_eyre("missing exit status receiver")? + .await + .wrap_err("channel closed")?; + self.rx_exited = None; + self.exit_status = Some(exit_status); + Ok(exit_status) + } + + async fn kill(&mut self) -> Result<()> { + self.flatpak_portal + .spawn_signal(self.flatpak_pid, SIGKILL as u32, true) + .await + .wrap_err("sending SIGKILL to child process") + } +} diff --git a/packages/modrinth-sandbox/src/backend/linux.rs b/packages/modrinth-sandbox/src/backend/linux.rs new file mode 100644 index 00000000000..0378694ad95 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/linux.rs @@ -0,0 +1,136 @@ +use std::{ + ffi::CStr, + os::fd::{AsRawFd, FromRawFd, OwnedFd}, +}; + +use crate::backend::unix::cvt; + +use std::{ + env, + ffi::OsStr, + path::{Path, PathBuf}, +}; + +use eyre::{ContextCompat, Result, eyre}; +use tokio::fs; + +pub async fn find_command( + command: &(impl AsRef + ?Sized), +) -> Result { + find_command_(command.as_ref()).await +} + +async fn find_command_(command: &OsStr) -> Result { + let path = env::var_os("PATH").wrap_err("missing `PATH`")?; + for mut path in env::split_paths(&path) { + if !path.is_absolute() { + continue; + } + path.push(command); + if fs::try_exists(&path).await.unwrap_or(false) { + return Ok(path); + } + } + + Err(eyre!("command not found in `PATH`")) +} + +pub struct WritableMemoryFile { + fd: OwnedFd, +} + +impl WritableMemoryFile { + pub fn open(name: &CStr) -> eyre::Result { + let fd = unsafe { + OwnedFd::from_raw_fd(cvt(libc::memfd_create( + name.as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ))?) + }; + Ok(Self { fd }) + } + + pub fn write_filter( + mut self, + filter: libseccomp::ScmpFilterContext, + ) -> eyre::Result { + filter.export_bpf(&self.fd)?; + self.reset_and_seal()?; + Ok(self.fd) + } + + pub fn write(mut self, data: &CStr) -> eyre::Result { + unsafe { + let fd = self.fd.as_raw_fd(); + cvt(libc::write( + fd, + data.as_ptr().cast(), + data.count_bytes() as libc::size_t, + ))?; + self.reset_and_seal()?; + } + Ok(self.fd) + } + + fn reset_and_seal(&mut self) -> eyre::Result<()> { + unsafe { + let fd = self.fd.as_raw_fd(); + libc::lseek(fd, 0, libc::SEEK_SET); + cvt(libc::fcntl( + fd, + libc::F_ADD_SEALS, + libc::F_SEAL_SEAL + | libc::F_SEAL_SHRINK + | libc::F_SEAL_GROW + | libc::F_SEAL_WRITE, + ))?; + } + Ok(()) + } +} + +pub fn open_pipe() -> eyre::Result<(OwnedFd, OwnedFd)> { + let mut fds = [0, 0]; + unsafe { + super::unix::cvt(libc::pipe2(&raw mut fds as *mut _, libc::O_CLOEXEC))?; + Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) + } +} + +pub async fn ensure_valid_command( + command: &crate::SandboxCommand, +) -> Result<()> { + for path in command + .ensure_dirs_exist + .iter() + .chain(&command.read_only_paths) + .chain(&command.read_write_paths) + .chain(std::iter::once(&command.executable)) + .chain(command.working_directory.iter()) + { + ensure_exposable_path(path).await?; + } + Ok(()) +} + +async fn ensure_exposable_path(path: &Path) -> Result<()> { + let check = |path: &Path| { + eyre::ensure!( + !path.starts_with("/tmp"), + "cannot expose {}: Flatpak's private /tmp cannot be exposed through the host portal; use a persistent or cache directory instead", + path.display() + ); + Ok(()) + }; + check(path)?; + for ancestor in path.ancestors() { + match tokio::fs::canonicalize(ancestor).await { + Ok(canonical) => return check(&canonical), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + continue; + } + Err(_) => break, + } + } + Ok(()) +} diff --git a/packages/modrinth-sandbox/src/backend/macos/mod.rs b/packages/modrinth-sandbox/src/backend/macos/mod.rs new file mode 100644 index 00000000000..48310bc5152 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/macos/mod.rs @@ -0,0 +1,463 @@ +use std::{ + ffi::{CString, OsString}, + os::unix::ffi::OsStringExt, + path::{Path, PathBuf}, + sync::Arc, +}; + +use async_trait::async_trait; +use derive_more::Debug; +use eyre::{Context, OptionExt, Result}; + +use crate::{ + ExposedPath, SandboxCommand, SandboxExitStatus, + backend::{ + Backend, SandboxChild, SandboxChildOp, SandboxEnv, SandboxHandleOp, + pathset::ReadWritePathSet, + unix::{self, UnixChild}, + }, + util::{RawStringVec, resolve_path}, +}; + +use super::SandboxHandle; + +#[derive(Debug)] +pub struct Macos; + +#[async_trait] +impl Backend for Macos { + async fn init( + _make_helper: crate::helper::MakeHelper, + ) -> Result> { + let dev_null = + super::unix::open_dev_null().wrap_err("opening /dev/null")?; + Ok(Box::new(MacosEnv { dev_null })) + } +} + +#[derive(Debug, Clone)] +#[debug("MacosEnv")] +pub struct MacosEnv { + dev_null: libc::c_int, +} + +#[async_trait] +impl SandboxEnv for MacosEnv { + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result { + let env = self.clone(); + crate::backend::run_on_spawn_thread(move || spawn(&env, command)) + .await? + } +} + +fn spawn( + env: &MacosEnv, + mut command: SandboxCommand, +) -> Result { + let resolved_executable = resolve_path(&command.executable)?; + + let temp_root = confstr(libc::_CS_DARWIN_USER_TEMP_DIR) + .map(OsString::from_vec) + .map(PathBuf::from) + .ok_or_eyre("macOS user temporary directory is unavailable")? + .canonicalize() + .wrap_err("resolving macOS user temporary directory")?; + let temp_dir = tempfile::Builder::new() + .prefix("modrinth-sandbox-") + .tempdir_in(&temp_root) + .wrap_err("creating sandbox temporary directory")?; + + let temp_path = temp_dir.path().to_path_buf(); + command.read_write_paths.push(temp_path.clone()); + + command + .extra_environment + .insert("TMPDIR".into(), temp_path.clone().into()); + if command.is_jvm { + let mut java_temp_argument = OsString::from("-Djava.io.tmpdir="); + java_temp_argument.push(&temp_path); + command.args.insert(0, java_temp_argument.into()); + } + + let environment = command.take_environment(); + let home = + std::env::var_os("HOME").ok_or_eyre("`HOME` not set in environment")?; + let mut sandbox_profile = SandboxProfile::new(home); + + if command.allow_network { + sandbox_profile.push(NETWORK); + } + + if command.is_jvm { + sandbox_profile.push("(allow file-write* file-read* (prefix "); + sandbox_profile + .push_path(temp_root.join("hsperfdata_").into_os_string()); + sandbox_profile.push("))\n"); + + let cache_root = confstr(libc::_CS_DARWIN_USER_CACHE_DIR) + .map(OsString::from_vec) + .map(PathBuf::from) + .ok_or_eyre("macOS user cache directory is unavailable")? + .canonicalize() + .wrap_err("resolving macOS user cache directory")?; + sandbox_profile.push("(allow file-write* file-read* file-map-executable process-exec (subpath "); + sandbox_profile.push_path( + cache_root.join("net.java.openjdk.java").into_os_string(), + ); + sandbox_profile.push("))\n"); + } + + for path in &command.ensure_dirs_exist { + std::fs::create_dir_all(path) + .wrap_err_with(|| format!("creating directory {path:?}"))?; + } + + let path_set = command.take_paths()?; + for path in path_set.iter_read_only() { + sandbox_profile.allow_read(path); + } + for path in path_set.iter_read_write() { + sandbox_profile.allow_read_write(path); + } + + sandbox_profile.push(PROTECT); + + let (sandbox_profile, sandbox_params) = sandbox_profile.finish()?; + + let (pipes, child) = unix::spawn( + resolved_executable.into(), + command.args, + environment, + command.stdin, + command.stdout, + command.stderr, + command.working_directory, + Vec::new(), + env.dev_null, + false, + sandbox_profile, + sandbox_params, + ) + .wrap_err("spawning child")?; + + let mut child = crate::SandboxChild { + stdin: pipes.stdin, + stdout: pipes.stdout, + stderr: pipes.stderr, + on_finish: command.on_finish, + handle: SandboxHandle::Macos(MacosSandboxHandle { + path_set: Arc::new(path_set), + }), + imp: SandboxChild::Macos(MacosChild { + child, + _temp_dir: temp_dir, + }), + }; + + for on_start in command.on_start { + (on_start)(&mut child); + } + + Ok(child) +} + +#[derive(Debug)] +pub struct MacosChild { + child: UnixChild, + _temp_dir: tempfile::TempDir, +} + +#[async_trait] +impl SandboxChildOp for MacosChild { + fn id(&self) -> Option { + self.child.id() + } + + fn try_wait(&mut self) -> Result> { + self.child.try_wait() + } + + async fn wait(&mut self) -> Result { + self.child.wait().await + } + + async fn kill(&mut self) -> Result<()> { + self.child.kill().await + } +} + +#[derive(Clone, Debug)] +pub struct MacosSandboxHandle { + path_set: Arc, +} + +impl SandboxHandleOp for MacosSandboxHandle { + fn expose_path( + &self, + _path: &Path, + _allow_write: bool, + ) -> eyre::Result { + Err(eyre::eyre!("unsupported")) + } + + fn is_path_readable(&self, path: &Path) -> bool { + self.path_set.can_read(path.to_path_buf()) + } + + fn is_path_writeable(&self, path: &Path) -> bool { + self.path_set.can_write(path.to_path_buf()) + } +} + +fn confstr(name: libc::c_int) -> Option> { + let size = unsafe { libc::confstr(name, std::ptr::null_mut(), 0) }; + if size == 0 { + return None; + } + + let mut buf = vec![0_u8; size]; + let new_size = + unsafe { libc::confstr(name, buf.as_mut_ptr().cast(), size) }; + assert_eq!(size, new_size); + buf.truncate(size - 1); + Some(buf) +} + +struct SandboxProfile { + profile: OsString, + params: Vec<(OsString, OsString)>, +} + +impl SandboxProfile { + fn new(home: OsString) -> Self { + Self { + profile: OsString::from(BASE_PROFILE), + params: vec![("HOME".into(), home)], + } + } + + fn push(&mut self, text: &str) { + self.profile.push(text); + } + + fn push_path(&mut self, path: OsString) { + let name = format!("PATH_{}", self.params.len()); + self.profile.push("(param \""); + self.profile.push(&name); + self.profile.push("\")"); + self.params.push((name.into(), path)); + } + + fn allow_read(&mut self, path: &Path) { + let Ok(path) = path.canonicalize() else { + return; + }; + if path.is_dir() { + self.push("(allow file-read* file-map-executable process-exec file-issue-extension (subpath "); + } else { + self.push("(allow file-read* file-map-executable process-exec file-issue-extension (literal "); + } + self.push_path(path.into_os_string()); + self.push("))\n"); + } + + fn allow_read_write(&mut self, path: &Path) { + let Ok(path) = path.canonicalize() else { + return; + }; + if path.is_dir() { + self.push("(allow file-write* file-link file-read* file-map-executable process-exec file-issue-extension (subpath "); + } else { + self.push("(allow file-write* file-read* file-map-executable process-exec file-issue-extension (literal "); + } + self.push_path(path.into_os_string()); + self.push("))\n"); + } + + fn finish(self) -> Result<(CString, RawStringVec)> { + let profile = CString::new(self.profile.into_encoded_bytes()) + .wrap_err("converting sandbox profile to C-string")?; + + let mut params = RawStringVec::with_capacity(self.params.len() * 2); + for (name, value) in self.params { + params.push_os(name)?; + params + .push_os(value) + .wrap_err("sandbox path contained a null byte")?; + } + + Ok((profile, params)) + } +} + +// View debug logs with `log stream --style compact --predicate 'eventMessage CONTAINS "Sandbox: "` + +static BASE_PROFILE: &str = r#" +(version 1) +(deny default) +(import "system.sb") + +; Debugging +; (debug deny) + +; Defines +(define (home path) + (string-append (param "HOME") path)) + +; Basic rules +(deny nvram*) +(deny process-info*) +(deny file-link) +(allow hid-control process-fork lsopen) +(allow signal (target same-sandbox)) +(allow process-info-pidinfo) +(allow + process-info-pidfdinfo + process-info-pidfileportinfo + process-info-setcontrol + process-info-dirtycontrol + process-info-rusage + process-info-ledger + (target self)) +(allow sysctl-write (sysctl-name "kern.tcsm_enable")) + +(system-graphics) + +; Allow any symlink to be resolved +(allow file-read-metadata) + +; Allow reading some system files +(allow file-read* + (literal "/private/etc/hosts") + (literal "/private/etc/passwd") + (literal "/private/etc/resolv.conf") + (literal "/private/etc/ssl/cert.pem") + (literal "/private/etc/ssl/openssl.cnf") + (literal "/private/var/run/resolv.conf") + (subpath (home "/Library/Audio")) + (subpath "/Library/Audio/Plug-Ins") + (literal (home "/.CFUserTextEncoding"))) +(allow file-read* process-exec + (subpath "/bin") + (subpath "/sbin") + (subpath "/usr/bin") + (subpath "/usr/sbin")) +(allow file-read* file-write* + (subpath "/dev/fd")) + +(allow user-preference-read + (preference-domain + "com.apple.MobileAsset" + "com.apple.HIToolbox" + "kcfpreferencesanyapplication" + "net.java.openjdk.java" + ; Text-to-speech + "com.apple.accessibility" + "com.apple.universalaccess" + "com.apple.speech.recognition.applespeechrecognition.prefs" + "com.apple.speakselection" + "com.apple.voiceservices" + "com.apple.assistant.backedup" + "com.apple.speech.voice.prefs")) + +(allow mach-lookup + ; Core + (global-name "com.apple.CoreServices.coreservicesd") + (global-name "com.apple.coreservices.appleevents") + (global-name "com.apple.coreservices.launchservicesd") + (global-name "com.apple.coreservices.quarantine-resolver") + (global-name "com.apple.DiskArbitration.diskarbitrationd") + (global-name "com.apple.pasteboard.1") + (global-name "com.apple.pbs.fetch_services") + (global-name "com.apple.spindump") + (global-name "com.apple.mobileassetd") + (global-name "com.apple.mobileassetd.v2") + (global-name "com.apple.distributed_notifications@1v3") + (global-name "com.apple.distributed_notifications@Uv3") + (global-name "com.apple.SystemConfiguration.configd") + (global-name "com.apple.uiintelligencesupport.agent") + (global-name "com.apple.pluginkit.pkd") + ; TCCD (Popup for microphone, webcam, etc.) + (global-name "com.apple.tccd") + (global-name "com.apple.tccd.system") + ; Input + (global-name "com.apple.tsm.uiserver") + (global-name "com.apple.inputanalyticsd") + (global-name "com.apple.inputmethodkit.launchagent") + (global-name "com.apple.inputmethodkit.launcher") + (global-name "com.apple.inputmethodkit.getxpcendpoint") + (global-name "com.apple.iohideventsystem") + (global-name "com.apple.touchbarserver.mig") + ; Windowing + (global-name "com.apple.windowmanager.server") + (global-name "com.apple.windowserver.active") + (global-name "com.apple.window_proxies") + (global-name "com.apple.dock.server") + (global-name "com.apple.dock.fullscreen") + ; Fonts + (global-name "com.apple.fonts") + (global-name "com.apple.FontObjectsServer") + ; Audio + (global-name "com.apple.audio.AudioComponentPrefs") + (global-name "com.apple.audio.AudioComponentRegistrar") + (global-name "com.apple.audio.AudioSession") + (global-name "com.apple.audio.audiohald") + (global-name "com.apple.audio.coreaudiod") + (global-name "com.apple.audioanalyticsd")) + +; Audio Input/Output +(allow device-microphone) +(allow iokit-open-user-client + (require-all + (iokit-connection "AppleHDAEngineInput") + (iokit-user-client-class + "IOAudioControlUserClient" + "IOAudioEngineUserClient"))) +(allow mach-lookup + (xpc-service-name "com.apple.audio.AudioConverterService") + (global-name "com.apple.cmio.registerassistantservice.system-extensions") + (global-name "com.apple.relatived.public") + (global-name "com.apple.relatived.status") + (global-name "com.apple.relatived.tempest")) +"#; + +static PROTECT: &str = r#" +(deny network-outbound (literal "/private/var/run/cupsd")) +(deny network-outbound (remote ip "localhost:631")) +(deny file-write-xattr (xattr "com.apple.quarantine") (with no-log)) +(deny file-read-xattr file-write-xattr (xattr-prefix "com.apple.security.private.")) +"#; + +static NETWORK: &str = r#" +(system-network) +(allow network-outbound (literal "/private/var/run/mDNSResponder")) +(allow network-outbound (remote ip)) +(allow network-inbound (local ip)) +(allow mach-lookup + (global-name + "com.apple.NetworkDiagnostic.agent" + "com.apple.WebKit.PluginAgent" + "com.apple.airportd" + "com.apple.cfnetwork.AuthBrokerAgent" + "com.apple.cfnetwork.cfnetworkagent" + "com.apple.corewlan-xpc" + "com.apple.nesessionmanager.content-filter" + "com.apple.networkserviceproxy.fetch-token" + "com.apple.nsurlsessiond")) +"#; + +// static ALLOWED_ENV_VARS: Lazy> = Lazy::new(|| { +// [ +// "TMPDIR", "PATH", "HOME", "LANG", "LC_ALL", "TERM", "USER", "USERNAME", +// ] +// .iter() +// .map(OsStr::new) +// .collect() +// }); + +// pub fn should_pass_env_var(var: &OsStr) -> bool { +// return ALLOWED_ENV_VARS.contains(var); +// } diff --git a/packages/modrinth-sandbox/src/backend/mod.rs b/packages/modrinth-sandbox/src/backend/mod.rs new file mode 100644 index 00000000000..a602fa9e781 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/mod.rs @@ -0,0 +1,290 @@ +//! Backend sandbox implementations, using OS-specific primitives. + +use std::{ + collections::{BTreeMap, HashSet}, + ffi::OsString, + fmt::Debug, + path::Path, + sync::OnceLock, +}; + +use async_trait::async_trait; +use enum_dispatch::enum_dispatch; +use eyre::{Context, Result}; + +use crate::{ + ExposedPath, SandboxCommand, + backend::pathset::ReadWritePathSet, + helper::MakeHelper, + util::{SandboxArg, resolve_path}, +}; + +#[cfg(target_os = "linux")] +mod bubblewrap; +#[cfg(target_os = "linux")] +mod flatpak; +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +pub mod noop; +pub(super) mod pathset; +#[cfg(unix)] +mod unix; +#[cfg(windows)] +mod windows; + +/// See [`crate::SandboxEnv::new`]. +#[async_trait] +pub trait Backend { + /// See [`crate::SandboxEnv::new`]. + async fn init(make_helper: MakeHelper) -> Result>; +} + +/// See [`crate::SandboxEnv`]. +#[async_trait] +pub trait SandboxEnv: Debug + Send + Sync { + /// See [`crate::SandboxEnv::spawn`]. + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result; +} + +/// See [`crate::SandboxEnv::new`]. +pub async fn create_env( + make_helper: MakeHelper, +) -> Result> { + #[cfg(target_os = "linux")] + { + const FLATPAK_INFO_PATH: &str = "/.flatpak-info"; + + if tokio::fs::try_exists(FLATPAK_INFO_PATH) + .await + .map_err(|err| { + eyre::eyre!(err) + .wrap_err("checking if `{FLATPAK_INFO_PATH}` exists") + })? + { + flatpak::Flatpak::init(make_helper).await + } else { + bubblewrap::Bubblewrap::init(make_helper).await + } + } + + #[cfg(target_os = "macos")] + { + return macos::Macos::init(make_helper).await; + } + + #[cfg(windows)] + { + return windows::appcontainer::AppContainer::init(make_helper).await; + } +} + +impl SandboxCommand { + pub(crate) fn take_paths(&mut self) -> eyre::Result { + let mut read_only_paths = std::mem::take(&mut self.read_only_paths); + let read_write_paths = std::mem::take(&mut self.read_write_paths); + + read_only_paths.push(resolve_path(&self.executable)?); + if let Some(working) = self.working_directory.clone() { + read_only_paths.push(working); + } + + Ok(ReadWritePathSet::from_vecs( + read_only_paths, + read_write_paths, + )) + } + + pub(crate) fn take_environment( + &mut self, + ) -> BTreeMap { + let mut passthrough_upper = + std::mem::take(&mut self.passthrough_environment) + .into_iter() + .map(|k| { + let mut k = k.into_os_string(); + k.make_ascii_uppercase(); + k + }) + .collect::>(); + + if cfg!(windows) { + passthrough_upper.insert("APPDATA".into()); + passthrough_upper.insert("LOCALAPPDATA".into()); + } + + if !passthrough_upper.is_empty() { + let ignore_overrides_upper = self + .extra_environment + .keys() + .map(|k| k.as_os_str().to_ascii_uppercase()) + .collect::>(); + + for (k, v) in std::env::vars_os() { + let upper_k = k.to_ascii_uppercase(); + if ignore_overrides_upper.contains(&upper_k) { + continue; + } + if !passthrough_upper.contains(&upper_k) { + continue; + } + + self.extra_environment.insert(k.into(), v.into()); + } + } + + std::mem::take(&mut self.extra_environment) + } +} + +#[derive(Debug)] +pub struct Pipes { + pub stdin: Option, + pub stdout: Option, + pub stderr: Option, +} + +#[async_trait] +#[enum_dispatch] +pub trait SandboxChildOp { + fn id(&self) -> Option; + fn try_wait(&mut self) -> Result>; + async fn wait(&mut self) -> Result; + async fn kill(&mut self) -> Result<()>; +} + +#[derive(Debug)] +#[enum_dispatch(SandboxChildOp)] +pub enum SandboxChild { + Noop(noop::StdChild), + #[cfg(target_os = "linux")] + Flatpak(flatpak::FlatpakChild), + #[cfg(target_os = "linux")] + Bubblewrap(bubblewrap::BubblewrapChild), + #[cfg(target_os = "macos")] + Macos(macos::MacosChild), + #[cfg(target_os = "windows")] + AppContainer(windows::WindowsChild), +} + +/// Describes the result of a process after it has terminated. +/// +/// This is analogous to [`std::process::ExitStatus`]. +#[derive(Default, Debug, Clone, Copy)] +pub struct SandboxExitStatus { + #[cfg(unix)] + imp: unix::UnixSandboxExitStatus, + #[cfg(windows)] + imp: windows::WindowsSandboxExitStatus, +} + +impl SandboxExitStatus { + /// Was termination successful? Signal termination is not considered a + /// success, and success is defined as a zero exit status. + /// + /// This is analogous to [`std::process::ExitStatus::success`]. + pub fn success(&self) -> bool { + self.imp.success() + } + + /// Returns the exit code of the process, if any. + /// + /// This is analogous to [`std::process::ExitStatus::code`]. + pub fn code(&self) -> Option { + self.imp.code() + } +} + +impl std::fmt::Display for SandboxExitStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&self.imp, f) + } +} + +#[enum_dispatch] +pub trait SandboxHandleOp { + fn expose_path( + &self, + path: &Path, + allow_write: bool, + ) -> eyre::Result; + fn is_path_readable(&self, path: &Path) -> bool; + fn is_path_writeable(&self, path: &Path) -> bool; +} + +#[derive(Clone, Debug)] +#[enum_dispatch(SandboxHandleOp)] +pub enum SandboxHandle { + Noop(noop::NoopSandboxHandle), + #[cfg(target_os = "linux")] + Flatpak(flatpak::FlatpakSandboxHandle), + #[cfg(target_os = "linux")] + Bubblewrap(bubblewrap::BubblewrapSandboxHandle), + #[cfg(target_os = "macos")] + Macos(macos::MacosSandboxHandle), + #[cfg(target_os = "windows")] + AppContainer(windows::WindowsSandboxHandle), +} + +pub fn run_helper(args: impl IntoIterator) -> Result { + #[cfg(windows)] + { + windows::appcontainer::run_helper(args) + } + #[cfg(not(windows))] + { + drop(args); + Ok(false) + } +} + +/// We use our own thread for spawning commands instead of tokio::spawn_blocking since +/// tokio::spawn_blocking threads can die after inactivity which can trigger PR_SET_PDEATHSIG. +/// On Windows the thread has COM initialized, so it is also used for shell calls like ShellExecuteExW. +pub async fn run_on_spawn_thread( + run: impl FnOnce() -> T + Send + 'static, +) -> Result { + let (sender, receiver) = tokio::sync::oneshot::channel(); + + type SpawnTask = Box; + + static SPAWNING_CHANNEL: OnceLock> = + OnceLock::new(); + let channel = SPAWNING_CHANNEL.get_or_init(|| { + let (send, recv) = std::sync::mpsc::channel::(); + + std::thread::Builder::new() + .name("Modrinth Sandbox Command Spawner".to_string()) + .spawn(|| { + #[cfg(windows)] + unsafe { + use ::windows::Win32::System::Com::{ + COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, + CoInitializeEx, + }; + _ = CoInitializeEx( + None, + COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE, + ); + } + + for task in recv { + task(); + } + }) + .unwrap(); + + send + }); + channel + .send(Box::new(move || { + _ = sender.send(run()); + })) + .unwrap(); + + receiver.await.context("spawn task dropped") +} diff --git a/packages/modrinth-sandbox/src/backend/noop.rs b/packages/modrinth-sandbox/src/backend/noop.rs new file mode 100644 index 00000000000..c165c92a4bf --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/noop.rs @@ -0,0 +1,263 @@ +use std::{ + io::{PipeReader, PipeWriter}, + path::Path, + process::Stdio, +}; + +use async_trait::async_trait; +use eyre::{Context, Result, eyre}; + +use crate::{ + SandboxCommand, SandboxExitStatus, SandboxStdio, + backend::{ + Backend, ExposedPath, SandboxChildOp, SandboxEnv, SandboxHandleOp, + }, +}; + +use super::SandboxHandle; + +#[derive(Debug)] +pub struct NoSandbox; + +#[async_trait] +impl Backend for NoSandbox { + async fn init( + _make_helper: crate::helper::MakeHelper, + ) -> Result> { + Ok(Box::new(Self)) + } +} + +#[async_trait] +impl SandboxEnv for NoSandbox { + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result { + spawn(command).await + } +} + +async fn spawn(mut command: SandboxCommand) -> Result { + for directory in &command.ensure_dirs_exist { + tokio::fs::create_dir_all(directory) + .await + .wrap_err_with(|| eyre!("creating directory {directory:?}"))?; + } + + let environment = command.take_environment(); + let mut builder = tokio::process::Command::new(&command.executable); + builder.args(command.args.iter().map(|arg| arg.as_os_str())); + builder.env_clear(); + builder.envs( + environment + .iter() + .map(|(key, value)| (key.as_os_str(), value.as_os_str())), + ); + if let Some(directory) = command.working_directory { + builder.current_dir(directory); + } + + let (stdin, stdin_writer) = input_stdio(command.stdin)?; + let (stdout, stdout_reader) = output_stdio(command.stdout)?; + let (stderr, stderr_reader) = output_stdio(command.stderr)?; + builder.stdin(stdin).stdout(stdout).stderr(stderr); + let child = builder.spawn().wrap_err("spawning unsandboxed process")?; + // Command retains the child-side pipe handles after spawning. + drop(builder); + + let mut child = crate::SandboxChild { + stdin: stdin_writer, + stdout: stdout_reader, + stderr: stderr_reader, + on_finish: command.on_finish, + handle: SandboxHandle::Noop(NoopSandboxHandle), + imp: super::SandboxChild::Noop(StdChild { child }), + }; + + for on_start in command.on_start { + (on_start)(&mut child); + } + + Ok(child) +} + +fn input_stdio(mode: SandboxStdio) -> Result<(Stdio, Option)> { + match mode { + SandboxStdio::Null => Ok((Stdio::null(), None)), + SandboxStdio::Inherit => Ok((Stdio::inherit(), None)), + SandboxStdio::Pipe => { + let (reader, writer) = + std::io::pipe().wrap_err("creating unsandboxed stdin pipe")?; + Ok((reader.into(), Some(writer))) + } + } +} + +fn output_stdio(mode: SandboxStdio) -> Result<(Stdio, Option)> { + match mode { + SandboxStdio::Null => Ok((Stdio::null(), None)), + SandboxStdio::Inherit => Ok((Stdio::inherit(), None)), + SandboxStdio::Pipe => { + let (reader, writer) = + std::io::pipe().wrap_err("creating unsandboxed output pipe")?; + Ok((writer.into(), Some(reader))) + } + } +} + +#[derive(Debug)] +pub struct StdChild { + child: tokio::process::Child, +} + +#[async_trait] +impl SandboxChildOp for StdChild { + fn id(&self) -> Option { + self.child.id() + } + + fn try_wait(&mut self) -> Result> { + self.child + .try_wait() + .map(|status| status.map(sandbox_exit_status)) + .wrap_err("checking unsandboxed child status") + } + + async fn wait(&mut self) -> Result { + self.child + .wait() + .await + .map(sandbox_exit_status) + .wrap_err("waiting for unsandboxed child") + } + + async fn kill(&mut self) -> Result<()> { + if self.child.try_wait()?.is_some() { + return Ok(()); + } + self.child + .kill() + .await + .wrap_err("killing unsandboxed child") + } +} + +fn sandbox_exit_status(status: std::process::ExitStatus) -> SandboxExitStatus { + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + + SandboxExitStatus { + imp: super::unix::UnixSandboxExitStatus(status.into_raw()), + } + } + #[cfg(windows)] + { + SandboxExitStatus { + imp: super::windows::WindowsSandboxExitStatus( + status + .code() + .expect("Windows exit status always has a code") + as u32, + ), + } + } +} + +#[derive(Clone, Debug)] +pub struct NoopSandboxHandle; + +impl SandboxHandleOp for NoopSandboxHandle { + fn expose_path( + &self, + _path: &Path, + _allow_write: bool, + ) -> eyre::Result { + Ok(ExposedPath::Direct) + } + + fn is_path_readable(&self, _path: &Path) -> bool { + true + } + + fn is_path_writeable(&self, _path: &Path) -> bool { + true + } +} + +#[cfg(all(test, unix))] +mod tests { + use std::{ + collections::{BTreeMap, BTreeSet}, + io::{Read, Write}, + }; + + use super::*; + + fn command(script: &'static str) -> SandboxCommand { + SandboxCommand { + executable: "/bin/sh".into(), + args: vec!["-c".into(), script.into()], + ensure_dirs_exist: Vec::new(), + read_only_paths: Vec::new(), + read_write_paths: Vec::new(), + working_directory: None, + passthrough_environment: BTreeSet::new(), + extra_environment: BTreeMap::new(), + allow_network: false, + is_jvm: false, + die_with_parent: false, + stdin: SandboxStdio::Pipe, + stdout: SandboxStdio::Pipe, + stderr: SandboxStdio::Pipe, + app_container_name: "test".into(), + app_container_description: "test".into(), + on_start: Vec::new(), + on_finish: Vec::new(), + } + } + + #[tokio::test] + async fn forwards_pipes_and_environment() -> Result<()> { + let mut command = command( + "IFS= read -r line; printf '%s:%s' \"$TEST_VALUE\" \"$line\"; printf error >&2; exit 7", + ); + command + .extra_environment + .insert("TEST_VALUE".into(), "value".into()); + let mut child = NoSandbox.spawn(command).await?; + assert!(child.id().is_some()); + child.stdin.take().unwrap().write_all(b"input\n")?; + let status = child.wait().await?; + assert_eq!(status.code(), Some(7)); + assert!(!status.success()); + assert_eq!(child.wait().await?.code(), Some(7)); + assert_eq!(child.try_wait()?.unwrap().code(), Some(7)); + child.kill().await?; + let mut stdout = String::new(); + child.stdout.take().unwrap().read_to_string(&mut stdout)?; + assert_eq!(stdout, "value:input"); + let mut stderr = String::new(); + child.stderr.take().unwrap().read_to_string(&mut stderr)?; + assert_eq!(stderr, "error"); + Ok(()) + } + + #[tokio::test] + async fn kills_running_child() -> Result<()> { + let mut child = NoSandbox.spawn(command("while :; do :; done")).await?; + assert!(child.try_wait()?.is_none()); + child.kill().await?; + assert!(!child.wait().await?.success()); + child.kill().await?; + Ok(()) + } + + #[tokio::test] + async fn reports_spawn_failure() { + let mut command = command(""); + command.executable = "/nonexistent/modrinth-sandbox-noop".into(); + assert!(NoSandbox.spawn(command).await.is_err()); + } +} diff --git a/packages/modrinth-sandbox/src/backend/pathset.rs b/packages/modrinth-sandbox/src/backend/pathset.rs new file mode 100644 index 00000000000..fd86c0ac2cb --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/pathset.rs @@ -0,0 +1,227 @@ +use std::path::PathBuf; + +#[derive(Debug, Default)] +pub struct PathSet { + paths: Vec, +} + +#[derive(Debug, Default)] +pub struct ReadWritePathSet { + readable: PathSet, + writeable: PathSet, +} + +impl PathSet { + pub fn insert(&mut self, path: PathBuf) -> bool { + #[cfg(windows)] + let path = normalize_path(path); + + match self.paths.binary_search(&path) { + Ok(_) => false, + Err(index) => { + if index > 0 && path.starts_with(&self.paths[index - 1]) { + return false; + } + + while index < self.paths.len() { + let potential_child = &self.paths[index]; + if potential_child.starts_with(&path) { + self.paths.remove(index); + } else { + break; + } + } + + self.paths.insert(index, path); + true + } + } + } + + pub fn contains(&self, path: PathBuf) -> bool { + #[cfg(windows)] + let path = normalize_path(path); + + match self.paths.binary_search(&path) { + Ok(_) => true, + Err(index) => index > 0 && path.starts_with(&self.paths[index - 1]), + } + } + + pub fn iter(&self) -> impl Iterator { + self.paths.iter() + } +} + +impl ReadWritePathSet { + pub fn from_vecs( + mut read_only: Vec, + mut read_write: Vec, + ) -> Self { + let mut set = Self::default(); + + read_write.sort(); + read_write.dedup(); + for path in read_write { + set.insert_writeable(path); + } + + read_only.sort(); + read_only.dedup(); + for path in read_only { + set.insert_readable(path); + } + + set + } + + pub fn insert_readable(&mut self, path: PathBuf) -> bool { + self.readable.insert(path) + } + + pub fn insert_writeable(&mut self, path: PathBuf) -> bool { + self.readable.insert(path.clone()); + self.writeable.insert(path) + } + + pub fn can_read(&self, path: PathBuf) -> bool { + self.readable.contains(path) + } + + pub fn can_write(&self, path: PathBuf) -> bool { + self.writeable.contains(path) + } + + #[cfg_attr(not(windows), allow(unused))] + pub fn iter_both(&self) -> impl Iterator { + self.readable.paths.iter() + } + + pub fn iter_read_only(&self) -> impl Iterator { + self.readable + .paths + .iter() + .filter(|path| !self.writeable.contains(path.to_path_buf())) + } + + pub fn iter_read_write(&self) -> impl Iterator { + self.writeable.paths.iter() + } +} + +#[cfg(windows)] +fn normalize_path(path: PathBuf) -> PathBuf { + let mut os_string = path.into_os_string(); + os_string.make_ascii_lowercase(); + + let encoded_bytes = os_string.as_os_str().as_encoded_bytes(); + if let Some(rest) = encoded_bytes.strip_prefix(b"\\\\?\\") { + return PathBuf::from(unsafe { + std::ffi::OsStr::from_encoded_bytes_unchecked(rest) + }); + } + + PathBuf::from(os_string) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn set(read_only: &[&str], read_write: &[&str]) -> ReadWritePathSet { + ReadWritePathSet::from_vecs( + read_only.iter().map(PathBuf::from).collect(), + read_write.iter().map(PathBuf::from).collect(), + ) + } + + fn paths<'a>(iter: impl Iterator) -> Vec { + iter.cloned().collect() + } + + #[test] + fn children_resolve_against_parent() { + let set = set(&["/jre"], &["/inst"]); + + assert!(set.can_read("/inst".into())); + assert!(set.can_write("/inst".into())); + assert!(set.can_read("/inst/saves/world".into())); + assert!(set.can_write("/inst/saves/world".into())); + + assert!(set.can_read("/jre".into())); + assert!(set.can_read("/jre/bin/java".into())); + assert!(!set.can_write("/jre".into())); + assert!(!set.can_write("/jre/bin/java".into())); + } + + #[test] + fn unrelated_and_partial_name_matches_are_rejected() { + let set = set(&["/jre"], &["/inst"]); + + for path in ["/", "/in", "/instance", "/inst-2/file", "/zzz", "/aaa"] { + assert!(!set.can_read(path.into()), "{path} should be unreadable"); + assert!( + !set.can_write(path.into()), + "{path} should be unwriteable" + ); + } + } + + #[test] + fn sibling_sorting_between_parent_and_child_does_not_hide_parent() { + let set = set(&["/a-b"], &["/a"]); + + assert!(set.can_write("/a/x".into())); + assert!(set.can_read("/a-b/x".into())); + assert!(!set.can_write("/a-b/x".into())); + assert!(!set.can_read("/a-c".into())); + } + + #[test] + fn read_only_child_of_writeable_parent_is_writeable() { + let set = set(&["/inst/mods"], &["/inst"]); + + assert!(set.can_write("/inst/mods/mod.jar".into())); + assert!(set.can_write("/inst/saves".into())); + assert_eq!(paths(set.iter_read_only()), Vec::::new()); + assert_eq!(paths(set.iter_read_write()), [PathBuf::from("/inst")]); + assert_eq!(paths(set.iter_both()), [PathBuf::from("/inst")]); + } + + #[test] + fn writeable_child_of_read_only_parent_stays_writeable() { + let set = set(&["/ro"], &["/ro/rw"]); + + assert!(set.can_read("/ro/file".into())); + assert!(!set.can_write("/ro/file".into())); + assert!(set.can_read("/ro/rw/file".into())); + assert!(set.can_write("/ro/rw/file".into())); + assert_eq!(paths(set.iter_read_only()), [PathBuf::from("/ro")]); + assert_eq!(paths(set.iter_read_write()), [PathBuf::from("/ro/rw")]); + } + + #[test] + fn insert_drops_nested_and_duplicate_entries() { + let mut set = PathSet::default(); + + assert!(set.insert("/a/b".into())); + assert!(set.insert("/a/c".into())); + assert!(!set.insert("/a/b".into())); + assert!(!set.insert("/a/b/deeper".into())); + + assert!(set.insert("/a".into())); + assert_eq!(set.paths, [PathBuf::from("/a")]); + + assert!(!set.insert("/a/d".into())); + assert!(set.contains("/a/b".into())); + assert!(set.contains("/a/d".into())); + } + + #[test] + fn empty_set_contains_nothing() { + let set = ReadWritePathSet::default(); + + assert!(!set.can_read("/".into())); + assert!(!set.can_write("/anything".into())); + } +} diff --git a/packages/modrinth-sandbox/src/backend/unix.rs b/packages/modrinth-sandbox/src/backend/unix.rs new file mode 100644 index 00000000000..54c6a2bd694 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/unix.rs @@ -0,0 +1,789 @@ +#[cfg(target_os = "linux")] +use std::os::fd::RawFd; +use std::{ + collections::BTreeMap, + ffi::CString, + io::ErrorKind, + os::{ + fd::{AsRawFd, OwnedFd}, + unix::ffi::OsStringExt, + }, + path::PathBuf, +}; + +use async_trait::async_trait; +use eyre::{Context, Result}; +use futures::FutureExt; + +use crate::{ + SandboxExitStatus, SandboxStdio, + backend::{Pipes, SandboxChildOp}, + util::{RawStringVec, SandboxArg}, +}; + +pub fn spawn( + program: SandboxArg, + arguments: Vec, + environment: BTreeMap, + stdin: SandboxStdio, + stdout: SandboxStdio, + stderr: SandboxStdio, + working_directory: Option, + pass_fds: Vec, + dev_null: libc::c_int, + double_fork: bool, + #[cfg(target_os = "linux")] die_with_parent: bool, + #[cfg(target_os = "macos")] sandbox_profile: CString, + #[cfg(target_os = "macos")] mut sandbox_params: RawStringVec, +) -> Result<(Pipes, UnixChild)> { + let program = CString::new(program.into_os_string().into_vec())?; + + // Arguments + let mut argv = RawStringVec::with_capacity(arguments.len() + 1); + argv.push_c(program.clone()); // arg0 is program name + for arg in arguments { + argv.push_os(arg.into_os_string())?; + } + + // Environment + let mut env = RawStringVec::with_capacity(environment.len()); + for (k, v) in environment { + let mut k = k.into_os_string(); + k.reserve_exact(v.as_os_str().len() + 2); + k.push("="); + k.push(v.as_os_str()); + + env.push_os(k)?; + } + + // Workdir + let workdir = if let Some(working_directory) = working_directory { + Some(CString::new(working_directory.into_os_string().into_vec())?) + } else { + None + }; + + // Stdio + let mut stdin_write = None; + let mut stdout_read = None; + let mut stderr_read = None; + + #[expect( + clippy::collection_is_never_read, + reason = "keep fds alive until we drop them" + )] + let mut fds_to_drop: Vec = Vec::new(); + let mut stdin_read = None; + let mut stdout_write = None; + let mut stderr_write = None; + + match stdin { + SandboxStdio::Null => { + stdin_read = Some(dev_null); + } + SandboxStdio::Inherit => {} + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + stdin_write = Some(write); + stdin_read = Some(read.as_raw_fd()); + fds_to_drop.push(read.into()); + } + } + match stdout { + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + stdout_read = Some(read); + stdout_write = Some(write.as_raw_fd()); + fds_to_drop.push(write.into()); + } + SandboxStdio::Null => { + stdout_write = Some(dev_null); + } + SandboxStdio::Inherit => {} + } + match stderr { + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + stderr_read = Some(read); + stderr_write = Some(write.as_raw_fd()); + fds_to_drop.push(write.into()); + } + SandboxStdio::Null => { + stderr_write = Some(dev_null); + } + SandboxStdio::Inherit => {} + } + + argv.ensure_null_terminated(); + env.ensure_null_terminated(); + #[cfg(target_os = "macos")] + sandbox_params.ensure_null_terminated(); + + // Built before forking so that the child doesn't need to allocate + #[cfg(target_os = "macos")] + let spawn_config = macos_posix_spawn::PosixSpawnConfig::new( + stdin_read, + stdout_write, + stderr_write, + &pass_fds, + ) + .wrap_err("preparing posix_spawn configuration")?; + + // Read before forking so that the child doesn't need to allocate + #[cfg(target_os = "linux")] + let kernel_fd_limit = read_kernel_fd_limit(); + + let child_pid = unsafe { cvt(libc::fork())? }; + if child_pid == 0 { + if double_fork { + if unsafe { libc::setsid() } == -1 { + unsafe { libc::_exit(1) }; + } + + match unsafe { libc::fork() } { + -1 => unsafe { libc::_exit(1) }, + 0 => {} + _ => unsafe { libc::_exit(0) }, + } + } + + #[cfg(target_os = "linux")] + { + _ = exec( + program.as_ptr(), + argv.into_null_terminated_ptr() as *const *const libc::c_char, + env.into_null_terminated_ptr() as *const *const libc::c_char, + stdin_read, + stdout_write, + stderr_write, + workdir.as_ref().map(|dir| dir.as_ptr()), + &pass_fds, + die_with_parent, + kernel_fd_limit, + ); + } + #[cfg(target_os = "macos")] + { + _ = exec( + program.as_ptr(), + argv.into_null_terminated_ptr(), + env.into_null_terminated_ptr(), + workdir.as_ref().map(|dir| dir.as_ptr()), + &spawn_config, + sandbox_profile, + sandbox_params, + ); + } + unsafe { libc::_exit(1) } + } + + if double_fork { + let mut status = 0 as libc::c_int; + cvt_r(|| unsafe { libc::waitpid(child_pid, &raw mut status, 0) })?; + eyre::ensure!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "double fork failed in intermediate child" + ); + + return Ok(( + Pipes { + stdin: stdin_write, + stdout: stdout_read, + stderr: stderr_read, + }, + UnixChild { + pid: 0, + exit_status: Some(SandboxExitStatus { + imp: UnixSandboxExitStatus(0), + }), + wait_task: None, + }, + )); + } + + Ok(( + Pipes { + stdin: stdin_write, + stdout: stdout_read, + stderr: stderr_read, + }, + UnixChild { + pid: child_pid, + exit_status: None, + wait_task: None, + }, + )) +} + +#[cfg(target_os = "linux")] +fn exec( + program: *const libc::c_char, + argv: *const *const libc::c_char, + env: *const *const libc::c_char, + stdin: Option, + stdout: Option, + stderr: Option, + workdir: Option<*const libc::c_char>, + pass_fds: &[OwnedFd], + die_with_parent: bool, + kernel_fd_limit: libc::rlim_t, +) -> eyre::Result<()> { + // `pass_fds` are unmarked again below + mark_inherited_fds_cloexec(kernel_fd_limit); + + if let Some(mut fd) = stdin { + if fd > 0 && fd <= libc::STDERR_FILENO { + fd = cvt_r(|| unsafe { libc::dup(fd) }) + .wrap_err("duplicating stdin fd")?; + } + cvt_r(|| unsafe { libc::dup2(fd, libc::STDIN_FILENO) }) + .wrap_err("setting stdin fd")?; + } + if let Some(mut fd) = stdout { + if fd > 0 && fd <= libc::STDERR_FILENO { + fd = cvt_r(|| unsafe { libc::dup(fd) }) + .wrap_err("duplicating stdout fd")?; + } + cvt_r(|| unsafe { libc::dup2(fd, libc::STDOUT_FILENO) }) + .wrap_err("setting stdout fd")?; + } + if let Some(mut fd) = stderr { + if fd > 0 && fd <= libc::STDERR_FILENO { + fd = cvt_r(|| unsafe { libc::dup(fd) }) + .wrap_err("duplicating stderr fd")?; + } + cvt_r(|| unsafe { libc::dup2(fd, libc::STDERR_FILENO) }) + .wrap_err("setting stderr fd")?; + } + + // Set working directory + if let Some(workdir) = workdir { + cvt_r(|| unsafe { libc::chdir(workdir) }) + .wrap_err("setting working directory")?; + } + + // Unset "close on exec" flag so fds are kept after the exec + for fd in pass_fds { + cvt_r(|| unsafe { libc::ioctl(fd.as_raw_fd(), libc::FIONCLEX) }) + .wrap_err("unsetting close on exec")?; + } + + // Set PR_SET_PDEATHSIG to SIGKILL + // This will kill the process when the parent thread or process dies + if die_with_parent { + cvt_r(|| unsafe { + libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0) + }) + .wrap_err("setting PR_SET_PDEATHSIG")?; + } + + cvt(unsafe { libc::execve(program, argv, env) })?; + Ok(()) +} + +#[cfg(target_os = "linux")] +fn read_kernel_fd_limit() -> libc::rlim_t { + std::fs::read_to_string("/proc/sys/fs/nr_open") + .ok() + .and_then(|nr_open| nr_open.trim().parse().ok()) + .unwrap_or(1 << 20) +} + +/// Try to mark all inherited fds as cloexec. We can do this in 1 of 3 ways: +/// 1. libc::close_range with CLOSE_RANGE_CLOEXEC (Linux 5.11+) +/// 2. Reading /proc/self/fd (May fail) +/// 3. Looping over every fd up to the limit +#[cfg(target_os = "linux")] +fn mark_inherited_fds_cloexec(kernel_fd_limit: libc::rlim_t) { + let result = unsafe { + libc::close_range( + 3, + libc::c_uint::MAX, + libc::CLOSE_RANGE_CLOEXEC as libc::c_int, + ) + }; + if result == 0 || mark_proc_self_fds_cloexec() { + return; + } + + let mut limit = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + let max_fd = + if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } == 0 + { + limit.rlim_cur.max(limit.rlim_max) + } else { + kernel_fd_limit + }; + + // Clamp between 1024 and the kernel's fd limit + let max_fd = max_fd.min(kernel_fd_limit).max(1024); + for fd in 3..max_fd as libc::c_int { + unsafe { libc::ioctl(fd, libc::FIOCLEX) }; + } +} + +#[cfg(target_os = "linux")] +fn mark_proc_self_fds_cloexec() -> bool { + // Byte offsets into `struct linux_dirent64` + // The struct is variable-length, so we can't transmute into it + const RECORD_LEN_OFFSET: usize = 16; + const NAME_OFFSET: usize = 19; + + #[repr(C, align(8))] + struct AlignedBuffer([u8; 4096]); + + let dir_fd = unsafe { + libc::open( + c"/proc/self/fd".as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + }; + if dir_fd == -1 { + return false; + } + let dir_fd = + unsafe { ::from_raw_fd(dir_fd) }; + + let mut buffer = AlignedBuffer([0; 4096]); + loop { + let read = unsafe { + libc::syscall( + libc::SYS_getdents64, + dir_fd.as_raw_fd(), + buffer.0.as_mut_ptr(), + buffer.0.len(), + ) + }; + if read == 0 { + return true; + } else if read < 0 { + return false; + } + + let entries = &buffer.0[..read as usize]; + let mut offset = 0; + while offset < entries.len() { + let Some(record) = entries.get(offset..) else { + return false; + }; + let Some(&[low, high]) = + record.get(RECORD_LEN_OFFSET..RECORD_LEN_OFFSET + 2) + else { + return false; + }; + let record_len = u16::from_ne_bytes([low, high]) as usize; + let Some(name) = record.get(NAME_OFFSET..record_len) else { + return false; + }; + + if let Some(fd) = parse_fd(name) + && fd >= 3 + && fd != dir_fd.as_raw_fd() + { + unsafe { libc::ioctl(fd, libc::FIOCLEX) }; + } + + offset += record_len; + } + } +} + +#[cfg(target_os = "linux")] +fn parse_fd(name: &[u8]) -> Option { + let mut fd: libc::c_int = 0; + for &byte in name.iter().take_while(|&&byte| byte != 0) { + if !byte.is_ascii_digit() { + return None; + } + fd = fd.checked_mul(10)?; + fd = fd.checked_add((byte - b'0') as libc::c_int)?; + } + Some(fd) +} + +#[cfg(target_os = "macos")] +fn exec( + program: *const libc::c_char, + argv: *const *mut libc::c_char, + env: *const *mut libc::c_char, + workdir: Option<*const libc::c_char>, + spawn_config: &macos_posix_spawn::PosixSpawnConfig, + sandbox_profile: CString, + sandbox_params: RawStringVec, +) -> eyre::Result<()> { + if let Some(workdir) = workdir { + cvt_r(|| unsafe { libc::chdir(workdir) }) + .wrap_err("setting working directory")?; + } + + let mut error_buf = std::ptr::null_mut(); + let sandbox_profile = sandbox_profile.as_ptr(); + let sandbox_params = sandbox_params.into_null_terminated_ptr().cast(); + let status_code = unsafe { + sandbox_init_with_parameters( + sandbox_profile, + 0, + sandbox_params, + &raw mut error_buf, + ) + }; + + if !error_buf.is_null() { + let error = unsafe { std::ffi::CStr::from_ptr(error_buf) }; + let error = error.to_string_lossy().to_string(); + unsafe { sandbox_free_error(error_buf) }; + return Err(eyre::eyre!(error).wrap_err("setting up sandbox")); + } + + eyre::ensure!(status_code == 0, "sandbox setup failed"); + + Err(eyre::eyre!(spawn_config.exec(program, argv, env)) + .wrap_err("executing program")) +} + +#[cfg(target_os = "macos")] +mod macos_posix_spawn { + use std::os::fd::{AsRawFd, OwnedFd, RawFd}; + + use super::cvt_r; + + pub struct PosixSpawnConfig { + attributes: libc::posix_spawnattr_t, + file_actions: libc::posix_spawn_file_actions_t, + dup_sources: [Option; 3], + } + + impl PosixSpawnConfig { + pub fn new( + stdin: Option, + stdout: Option, + stderr: Option, + pass_fds: &[OwnedFd], + ) -> std::io::Result { + let mut config = Self { + attributes: std::ptr::null_mut(), + file_actions: std::ptr::null_mut(), + dup_sources: [None; 3], + }; + + unsafe { + cvt_errno(libc::posix_spawnattr_init( + &raw mut config.attributes, + ))?; + cvt_errno(libc::posix_spawnattr_setflags( + &raw mut config.attributes, + (libc::POSIX_SPAWN_SETEXEC + | libc::POSIX_SPAWN_CLOEXEC_DEFAULT) + as libc::c_short, + ))?; + cvt_errno(libc::posix_spawn_file_actions_init( + &raw mut config.file_actions, + ))?; + } + + config.add_stdio(stdin, libc::STDIN_FILENO)?; + config.add_stdio(stdout, libc::STDOUT_FILENO)?; + config.add_stdio(stderr, libc::STDERR_FILENO)?; + + for fd in pass_fds { + config.add_inherit(fd.as_raw_fd())?; + } + + Ok(config) + } + + pub fn exec( + &self, + program: *const libc::c_char, + argv: *const *mut libc::c_char, + env: *const *mut libc::c_char, + ) -> std::io::Error { + // We need to unset cloexec on the source of the dup2, otherwise + // it'll fail. It'll be closed by POSIX_SPAWN_CLOEXEC_DEFAULT later anyways + if let Err(error) = self.clear_cloexec_on_dup_sources() { + return error; + } + + let error = unsafe { + libc::posix_spawnp( + std::ptr::null_mut(), + program, + &raw const self.file_actions, + &raw const self.attributes, + argv, + env, + ) + }; + std::io::Error::from_raw_os_error(error) + } + + fn add_stdio( + &mut self, + source: Option, + target: RawFd, + ) -> std::io::Result<()> { + if let Some(source) = source + && source != target + { + self.dup_sources[target as usize] = Some(source); + cvt_errno(unsafe { + libc::posix_spawn_file_actions_adddup2( + &raw mut self.file_actions, + source, + target, + ) + }) + } else { + self.add_inherit(target) + } + } + + fn clear_cloexec_on_dup_sources(&self) -> std::io::Result<()> { + for source in self.dup_sources.into_iter().flatten() { + cvt_r(|| unsafe { libc::ioctl(source, libc::FIONCLEX) })?; + } + Ok(()) + } + + fn add_inherit(&mut self, fd: RawFd) -> std::io::Result<()> { + if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 { + // fd is closed, avoid trying to inherit it since + // otherwise the spawn will fail + return Ok(()); + } + cvt_errno(unsafe { + posix_spawn_file_actions_addinherit_np( + &raw mut self.file_actions, + fd, + ) + }) + } + } + + impl Drop for PosixSpawnConfig { + fn drop(&mut self) { + unsafe { + if !self.attributes.is_null() { + libc::posix_spawnattr_destroy(&raw mut self.attributes); + } + if !self.file_actions.is_null() { + libc::posix_spawn_file_actions_destroy( + &raw mut self.file_actions, + ); + } + } + } + } + + fn cvt_errno(error: libc::c_int) -> std::io::Result<()> { + if error == 0 { + Ok(()) + } else { + Err(std::io::Error::from_raw_os_error(error)) + } + } + + unsafe extern "C" { + fn posix_spawn_file_actions_addinherit_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: libc::c_int, + ) -> libc::c_int; + } +} + +#[derive(Debug)] +pub struct UnixChild { + pid: libc::pid_t, + exit_status: Option, + wait_task: Option>>, +} + +#[async_trait] +impl SandboxChildOp for UnixChild { + fn id(&self) -> Option { + if self.exit_status.is_some() { + return None; + } + Some(self.pid as u32) + } + + fn try_wait(&mut self) -> Result> { + // Need to remember the exit status due to waitpid at-most-once semantics + if let Some(exit_status) = self.exit_status { + return Ok(Some(exit_status)); + } + + if let Some(task) = self.wait_task.as_mut() { + let Some(result) = task.now_or_never() else { + return Ok(None); + }; + self.wait_task = None; + self.exit_status = Some(SandboxExitStatus { + imp: UnixSandboxExitStatus(result??), + }); + return Ok(self.exit_status); + } + + let mut status = 0 as libc::c_int; + let pid = cvt_r(|| unsafe { + libc::waitpid(self.pid, &raw mut status, libc::WNOHANG) + })?; + + if pid == 0 { + Ok(None) + } else { + self.exit_status = Some(SandboxExitStatus { + imp: UnixSandboxExitStatus(status), + }); + Ok(self.exit_status) + } + } + + async fn wait(&mut self) -> Result { + if let Some(exit_status) = self.exit_status { + return Ok(exit_status); + } + + let wait_for_pid = self.pid; + let task = self.wait_task.get_or_insert_with(|| { + tokio::task::spawn_blocking(move || { + let mut status = 0 as libc::c_int; + cvt_r(|| unsafe { + libc::waitpid(wait_for_pid, &raw mut status, 0) + })?; + eyre::Ok(status) + }) + }); + let result = task.await; + self.wait_task = None; + let exit_status = SandboxExitStatus { + imp: UnixSandboxExitStatus(result??), + }; + self.exit_status = Some(exit_status); + Ok(exit_status) + } + + async fn kill(&mut self) -> Result<()> { + if let Some(task) = self.wait_task.as_mut() + && let Some(result) = task.now_or_never() + { + self.wait_task = None; + self.exit_status = Some(SandboxExitStatus { + imp: UnixSandboxExitStatus(result??), + }); + } + + if self.exit_status.is_some() { + return Ok(()); + } + + let kill_pid = self.pid; + tokio::task::spawn_blocking(move || { + cvt_r(|| unsafe { libc::kill(kill_pid, libc::SIGKILL) }) + }) + .await??; + Ok(()) + } +} + +#[derive(Default, Clone, Copy)] +pub(crate) struct UnixSandboxExitStatus(pub(crate) libc::c_int); + +impl UnixSandboxExitStatus { + pub(crate) fn success(&self) -> bool { + self.code() == Some(0) + } + + pub(crate) fn code(&self) -> Option { + if libc::WIFEXITED(self.0) { + Some(libc::WEXITSTATUS(self.0)) + } else { + None + } + } +} + +impl std::fmt::Display for UnixSandboxExitStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // std::process::ExitStatus + if libc::WIFEXITED(self.0) { + f.write_fmt(format_args!("exitcode={}", libc::WEXITSTATUS(self.0))) + } else if libc::WIFSIGNALED(self.0) { + f.write_fmt(format_args!("signal={}", libc::WTERMSIG(self.0))) + } else { + f.write_fmt(format_args!("unknownwait=0x{:#x}", self.0)) + } + } +} + +impl std::fmt::Debug for UnixSandboxExitStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut debug = f.debug_struct("UnixSandboxExitStatus"); + debug.field("raw", &self.0); + if libc::WIFEXITED(self.0) { + debug.field("exitcode", &libc::WEXITSTATUS(self.0)); + } + if libc::WIFSIGNALED(self.0) { + debug.field("signal", &libc::WTERMSIG(self.0)); + } + debug.finish() + } +} + +pub fn open_dev_null() -> eyre::Result { + Ok(unsafe { cvt(libc::open(c"/dev/null".as_ptr(), libc::O_RDWR))? }) +} + +#[doc(hidden)] +pub trait IsMinusOne { + fn is_minus_one(&self) -> bool; +} + +macro_rules! impl_is_minus_one { + ($($t:ident)*) => ($(impl IsMinusOne for $t { + fn is_minus_one(&self) -> bool { + *self == -1 + } + })*) +} + +impl_is_minus_one! { i8 i16 i32 i64 isize } + +/// Converts native return values to Result using the *-1 means error is in `errno`* convention. +/// Non-error values are `Ok`-wrapped. +pub fn cvt(t: T) -> std::io::Result { + if t.is_minus_one() { + Err(std::io::Error::last_os_error()) + } else { + Ok(t) + } +} + +/// `-1` → look at `errno` → retry on `EINTR`. Otherwise `Ok()`-wrap the closure return value. +pub fn cvt_r(mut f: F) -> std::io::Result +where + T: IsMinusOne, + F: FnMut() -> T, +{ + loop { + match cvt(f()) { + Err(ref e) if e.kind() == ErrorKind::Interrupted => {} + other => return other, + } + } +} + +#[cfg(target_os = "macos")] +unsafe extern "C" { + fn sandbox_init_with_parameters( + profile: *const libc::c_char, + flags: u64, + parameters: *const *const libc::c_char, + errorbuf: *mut *mut libc::c_char, + ) -> libc::c_int; + + fn sandbox_free_error(errorbuf: *mut libc::c_char); +} diff --git a/packages/modrinth-sandbox/src/backend/windows/acl.rs b/packages/modrinth-sandbox/src/backend/windows/acl.rs new file mode 100644 index 00000000000..7086160aba2 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/windows/acl.rs @@ -0,0 +1,537 @@ +//! Handles tracking which file paths we've given the sandbox access to, in a +//! global per-container [`AppliedAclLedger`]. +//! +//! For each AppContainer we make, we give it a registry key at +//! `HKCU\Software\MinecraftSandbox\`, under the name `Grant`. When we give +//! the sandbox permission to access a specific path, we add it to the ACL, and +//! record it in the ledger; when we want to reset the sandbox's file access, +//! we can read the ledger to see what access we previously gave it, and revoke +//! those. +//! +//! The reason we need a ledger is because Windows doesn't let us list all files +//! which we've allowed to an AppContainer via ACL. Instead, it works the other +//! way around, where individual files/directories list what AppContainers are +//! allowed to read/write/traverse them. It would be impractical to scan every +//! single file on the disk to see if our container can access it, so instead we +//! keep track of it ourselves. +//! +//! We record grants in the ledger before adding them to the ACL, and revoke +//! grants from the ACL before removing them from the ledger. This means that: +//! - all ACL grants **must** be in the ledger +//! - all grants in the ledger **may** also exist in the ACL +//! +//! The first one is the important part, since we need to ensure that we can +//! always clean up ACL entries after ourselves; and addition/removal of a +//! grant or ACL entry is idempotent, so it's OK to remove or add a path that's +//! already removed/added. +//! +//! While reading/writing the ledger, we take a global Windows mutex keyed to +//! that container, to make sure that reads/writes won't conflict with another +//! process trying to read/write to the same ledger. +//! +//! When we spawn an instance, we keep track of what permissions it has in the +//! ledger, and key those grants by the instance we've just made[^1]. We +//! also prune the ledger - find any entries keyed by a process which is now +//! dead, and remove it. This lets up clean up the grants list automatically. +//! +//! ACL grants are per-container, **not** per process. So all processes in the +//! same AppContainer sandbox share the same access. If you spawn a new process, +//! and it has less permissions than a process that we spawned before, then we +//! wouldn't want that old process to suddenly stop working since it can no +//! longer access some files; to solve this, the real ACL that we apply is the +//! *union* of all grants of all instances. Since instances get cleaned up +//! later, revoking a grant still works. +//! +//! [^1]: When we're preparing to spawn an instance, we give the ledger entry a +//! UUID; after we've actually spawned the process, *then* we put the PID and +//! process creation time into the ledger (both of these let us uniquely +//! identify the process, since Windows can reuse PIDs). + +use std::collections::{BTreeMap, HashSet}; +use std::io; +use std::os::windows::io::{AsRawHandle, OwnedHandle}; +use std::path::Path; +use std::{ffi::OsStr, os::windows::ffi::OsStrExt}; + +use eyre::Result; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; +use windows::{ + Win32::{ + Foundation::{ + CloseHandle, E_ACCESSDENIED, E_INVALIDARG, FILETIME, HANDLE, + WAIT_ABANDONED, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT, + }, + System::Threading::{ + CreateMutexW, GetCurrentProcess, GetCurrentProcessId, + GetProcessTimes, INFINITE, OpenProcess, PROCESS_ACCESS_RIGHTS, + PROCESS_QUERY_LIMITED_INFORMATION, ReleaseMutex, + WaitForSingleObject, + }, + }, + core::PCWSTR, +}; +use winreg::{RegKey, enums::HKEY_CURRENT_USER}; + +const REGISTRY_BASE: &str = r"Software\MinecraftSandbox"; +const GRANT_VALUE: &str = "Grant"; +const SYNCHRONIZE_PROCESS: PROCESS_ACCESS_RIGHTS = + PROCESS_ACCESS_RIGHTS(0x00100000); + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PermissionType { + /// Allows access through the named directory without inheriting the grant + /// to any of its children. + Traverse, + Read, + Write, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct Grant { + pub path: String, + pub permission: PermissionType, +} + +impl Grant { + pub fn from_path( + path: &Path, + permission: PermissionType, + ) -> Result> { + let Ok(path) = path.canonicalize() else { + return Ok(None); + }; + let path = path.to_str().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("ACL path is not valid Unicode: {path:?}"), + ) + })?; + Ok(Some(Self { + path: path.to_owned(), + permission, + })) + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub(super) struct ProcessIdentity { + pid: u32, + creation_time: u64, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +struct RegistryState { + #[serde(default)] + instances: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +struct Instance { + #[serde(with = "uuid_string")] + id: Uuid, + #[serde(flatten)] + state: InstanceState, + grants: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(tag = "state", rename_all = "snake_case")] +enum InstanceState { + Pending { process: ProcessIdentity }, + Running { process: ProcessIdentity }, +} + +impl InstanceState { + fn process(&self) -> ProcessIdentity { + match self { + Self::Pending { process } | Self::Running { process } => *process, + } + } +} + +pub struct AppliedAclLedger { + key: RegKey, + mutex_name: Vec, +} + +impl AppliedAclLedger { + pub fn open(app_container_sid: &OsStr) -> Result { + let sid = app_container_sid.to_str().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "AppContainer SID is not valid Unicode", + ) + })?; + let key_path = format!(r"{REGISTRY_BASE}\{sid}"); + let (key, _) = + RegKey::predef(HKEY_CURRENT_USER).create_subkey(key_path)?; + let mutex_name = + OsStr::new(&format!(r"Global\MinecraftSandboxAclLedger-{sid}")) + .encode_wide() + .chain([0]) + .collect(); + Ok(Self { key, mutex_name }) + } + + /// Locks the global Windows mutex, allowing safe access to the sandbox ACL + /// ledger. + pub fn lock(&self) -> Result> { + let mutex = LedgerMutexGuard::acquire(&self.mutex_name)?; + LockedAclLedger::open(&self.key, mutex) + } + + pub fn add_grants( + &self, + instance_id: Uuid, + grants: Vec, + ) -> Result> { + let mut ledger = self.lock()?; + let old_effective = effective_union(&ledger.state, |_| true); + let instance = ledger + .state + .instances + .iter_mut() + .find(|instance| instance.id == instance_id) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "active ACL instance not found", + ) + })?; + instance.grants.extend(grants); + instance.grants = normalize_grants(instance.grants.iter()); + let desired_effective = effective_union(&ledger.state, |_| true); + let changed = desired_effective + .iter() + .filter(|desired| { + old_effective + .iter() + .find(|old| paths_equal(&old.path, &desired.path)) + .is_none_or(|old| { + permission_strength(desired.permission) + > permission_strength(old.permission) + }) + }) + .cloned() + .collect(); + ledger.persist()?; + Ok(changed) + } +} + +pub struct LockedAclLedger<'a> { + key: &'a RegKey, + state: RegistryState, + _mutex: LedgerMutexGuard, +} + +impl<'a> LockedAclLedger<'a> { + fn open(key: &'a RegKey, mutex: LedgerMutexGuard) -> Result { + let state: String = match key.get_value(GRANT_VALUE) { + Ok(state) => state, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return Ok(Self { + key, + state: RegistryState::default(), + _mutex: mutex, + }); + } + Err(error) => return Err(error.into()), + }; + let state = serde_json::from_str(&state).map_err(|error| { + io::Error::new(io::ErrorKind::InvalidData, error) + })?; + Ok(Self { + key, + state, + _mutex: mutex, + }) + } + + /// Removes stale instances, and prepares the ledger to add a new instance. + pub fn prepare( + mut self, + grants: Vec, + ) -> Result> { + let process = ProcessIdentity::current()?; + let grants = normalize_grants(grants.iter()); + let old_effective = effective_union(&self.state, |_| true); + let mut dead_instances = HashSet::new(); + for instance in &self.state.instances { + match instance.state.process().is_alive() { + Ok(true) => {} + Ok(false) => { + dead_instances.insert(instance.id); + } + Err(error) => { + tracing::warn!( + instance = %instance.id, + "unable to determine whether ACL instance is alive, keeping its grants: {error:#}" + ); + } + } + } + let id = Uuid::now_v7(); + self.state.instances.push(Instance { + id, + state: InstanceState::Pending { process }, + grants, + }); + let desired_effective = effective_union(&self.state, |instance| { + !dead_instances.contains(&instance.id) + }); + self.persist()?; + Ok(PreparedInstance { + ledger: self, + id, + dead_instances, + old_effective, + desired_effective, + }) + } + + fn persist(&self) -> Result<()> { + let state = serde_json::to_string(&self.state).map_err(|error| { + io::Error::new(io::ErrorKind::InvalidData, error) + })?; + self.key.set_value(GRANT_VALUE, &state)?; + Ok(()) + } +} + +pub struct PreparedInstance<'a> { + ledger: LockedAclLedger<'a>, + id: Uuid, + dead_instances: HashSet, + old_effective: Vec, + desired_effective: Vec, +} + +impl PreparedInstance<'_> { + pub fn id(&self) -> Uuid { + self.id + } + + pub fn old_effective(&self) -> &[Grant] { + &self.old_effective + } + + pub fn desired_effective(&self) -> &[Grant] { + &self.desired_effective + } + + pub fn finalize_pruning(&mut self) -> Result<()> { + self.ledger + .state + .instances + .retain(|instance| !self.dead_instances.contains(&instance.id)); + self.dead_instances.clear(); + self.ledger.persist() + } + + pub fn activate(&mut self, process: ProcessIdentity) -> Result<()> { + let instance = self.instance_mut()?; + instance.state = InstanceState::Running { process }; + self.ledger.persist() + } + + fn instance_mut(&mut self) -> Result<&mut Instance> { + Ok(self + .ledger + .state + .instances + .iter_mut() + .find(|instance| instance.id == self.id) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "pending ACL instance not found", + ) + })?) + } +} + +impl ProcessIdentity { + fn current() -> Result { + Self::from_handle(unsafe { GetCurrentProcessId() }, unsafe { + GetCurrentProcess() + }) + } + + pub(super) fn from_handle(pid: u32, handle: HANDLE) -> Result { + Ok(Self { + pid, + creation_time: process_creation_time(handle)?, + }) + } + + fn is_alive(self) -> Result { + let handle = match unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE_PROCESS, + false, + self.pid, + ) + } { + Ok(handle) => handle, + Err(error) if error.code() == E_INVALIDARG => return Ok(false), + // Processes we spawn are always openable by us, so a denied open + // means the PID has been reused by an unrelated process + Err(error) if error.code() == E_ACCESSDENIED => return Ok(false), + Err(error) => { + return Err(io::Error::other(error.to_string()).into()); + } + }; + let handle = ProcessHandle(handle); + if process_creation_time(handle.0)? != self.creation_time { + return Ok(false); + } + match unsafe { WaitForSingleObject(handle.0, 0) } { + WAIT_TIMEOUT => Ok(true), + WAIT_OBJECT_0 => Ok(false), + WAIT_FAILED => Err(io::Error::last_os_error().into()), + wait => Err(io::Error::other(format!( + "unexpected process wait result: {wait:?}" + )) + .into()), + } + } +} + +fn process_creation_time(handle: HANDLE) -> Result { + let mut creation = FILETIME::default(); + let mut exit = FILETIME::default(); + let mut kernel = FILETIME::default(); + let mut user = FILETIME::default(); + unsafe { + GetProcessTimes( + handle, + &mut creation, + &mut exit, + &mut kernel, + &mut user, + )?; + } + Ok((u64::from(creation.dwHighDateTime) << 32) + | u64::from(creation.dwLowDateTime)) +} + +fn effective_union<'a>( + state: &'a RegistryState, + include_instance: impl Fn(&Instance) -> bool, +) -> Vec { + normalize_grants( + state + .instances + .iter() + .filter(|instance| include_instance(instance)) + .flat_map(|instance| instance.grants.iter()), + ) +} + +pub fn paths_equal(first: &str, second: &str) -> bool { + path_key(first) == path_key(second) +} + +fn path_key(path: &str) -> String { + path.to_lowercase() +} + +fn normalize_grants<'a>( + grants: impl IntoIterator, +) -> Vec { + let mut normalized = BTreeMap::::new(); + for grant in grants { + let key = path_key(&grant.path); + match normalized.get_mut(&key) { + Some(existing) + if permission_strength(grant.permission) + > permission_strength(existing.permission) => + { + existing.permission = grant.permission; + } + Some(_) => {} + None => { + normalized.insert(key, grant.clone()); + } + } + } + normalized.into_values().collect() +} + +fn permission_strength(permission: PermissionType) -> u8 { + match permission { + PermissionType::Traverse => 0, + PermissionType::Read => 1, + PermissionType::Write => 2, + } +} + +struct ProcessHandle(HANDLE); + +impl Drop for ProcessHandle { + fn drop(&mut self) { + unsafe { + let _ = CloseHandle(self.0); + } + } +} + +struct LedgerMutexGuard { + handle: OwnedHandle, +} + +impl LedgerMutexGuard { + fn acquire(name: &[u16]) -> Result { + let handle = + unsafe { CreateMutexW(None, false, PCWSTR(name.as_ptr())) }?; + let handle = super::to_owned_handle(handle) + .map_err(|error| io::Error::other(error.to_string()))?; + let wait = unsafe { + WaitForSingleObject(HANDLE(handle.as_raw_handle()), INFINITE) + }; + if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { + if wait == WAIT_FAILED { + return Err(io::Error::last_os_error().into()); + } + return Err(io::Error::other(format!( + "unexpected mutex wait result: {wait:?}" + )) + .into()); + } + Ok(Self { handle }) + } +} + +impl Drop for LedgerMutexGuard { + fn drop(&mut self) { + let _ = unsafe { ReleaseMutex(HANDLE(self.handle.as_raw_handle())) }; + } +} + +mod uuid_string { + use serde::{Deserialize, Deserializer, Serializer}; + use uuid::Uuid; + + pub fn serialize( + uuid: &Uuid, + serializer: S, + ) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(&uuid.to_string()) + } + + pub fn deserialize<'de, D>( + deserializer: D, + ) -> std::result::Result + where + D: Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Uuid::parse_str(&value).map_err(serde::de::Error::custom) + } +} diff --git a/packages/modrinth-sandbox/src/backend/windows/appcontainer.rs b/packages/modrinth-sandbox/src/backend/windows/appcontainer.rs new file mode 100644 index 00000000000..900bbc558bf --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/windows/appcontainer.rs @@ -0,0 +1,1215 @@ +use std::{ + collections::HashSet, + ffi::{OsStr, OsString}, + io::{Error, ErrorKind}, + os::windows::ffi::{OsStrExt, OsStringExt}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use tracing::info; +use windows::{ + Win32::{ + Foundation::{ + ERROR_ACCESS_DENIED, ERROR_ALREADY_EXISTS, ERROR_FILE_NOT_FOUND, + ERROR_INSUFFICIENT_BUFFER, ERROR_PATH_NOT_FOUND, ERROR_SUCCESS, + GetLastError, HANDLE, LocalFree, + }, + NetworkManagement::WindowsFirewall::{ + NetworkIsolationGetAppContainerConfig, + NetworkIsolationSetAppContainerConfig, + }, + Security::{ + ACE_HEADER, ACL, + Authorization::{ + ConvertSidToStringSidW, ConvertStringSidToSidW, + EXPLICIT_ACCESS_W, GRANT_ACCESS, GetNamedSecurityInfoW, + GetSecurityInfo, NO_MULTIPLE_TRUSTEE, REVOKE_ACCESS, + SE_FILE_OBJECT, SE_WINDOW_OBJECT, SET_ACCESS, SetEntriesInAclW, + SetNamedSecurityInfoW, SetSecurityInfo, TRUSTEE_IS_GROUP, + TRUSTEE_IS_SID, + }, + CONTAINER_INHERIT_ACE, CreateWellKnownSid, + DACL_SECURITY_INFORMATION, DeriveCapabilitySidsFromName, EqualSid, + FreeSid, GetAce, InitializeSecurityDescriptor, + Isolation::{ + CreateAppContainerProfile, + DeriveAppContainerSidFromAppContainerName, + GetAppContainerFolderPath, + }, + NO_INHERITANCE, OBJECT_INHERIT_ACE, PSECURITY_DESCRIPTOR, PSID, + SECURITY_CAPABILITIES, SID_AND_ATTRIBUTES, SetFileSecurityW, + SetSecurityDescriptorDacl, WELL_KNOWN_SID_TYPE, + WinCapabilityInternetClientServerSid, + WinCapabilityInternetClientSid, + WinCapabilityPrivateNetworkClientServerSid, + }, + Storage::FileSystem::{ + DELETE, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, + FILE_GENERIC_WRITE, FILE_TRAVERSE, READ_CONTROL, WRITE_DAC, + }, + System::{ + Com::CoTaskMemFree, + Memory::{GetProcessHeap, HEAP_FLAGS, HeapFree}, + StationsAndDesktops::OpenWindowStationW, + SystemServices::{SE_GROUP_ENABLED, SECURITY_DESCRIPTOR_REVISION}, + Threading::PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, + }, + UI::WindowsAndMessaging::WINSTA_WRITEATTRIBUTES, + }, + core::{HRESULT, PCWSTR, PWSTR}, +}; + +use async_trait::async_trait; +use derive_more::Debug; +use eyre::{Context, Result, bail, ensure, eyre}; +use parking_lot::{Mutex, RwLock}; +use uuid::Uuid; + +use crate::{ + SandboxArg, SandboxCommand, + backend::{ + Backend, ExposedPath, SandboxChild, SandboxEnv, SandboxHandle, + SandboxHandleOp, pathset::ReadWritePathSet, + }, + helper::MakeHelper, +}; + +use super::acl::{AppliedAclLedger, Grant, PermissionType, paths_equal}; + +#[derive(Debug)] +pub struct AppContainer; + +#[async_trait] +impl Backend for AppContainer { + async fn init(make_helper: MakeHelper) -> Result> { + Ok(Box::new(AppContainerEnv { + make_helper, + job_handle: super::create_job_object() + .wrap_err("error creating job object")?, + null_device: super::open_null_device() + .wrap_err("error opening null device")?, + })) + } +} + +#[derive(Clone, Debug)] +#[debug("AppContainerEnv")] +pub struct AppContainerEnv { + make_helper: MakeHelper, + job_handle: HANDLE, + null_device: HANDLE, +} + +// HANDLE can be sent across threads despite containing *mut c_void +unsafe impl Send for AppContainerEnv {} +unsafe impl Sync for AppContainerEnv {} + +#[async_trait] +impl SandboxEnv for AppContainerEnv { + async fn spawn( + &self, + command: SandboxCommand, + ) -> Result { + let env = self.clone(); + crate::backend::run_on_spawn_thread(move || spawn(&env, command)) + .await? + } +} + +fn spawn( + env: &AppContainerEnv, + mut command: SandboxCommand, +) -> Result { + let app_container_sid = create_app_container( + command.app_container_name.as_os_str(), + command.app_container_description.as_os_str(), + )?; + scopeguard::defer! { + unsafe { FreeSid(app_container_sid) }; + } + + let app_container_sid_string = + app_container_sid_to_string(&app_container_sid)?; + let acl_ledger = AppliedAclLedger::open(&app_container_sid_string) + .wrap_err("opening AppContainer ACL ledger")?; + let app_container_folder = + get_app_container_folder(&app_container_sid_string)?; + let local_state = app_container_folder.join("LocalState"); + let roaming_state = app_container_folder.join("RoamingState"); + let temp_state = app_container_folder.join("TempState"); + let home = local_state.join("Home"); + for path in [&local_state, &roaming_state, &temp_state, &home] { + std::fs::create_dir_all(path).wrap_err_with(|| { + format!("creating AppContainer storage directory {path:?}") + })?; + } + + command.extra_environment.extend([ + ("APPDATA".into(), roaming_state.into()), + ("LOCALAPPDATA".into(), local_state.into()), + ("HOME".into(), home.clone().into()), + ("USERPROFILE".into(), home.clone().into()), + ("HOMEDRIVE".into(), "".into()), + ("HOMEPATH".into(), home.clone().into()), + ("TEMP".into(), temp_state.clone().into()), + ("TMP".into(), temp_state.into()), + ]); + if command.is_jvm { + let mut user_home = OsString::from("-Duser.home="); + user_home.push(home); + command.args.insert(0, user_home.into()); + } + + let environment = command.take_environment(); + + let mut owned_capabilities: Vec = Vec::new(); + + if command.allow_network { + owned_capabilities + .push(OwnedCapability::new(WinCapabilityInternetClientSid)?); + owned_capabilities + .push(OwnedCapability::new(WinCapabilityInternetClientServerSid)?); + owned_capabilities.push(OwnedCapability::new( + WinCapabilityPrivateNetworkClientServerSid, + )?); + } + + let mut capabilities = owned_capabilities + .iter_mut() + .map(|cap| SID_AND_ATTRIBUTES { + Sid: cap.as_psid(), + Attributes: SE_GROUP_ENABLED as u32, + }) + .collect::>(); + + // Ideally we could just add the appcontainer's sid to winsta0 directly, + // but for some reason this triggers a bug in chrome. + // See https://github.com/Moulberry/PandoraLauncher/issues/415 + + let mut group_sids = std::ptr::null_mut(); + let mut group_sid_count = 0; + let mut capability_sids = std::ptr::null_mut(); + let mut capability_sid_count = 0; + unsafe { + DeriveCapabilitySidsFromName( + windows::core::w!( + "modrinth.grantWinstaWriteAttributesCapability_ikU1gY09aHdb3PsX" + ), + &mut group_sids, + &mut group_sid_count, + &mut capability_sids, + &mut capability_sid_count, + )? + }; + + if capability_sid_count == 0 { + tracing::error!( + "DeriveCapabilitySidsFromName returned 0 for capabilitysidcount" + ); + } else if capability_sids.is_null() { + tracing::error!( + "DeriveCapabilitySidsFromName returned null for capability_sids" + ); + } else { + let derived_sid = unsafe { capability_sids.read() }; + if let Err(err) = add_writeattributes_to_winsta(&derived_sid) { + tracing::error!("Unable to set WINSTA_WRITEATTRIBUTES: {err}"); + } else { + capabilities.push(SID_AND_ATTRIBUTES { + Sid: derived_sid, + Attributes: SE_GROUP_ENABLED as u32, + }); + } + } + + scopeguard::defer! { + // https://github.com/microsoft/Windows-universal-samples/blob/082195895276903b6630d5cb4d03c9d365ec210c/Samples/CustomCapability/Service/Server/RpcServer.cpp#L33 + if !group_sids.is_null() { + for i in 0..group_sid_count { + let group_sid = unsafe { group_sids.offset(i as isize).read() }; + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(group_sid.0))) }; + } + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(group_sids.cast()))) }; + } + if !capability_sids.is_null() { + for i in 0..capability_sid_count { + let group_sid = unsafe { capability_sids.offset(i as isize).read() }; + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(group_sid.0))) }; + } + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(capability_sids.cast()))) }; + } + } + + let mut security_capabilities = SECURITY_CAPABILITIES::default(); + security_capabilities.CapabilityCount = capabilities.len() as u32; + security_capabilities.Capabilities = capabilities.as_mut_ptr(); + security_capabilities.AppContainerSid = app_container_sid; + + let mut attribute_list = Vec::new(); + attribute_list.push(super::ProcThreadAttribute { + attribute: PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES as usize, + value: &security_capabilities as *const SECURITY_CAPABILITIES + as *const _, + size: size_of::(), + }); + + for path in &command.ensure_dirs_exist { + std::fs::create_dir_all(path) + .wrap_err_with(|| eyre!("creating directory {path:?}"))?; + } + + let mut parents_to_add: HashSet = HashSet::default(); + let path_set = command.take_paths()?; + + for path in path_set.iter_both() { + if let Some(parent) = path.parent() { + parents_to_add.insert(parent.to_path_buf()); + } + } + + let mut parents: HashSet = HashSet::default(); + loop { + let taken = std::mem::take(&mut parents_to_add); + if taken.is_empty() { + break; + } + for to_add in taken { + if path_set.can_read(to_add.clone()) { + continue; + } + let parent = to_add.parent().map(Path::to_path_buf); + if parents.insert(to_add) + && let Some(parent) = parent + { + parents_to_add.insert(parent); + } + } + } + + // Read-only directories can contain a read-write, but not vice-versa. So we bind read then write + let mut instance_grants = Vec::new(); + for path in path_set.iter_read_only() { + instance_grants.extend( + Grant::from_path(path, PermissionType::Read) + .wrap_err_with(|| eyre!("creating read grant for {path:?}"))?, + ); + } + for path in path_set.iter_read_write() { + instance_grants.extend( + Grant::from_path(path, PermissionType::Write) + .wrap_err_with(|| eyre!("creating write grant for {path:?}"))?, + ); + } + for path in parents { + instance_grants.extend( + Grant::from_path(&path, PermissionType::Traverse).wrap_err_with( + || eyre!("creating traverse grant for {path:?}"), + )?, + ); + } + + let locked_acl_ledger = acl_ledger + .lock() + .wrap_err("locking AppContainer ACL ledger")?; + let mut prepared = locked_acl_ledger + .prepare(instance_grants) + .wrap_err("preparing AppContainer ACL instance")?; + let mut parents_to_elevate = Vec::new(); + let mut read_paths_to_elevate = Vec::new(); + let mut write_paths_to_elevate = Vec::new(); + let mut remove_paths_to_elevate = Vec::new(); + + for grant in prepared.old_effective() { + if !prepared + .desired_effective() + .iter() + .any(|desired| paths_equal(&desired.path, &grant.path)) + { + let path = PathBuf::from(&grant.path); + if let Err(err) = remove_from_acl(&app_container_sid, &path) { + if is_access_denied(&err) { + remove_paths_to_elevate.push(path); + } else { + return Err(err).wrap_err_with(|| { + format!("revoking sandbox access from {path:?}") + }); + } + } + } + } + + for grant in prepared.desired_effective() { + let path = PathBuf::from(&grant.path); + if let Err(err) = set_acl(&app_container_sid, &path, grant.permission) { + if is_access_denied(&err) { + match grant.permission { + PermissionType::Traverse => parents_to_elevate.push(path), + PermissionType::Read => read_paths_to_elevate.push(path), + PermissionType::Write => write_paths_to_elevate.push(path), + } + } else { + return Err(err).wrap_err_with(|| { + format!("granting sandbox access to {path:?}") + }); + } + } + } + + let mut need_set_network_isolation_elevated = false; + if command.allow_network { + if let Err(err) = try_set_network_isolation(&app_container_sid) { + if is_access_denied(&err) { + info!( + "lacking permission to allow localhost access, elevating" + ); + need_set_network_isolation_elevated = true; + } else { + return Err(err) + .wrap_err("configuring AppContainer network isolation"); + } + } + } + + if !parents_to_elevate.is_empty() + || !read_paths_to_elevate.is_empty() + || !write_paths_to_elevate.is_empty() + || !remove_paths_to_elevate.is_empty() + || need_set_network_isolation_elevated + { + let mut arguments = Vec::::new(); + arguments.push(command.app_container_name.clone()); + arguments.push(if need_set_network_isolation_elevated { + "true".into() + } else { + "false".into() + }); + arguments.push(std::env::join_paths(parents_to_elevate)?.into()); + arguments.push(std::env::join_paths(read_paths_to_elevate)?.into()); + arguments.push(std::env::join_paths(write_paths_to_elevate)?.into()); + arguments.push(std::env::join_paths(remove_paths_to_elevate)?.into()); + + info!(?arguments, "spawning elevated helper command"); + let mut elevated = super::runas::spawn(env.make_helper, arguments) + .wrap_err("spawning elevated helper command")?; + let elevated_status = elevated + .blocking_wait() + .wrap_err("running elevated helper")?; + info!("elevated helper command finished: {elevated_status}"); + eyre::ensure!( + elevated_status.success(), + "elevated helper failed with {elevated_status}" + ); + } + + prepared + .finalize_pruning() + .wrap_err("finalizing AppContainer ACL pruning")?; + + let (pipes, child) = super::spawn( + command.executable.clone().into(), + std::mem::take(&mut command.args), + environment, + command.stdin, + command.stdout, + command.stderr, + command.working_directory, + env.job_handle.clone(), + env.null_device.clone(), + attribute_list, + ) + .wrap_err("spawning child")?; + let process_identity = child + .process_identity() + .wrap_err("reading spawned child process identity")?; + let acl_instance_id = prepared.id(); + prepared + .activate(process_identity) + .wrap_err("activating AppContainer ACL instance")?; + drop(prepared); + + let mut child = crate::SandboxChild { + stdin: pipes.stdin, + stdout: pipes.stdout, + stderr: pipes.stderr, + on_finish: command.on_finish, + handle: SandboxHandle::AppContainer(WindowsSandboxHandle { + path_set: Arc::new(Mutex::new(path_set)), + app_container_sid: Arc::new(app_container_sid_string), + acl_instance_id, + expose_lock: Arc::new(Mutex::new(())), + }), + imp: SandboxChild::AppContainer(child), + }; + + for on_start in command.on_start { + (on_start)(&mut child); + } + + Ok(child) +} + +#[derive(Clone)] +pub struct WindowsSandboxHandle { + path_set: Arc>, + app_container_sid: Arc, + acl_instance_id: Uuid, + expose_lock: Arc>, +} + +impl std::fmt::Debug for WindowsSandboxHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WindowsSandboxHandle") + .finish_non_exhaustive() + } +} + +impl SandboxHandleOp for WindowsSandboxHandle { + fn expose_path( + &self, + path: &Path, + allow_write: bool, + ) -> eyre::Result { + if allow_write { + // Try create an empty file if one doesn't exist yet + // Save dialogs return paths which may not exist, creating + // an empty file allows us to grant permission to that file + // rather than the whole parent directory + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + { + Ok(_) => {} + Err(err) if err.kind() == ErrorKind::AlreadyExists => {} + Err(err) => { + return Err(err).wrap_err_with(|| { + format!("creating empty file {path:?}") + }); + } + } + } + + let path = path + .canonicalize() + .wrap_err_with(|| format!("canonicalizing path {path:?}"))?; + + // Grants on directories are inherited by everything inside them, so + // granting a whole drive would be extremely slow and far too broad + ensure!( + path.parent().is_some(), + "refusing to expose a drive root: {path:?}" + ); + + let permission = if allow_write { + PermissionType::Write + } else { + PermissionType::Read + }; + + let _expose_guard = self.expose_lock.lock(); + + let already_accessible = if allow_write { + self.path_set.lock().can_write(path.to_path_buf()) + } else { + self.path_set.lock().can_read(path.to_path_buf()) + }; + if already_accessible { + return Ok(ExposedPath::Direct); + } + + let mut grants = + vec![Grant::from_path(&path, permission)?.ok_or_else(|| { + eyre!("unable to canonicalize path: {path:?}") + })?]; + let mut parent = path.parent(); + while let Some(parent_path) = parent { + grants.extend(Grant::from_path( + parent_path, + PermissionType::Traverse, + )?); + parent = parent_path.parent(); + } + + let acl_ledger = AppliedAclLedger::open(&self.app_container_sid) + .wrap_err("opening AppContainer ACL ledger")?; + let changed_grants = acl_ledger + .add_grants(self.acl_instance_id, grants) + .wrap_err("recording dynamic AppContainer ACL grants")?; + + let sid = self + .app_container_sid + .encode_wide() + .chain([0]) + .collect::>(); + let mut app_container_sid = PSID::default(); + unsafe { + ConvertStringSidToSidW( + PCWSTR(sid.as_ptr()), + &mut app_container_sid, + )? + }; + ensure!( + !app_container_sid.is_invalid(), + "ConvertStringSidToSidW returned invalid SID" + ); + scopeguard::defer! { + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(app_container_sid.0))) }; + } + + for grant in changed_grants { + let grant_path = PathBuf::from(&grant.path); + set_acl(&app_container_sid, &grant_path, grant.permission) + .wrap_err_with(|| { + format!( + "granting dynamic sandbox {:?} access to {grant_path:?}", + grant.permission + ) + })?; + } + + if allow_write { + self.path_set.lock().insert_writeable(path); + } else { + self.path_set.lock().insert_readable(path); + } + Ok(ExposedPath::Direct) + } + + fn is_path_readable(&self, path: &Path) -> bool { + self.path_set.lock().can_read(path.to_path_buf()) + } + + fn is_path_writeable(&self, path: &Path) -> bool { + self.path_set.lock().can_write(path.to_path_buf()) + } +} + +struct OwnedCapability { + sid_alloc: Vec, +} + +impl OwnedCapability { + pub fn new(known: WELL_KNOWN_SID_TYPE) -> Result { + let mut size = 0; + let result = + unsafe { CreateWellKnownSid(known, None, None, &mut size) }; + if result + != Err(windows::core::Error::from_hresult(HRESULT::from_win32( + ERROR_INSUFFICIENT_BUFFER.0, + ))) + { + result?; + } + let mut sid_alloc = vec![0; size as usize]; + unsafe { + CreateWellKnownSid( + known, + None, + Some(PSID(sid_alloc.as_mut_ptr() as *mut _)), + &mut size, + )? + }; + Ok(Self { sid_alloc }) + } + + pub fn as_psid(&mut self) -> PSID { + PSID(self.sid_alloc.as_mut_ptr() as *mut _) + } +} + +fn app_container_sid_to_string(app_container_sid: &PSID) -> Result { + let mut string_sid = PWSTR::default(); + unsafe { ConvertSidToStringSidW(*app_container_sid, &mut string_sid)? }; + if string_sid.is_null() { + return Err(eyre!("ConvertSidToStringSidW returned a null SID")); + } + scopeguard::defer! { + unsafe { + LocalFree(Some(windows::Win32::Foundation::HLOCAL( + string_sid.0.cast(), + ))) + }; + } + + Ok(OsString::from_wide(unsafe { string_sid.as_wide() })) +} + +fn get_app_container_folder(app_container_sid: &OsStr) -> Result { + let string_sid = app_container_sid + .encode_wide() + .chain([0]) + .collect::>(); + let folder = + unsafe { GetAppContainerFolderPath(PCWSTR(string_sid.as_ptr()))? }; + if folder.is_null() { + return Err(eyre!("GetAppContainerFolderPath returned a null path")); + } + scopeguard::defer! { + unsafe { CoTaskMemFree(Some(folder.0.cast())) }; + } + + Ok(PathBuf::from(OsString::from_wide(unsafe { + folder.as_wide() + }))) +} + +fn create_app_container( + name: &OsStr, + description: &OsStr, +) -> windows::core::Result { + let encoded_name = name.encode_wide().chain([0]).collect::>(); + let encoded_description = + description.encode_wide().chain([0]).collect::>(); + + let mut result = unsafe { + CreateAppContainerProfile( + PCWSTR(encoded_name.as_ptr()), + PCWSTR(encoded_name.as_ptr()), + PCWSTR(encoded_description.as_ptr()), + None, + ) + }; + + if result + == Err(windows::core::Error::from_hresult(HRESULT::from_win32( + ERROR_ALREADY_EXISTS.0, + ))) + { + result = unsafe { + DeriveAppContainerSidFromAppContainerName(PCWSTR( + encoded_name.as_ptr(), + )) + }; + } + + result +} + +fn try_set_network_isolation(app_container: &PSID) -> Result<()> { + let mut current_count: u32 = 0; + let mut current_containers: *mut SID_AND_ATTRIBUTES = std::ptr::null_mut(); + + let result = unsafe { + NetworkIsolationGetAppContainerConfig( + &mut current_count, + &mut current_containers, + ) + }; + scopeguard::defer! { + // https://learn.microsoft.com/en-us/windows/win32/api/netfw/nf-netfw-networkisolationgetappcontainerconfig + let process_heap = unsafe { GetProcessHeap() }; + if let Ok(process_heap) = process_heap { + for index in 0..current_count { + let sid = unsafe { current_containers.offset(index as isize).read() }.Sid; + let _ = unsafe { HeapFree(process_heap, HEAP_FLAGS(0), Some(sid.0)) }; + } + if !current_containers.is_null() { + let _ = unsafe { HeapFree(process_heap, HEAP_FLAGS(0), Some(current_containers as *mut _)) }; + } + } + } + + if result != 0 { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + result, + )) + .into()); + } + + let mut new_containers = Vec::with_capacity(current_count as usize + 1); + for index in 0..current_count { + let sid_and_attributes = + unsafe { current_containers.offset(index as isize).read() }; + if unsafe { EqualSid(sid_and_attributes.Sid, *app_container) }.is_ok() { + // Already allowed + return Ok(()); + } + + new_containers.push(sid_and_attributes); + } + new_containers.push(SID_AND_ATTRIBUTES { + Sid: *app_container, + Attributes: 0, + }); + + let result = unsafe { + NetworkIsolationSetAppContainerConfig(new_containers.as_slice()) + }; + if result != 0 { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + result, + )) + .into()); + } + + Ok(()) +} + +fn is_access_denied(err: &eyre::Report) -> bool { + err.downcast_ref::().is_some_and(|err| { + err.kind() == ErrorKind::PermissionDenied + || err.raw_os_error().unwrap_or(0) + == HRESULT::from_win32(ERROR_ACCESS_DENIED.0).0 + }) || err + .downcast_ref::() + .is_some_and(|err| { + err.code() == HRESULT::from_win32(ERROR_ACCESS_DENIED.0) + }) +} + +fn add_writeattributes_to_winsta(app_container: &PSID) -> Result<()> { + let winsta = unsafe { + OpenWindowStationW( + windows::core::w!("winsta0"), + false, + (READ_CONTROL | WRITE_DAC).0, + ) + }?; + let mut old_acl = std::ptr::null_mut(); + let err = unsafe { + GetSecurityInfo( + HANDLE(winsta.0), + SE_WINDOW_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(&mut old_acl), + None, + None, + ) + }; + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + let mut ea = EXPLICIT_ACCESS_W::default(); + ea.grfAccessMode = GRANT_ACCESS; + ea.grfAccessPermissions = WINSTA_WRITEATTRIBUTES as u32; // Allows use of ClipCursor / SetCursorPos / etc. + ea.grfInheritance = NO_INHERITANCE; + ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; + ea.Trustee.pMultipleTrustee = std::ptr::null_mut(); + ea.Trustee.ptstrName = windows::core::PWSTR(app_container.0 as *mut u16); + ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP; + + let mut new_acl = std::ptr::null_mut(); + let err = + unsafe { SetEntriesInAclW(Some(&[ea]), Some(old_acl), &mut new_acl) }; + if new_acl.is_null() { + return Err(Error::new(ErrorKind::Other, "new acl was null").into()); + } + scopeguard::defer! { + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(new_acl as *mut _))) }; + } + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + match acl_eq(old_acl, new_acl) { + Ok(true) => return Ok(()), + Ok(false) => {} + Err(err) => { + tracing::error!( + "Error comparing ACL for winsta0, updating acl anyways: {err}" + ); + } + } + + let err = unsafe { + SetSecurityInfo( + HANDLE(winsta.0), + SE_WINDOW_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(new_acl), + None, + ) + }; + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + Ok(()) +} + +fn set_acl( + app_container: &PSID, + path: &Path, + perms: PermissionType, +) -> Result<()> { + let encoded_path = path + .as_os_str() + .encode_wide() + .chain([0]) + .collect::>(); + let mut old_acl = std::ptr::null_mut(); + let err = unsafe { + GetNamedSecurityInfoW( + PCWSTR(encoded_path.as_ptr()), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(&mut old_acl), + None, + std::ptr::null_mut(), + ) + }; + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + const TRAVERSE_PERMISSIONS: u32 = FILE_GENERIC_READ.0 | FILE_TRAVERSE.0; + const READ_PERMISSIONS: u32 = TRAVERSE_PERMISSIONS | FILE_GENERIC_EXECUTE.0; + const WRITE_PERMISSIONS: u32 = + READ_PERMISSIONS | FILE_GENERIC_WRITE.0 | DELETE.0; + + let mut ea = EXPLICIT_ACCESS_W::default(); + ea.grfAccessMode = SET_ACCESS; + ea.grfAccessPermissions = match perms { + PermissionType::Traverse => TRAVERSE_PERMISSIONS, + PermissionType::Read => READ_PERMISSIONS, + PermissionType::Write => WRITE_PERMISSIONS, + }; + ea.grfInheritance = if matches!(perms, PermissionType::Traverse) { + NO_INHERITANCE + } else { + OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE + }; + ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; + ea.Trustee.pMultipleTrustee = std::ptr::null_mut(); + ea.Trustee.ptstrName = windows::core::PWSTR(app_container.0 as *mut u16); + ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP; + + let mut new_acl = std::ptr::null_mut(); + let err = + unsafe { SetEntriesInAclW(Some(&[ea]), Some(old_acl), &mut new_acl) }; + if new_acl.is_null() { + return Err(Error::new(ErrorKind::Other, "new acl was null").into()); + } + scopeguard::defer! { + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(new_acl as *mut _))) }; + } + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + if ea.grfInheritance == NO_INHERITANCE { + // Only compare ACLs if inheritance is disabled. + // Sometimes children don't properly inherit the ACLs, + // so we need to be sure to apply them even if the parent is correct + match acl_eq(old_acl, new_acl) { + Ok(true) => return Ok(()), + Ok(false) => {} + Err(err) => { + tracing::error!( + "Error comparing ACL for {path:?}, updating acl anyways: {err}" + ); + } + } + } + + let err = if ea.grfInheritance == NO_INHERITANCE { + // We use SetFileSecurityW (obselete) instead of SetNamedSecurityInfoW (recommended) + // because SetFileSecurityW doesn't automatically propagate changes to children. + // Ideally SetNamedSecurityInfoW would realize that the changes don't affect the + // children, but it's not smart enough. + // This is necessary because propagating to all children of C:\ (for example) is extremely slow + + let mut security_buf = vec![0; 64]; // 64 is SECURITY_DESCRIPTOR_MIN_LENGTH + + unsafe { + InitializeSecurityDescriptor( + PSECURITY_DESCRIPTOR(security_buf.as_mut_ptr() as *mut _), + SECURITY_DESCRIPTOR_REVISION, + )?; + } + + unsafe { + SetSecurityDescriptorDacl( + PSECURITY_DESCRIPTOR(security_buf.as_mut_ptr() as *mut _), + true, + Some(new_acl), + false, + )?; + } + + unsafe { + let success = SetFileSecurityW( + PCWSTR(encoded_path.as_ptr()), + DACL_SECURITY_INFORMATION, + PSECURITY_DESCRIPTOR(security_buf.as_mut_ptr() as *mut _), + ); + if success.as_bool() { + ERROR_SUCCESS + } else { + GetLastError() + } + } + } else { + unsafe { + SetNamedSecurityInfoW( + PCWSTR(encoded_path.as_ptr()), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(new_acl), + None, + ) + } + }; + + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + Ok(()) +} + +fn remove_from_acl(app_container: &PSID, path: &Path) -> Result<()> { + let encoded_path = path + .as_os_str() + .encode_wide() + .chain([0]) + .collect::>(); + let mut old_acl = std::ptr::null_mut(); + let err = unsafe { + GetNamedSecurityInfoW( + PCWSTR(encoded_path.as_ptr()), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(&mut old_acl), + None, + std::ptr::null_mut(), + ) + }; + if err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND { + return Ok(()); + } + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + let mut access = EXPLICIT_ACCESS_W::default(); + access.grfAccessMode = REVOKE_ACCESS; + access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; + access.Trustee.pMultipleTrustee = std::ptr::null_mut(); + access.Trustee.ptstrName = PWSTR(app_container.0 as *mut u16); + access.Trustee.TrusteeForm = TRUSTEE_IS_SID; + access.Trustee.TrusteeType = TRUSTEE_IS_GROUP; + + let mut new_acl = std::ptr::null_mut(); + let err = unsafe { + SetEntriesInAclW(Some(&[access]), Some(old_acl), &mut new_acl) + }; + if new_acl.is_null() { + return Err(Error::new(ErrorKind::Other, "new acl was null").into()); + } + scopeguard::defer! { + unsafe { LocalFree(Some(windows::Win32::Foundation::HLOCAL(new_acl.cast()))) }; + } + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + + let err = unsafe { + SetNamedSecurityInfoW( + PCWSTR(encoded_path.as_ptr()), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(new_acl), + None, + ) + }; + if err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND { + return Ok(()); + } + if err != ERROR_SUCCESS { + return Err(windows::core::Error::from_hresult(HRESULT::from_win32( + err.0, + )) + .into()); + } + Ok(()) +} + +fn acl_eq(first: *const ACL, second: *const ACL) -> Result { + if first.is_null() && second.is_null() { + return Ok(true); + } + let first = unsafe { first.as_ref() }; + let Some(first) = first else { + return Ok(false); + }; + let second = unsafe { second.as_ref() }; + let Some(second) = second else { + return Ok(false); + }; + if first.AceCount != second.AceCount { + return Ok(false); + } + + for i in 0..first.AceCount { + let mut first_ace_ptr = std::ptr::null_mut(); + let mut second_ace_ptr = std::ptr::null_mut(); + unsafe { GetAce(first, i as u32, &mut first_ace_ptr)? }; + unsafe { GetAce(second, i as u32, &mut second_ace_ptr)? }; + + if first_ace_ptr.is_null() && second_ace_ptr.is_null() { + continue; + } + let first_ace_header = + unsafe { first_ace_ptr.cast::().as_ref() }; + let Some(first_ace_header) = first_ace_header else { + return Ok(false); + }; + let second_ace_header = + unsafe { second_ace_ptr.cast::().as_ref() }; + let Some(second_ace_header) = second_ace_header else { + return Ok(false); + }; + + if first_ace_header != second_ace_header { + return Ok(false); + } + + let first_data = unsafe { + std::slice::from_raw_parts( + first_ace_ptr.cast::(), + first_ace_header.AceSize as usize, + ) + }; + let second_data = unsafe { + std::slice::from_raw_parts( + second_ace_ptr.cast::(), + second_ace_header.AceSize as usize, + ) + }; + + if first_data != second_data { + return Ok(false); + } + } + + Ok(true) +} + +pub fn run_helper( + args: impl IntoIterator, +) -> eyre::Result { + let mut args = args.into_iter(); + let ( + Some(app_container_name), + Some(need_set_network_isolation_elevated), + Some(traverse_paths), + Some(read_paths), + Some(write_paths), + Some(remove_paths), + None, + ) = ( + args.next(), + args.next(), + args.next(), + args.next(), + args.next(), + args.next(), + args.next(), + ) + else { + bail!("invalid arguments"); + }; + + let encoded_name = app_container_name + .as_os_str() + .encode_wide() + .chain([0]) + .collect::>(); + + let psid = unsafe { + DeriveAppContainerSidFromAppContainerName(PCWSTR( + encoded_name.as_ptr(), + ))? + }; + scopeguard::defer! { + unsafe { FreeSid(psid) }; + } + ensure!( + !psid.is_invalid(), + "DeriveAppContainerSidFromAppContainerName returned invalid sid" + ); + + let need_set_network_isolation_elevated = + need_set_network_isolation_elevated == OsStr::new("true"); + if need_set_network_isolation_elevated { + try_set_network_isolation(&psid)?; + } + + for path in std::env::split_paths(remove_paths.as_os_str()) { + if !path.as_os_str().is_empty() { + remove_from_acl(&psid, &path)?; + } + } + apply_acl_paths( + &psid, + std::env::split_paths(traverse_paths.as_os_str()), + PermissionType::Traverse, + )?; + apply_acl_paths( + &psid, + std::env::split_paths(read_paths.as_os_str()), + PermissionType::Read, + )?; + apply_acl_paths( + &psid, + std::env::split_paths(write_paths.as_os_str()), + PermissionType::Write, + )?; + + Ok(true) +} + +fn apply_acl_paths( + app_container: &PSID, + paths: impl IntoIterator, + permission: PermissionType, +) -> Result<()> { + for path in paths { + if path.as_os_str().is_empty() { + continue; + } + set_acl(app_container, &path, permission)?; + } + Ok(()) +} diff --git a/packages/modrinth-sandbox/src/backend/windows/mod.rs b/packages/modrinth-sandbox/src/backend/windows/mod.rs new file mode 100644 index 00000000000..db151f12f52 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/windows/mod.rs @@ -0,0 +1,661 @@ +use std::{ + collections::BTreeMap, + ffi::{OsString, c_void}, + os::windows::{ + ffi::OsStrExt, + io::{AsRawHandle, HandleOrInvalid, OwnedHandle}, + }, + path::PathBuf, +}; + +use async_trait::async_trait; +use eyre::{Result, WrapErr, eyre}; +use windows::{ + Win32::{ + Foundation::{ + DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_INSUFFICIENT_BUFFER, + GENERIC_READ, GENERIC_WRITE, HANDLE, HANDLE_FLAG_INHERIT, + SetHandleInformation, TRUE, + }, + Security::SECURITY_ATTRIBUTES, + Storage::FileSystem::{ + CreateFileW, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, + OPEN_EXISTING, + }, + System::{ + Console::{ + GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE, + }, + JobObjects::{ + CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectExtendedLimitInformation, SetInformationJobObject, + }, + Threading::{ + CREATE_UNICODE_ENVIRONMENT, CreateProcessW, + DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, + GetCurrentProcess, InitializeProcThreadAttributeList, + LPPROC_THREAD_ATTRIBUTE_LIST, + PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + PROC_THREAD_ATTRIBUTE_JOB_LIST, PROCESS_CREATION_FLAGS, + PROCESS_INFORMATION, STARTF_FORCEONFEEDBACK, + STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW, + UpdateProcThreadAttribute, + }, + }, + }, + core::{Free, HRESULT}, +}; + +use crate::{ + SandboxArg, SandboxExitStatus, SandboxStdio, + backend::{Pipes, SandboxChildOp}, + util::resolve_path, +}; + +mod acl; +pub(crate) mod appcontainer; +pub(crate) mod runas; + +pub use appcontainer::WindowsSandboxHandle; + +pub(crate) struct ProcThreadAttribute { + pub(crate) attribute: usize, + pub(crate) value: *const std::ffi::c_void, + pub(crate) size: usize, +} + +pub(crate) fn spawn( + program: PathBuf, + arguments: Vec, + environment: BTreeMap, + stdin: SandboxStdio, + stdout: SandboxStdio, + stderr: SandboxStdio, + working_directory: Option, + job_handle: HANDLE, + null_device: HANDLE, + mut attributes: Vec, +) -> Result<(Pipes, WindowsChild)> { + let program = resolve_path(&program).wrap_err("resolving program path")?; + let working_directory = working_directory + .map(|path| resolve_path(&path)) + .transpose() + .wrap_err("resolving working directory path")?; + let application_name = program + .as_os_str() + .encode_wide() + .chain([0]) + .collect::>(); + let mut command_arguments = Vec::with_capacity(arguments.len() + 1); + command_arguments.push(program.clone().into()); + command_arguments.extend(arguments); + let mut command_line = join_windows_shell_arg(&command_arguments) + .encode_wide() + .chain([0]) + .collect::>(); + let current_directory = working_directory.map(|dir| { + dir.as_os_str().encode_wide().chain([0]).collect::>() + }); + + // Create env + let mut env = Vec::new(); + if environment.is_empty() { + env.push(0); + } + for (k, v) in environment { + if k.as_os_str().as_encoded_bytes().contains(&b'\0') + || v.as_os_str().as_encoded_bytes().contains(&b'\0') + { + return Err(eyre!("environment variable contained null byte")); + } + if k.as_os_str().as_encoded_bytes().contains(&b'=') { + return Err(eyre!( + "environment variable key contained equals sign" + )); + } + env.extend(k.as_os_str().encode_wide()); + env.push('=' as u16); + env.extend(v.as_os_str().encode_wide()); + env.push(0); + } + env.push(0); + + // Stdio + let mut stdin_write = None; + let mut stdout_read = None; + let mut stderr_read = None; + + let mut handles_to_close = Vec::new(); + + let mut stdin_read = None; + let mut stdout_write = None; + let mut stderr_write = None; + + match stdin { + SandboxStdio::Null => { + stdin_read = Some(null_device); + } + SandboxStdio::Inherit => { + let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) }?; + if !handle.is_invalid() { + let handle = duplicate_handle_as_inheritable(handle)?; + handles_to_close.push(to_owned_handle(handle)?); + stdin_read = Some(handle); + } + } + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + let owned: OwnedHandle = read.into(); + + stdin_write = Some(write); + unsafe { + SetHandleInformation( + HANDLE(owned.as_raw_handle()), + HANDLE_FLAG_INHERIT.0, + HANDLE_FLAG_INHERIT, + )? + }; + stdin_read = Some(HANDLE(owned.as_raw_handle())); + handles_to_close.push(owned); + } + } + match stdout { + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + let owned: OwnedHandle = write.into(); + + stdout_read = Some(read); + unsafe { + SetHandleInformation( + HANDLE(owned.as_raw_handle()), + HANDLE_FLAG_INHERIT.0, + HANDLE_FLAG_INHERIT, + )? + }; + stdout_write = Some(HANDLE(owned.as_raw_handle())); + handles_to_close.push(owned); + } + SandboxStdio::Null => { + stdout_write = Some(null_device); + } + SandboxStdio::Inherit => { + let handle = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }?; + if !handle.is_invalid() { + let handle = duplicate_handle_as_inheritable(handle)?; + handles_to_close.push(to_owned_handle(handle)?); + stdout_write = Some(handle); + } + } + } + match stderr { + SandboxStdio::Pipe => { + let (read, write) = std::io::pipe()?; + let owned: OwnedHandle = write.into(); + + stderr_read = Some(read); + unsafe { + SetHandleInformation( + HANDLE(owned.as_raw_handle()), + HANDLE_FLAG_INHERIT.0, + HANDLE_FLAG_INHERIT, + )? + }; + stderr_write = Some(HANDLE(owned.as_raw_handle())); + handles_to_close.push(owned); + } + SandboxStdio::Null => { + stderr_write = Some(null_device); + } + SandboxStdio::Inherit => { + let handle = unsafe { GetStdHandle(STD_ERROR_HANDLE) }?; + if !handle.is_invalid() { + let handle = duplicate_handle_as_inheritable(handle)?; + handles_to_close.push(to_owned_handle(handle)?); + stderr_write = Some(handle); + } + } + } + + let mut process_creation_flags = PROCESS_CREATION_FLAGS::default(); + process_creation_flags |= CREATE_UNICODE_ENVIRONMENT; + + let mut si: STARTUPINFOW = Default::default(); + si.cb = size_of::() as u32; + + let mut handle_list = Vec::new(); + if let Some(stdin_read) = stdin_read { + si.dwFlags |= STARTF_USESTDHANDLES; + si.hStdInput = stdin_read; + handle_list.push(stdin_read); + } + if let Some(stdout_write) = stdout_write { + si.dwFlags |= STARTF_USESTDHANDLES; + si.hStdOutput = stdout_write; + handle_list.push(stdout_write); + } + if let Some(stderr_write) = stderr_write { + si.dwFlags |= STARTF_USESTDHANDLES; + si.hStdError = stderr_write; + handle_list.push(stderr_write); + } + + si.dwFlags |= STARTF_FORCEONFEEDBACK; + + if !handle_list.is_empty() { + attributes.push(ProcThreadAttribute { + attribute: PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize, + value: handle_list.as_ptr() as *const _, + size: size_of::() * handle_list.len(), + }); + } + let job_list = &[job_handle]; + attributes.push(ProcThreadAttribute { + attribute: PROC_THREAD_ATTRIBUTE_JOB_LIST as usize, + value: job_list.as_ptr() as *const _, + size: size_of::() * job_list.len(), + }); + + let attribute_count = attributes.len() as u32; + let mut lpsize = 0; + let result = unsafe { + InitializeProcThreadAttributeList( + None, + attribute_count, + None, + &mut lpsize, + ) + }; + + if result + != Err(windows::core::Error::from_hresult(HRESULT::from_win32( + ERROR_INSUFFICIENT_BUFFER.0, + ))) + { + result?; + } + + let mut proc_thread_attribute_list_alloc = vec![0; lpsize]; + let lpproc_thread_attribute_list = LPPROC_THREAD_ATTRIBUTE_LIST( + proc_thread_attribute_list_alloc.as_mut_ptr() as *mut _, + ); + + unsafe { + InitializeProcThreadAttributeList( + Some(lpproc_thread_attribute_list), + attribute_count, + None, + &mut lpsize, + )? + }; + scopeguard::defer! { + unsafe { DeleteProcThreadAttributeList(lpproc_thread_attribute_list) }; + } + + for attribute in attributes { + unsafe { + UpdateProcThreadAttribute( + lpproc_thread_attribute_list, + 0, + attribute.attribute, + Some(attribute.value), + attribute.size, + None, + None, + )? + }; + } + + process_creation_flags |= EXTENDED_STARTUPINFO_PRESENT; + si.cb = size_of::() as u32; + let si_ex = STARTUPINFOEXW { + StartupInfo: si, + lpAttributeList: lpproc_thread_attribute_list, + }; + + let mut pi: PROCESS_INFORMATION = Default::default(); + unsafe { + CreateProcessW( + windows::core::PCWSTR(application_name.as_ptr()), + Some(windows::core::PWSTR(command_line.as_mut_ptr())), + None, + None, + !handle_list.is_empty(), + process_creation_flags, + Some(env.as_ptr() as *mut c_void), + current_directory + .as_ref() + .map(|dir| windows::core::PCWSTR(dir.as_ptr())) + .unwrap_or_default(), + &si_ex.StartupInfo, + &mut pi, + )? + } + + unsafe { + pi.hThread.free(); + }; + + if pi.hProcess.is_invalid() { + return Err(eyre!("CreateProcessW returned invalid process handle")); + } + + drop(handles_to_close); + + return Ok(( + Pipes { + stdin: stdin_write, + stdout: stdout_read, + stderr: stderr_read, + }, + WindowsChild { + process_handle: pi.hProcess, + exit_status: None, + }, + )); +} + +#[derive(Debug)] +pub(crate) struct WindowsChild { + process_handle: HANDLE, + exit_status: Option, +} + +// HANDLE can be sent across threads despite containing *mut c_void +unsafe impl Send for WindowsChild {} +unsafe impl Sync for WindowsChild {} + +impl Drop for WindowsChild { + fn drop(&mut self) { + use windows::core::Free; + unsafe { + std::mem::take(&mut self.process_handle).free(); + } + } +} + +#[async_trait] +impl SandboxChildOp for WindowsChild { + fn id(&self) -> Option { + if self.exit_status.is_some() { + return None; + } + return Some(unsafe { + windows::Win32::System::Threading::GetProcessId(self.process_handle) + }); + } + + fn try_wait(&mut self) -> Result> { + if let Some(exit_status) = self.exit_status { + return Ok(Some(exit_status)); + } + + unsafe { + let wait = windows::Win32::System::Threading::WaitForSingleObject( + self.process_handle, + 0, + ); + if wait == windows::Win32::Foundation::WAIT_FAILED { + return Err(eyre!("wait failed")); + } else if wait == windows::Win32::Foundation::WAIT_TIMEOUT { + return Ok(None); + } + + let mut code = 0; + windows::Win32::System::Threading::GetExitCodeProcess( + self.process_handle, + &mut code, + )?; + self.exit_status = Some(SandboxExitStatus { + imp: WindowsSandboxExitStatus(code), + }); + return Ok(self.exit_status); + } + } + + async fn wait(&mut self) -> Result { + if let Some(exit_status) = self.exit_status { + return Ok(exit_status); + } + + let process_handle = + to_owned_handle(duplicate_handle(self.process_handle, false)?)?; + let code = tokio::task::spawn_blocking(move || unsafe { + let process_handle = HANDLE(process_handle.as_raw_handle()); + let wait = windows::Win32::System::Threading::WaitForSingleObject( + process_handle, + windows::Win32::System::Threading::INFINITE, + ); + if wait == windows::Win32::Foundation::WAIT_FAILED { + return Err(eyre!("wait failed")); + } + + let mut code = 0; + windows::Win32::System::Threading::GetExitCodeProcess( + process_handle, + &mut code, + )?; + Ok(code) + }) + .await + .wrap_err("joining process wait task")??; + + let exit_status = SandboxExitStatus { + imp: WindowsSandboxExitStatus(code), + }; + self.exit_status = Some(exit_status); + Ok(exit_status) + } + + async fn kill(&mut self) -> Result<()> { + unsafe { + windows::Win32::System::Threading::TerminateProcess( + self.process_handle, + 1, + )?; + } + Ok(()) + } +} + +impl WindowsChild { + fn process_identity(&self) -> Result { + let pid = unsafe { + windows::Win32::System::Threading::GetProcessId(self.process_handle) + }; + if pid == 0 { + return Err(std::io::Error::last_os_error().into()); + } + acl::ProcessIdentity::from_handle(pid, self.process_handle) + } + + pub(crate) fn blocking_wait(&mut self) -> Result { + if let Some(exit_status) = self.exit_status { + return Ok(exit_status); + } + + unsafe { + let wait = windows::Win32::System::Threading::WaitForSingleObject( + self.process_handle, + windows::Win32::System::Threading::INFINITE, + ); + if wait == windows::Win32::Foundation::WAIT_FAILED { + return Err(eyre!("wait failed")); + } + + let mut code = 0; + windows::Win32::System::Threading::GetExitCodeProcess( + self.process_handle, + &mut code, + )?; + self.exit_status = Some(SandboxExitStatus { + imp: WindowsSandboxExitStatus(code), + }); + return Ok(SandboxExitStatus { + imp: WindowsSandboxExitStatus(code), + }); + } + } +} + +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct WindowsSandboxExitStatus(pub(crate) u32); + +#[cfg(windows)] +impl std::fmt::Display for WindowsSandboxExitStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.0 & 0x80000000 != 0 { + f.write_fmt(format_args!("exitcode=0x{:#x}", self.0)) + } else { + f.write_fmt(format_args!("exitcode={}", self.0)) + } + } +} + +impl WindowsSandboxExitStatus { + pub fn success(&self) -> bool { + self.0 == 0 + } + + pub fn code(&self) -> Option { + Some(self.0 as i32) + } +} + +pub fn join_windows_shell_arg(args: &[SandboxArg]) -> OsString { + let mut string = Vec::new(); + + let mut first = true; + for arg in args { + let arg = arg.as_os_str(); + let mut backslashes = 0; + + if first { + first = false; + } else { + string.push(b' '); + } + + if arg.is_empty() { + string.extend(b"\"\""); + continue; + } + + let arg_raw = arg.as_encoded_bytes(); + let quoted = arg_raw.contains(&b' ') || arg_raw.contains(&b'\t'); + if quoted { + string.push(b'"'); + } + + for byte in arg_raw { + if *byte == b'\\' { + backslashes += 1; + } else if *byte == b'"' { + for _ in 0..backslashes * 2 { + string.push(b'\\'); + } + string.push(b'\\'); + string.push(b'"'); + backslashes = 0; + } else { + for _ in 0..backslashes { + string.push(b'\\'); + } + backslashes = 0; + string.push(*byte); + } + } + + if quoted { + for _ in 0..backslashes * 2 { + string.push(b'\\'); + } + } else { + for _ in 0..backslashes { + string.push(b'\\'); + } + } + + if quoted { + string.push(b'"'); + } + } + + unsafe { OsString::from_encoded_bytes_unchecked(string) } +} + +pub fn create_job_object() -> Result { + let job_handle = + unsafe { CreateJobObjectW(None, windows::core::PCWSTR::default())? }; + if job_handle.is_invalid() { + return Err(eyre!("CreateJobObjectW returned invalid handle")); + } + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + unsafe { + SetInformationJobObject( + job_handle, + JobObjectExtendedLimitInformation, + &info as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION as _, + size_of::() as u32, + )? + } + Ok(job_handle) +} + +pub fn open_null_device() -> Result { + let sa = SECURITY_ATTRIBUTES { + nLength: size_of::() as u32, + lpSecurityDescriptor: std::ptr::null_mut(), + bInheritHandle: TRUE, + }; + let handle = unsafe { + CreateFileW( + windows::core::w!(r"\\.\NUL"), + (GENERIC_READ | GENERIC_WRITE).0, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + Some(&sa), + OPEN_EXISTING, + Default::default(), + None, + )? + }; + if handle.is_invalid() { + return Err(eyre!("CreateFileW returned invalid handle")); + } + Ok(handle) +} + +pub fn duplicate_handle_as_inheritable(handle: HANDLE) -> Result { + duplicate_handle(handle, true) +} + +fn duplicate_handle(handle: HANDLE, inheritable: bool) -> Result { + let mut duplicated = HANDLE::default(); + unsafe { + let cur_proc = GetCurrentProcess(); + DuplicateHandle( + cur_proc, + handle, + cur_proc, + &mut duplicated, + 0, + inheritable, + DUPLICATE_SAME_ACCESS, + )?; + } + if duplicated.is_invalid() { + return Err(eyre!("DuplicateHandle returned invalid handle")); + } + Ok(duplicated) +} + +pub fn to_owned_handle(handle: HANDLE) -> Result { + let handle = unsafe { HandleOrInvalid::from_raw_handle(handle.0) }; + if let Ok(handle) = OwnedHandle::try_from(handle) { + Ok(handle) + } else { + Err(eyre!("cannot convert invalid handle to owned handle")) + } +} diff --git a/packages/modrinth-sandbox/src/backend/windows/runas.rs b/packages/modrinth-sandbox/src/backend/windows/runas.rs new file mode 100644 index 00000000000..6cf749fff77 --- /dev/null +++ b/packages/modrinth-sandbox/src/backend/windows/runas.rs @@ -0,0 +1,51 @@ +use std::os::windows::ffi::OsStrExt; + +use eyre::{Result, eyre}; +use windows::Win32::UI::Shell::SHELLEXECUTEINFOW; + +use crate::{SandboxArg, helper::MakeHelper}; + +pub fn spawn( + make_helper: MakeHelper, + extra_arguments: Vec, +) -> Result { + let helper = (make_helper)(); + let application_name = helper + .get_program() + .encode_wide() + .chain([0]) + .collect::>(); + let arguments = helper + .get_args() + .map(|argument| argument.to_os_string().into()) + .chain(extra_arguments) + .collect::>(); + let command_line = super::join_windows_shell_arg(arguments.as_slice()) + .encode_wide() + .chain([0]) + .collect::>(); + + let mut sei: SHELLEXECUTEINFOW = SHELLEXECUTEINFOW::default(); + sei.fMask = windows::Win32::UI::Shell::SEE_MASK_NOASYNC + | windows::Win32::UI::Shell::SEE_MASK_NOCLOSEPROCESS; + sei.cbSize = std::mem::size_of::() as _; + sei.lpVerb = windows::core::w!("runas"); + sei.lpFile = windows::core::PCWSTR(application_name.as_ptr()); + sei.lpParameters = windows::core::PCWSTR::from_raw(command_line.as_ptr()); + sei.nShow = windows::Win32::UI::WindowsAndMessaging::SW_HIDE.0; + + unsafe { + windows::Win32::UI::Shell::ShellExecuteExW(&mut sei)?; + } + + if sei.hProcess.is_invalid() { + return Err(eyre!( + "ShellExecuteExW returned invalid process handle. Operation completed via DDE?" + )); + } + + Ok(super::WindowsChild { + process_handle: sei.hProcess, + exit_status: None, + }) +} diff --git a/packages/modrinth-sandbox/src/ffi/child.rs b/packages/modrinth-sandbox/src/ffi/child.rs new file mode 100644 index 00000000000..265eeee4faa --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/child.rs @@ -0,0 +1,427 @@ +use std::{ + io::{PipeReader, PipeWriter, Read, Write}, + ptr::NonNull, + slice, + sync::Arc, +}; + +use eyre::{Context, ContextCompat, Result}; +use libc::size_t; + +use crate::{ + SandboxChild, SandboxExitStatus, + ffi::op::{free, try_do, try_return_optional}, +}; + +pub struct ModrinthSandboxChild { + pub(super) inner: SandboxChild, + pub(super) rt: Arc, +} + +pub struct ModrinthSandboxPipeReader { + inner: PipeReader, +} + +pub struct ModrinthSandboxPipeWriter { + inner: PipeWriter, +} + +/// C representation of a sandboxed child's exit status. +/// +/// If `exited` is false, the other fields have no meaning. If `has_code` is +/// false, the process terminated without an exit code, such as from a signal. +#[derive(Clone, Copy, Debug, Default)] +#[repr(C)] +pub struct ModrinthSandboxExitStatus { + pub exited: bool, + pub success: bool, + pub has_code: bool, + pub code: i32, +} + +impl From> for ModrinthSandboxExitStatus { + fn from(status: Option) -> Self { + let Some(status) = status else { + return Self::default(); + }; + let code = status.code(); + Self { + exited: true, + success: status.success(), + has_code: code.is_some(), + code: code.unwrap_or_default(), + } + } +} + +unsafe fn write_output(out: *mut T, value: T, name: &str) -> Result<()> { + let out = NonNull::new(out) + .wrap_err_with(|| format!("`{name}` must not be null"))?; + + // SAFETY: The caller guarantees that `out` points to valid, properly + // aligned storage for one `T` and does not alias an active reference. + unsafe { out.write(value) }; + Ok(()) +} + +/// Returns the child's platform process ID, or zero when no stable process ID +/// is available for this backend or the child has already exited. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`]. `out_id` must be properly +/// aligned and valid for writing one `u32`. Neither pointer may be concurrently +/// accessed for the duration of this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_id( + child: *const ModrinthSandboxChild, + out_id: *mut u32, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract requires `child` to point to + // a live child for the duration of this call. + let child = + unsafe { child.as_ref() }.wrap_err("`child` must not be null")?; + let id = child.inner.id().unwrap_or_default(); + + // SAFETY: The function's safety contract requires `out_id` to point to + // valid, writable storage for one `u32`. + unsafe { write_output(out_id, id, "out_id") } + }) +} + +/// Attempts to collect the child's exit status without blocking. +/// +/// On success, `out_status.exited` is false when the child is still running. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. `out_status` must be properly aligned and +/// valid for writing one [`ModrinthSandboxExitStatus`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_try_wait( + child: *mut ModrinthSandboxChild, + out_status: *mut ModrinthSandboxExitStatus, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live child for the duration of this call. + let child = + unsafe { child.as_mut() }.wrap_err("`child` must not be null")?; + let status = child + .inner + .try_wait() + .wrap_err("checking sandboxed child status")?; + + // SAFETY: The function's safety contract requires `out_status` to + // point to valid, writable status storage. + unsafe { write_output(out_status, status.into(), "out_status") } + }) +} + +/// Blocks until the child exits and writes its exit status. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. `out_status` must be properly aligned and +/// valid for writing one [`ModrinthSandboxExitStatus`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_wait( + child: *mut ModrinthSandboxChild, + out_status: *mut ModrinthSandboxExitStatus, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live child for the duration of this call. + let child = + unsafe { child.as_mut() }.wrap_err("`child` must not be null")?; + let rt = Arc::clone(&child.rt); + let status = rt + .block_on(child.inner.wait()) + .wrap_err("waiting for sandboxed child")?; + + // SAFETY: The function's safety contract requires `out_status` to + // point to valid, writable status storage. + unsafe { write_output(out_status, Some(status).into(), "out_status") } + }) +} + +/// Forces the child process to exit. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_kill( + child: *mut ModrinthSandboxChild, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live child for the duration of this call. + let child = + unsafe { child.as_mut() }.wrap_err("`child` must not be null")?; + let rt = Arc::clone(&child.rt); + rt.block_on(child.inner.kill()) + .wrap_err("killing sandboxed child") + }) +} + +/// Takes ownership of the child's standard-input pipe. +/// +/// On success, `*out_stdin` is null if stdin was not configured as a pipe or +/// was already taken. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. `out_stdin` must be properly aligned and +/// valid for writing a `*mut ModrinthSandboxPipeWriter`, and must not contain an +/// owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_take_stdin( + child: *mut ModrinthSandboxChild, + out_stdin: *mut *mut ModrinthSandboxPipeWriter, +) -> bool { + // SAFETY: The function's safety contract requires `out_stdin` to point to + // valid, writable pointer storage. + unsafe { + try_return_optional(out_stdin, || { + // SAFETY: The function's safety contract guarantees exclusive + // access to a live child for the duration of this call. + let child = child.as_mut().wrap_err("`child` must not be null")?; + Ok(child + .inner + .stdin + .take() + .map(|inner| ModrinthSandboxPipeWriter { inner })) + }) + } +} + +/// Takes ownership of the child's standard-output pipe. +/// +/// On success, `*out_stdout` is null if stdout was not configured as a pipe or +/// was already taken. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. `out_stdout` must be properly aligned and +/// valid for writing a `*mut ModrinthSandboxPipeReader`, and must not contain an +/// owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_take_stdout( + child: *mut ModrinthSandboxChild, + out_stdout: *mut *mut ModrinthSandboxPipeReader, +) -> bool { + // SAFETY: The function's safety contract requires `out_stdout` to point to + // valid, writable pointer storage. + unsafe { + try_return_optional(out_stdout, || { + // SAFETY: The function's safety contract guarantees exclusive + // access to a live child for the duration of this call. + let child = child.as_mut().wrap_err("`child` must not be null")?; + Ok(child + .inner + .stdout + .take() + .map(|inner| ModrinthSandboxPipeReader { inner })) + }) + } +} + +/// Takes ownership of the child's standard-error pipe. +/// +/// On success, `*out_stderr` is null if stderr was not configured as a pipe or +/// was already taken. +/// +/// # Safety +/// +/// `child` must point to a live child returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] and be exclusively accessible +/// for the duration of this call. `out_stderr` must be properly aligned and +/// valid for writing a `*mut ModrinthSandboxPipeReader`, and must not contain an +/// owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_take_stderr( + child: *mut ModrinthSandboxChild, + out_stderr: *mut *mut ModrinthSandboxPipeReader, +) -> bool { + // SAFETY: The function's safety contract requires `out_stderr` to point to + // valid, writable pointer storage. + unsafe { + try_return_optional(out_stderr, || { + // SAFETY: The function's safety contract guarantees exclusive + // access to a live child for the duration of this call. + let child = child.as_mut().wrap_err("`child` must not be null")?; + Ok(child + .inner + .stderr + .take() + .map(|inner| ModrinthSandboxPipeReader { inner })) + }) + } +} + +/// Reads up to `buffer_len` bytes from a child output pipe. +/// +/// A successful read of zero bytes indicates end-of-file. A null `buffer` is +/// permitted only when `buffer_len` is zero. +/// +/// # Safety +/// +/// `reader` must point to a live reader returned by a child pipe accessor and +/// be exclusively accessible for the duration of this call. If `buffer_len` is +/// nonzero, `buffer` must be valid for writes of `buffer_len` bytes and may not +/// alias `reader` or `out_read`. `out_read` must be properly aligned and valid +/// for writing one `size_t`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_pipe_reader_read( + reader: *mut ModrinthSandboxPipeReader, + buffer: *mut u8, + buffer_len: size_t, + out_read: *mut size_t, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live reader for the duration of this call. + let reader = + unsafe { reader.as_mut() }.wrap_err("`reader` must not be null")?; + let buffer = if buffer_len == 0 { + &mut [] + } else { + let buffer = NonNull::new(buffer).wrap_err( + "`buffer` must not be null when `buffer_len` is nonzero", + )?; + // SAFETY: The function's safety contract guarantees that `buffer` + // is valid for writes of `buffer_len` bytes and uniquely borrowed. + unsafe { slice::from_raw_parts_mut(buffer.as_ptr(), buffer_len) } + }; + let read = reader + .inner + .read(buffer) + .wrap_err("reading child output pipe")?; + + // SAFETY: The function's safety contract requires `out_read` to point + // to valid, writable storage for one `size_t`. + unsafe { write_output(out_read, read, "out_read") } + }) +} + +/// Writes up to `buffer_len` bytes to a child input pipe. +/// +/// A null `buffer` is permitted only when `buffer_len` is zero. +/// +/// # Safety +/// +/// `writer` must point to a live writer returned by +/// [`modrinth_sandbox_child_take_stdin`] and be exclusively accessible for the +/// duration of this call. If `buffer_len` is nonzero, `buffer` must be valid for +/// reads of `buffer_len` bytes and may not alias `writer` or `out_written`. +/// `out_written` must be properly aligned and valid for writing one `size_t`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_pipe_writer_write( + writer: *mut ModrinthSandboxPipeWriter, + buffer: *const u8, + buffer_len: size_t, + out_written: *mut size_t, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live writer for the duration of this call. + let writer = + unsafe { writer.as_mut() }.wrap_err("`writer` must not be null")?; + let buffer = if buffer_len == 0 { + &[] + } else { + let buffer = NonNull::new(buffer.cast_mut()).wrap_err( + "`buffer` must not be null when `buffer_len` is nonzero", + )?; + // SAFETY: The function's safety contract guarantees that `buffer` + // is valid for reads of `buffer_len` bytes. + unsafe { slice::from_raw_parts(buffer.as_ptr(), buffer_len) } + }; + let written = writer + .inner + .write(buffer) + .wrap_err("writing child input pipe")?; + + // SAFETY: The function's safety contract requires `out_written` to + // point to valid, writable storage for one `size_t`. + unsafe { write_output(out_written, written, "out_written") } + }) +} + +/// Flushes a child input pipe. +/// +/// # Safety +/// +/// `writer` must point to a live writer returned by +/// [`modrinth_sandbox_child_take_stdin`] and be exclusively accessible for the +/// duration of this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_pipe_writer_flush( + writer: *mut ModrinthSandboxPipeWriter, +) -> bool { + try_do(|| { + // SAFETY: The function's safety contract guarantees exclusive access + // to a live writer for the duration of this call. + let writer = + unsafe { writer.as_mut() }.wrap_err("`writer` must not be null")?; + writer.inner.flush().wrap_err("flushing child input pipe") + }) +} + +/// Frees a child output pipe reader. +/// +/// # Safety +/// +/// `reader` must be null or a pointer returned by a child pipe accessor that +/// has not already been freed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_pipe_reader_free( + reader: *mut ModrinthSandboxPipeReader, +) { + // SAFETY: The function's safety contract requires every non-null pointer + // to be a uniquely owned allocation returned by `try_return_optional`. + unsafe { free(reader) }; +} + +/// Frees a child input pipe writer, closing the child's standard input. +/// +/// # Safety +/// +/// `writer` must be null or a pointer returned by +/// [`modrinth_sandbox_child_take_stdin`] that has not already been freed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_pipe_writer_free( + writer: *mut ModrinthSandboxPipeWriter, +) { + // SAFETY: The function's safety contract requires every non-null pointer + // to be a uniquely owned allocation returned by `try_return_optional`. + unsafe { free(writer) }; +} + +/// Frees a child returned by [`crate::ffi::modrinth_sandbox_spawn`]. +/// +/// # Safety +/// +/// `child` must be null or a pointer returned by +/// [`crate::ffi::env::modrinth_sandbox_spawn`] that has not already been freed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_child_free( + child: *mut ModrinthSandboxChild, +) { + // SAFETY: The function's safety contract requires every non-null pointer + // to be a uniquely owned allocation returned by `try_return`. + unsafe { free(child) }; +} diff --git a/packages/modrinth-sandbox/src/ffi/command.rs b/packages/modrinth-sandbox/src/ffi/command.rs new file mode 100644 index 00000000000..796f4245086 --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/command.rs @@ -0,0 +1,179 @@ +use eyre::{Context, Result, bail}; + +use crate::ffi::{ + op::{free, try_return}, + str::{ + ModrinthSandboxString, ModrinthSandboxStringOption, + ModrinthSandboxStringPairsSlice, ModrinthSandboxStringSlice, + }, +}; + +#[repr(C)] +pub struct ModrinthSandboxCommandView { + pub executable: ModrinthSandboxString, + pub args: ModrinthSandboxStringSlice, + pub ensure_dirs_exist: ModrinthSandboxStringSlice, + pub read_only_paths: ModrinthSandboxStringSlice, + pub read_write_paths: ModrinthSandboxStringSlice, + pub working_directory: ModrinthSandboxStringOption, + pub passthrough_environment: ModrinthSandboxStringSlice, + pub extra_environment: ModrinthSandboxStringPairsSlice, + pub allow_network: bool, + pub is_jvm: bool, + pub die_with_parent: bool, + pub child_stdin: u32, + pub child_stdout: u32, + pub child_stderr: u32, + pub app_container_name: ModrinthSandboxString, + pub app_container_description: ModrinthSandboxString, +} + +pub struct ModrinthSandboxCommand { + pub(super) inner: crate::SandboxCommand, +} + +pub const MODRINTH_SANDBOX_STDIO_NULL: u32 = 0; +pub const MODRINTH_SANDBOX_STDIO_INHERIT: u32 = 1; +pub const MODRINTH_SANDBOX_STDIO_PIPE: u32 = 2; + +fn stdio(value: u32) -> Result { + match value { + MODRINTH_SANDBOX_STDIO_NULL => Ok(crate::SandboxStdio::Null), + MODRINTH_SANDBOX_STDIO_INHERIT => Ok(crate::SandboxStdio::Inherit), + MODRINTH_SANDBOX_STDIO_PIPE => Ok(crate::SandboxStdio::Pipe), + _ => bail!("unknown sandbox stdio value {value}"), + } +} + +/// Copies a borrowed C command view into a Rust-owned sandbox command. +/// +/// Stdio values use `0` for null, `1` for inherit, and `2` for pipe. +/// +/// # Safety +/// +/// Every pointer reachable through `command_view` must uphold its string or +/// slice type's safety contract for the duration of this call. If `out_command` +/// is non-null, it must be properly aligned and valid for writing a +/// `*mut ModrinthSandboxCommand`, and must not contain an owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_prepare_command( + command_view: ModrinthSandboxCommandView, + out_command: *mut *mut ModrinthSandboxCommand, +) -> bool { + // SAFETY: The function's safety contract requires `out_command` to point + // to valid, writable pointer storage when non-null. The closure copies all + // memory borrowed by `command_view` before returning. + unsafe { + try_return(out_command, move || { + let executable = command_view + .executable + .try_to_owned() + .wrap_err("converting `executable`")?; + let args = command_view + .args + .try_to_owned() + .wrap_err("converting `args`")?; + let ensure_dirs_exist = command_view + .ensure_dirs_exist + .try_to_owned() + .wrap_err("converting `ensure_dirs_exist`")?; + let read_only_paths = command_view + .read_only_paths + .try_to_owned() + .wrap_err("converting `read_only_paths`")?; + let read_write_paths = command_view + .read_write_paths + .try_to_owned() + .wrap_err("converting `read_write_paths`")?; + let working_directory = command_view + .working_directory + .try_to_owned() + .wrap_err("converting `working_directory`")?; + let passthrough_environment = command_view + .passthrough_environment + .try_to_owned() + .wrap_err("converting `passthrough_environment`")?; + let extra_environment = command_view + .extra_environment + .try_to_owned() + .wrap_err("converting `extra_environment`")?; + let app_container_name = command_view + .app_container_name + .try_to_owned() + .wrap_err("converting `app_container_name`")?; + let app_container_description = command_view + .app_container_description + .try_to_owned() + .wrap_err("converting `app_container_description`")?; + + let stdin = stdio(command_view.child_stdin) + .wrap_err("converting `child_stdin`")?; + let stdout = stdio(command_view.child_stdout) + .wrap_err("converting `child_stdout`")?; + let stderr = stdio(command_view.child_stderr) + .wrap_err("converting `child_stderr`")?; + + let command = crate::SandboxCommand { + executable: executable.as_ref().into(), + args: args + .into_iter() + .map(String::from) + .map(Into::into) + .collect(), + ensure_dirs_exist: ensure_dirs_exist + .into_iter() + .map(|path| path.as_ref().into()) + .collect(), + read_only_paths: read_only_paths + .into_iter() + .map(|path| path.as_ref().into()) + .collect(), + read_write_paths: read_write_paths + .into_iter() + .map(|path| path.as_ref().into()) + .collect(), + working_directory: working_directory + .map(|path| path.as_ref().into()), + passthrough_environment: passthrough_environment + .into_iter() + .map(String::from) + .map(Into::into) + .collect(), + extra_environment: extra_environment + .into_iter() + .map(|(key, value)| (key.into(), value.into())) + .collect(), + allow_network: command_view.allow_network, + is_jvm: command_view.is_jvm, + die_with_parent: command_view.die_with_parent, + stdin, + stdout, + stderr, + app_container_name: String::from(app_container_name).into(), + app_container_description: String::from( + app_container_description, + ) + .into(), + on_start: Vec::new(), + on_finish: Vec::new(), + }; + + Ok(ModrinthSandboxCommand { inner: command }) + }) + } +} + +/// Frees a command returned by [`modrinth_sandbox_prepare_command`]. +/// +/// # Safety +/// +/// `command` must be null or a pointer returned by +/// [`modrinth_sandbox_prepare_command`] that has not already been freed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_command_free( + command: *mut ModrinthSandboxCommand, +) { + // SAFETY: The function's safety contract requires every non-null pointer + // to be a uniquely owned allocation returned by `try_return`. + unsafe { free(command) }; +} diff --git a/packages/modrinth-sandbox/src/ffi/env.rs b/packages/modrinth-sandbox/src/ffi/env.rs new file mode 100644 index 00000000000..85e2ba57dd6 --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/env.rs @@ -0,0 +1,146 @@ +use std::{ptr::NonNull, sync::Arc}; + +use eyre::{Context, ContextCompat}; + +use crate::{ + SandboxEnv, + ffi::{ + ModrinthSandboxCommand, + child::ModrinthSandboxChild, + op::{free, try_return}, + }, +}; + +pub struct ModrinthSandboxEnv { + pub(super) env: SandboxEnv, + pub(super) rt: Arc, +} + +/// Creates a sandbox environment and returns an opaque, Rust-owned handle. +/// +/// # Safety +/// +/// If `out_env` is non-null, it must be properly aligned and valid for writing +/// a `*mut ModrinthSandboxEnv`. It must not currently contain an owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_create_env( + out_env: *mut *mut ModrinthSandboxEnv, +) -> bool { + // SAFETY: The function's safety contract requires `out_env` to point to + // valid, writable pointer storage when non-null. + unsafe { + try_return(out_env, || { + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .wrap_err("creating tokio runtime")?; + let env = rt.block_on(SandboxEnv::new())?; + Ok(ModrinthSandboxEnv { + env, + rt: Arc::new(rt), + }) + }) + } +} + +/// Creates an environment that launches processes without sandboxing. +/// +/// This applies no filesystem or network isolation. Sandbox-specific options, +/// including `die_with_parent`, are not enforced. Use [`modrinth_sandbox_spawn`] +/// to launch processes and [`modrinth_sandbox_env_free`] to release the handle. +/// +/// # Safety +/// +/// If `out_env` is non-null, it must be properly aligned and valid for writing +/// a `*mut ModrinthSandboxEnv`. It must not currently contain an owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_create_noop_env( + out_env: *mut *mut ModrinthSandboxEnv, +) -> bool { + // SAFETY: The caller guarantees valid, writable pointer storage when non-null. + unsafe { + try_return(out_env, || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .wrap_err("creating tokio runtime")?; + Ok(ModrinthSandboxEnv { + env: SandboxEnv::noop(), + rt: Arc::new(rt), + }) + }) + } +} + +/// Frees a sandbox or no-op environment. +/// +/// Children spawned through the environment remain usable after the environment +/// is freed because they retain the runtime needed for asynchronous operations. +/// +/// # Safety +/// +/// `env` must be null or a pointer returned by +/// [`modrinth_sandbox_create_env`] or [`modrinth_sandbox_create_noop_env`] +/// that has not already been freed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_env_free( + env: *mut ModrinthSandboxEnv, +) { + // SAFETY: The function's safety contract requires every non-null pointer + // to be a uniquely owned allocation returned by `try_return`. + unsafe { free(env) }; +} + +/// Spawns a sandboxed child and consumes `*command`. +/// +/// Once a non-null command handle has been validated, `*command` is set to +/// null and the command is consumed whether spawning succeeds or fails. +/// +/// # Safety +/// +/// `env` must point to a live environment returned by +/// [`modrinth_sandbox_create_env`] or [`modrinth_sandbox_create_noop_env`] +/// and must not be freed for the duration of +/// this call. `command` must point to valid, writable pointer storage, and a +/// non-null `*command` must be a uniquely owned handle returned by +/// [`crate::ffi::modrinth_sandbox_prepare_command`]. If `out_child` is +/// non-null, it must be properly aligned and valid for writing a +/// `*mut ModrinthSandboxChild`, and must not contain an owned handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_spawn( + env: *const ModrinthSandboxEnv, + command: *mut *mut ModrinthSandboxCommand, + out_child: *mut *mut ModrinthSandboxChild, +) -> bool { + let spawn = move || { + // SAFETY: The caller guarantees that `env` points to a live environment + // which remains valid for the duration of this call. + let env = unsafe { env.as_ref() }.wrap_err("`env` must not be null")?; + + // SAFETY: The caller guarantees that `command` points to valid, + // writable storage containing a command handle. + let command_slot = unsafe { command.as_mut() } + .wrap_err("`command` must not be null")?; + let command = std::mem::replace(command_slot, std::ptr::null_mut()); + let command = + NonNull::new(command).wrap_err("`*command` must not be null")?; + + // SAFETY: The command pointer was returned by `try_return` during + // command preparation. Its ownership was removed from the caller by + // replacing the caller's pointer with null above. + let command = unsafe { Box::from_raw(command.as_ptr()) }; + let ModrinthSandboxCommand { inner: command } = *command; + + let child = env + .rt + .block_on(env.env.spawn(command)) + .wrap_err("spawning sandboxed child")?; + Ok(ModrinthSandboxChild { + inner: child, + rt: Arc::clone(&env.rt), + }) + }; + + // SAFETY: The function's safety contract requires `out_child` to point to + // valid, writable pointer storage when non-null. + unsafe { try_return(out_child, spawn) } +} diff --git a/packages/modrinth-sandbox/src/ffi/helper.rs b/packages/modrinth-sandbox/src/ffi/helper.rs new file mode 100644 index 00000000000..58c7b9e7f10 --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/helper.rs @@ -0,0 +1,77 @@ +use std::{ffi::OsString, ptr::NonNull}; + +use eyre::ContextCompat; + +use super::{op::try_do, str::ModrinthSandboxStringSlice}; + +/// Handles a sandbox helper invocation for the default helper command. +/// +/// Call this near the beginning of the executable, before parsing application +/// arguments or creating a sandbox environment. On success, `out_handled` is +/// true when a helper invocation was handled; the caller should then exit +/// successfully without continuing application initialization. Otherwise, +/// normal application startup should continue. +/// +/// Returns false on failure and sets the last FFI error. A non-null +/// `out_handled` is initialized to false before running the helper. +/// +/// # Safety +/// +/// If `out_handled` is non-null, it must be properly aligned and valid for +/// writing one `bool`, and must not be concurrently accessed during this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_helper_run_default( + out_handled: *mut bool, +) -> bool { + try_do(|| { + let out_handled = NonNull::new(out_handled) + .wrap_err("`out_handled` must not be null")?; + + // SAFETY: The caller guarantees valid, writable storage for one bool. + unsafe { out_handled.write(false) }; + let handled = crate::helper::run_default()?; + // SAFETY: The output storage remains valid for the duration of the call. + unsafe { out_handled.write(handled) }; + Ok(()) + }) +} + +/// Handles a sandbox helper invocation using the provided UTF-8 arguments. +/// +/// The argument list must not include the executable name or +/// `--modrinth-sandbox-helper` argument. On success, `out_handled` is true +/// when a helper invocation was handled; the caller should then exit +/// successfully without continuing application initialization. +/// +/// Returns false on failure and sets the last FFI error. A non-null +/// `out_handled` is initialized to false before converting arguments or +/// running the helper. A null argument pointer with zero length is allowed. +/// +/// # Safety +/// +/// Every pointer reachable through `args` must uphold +/// [`ModrinthSandboxStringSlice::try_to_owned`]'s safety contract for the +/// duration of this call. If `out_handled` is non-null, it must be properly +/// aligned and valid for writing one `bool`, and must not be concurrently +/// accessed during this call or overlap the argument storage. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_helper_run_with_args( + args: ModrinthSandboxStringSlice, + out_handled: *mut bool, +) -> bool { + try_do(|| { + let out_handled = NonNull::new(out_handled) + .wrap_err("`out_handled` must not be null")?; + + // SAFETY: The caller guarantees valid, writable storage for one bool. + unsafe { out_handled.write(false) }; + // SAFETY: The caller guarantees valid argument descriptors and strings. + let args = unsafe { args.try_to_owned() }?; + let handled = crate::helper::run_with_args( + args.into_iter().map(String::from).map(OsString::from), + )?; + // SAFETY: The output storage remains valid for the duration of the call. + unsafe { out_handled.write(handled) }; + Ok(()) + }) +} diff --git a/packages/modrinth-sandbox/src/ffi/mod.rs b/packages/modrinth-sandbox/src/ffi/mod.rs new file mode 100644 index 00000000000..38d37ad54bf --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/mod.rs @@ -0,0 +1,13 @@ +mod child; +mod command; +mod env; +mod helper; +mod op; +mod str; + +pub use child::*; +pub use command::*; +pub use env::*; +pub use helper::*; +pub use op::*; +pub use str::*; diff --git a/packages/modrinth-sandbox/src/ffi/op.rs b/packages/modrinth-sandbox/src/ffi/op.rs new file mode 100644 index 00000000000..291c709709b --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/op.rs @@ -0,0 +1,143 @@ +use std::{ + ffi::c_char, + ptr::{self, NonNull}, + sync::Mutex, +}; + +use eyre::ContextCompat; +use libc::size_t; + +static LAST_ERROR: Mutex> = Mutex::new(None); + +/// Returns the most recent FFI error message. +/// +/// The returned message is not null-terminated and remains valid until the +/// next FFI operation that updates the last error. +/// +/// # Safety +/// +/// `out_message` and `out_message_len` must be valid, properly aligned, +/// writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn modrinth_sandbox_get_last_error( + out_message: *mut *const c_char, + out_message_len: *mut size_t, +) { + let error = LAST_ERROR.lock().expect("should never be poisoned"); + if let Some(error) = error.as_ref() { + // SAFETY: The function's safety contract requires both output + // parameters to point to valid, writable storage. + unsafe { + out_message.write(error.as_ptr().cast()); + out_message_len.write(error.len()); + } + } else { + // SAFETY: The function's safety contract requires both output + // parameters to point to valid, writable storage. + unsafe { + out_message.write(std::ptr::null()); + out_message_len.write(0); + } + } +} + +/// Runs `f` and handles failure. +/// +/// Before every run, the last error is cleared. +/// +/// If `f` returns [`Ok`], this returns `true` and no error is written. +/// +/// If `f` returns [`Err`], this returns `false` and sets the last error to +/// the error message. +pub fn try_do(f: impl FnOnce() -> eyre::Result<()>) -> bool { + *LAST_ERROR.lock().expect("should never be poisoned") = None; + match f() { + Ok(()) => true, + Err(err) => { + *LAST_ERROR.lock().expect("should never be poisoned") = + Some(format!("{err:#}")); + false + } + } +} + +/// Runs `f` and writes its return value to a Rust-owned opaque pointer. +/// +/// # Safety +/// +/// If `out` is non-null, it must be properly aligned and valid for writing a +/// `*mut R`. It must not currently contain an owned pointer that would be +/// leaked by overwriting it. +pub unsafe fn try_return( + out: *mut *mut R, + f: impl FnOnce() -> eyre::Result, +) -> bool { + try_do(move || { + let out = NonNull::new(out) + .wrap_err("out parameter value must not be null")?; + + // SAFETY: The caller guarantees that `out` points to valid, writable + // storage for one pointer. Writing null establishes the failure state + // without reading or dropping the previous pointer value. + unsafe { out.write(ptr::null_mut()) }; + + match f() { + Ok(r) => { + let r = Box::new(r); + + // SAFETY: The caller guarantees that `out` points to valid, + // writable storage for one pointer. `Box::into_raw` returns a + // valid owned pointer for the caller to release through the + // corresponding FFI free function. + unsafe { out.write(Box::into_raw(r)) }; + Ok(()) + } + Err(err) => Err(err), + } + }) +} + +/// Runs `f` and writes its optional return value to a Rust-owned opaque pointer. +/// +/// A successful [`None`] result is represented by a null output pointer. +/// +/// # Safety +/// +/// If `out` is non-null, it must be properly aligned and valid for writing a +/// `*mut R`. It must not currently contain an owned pointer that would be +/// leaked by overwriting it. +pub unsafe fn try_return_optional( + out: *mut *mut R, + f: impl FnOnce() -> eyre::Result>, +) -> bool { + try_do(move || { + let out = NonNull::new(out) + .wrap_err("out parameter value must not be null")?; + + // SAFETY: The caller guarantees that `out` points to valid, writable + // storage for one pointer. Writing null represents both the initial + // failure state and a successful `None` result. + unsafe { out.write(ptr::null_mut()) }; + + if let Some(value) = f()? { + // SAFETY: The caller guarantees that `out` points to valid, + // writable storage for one pointer. `Box::into_raw` returns a + // valid owned pointer for the caller to release through the + // corresponding FFI free function. + unsafe { out.write(Box::into_raw(Box::new(value))) }; + } + Ok(()) + }) +} + +/// Frees the value behind `ptr` if the pointer is not null. +/// +/// # Safety +/// +/// `ptr` must be null or point to a valid `T` that has not already been freed. +pub unsafe fn free(ptr: *mut T) { + if !ptr.is_null() { + let value = unsafe { Box::from_raw(ptr) }; + drop(value); + } +} diff --git a/packages/modrinth-sandbox/src/ffi/str.rs b/packages/modrinth-sandbox/src/ffi/str.rs new file mode 100644 index 00000000000..af8bf6cc433 --- /dev/null +++ b/packages/modrinth-sandbox/src/ffi/str.rs @@ -0,0 +1,176 @@ +use std::{ffi::c_char, ptr::NonNull, slice, str}; + +use eyre::{Context, ContextCompat, Result, ensure}; +use libc::size_t; + +/// A borrowed UTF-8 string. `len` counts bytes; no trailing NUL is required. +#[derive(Clone, Copy)] +#[repr(C)] +pub struct ModrinthSandboxString { + pub ptr: *const c_char, + pub len: size_t, +} + +/// An optional borrowed UTF-8 string. `len` counts bytes; no trailing NUL is +/// required. A null pointer with zero length represents an absent string. +#[derive(Clone, Copy)] +#[repr(C)] +pub struct ModrinthSandboxStringOption { + pub ptr: *const c_char, + pub len: size_t, +} + +#[derive(Clone, Copy)] +#[repr(C)] +pub struct ModrinthSandboxStringSlice { + pub ptr: *const ModrinthSandboxString, + pub len: size_t, +} + +#[derive(Clone, Copy)] +#[repr(C)] +pub struct ModrinthSandboxStringPairsSlice { + pub key_ptr: *const ModrinthSandboxString, + pub key_len: size_t, + pub value_ptr: *const ModrinthSandboxString, + pub value_len: size_t, +} + +impl ModrinthSandboxString { + /// Copies this borrowed UTF-8 string into Rust-owned memory. + /// + /// # Safety + /// + /// `ptr` must be non-null. If `len` is nonzero, `ptr` must be valid for + /// reading `len` bytes for the duration of this call. + pub unsafe fn try_to_owned(self) -> Result> { + let ptr = NonNull::new(self.ptr.cast_mut()) + .wrap_err("expected a non-null string")?; + + // SAFETY: The caller guarantees that `ptr` is valid for reading + // `len` bytes. The pointer was checked for null above, and `u8` has + // alignment 1, including for an empty slice. + let bytes = unsafe { + slice::from_raw_parts(ptr.as_ptr().cast::(), self.len) + }; + + let value = str::from_utf8(bytes).wrap_err("string is not UTF-8")?; + Ok(value.into()) + } +} + +impl ModrinthSandboxStringOption { + /// Copies this optional borrowed UTF-8 string into Rust-owned memory. + /// + /// A null pointer with a zero length represents [`None`]. A non-null + /// pointer represents [`Some`], including when the length is zero. + /// + /// # Safety + /// + /// If `ptr` is non-null and `len` is nonzero, `ptr` must be valid for + /// reading `len` bytes for the duration of this call. + pub unsafe fn try_to_owned(self) -> Result>> { + if self.ptr.is_null() { + ensure!( + self.len == 0, + "optional string has a null pointer with a nonzero length" + ); + return Ok(None); + } + + // SAFETY: The caller guarantees that a non-null pointer is valid for + // reading `len` bytes. `ModrinthSandboxString` has the same contract. + let value = unsafe { + ModrinthSandboxString { + ptr: self.ptr, + len: self.len, + } + .try_to_owned() + }?; + Ok(Some(value)) + } +} + +impl ModrinthSandboxStringSlice { + /// Copies this borrowed slice and all of its UTF-8 strings into + /// Rust-owned memory. + /// + /// A null pointer with a zero length represents an empty slice. + /// + /// # Safety + /// + /// If `len` is nonzero, `ptr` must be properly aligned and valid for + /// reading `len` [`ModrinthSandboxString`] values. Every string in the + /// slice must uphold [`ModrinthSandboxString::try_to_owned`]'s safety + /// contract. + pub unsafe fn try_to_owned(self) -> Result>> { + if self.len == 0 { + return Ok(Vec::new()); + } + + let ptr = NonNull::new(self.ptr.cast_mut()) + .wrap_err("expected a non-null string slice")?; + + // SAFETY: The caller guarantees that `ptr` is properly aligned and + // valid for reading `len` string descriptors. The zero-length case was + // handled above and the pointer was checked for null. + let items = unsafe { slice::from_raw_parts(ptr.as_ptr(), self.len) }; + let mut strings = Vec::with_capacity(items.len()); + for (index, item) in items.iter().copied().enumerate() { + // SAFETY: The caller guarantees that every string descriptor in + // the slice upholds `ModrinthSandboxString`'s safety contract. + let string = unsafe { item.try_to_owned() } + .wrap_err_with(|| format!("reading string at index {index}"))?; + strings.push(string); + } + + Ok(strings) + } +} + +impl ModrinthSandboxStringPairsSlice { + /// Copies these parallel key and value slices into Rust-owned pairs. + /// + /// # Safety + /// + /// If the corresponding length is nonzero, `key_ptr` and `value_ptr` must + /// each be properly aligned and valid for reading that many + /// [`ModrinthSandboxString`] values. Every string in both slices must + /// uphold [`ModrinthSandboxString::try_to_owned`]'s safety contract. + pub unsafe fn try_to_owned(self) -> Result> { + ensure!( + self.key_len == self.value_len, + "string pair slices have different lengths: {} keys and {} values", + self.key_len, + self.value_len + ); + + // SAFETY: The caller guarantees that the key slice and each of its + // string descriptors uphold their respective safety contracts. + let keys = unsafe { + ModrinthSandboxStringSlice { + ptr: self.key_ptr, + len: self.key_len, + } + .try_to_owned() + } + .wrap_err("reading string pair keys")?; + + // SAFETY: The caller guarantees that the value slice and each of its + // string descriptors uphold their respective safety contracts. + let values = unsafe { + ModrinthSandboxStringSlice { + ptr: self.value_ptr, + len: self.value_len, + } + .try_to_owned() + } + .wrap_err("reading string pair values")?; + + Ok(keys + .into_iter() + .zip(values) + .map(|(key, value)| (String::from(key), String::from(value))) + .collect()) + } +} diff --git a/packages/modrinth-sandbox/src/file_sharing.rs b/packages/modrinth-sandbox/src/file_sharing.rs new file mode 100644 index 00000000000..192f28606aa --- /dev/null +++ b/packages/modrinth-sandbox/src/file_sharing.rs @@ -0,0 +1,3038 @@ +use std::{ + collections::{HashMap, HashSet, VecDeque}, + ffi::OsStr, + hash::Hash, + os::{ + fd::{AsFd, BorrowedFd, OwnedFd}, + unix::ffi::OsStrExt, + }, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, SystemTime}, +}; + +use eyre::{Context, bail, eyre}; +use indexmap::IndexMap; +use parking_lot::Mutex; +use rand::RngExt; +use rustix::fs::{AtFlags, OFlags, RenameFlags}; + +const TTL: Duration = Duration::ZERO; +const O_DEFAULT: OFlags = OFlags::NOFOLLOW.union(OFlags::CLOEXEC); + +pub fn mount(mountpoint: PathBuf) -> eyre::Result { + if fuser::INodeNo::ROOT.0 != 1 { + bail!("expected root inode to have value 1"); + } + + let abort = AbortHandle::default(); + let filesystem = FileSharingFS(Arc::new(Mutex::new(FileSharingFSInner { + mountpoint: mountpoint.clone(), + process_uid: rustix::process::getuid().as_raw(), + process_gid: rustix::process::getgid().as_raw(), + abort: abort.clone(), + files: FileSharingFiles { + abort, + ..Default::default() + }, + ..Default::default() + }))); + let mut cfg = fuser::Config::default(); + cfg.mount_options.push(fuser::MountOption::FSName( + "modrinth-sandbox-file-sharing".to_string(), + )); + cfg.mount_options.push(fuser::MountOption::RW); + cfg.mount_options.push(fuser::MountOption::NoDev); + cfg.mount_options.push(fuser::MountOption::NoSuid); + cfg.mount_options + .push(fuser::MountOption::DefaultPermissions); + cfg.acl = fuser::SessionACL::Owner; + _ = std::fs::create_dir_all(&mountpoint); + let session = fuser::spawn_mount(filesystem.clone(), mountpoint, &cfg) + .context("mounting fuse filesystem")?; + + let (delete_sender, delete_receiver) = std::sync::mpsc::channel::<( + fuser::INodeNo, + fuser::INodeNo, + Arc, + )>(); + + let notifier = session.notifier(); + std::thread::Builder::new() + .name("INode Delete Notifier Thread".to_string()) + .stack_size(16384) + .spawn(move || { + loop { + let Ok((parent, child, name)) = delete_receiver.recv() else { + return; + }; + _ = notifier.delete(parent, child, &name); + } + }) + .context("spawning thread to handle inode deletion")?; + + filesystem.0.lock().files.delete_notifier = Some(delete_sender); + Ok(FileSharing { + filesystem, + session: Arc::new(session), + }) +} + +#[derive(Clone, Debug)] +pub struct FileSharing { + filesystem: FileSharingFS, + session: Arc, +} + +impl FileSharing { + pub fn add(&self, path: PathBuf, mutable: bool) -> eyre::Result { + let mut fs = self.filesystem.0.lock(); + if let Some(shutdown_reason) = fs.abort.get_abort_message() { + bail!(shutdown_reason); + } + + let Some(parent) = path.parent() else { + bail!("path must have a parent to be shared"); + }; + let Some(filename) = path.file_name() else { + bail!("path must have a filename to be shared"); + }; + let filename: Arc = filename.into(); + + let dirfd = match rustix::fs::open( + parent, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) { + Ok(dirfd) => dirfd, + Err(errno) => { + let io_error = + std::io::Error::from_raw_os_error(errno.raw_os_error()); + return Err( + eyre!("unable to open parent directory").wrap_err(io_error) + ); + } + }; + + let parent_stat = match rustix::fs::fstat(&dirfd) { + Ok(stat) => stat, + Err(errno) => { + let io_error = + std::io::Error::from_raw_os_error(errno.raw_os_error()); + return Err( + eyre!("unable to stat parent directory").wrap_err(io_error) + ); + } + }; + let child_stat = match rustix::fs::statat( + &dirfd, + &*filename, + AtFlags::SYMLINK_NOFOLLOW, + ) { + Ok(stat) => Some(stat), + Err(errno) => { + if errno == rustix::io::Errno::NOENT { + None + } else { + let io_error = + std::io::Error::from_raw_os_error(errno.raw_os_error()); + return Err(eyre!("unable to stat file").wrap_err(io_error)); + } + } + }; + + let mut identified_parent = IdentifiedFd { + st_ino: parent_stat.st_ino, + st_dev: parent_stat.st_dev as u64, + fd: Arc::new(dirfd), + }; + + let files = &mut fs.files; + if let Some(parent_data) = + files.existing_parents.get_mut(&identified_parent) + { + // Reuse existing parent fd + identified_parent = parent_data.own_fd.clone(); + + // Try find existing bind + let hexes = if mutable { + &parent_data.rw + } else { + &parent_data.ro + }; + + for hex_bytes in hexes { + let Some(node_index) = files.hex_to_node_index.get(hex_bytes) + else { + continue; + }; + let Some(Some(node)) = files.nodes.get_mut(node_index.0) else { + continue; + }; + let FileNodeInner::RootFile(root) = &node.inner else { + continue; + }; + if node.filename == filename { + let hex_bytes = root.hex; + + let mut path = fs.mountpoint.join(hex::encode(hex_bytes)); + path.push(&*filename); + + return Ok(path); + } + } + } + + let file_type = child_stat.map(|stat| { + to_fuser_filetype(rustix::fs::FileType::from_raw_mode(stat.st_mode)) + }); + let hex_bytes = fs.files.add_file( + identified_parent.clone(), + filename.clone(), + file_type, + mutable, + ); + + if let Some(shutdown_reason) = fs.abort.get_abort_message() { + bail!(shutdown_reason); + } + + let parent_data = fs + .files + .existing_parents + .entry(identified_parent.clone()) + .or_insert_with(|| ExistingParentData { + own_fd: identified_parent, + ro: Vec::new(), + rw: Vec::new(), + }); + if mutable { + parent_data.rw.push(hex_bytes); + } else { + parent_data.ro.push(hex_bytes); + }; + + let mut path = fs.mountpoint.join(hex::encode(hex_bytes)); + path.push(&*filename); + + Ok(path) + } + + pub fn join(self) -> eyre::Result<()> { + Arc::into_inner(self.session).unwrap().join()?; + Ok(()) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum INodeType { + Root, + HexFolder(FileNodeIndex), + FileNode(FileNodeIndex), +} + +impl INodeType { + pub fn from_ino(ino: fuser::INodeNo) -> Option { + if ino.0 == 0 { + return None; + } + debug_assert_eq!(fuser::INodeNo::ROOT.0, 1); + if ino == fuser::INodeNo::ROOT { + return Some(Self::Root); + } + let index = (ino.0 >> 1).checked_sub(1)?; + if (ino.0 & 1) == 1 { + Some(Self::HexFolder(FileNodeIndex(index as usize))) + } else { + Some(Self::FileNode(FileNodeIndex(index as usize))) + } + } + + pub fn to_ino(self) -> fuser::INodeNo { + match self { + INodeType::Root => fuser::INodeNo::ROOT, + INodeType::HexFolder(index) => { + fuser::INodeNo(((index.0.strict_add(1) << 1) | 1) as u64) + } + INodeType::FileNode(index) => { + fuser::INodeNo((index.0.strict_add(1) << 1) as u64) + } + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +struct FileNodeIndex(usize); + +#[derive(Debug)] +struct FileNode { + own_index: FileNodeIndex, + generation: fuser::Generation, + refcnt: usize, + file_type: Option, + filename: Arc, + subfiles: IndexMap, FileNodeIndex>, + inner: FileNodeInner, +} + +#[derive(Debug)] +enum FileNodeInner { + RootFile(RootFileNode), + Subfile(SubfileNode), +} + +#[derive(Debug)] +struct RootFileNode { + hex: [u8; 16], + // SECURITY: We store the parent FD + filename here instead of a path to prevent exploits + // If a path was used instead, a parent directory or the file itself could be set to a symlink + // pointing outside the folder. + // We use methods like openat, fstatat, etc. with the parent fd + filename and the NOFOLLOW flag + // to interact with the referenced file in a safe way + dirfd: IdentifiedFd, + mutable: bool, +} + +#[derive(Debug)] +struct SubfileNode { + parent: FileNodeIndex, +} + +#[derive(Clone, Debug)] +struct IdentifiedFd { + st_ino: u64, + st_dev: u64, + fd: Arc, +} + +impl AsFd for IdentifiedFd { + fn as_fd(&self) -> BorrowedFd<'_> { + self.fd.as_fd() + } +} + +impl PartialEq for IdentifiedFd { + fn eq(&self, other: &Self) -> bool { + self.st_ino == other.st_ino && self.st_dev == other.st_dev + } +} + +impl Eq for IdentifiedFd {} + +impl PartialOrd for IdentifiedFd { + fn partial_cmp(&self, other: &Self) -> Option { + match self.st_ino.partial_cmp(&other.st_ino) { + Some(std::cmp::Ordering::Equal) => {} + ord => return ord, + } + match self.st_dev.partial_cmp(&other.st_dev) { + Some(std::cmp::Ordering::Equal) => {} + ord => return ord, + } + Some(std::cmp::Ordering::Equal) + } +} + +impl Ord for IdentifiedFd { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + match self.st_ino.cmp(&other.st_ino) { + std::cmp::Ordering::Equal => {} + ord => return ord, + } + match self.st_dev.cmp(&other.st_dev) { + std::cmp::Ordering::Equal => {} + ord => return ord, + } + std::cmp::Ordering::Equal + } +} + +impl Hash for IdentifiedFd { + fn hash(&self, state: &mut H) { + self.st_ino.hash(state); + self.st_dev.hash(state); + } +} + +#[derive(PartialEq, Eq, Debug)] +enum FileHandleOpenedBy { + Open, + Opendir, +} + +#[derive(Debug)] +struct FileHandleData { + opened_by: FileHandleOpenedBy, + underlying_fd: Option>, + underlying_dir_entries: Option, + mutable: bool, +} + +#[derive(Debug)] +enum UnderlyingDirEntries { + HexFolders { + hex_folders: Box<[([u8; 16], FileNodeIndex)]>, + }, + Single { + filename: Arc, + file_node_index: FileNodeIndex, + }, + Backed { + dir: rustix::fs::Dir, + last_offset: u64, + pending: Option, + parent: FileNodeIndex, + }, +} + +#[derive(Default, Clone, Debug)] +struct AbortHandle(Arc); + +#[derive(Default, Debug)] +struct AbortHandleInner { + reason: Mutex<&'static str>, + aborted: AtomicBool, +} + +impl AbortHandle { + pub fn abort(&self, reason: &'static str) { + if !self.0.aborted.swap(true, Ordering::Relaxed) { + *self.0.reason.lock() = reason; + } + tracing::error!( + "Aborting file sharing fs due to unexpected error: {reason})" + ); + } + + pub fn is_aborted(&self) -> bool { + self.0.aborted.load(Ordering::Relaxed) + } + + pub fn get_abort_message(&self) -> Option<&'static str> { + if self.0.aborted.load(Ordering::Relaxed) { + Some(*self.0.reason.lock()) + } else { + None + } + } +} + +#[derive(Default, Debug)] +struct FileSharingFSInner { + mountpoint: PathBuf, + process_uid: u32, + process_gid: u32, + abort: AbortHandle, + reuse_buffer: Vec, + + files: FileSharingFiles, + + last_handle_id: u64, + file_handle_data: HashMap, +} + +#[derive(Debug)] +struct ExistingParentData { + own_fd: IdentifiedFd, + ro: Vec<[u8; 16]>, + rw: Vec<[u8; 16]>, +} + +#[derive(Default, Debug)] +struct FileSharingFiles { + abort: AbortHandle, + nodes: Vec>, + node_index_pending_forget: + HashMap, + node_index_free_list: VecDeque<(FileNodeIndex, fuser::Generation)>, + hex_to_node_index: IndexMap<[u8; 16], FileNodeIndex>, + + existing_parents: HashMap, + + delete_notifier: Option< + std::sync::mpsc::Sender<(fuser::INodeNo, fuser::INodeNo, Arc)>, + >, +} + +impl FileSharingFiles { + fn get_node_mut( + &mut self, + file_node_index: FileNodeIndex, + ) -> Result<&mut FileNode, fuser::Errno> { + let Some(Some(file_node)) = self.nodes.get_mut(file_node_index.0) + else { + return Err(fuser::Errno::ENOENT); + }; + if file_node.own_index != file_node_index { + self.abort.abort("get_node_mut: file_node.own_index doesn't match index in fs.nodes"); + Err(fuser::Errno::EIO) + } else { + Ok(file_node) + } + } + + fn get_node( + &self, + file_node_index: FileNodeIndex, + ) -> Result<&FileNode, fuser::Errno> { + let Some(Some(file_node)) = self.nodes.get(file_node_index.0) else { + return Err(fuser::Errno::ENOENT); + }; + if file_node.own_index != file_node_index { + self.abort.abort( + "get_node: file_node.own_index doesn't match index in fs.nodes", + ); + Err(fuser::Errno::EIO) + } else { + Ok(file_node) + } + } + + fn take_node_index(&mut self) -> (FileNodeIndex, fuser::Generation) { + if let Some((id, generation)) = self.node_index_free_list.pop_front() { + (id, fuser::Generation(generation.0 + 1)) + } else { + (FileNodeIndex(self.nodes.len()), fuser::Generation(0)) + } + } + + fn open_ino( + &mut self, + ino: fuser::INodeNo, + flags: OFlags, + ) -> Result, fuser::Errno> { + self.open_ino_and_check_mutable( + ino, + flags, + (flags & OFlags::ACCMODE) != OFlags::RDONLY, + ) + } + + fn open_ino_and_check_mutable( + &mut self, + ino: fuser::INodeNo, + flags: OFlags, + check_mutable: bool, + ) -> Result, fuser::Errno> { + let flags = O_DEFAULT | flags; + + let Some(ino_type) = INodeType::from_ino(ino) else { + return Err(fuser::Errno::ENOENT); + }; + + let file_node_index = match ino_type { + INodeType::Root | INodeType::HexFolder(_) => { + return Err(fuser::Errno::EACCES); + } + INodeType::FileNode(file_node_index) => file_node_index, + }; + + let node = self.get_node(file_node_index)?; + + match &node.inner { + FileNodeInner::RootFile(root_file_node) => { + if check_mutable && !root_file_node.mutable { + return Err(fuser::Errno::EACCES); + } + + let fd = rustix::fs::openat( + &root_file_node.dirfd, + &*node.filename, + flags, + rustix::fs::Mode::empty(), + ) + .map_err(to_fuser_errno)?; + + Ok(Arc::new(fd)) + } + FileNodeInner::Subfile(_) => { + let mut visited = HashSet::new(); + let mut filenames = VecDeque::new(); + + let mut scan_node_index = file_node_index; + let parent_fd = loop { + let node = self.get_node(scan_node_index)?; + + match &node.inner { + FileNodeInner::RootFile(root_file_node) => { + if check_mutable && !root_file_node.mutable { + return Err(fuser::Errno::EACCES); + } + + break rustix::fs::openat( + &root_file_node.dirfd, + &*node.filename, + O_DEFAULT | OFlags::RDONLY | OFlags::DIRECTORY, + rustix::fs::Mode::empty(), + ) + .map_err(to_fuser_errno)?; + } + FileNodeInner::Subfile(subfile_node) => { + filenames.push_front(node.filename.clone()); + + visited.insert(scan_node_index); + if visited.contains(&subfile_node.parent) { + return Err(fuser::Errno::ELOOP); + } + if visited.len() > 256 { + return Err(fuser::Errno::ENAMETOOLONG); + } + scan_node_index = subfile_node.parent; + } + } + }; + + // Try to use OPENAT2 with RESOLVE_BENEATH + #[cfg(target_os = "linux")] + { + let mut relative_path = PathBuf::new(); + for filename in &filenames { + relative_path.push(&**filename); + } + + static SUPPORTS_OPENAT2: AtomicBool = AtomicBool::new(true); + if SUPPORTS_OPENAT2.load(Ordering::Relaxed) { + for _ in 0..3 { + // Retry up to 3 times if receiving EAGAIN + let result = rustix::fs::openat2( + &parent_fd, + &relative_path, + flags, + rustix::fs::Mode::empty(), + rustix::fs::ResolveFlags::BENEATH, + ) + .map_err(to_fuser_errno); + match result { + Ok(fd) => { + return Ok(Arc::new(fd)); + } + Err(errno) => { + if errno == fuser::Errno::ENOSYS + || errno == fuser::Errno::EPERM + { + SUPPORTS_OPENAT2 + .store(false, Ordering::Relaxed); + break; + } else if errno == fuser::Errno::EAGAIN { + continue; + } else { + return Err(errno); + } + } + } + } + } + } + + // When OPENAT2 isn't supported, we fall back to opening each directory in order with O_NOFOLLOW + let mut last_fd = parent_fd; + + let filenames_len = filenames.len(); + for (index, filename) in filenames.into_iter().enumerate() { + let open_flags = if index + 1 < filenames_len { + // Open directory + O_DEFAULT | OFlags::RDONLY | OFlags::DIRECTORY + } else { + flags + }; + last_fd = rustix::fs::openat( + &last_fd, + &*filename, + open_flags, + rustix::fs::Mode::empty(), + ) + .map_err(to_fuser_errno)?; + } + + Ok(Arc::new(last_fd)) + } + } + } + + fn open_ino_for_child( + &mut self, + ino: fuser::INodeNo, + child: &OsStr, + check_mutable: bool, + ) -> Result, fuser::Errno> { + let Some(inode_type) = INodeType::from_ino(ino) else { + return Err(fuser::Errno::ENOENT); + }; + + let flags = O_DEFAULT | OFlags::RDONLY | OFlags::DIRECTORY; + + match inode_type { + INodeType::Root => Err(fuser::Errno::EACCES), + INodeType::HexFolder(file_node_index) => { + let node = self.get_node(file_node_index)?; + match &node.inner { + FileNodeInner::RootFile(root_file_node) => { + if check_mutable && !root_file_node.mutable { + Err(fuser::Errno::EACCES) + } else if &*node.filename != child { + if check_mutable { + Err(fuser::Errno::EACCES) + } else { + Err(fuser::Errno::ENOENT) + } + } else { + Ok(root_file_node.dirfd.fd.clone()) + } + } + FileNodeInner::Subfile(_) => { + self.abort.abort("open_ino_for_child: HexFolder inode contained subfile instead of rootfile"); + Err(fuser::Errno::EIO) + } + } + } + INodeType::FileNode(_) => { + self.open_ino_and_check_mutable(ino, flags, check_mutable) + } + } + } + + fn open_parent_ino( + &mut self, + ino: fuser::INodeNo, + check_mutable: bool, + ) -> Result<(Arc, Arc), fuser::Errno> { + let Some(inode_type) = INodeType::from_ino(ino) else { + return Err(fuser::Errno::ENOENT); + }; + + let flags = O_DEFAULT | OFlags::RDONLY | OFlags::DIRECTORY; + + match inode_type { + INodeType::Root => Err(fuser::Errno::EACCES), + INodeType::HexFolder(_) => Err(fuser::Errno::EACCES), + INodeType::FileNode(file_node_index) => { + let node = self.get_node(file_node_index)?; + + match &node.inner { + FileNodeInner::RootFile(root_file_node) => { + if check_mutable && !root_file_node.mutable { + return Err(fuser::Errno::EACCES); + } + Ok(( + root_file_node.dirfd.fd.clone(), + node.filename.clone(), + )) + } + FileNodeInner::Subfile(subfile_node) => { + let filename = node.filename.clone(); + let parent_ino = + INodeType::FileNode(subfile_node.parent).to_ino(); + let parent = self.open_ino_and_check_mutable( + parent_ino, + flags, + check_mutable, + )?; + Ok((parent, filename)) + } + } + } + } + } + + fn add_file( + &mut self, + dirfd: IdentifiedFd, + filename: Arc, + file_type: Option, + mutable: bool, + ) -> [u8; 16] { + let (node_index, node_generation) = self.take_node_index(); + + let hex = loop { + let hex: [u8; 16] = rand::rng().random(); + if !self.hex_to_node_index.contains_key(&hex) { + break hex; + } + }; + + let node = FileNode { + own_index: node_index, + generation: node_generation, + refcnt: 0, + file_type, + filename, + subfiles: Default::default(), + inner: FileNodeInner::RootFile(RootFileNode { + hex, + dirfd, + mutable, + }), + }; + + if node_index.0 == self.nodes.len() { + self.nodes.push(Some(node)); + } else { + if self.nodes[node_index.0].is_some() { + self.abort.abort( + "add_file: reused file_index already had data at index", + ); + } + self.nodes[node_index.0] = Some(node); + } + + self.hex_to_node_index.insert(hex, node_index); + hex + } + + fn add_subfile( + &mut self, + parent: FileNodeIndex, + filename: Arc, + refcnt: usize, + file_type: fuser::FileType, + ) -> (FileNodeIndex, fuser::Generation) { + let (node_index, node_generation) = self.take_node_index(); + + let node = FileNode { + own_index: node_index, + generation: node_generation, + refcnt, + file_type: Some(file_type), + filename, + subfiles: Default::default(), + inner: FileNodeInner::Subfile(SubfileNode { parent }), + }; + + if node_index.0 == self.nodes.len() { + self.nodes.push(Some(node)); + } else { + if self.nodes[node_index.0].is_some() { + self.abort.abort( + "add_subfile: reused file_index already had data at index", + ); + } + self.nodes[node_index.0] = Some(node); + } + + (node_index, node_generation) + } + + fn try_remove_ino_child( + &mut self, + parent: fuser::INodeNo, + name: &OsStr, + ) -> Result<(), fuser::Errno> { + let Some(inode_type) = INodeType::from_ino(parent) else { + return Err(fuser::Errno::ENOENT); + }; + + match inode_type { + INodeType::Root => Err(fuser::Errno::EACCES), + INodeType::HexFolder(file_node_index) => { + let node = self.get_node(file_node_index)?; + + if &*node.filename == name { + self.remove_node(file_node_index) + } else { + Ok(()) + } + } + INodeType::FileNode(file_node_index) => { + let node = self.get_node_mut(file_node_index)?; + + if let Some(removed) = node.subfiles.shift_remove(&*name) { + self.remove_node(removed) + } else { + Ok(()) + } + } + } + } + + fn remove_node( + &mut self, + file_node_index: FileNodeIndex, + ) -> Result<(), fuser::Errno> { + if file_node_index.0 >= self.nodes.len() { + return Err(fuser::Errno::ENOENT); + } + + let existing = &mut self.nodes[file_node_index.0 as usize]; + let Some(mut node) = std::mem::replace(existing, None) else { + self.abort.abort( + "remove_node: file that was being removed was missing data", + ); + return Err(fuser::Errno::EIO); + }; + + if node.own_index != file_node_index { + self.abort.abort("remove_node: own_index of removed node doesn't match index in fs.nodes"); + return Err(fuser::Errno::EIO); + } + + if node.refcnt == 0 { + self.node_index_free_list + .push_back((node.own_index, node.generation)); + } else { + self.node_index_pending_forget + .insert(node.own_index, (node.refcnt, node.generation)); + } + + let subfiles = std::mem::take(&mut node.subfiles); + for (_, subfile_index) in subfiles { + self.remove_node(subfile_index)?; + } + + match node.inner { + FileNodeInner::RootFile(root) => { + // Remove node from hex map + if self.hex_to_node_index.shift_remove(&root.hex) + != Some(file_node_index) + { + self.abort.abort("remove_node: hex_to_file_index[file.hex] != Some(file_index)"); + return Err(fuser::Errno::EIO); + } + + // Remove info from real parent data + let empty = if let Some(real_parent_data) = + self.existing_parents.get_mut(&root.dirfd) + { + real_parent_data.ro.retain(|ro| ro != &root.hex); + real_parent_data.rw.retain(|rw| rw != &root.hex); + real_parent_data.ro.is_empty() + && real_parent_data.rw.is_empty() + } else { + false + }; + if empty { + self.existing_parents.remove(&root.dirfd); + } + + if let Some(delete_notifier) = &self.delete_notifier { + // File itself + let hex_folder = + INodeType::HexFolder(file_node_index).to_ino(); + let root_file = + INodeType::FileNode(file_node_index).to_ino(); + + _ = delete_notifier.send(( + hex_folder, + root_file, + node.filename.clone(), + )); + + // Hex folder + let hex_name = hex::encode(root.hex); + _ = delete_notifier.send(( + fuser::INodeNo::ROOT, + hex_folder, + OsStr::new(&hex_name).into(), + )); + } + } + FileNodeInner::Subfile(subfile_node) => { + if let Some(delete_notifier) = &self.delete_notifier { + _ = delete_notifier.send(( + INodeType::FileNode(subfile_node.parent).to_ino(), + INodeType::FileNode(file_node_index).to_ino(), + node.filename.clone(), + )); + } + } + } + + Ok(()) + } + + fn get_or_create_child( + &mut self, + parent: FileNodeIndex, + name: &OsStr, + increase_refcnt: bool, + ) -> Result< + (FileNodeIndex, fuser::Generation, rustix::fs::Stat), + fuser::Errno, + > { + let parent_ino = INodeType::FileNode(parent).to_ino(); + let dirfd = self.open_ino_for_child(parent_ino, name, false)?; + + let stat = rustix::fs::statat(dirfd, name, AtFlags::SYMLINK_NOFOLLOW) + .map_err(to_fuser_errno); + let stat = match stat { + Ok(stat) => stat, + Err(errno) => { + if should_remove_on_error(errno) { + self.try_remove_ino_child(parent_ino, name)?; + } + return Err(errno); + } + }; + + let parent_node = self.get_node_mut(parent)?; + + if let Some(subfile_node_index) = + parent_node.subfiles.get(name).copied() + { + let subfile_node = self.get_node_mut(subfile_node_index)?; + if increase_refcnt { + subfile_node.refcnt += 1; + } + subfile_node.file_type = Some(to_fuser_filetype( + rustix::fs::FileType::from_raw_mode(stat.st_mode), + )); + Ok((subfile_node_index, subfile_node.generation, stat)) + } else { + let name: Arc = name.into(); + let initial_refcnt = if increase_refcnt { 1 } else { 0 }; + let file_type = to_fuser_filetype( + rustix::fs::FileType::from_raw_mode(stat.st_mode), + ); + let (subfile_node_index, subfile_generation) = self.add_subfile( + parent, + name.clone(), + initial_refcnt, + file_type, + ); + + let parent_node = self.get_node_mut(parent)?; + parent_node.subfiles.insert(name, subfile_node_index); + Ok((subfile_node_index, subfile_generation, stat)) + } + } +} + +impl FileSharingFSInner { + pub fn abort(&self, reason: &'static str) { + self.abort.abort(reason); + } + + fn create_dummy_directory_attr( + &self, + ino: fuser::INodeNo, + ) -> fuser::FileAttr { + fuser::FileAttr { + ino, + size: 0, + blocks: 0, + atime: SystemTime::UNIX_EPOCH, + mtime: SystemTime::UNIX_EPOCH, + ctime: SystemTime::UNIX_EPOCH, + crtime: SystemTime::UNIX_EPOCH, + kind: fuser::FileType::Directory, + perm: 0o755, + nlink: 1, + uid: self.process_uid, + gid: self.process_gid, + rdev: 0, + blksize: 512, + flags: 0, + } + } + + fn create_root_attr(&self) -> fuser::FileAttr { + self.create_dummy_directory_attr(fuser::INodeNo::ROOT) + } + + fn create_hex_folder_attr( + &self, + node_index: FileNodeIndex, + ) -> fuser::FileAttr { + self.create_dummy_directory_attr( + INodeType::HexFolder(node_index).to_ino(), + ) + } + + fn create_file_attr( + &self, + ino: fuser::INodeNo, + stat: rustix::fs::Stat, + ) -> fuser::FileAttr { + fuser::FileAttr { + ino, + size: stat.st_size as _, + blocks: stat.st_blocks as _, + atime: i64_to_systemtime(stat.st_atime), + mtime: i64_to_systemtime(stat.st_mtime), + ctime: i64_to_systemtime(stat.st_ctime), + #[cfg(target_vendor = "apple")] + crtime: i64_to_systemtime(stat.st_birthtime), + #[cfg(not(target_vendor = "apple"))] + crtime: SystemTime::UNIX_EPOCH, + kind: to_fuser_filetype(rustix::fs::FileType::from_raw_mode( + stat.st_mode, + )), + perm: stat.st_mode as u16, + nlink: stat.st_nlink as _, + uid: stat.st_uid as _, + gid: stat.st_gid as _, + rdev: stat.st_rdev as _, + blksize: stat.st_blksize as _, + #[cfg(target_vendor = "apple")] + flags: stat.st_flags, + #[cfg(not(target_vendor = "apple"))] + flags: 0, + } + } + + fn push_file_handle_data( + &mut self, + data: FileHandleData, + ) -> fuser::FileHandle { + self.last_handle_id += 1; + while self.file_handle_data.contains_key(&self.last_handle_id) + || self.last_handle_id == 0 + { + self.last_handle_id += 1; + } + self.file_handle_data.insert(self.last_handle_id, data); + fuser::FileHandle(self.last_handle_id) + } + + fn do_lookup( + &mut self, + parent: fuser::INodeNo, + name: &OsStr, + increase_refcnt: bool, + ) -> Result<(fuser::FileAttr, fuser::Generation), fuser::Errno> { + let Some(inode_type) = INodeType::from_ino(parent) else { + return Err(fuser::Errno::ENOENT); + }; + + match inode_type { + INodeType::Root => { + let mut id = [0_u8; 16]; + if hex::decode_to_slice(name.as_encoded_bytes(), &mut id) + .is_err() + { + return Err(fuser::Errno::ENOENT); + } + + let Some(file_node_index) = + self.files.hex_to_node_index.get(&id).copied() + else { + return Err(fuser::Errno::ENOENT); + }; + + let attr = self.create_hex_folder_attr(file_node_index); + let node = self.files.get_node_mut(file_node_index)?; + let generation = node.generation; + + if increase_refcnt { + node.refcnt += 1; + } + + Ok((attr, generation)) + } + INodeType::HexFolder(file_node_index) => { + let node = self.files.get_node_mut(file_node_index)?; + + let FileNodeInner::RootFile(root_file_node) = &mut node.inner + else { + self.abort("do_lookup: HexFolder inode contained subfile instead of rootfile"); + return Err(fuser::Errno::EIO); + }; + + if &*node.filename != name { + return Err(fuser::Errno::ENOENT); + } + + let stat = match rustix::fs::statat( + &root_file_node.dirfd, + name, + AtFlags::SYMLINK_NOFOLLOW, + ) { + Ok(stat) => stat, + Err(errno) => { + let errno = to_fuser_errno(errno); + + if node.file_type.is_some() + && should_remove_on_error(errno) + { + self.files.remove_node(file_node_index)?; + } + + return Err(errno); + } + }; + + node.file_type = Some(to_fuser_filetype( + rustix::fs::FileType::from_raw_mode(stat.st_mode), + )); + + let generation = node.generation; + + if increase_refcnt { + node.refcnt += 1; + } + + let attr = self.create_file_attr( + INodeType::FileNode(file_node_index).to_ino(), + stat, + ); + Ok((attr, generation)) + } + INodeType::FileNode(parent_file_node_index) => { + let (subfile_node_index, subfile_generation, stat) = + self.files.get_or_create_child( + parent_file_node_index, + name, + increase_refcnt, + )?; + + let attr = self.create_file_attr( + INodeType::FileNode(subfile_node_index).to_ino(), + stat, + ); + Ok((attr, subfile_generation)) + } + } + } + + fn do_read_dir( + &mut self, + folder_ino: fuser::INodeNo, + fh: fuser::FileHandle, + mut offset: u64, + reply: &mut fuser::ReplyDirectory, + ) -> Result<(), fuser::Errno> { + let Some(inode_type) = INodeType::from_ino(folder_ino) else { + return Err(fuser::Errno::ENOENT); + }; + + let parent_ino = match inode_type { + INodeType::Root => { + // For parent inode on the root, just return the inode of the root + folder_ino + } + INodeType::HexFolder(_) => fuser::INodeNo::ROOT, + INodeType::FileNode(file_node_index) => { + let node = self.files.get_node(file_node_index)?; + match &node.inner { + FileNodeInner::RootFile(_) => { + INodeType::HexFolder(file_node_index) + } + FileNodeInner::Subfile(subfile_node) => { + INodeType::FileNode(subfile_node.parent) + } + } + .to_ino() + } + }; + + let Some(file_handle_data) = self.file_handle_data.get_mut(&fh.0) + else { + return Err(fuser::Errno::EBADF); + }; + + let Some(underlying_dir_entries) = + &mut file_handle_data.underlying_dir_entries + else { + return Err(fuser::Errno::EBADF); + }; + + if !matches!( + underlying_dir_entries, + UnderlyingDirEntries::Backed { .. } + ) { + if offset == 0 { + if reply.add(folder_ino, 1, fuser::FileType::Directory, ".") { + return Ok(()); + } + } else { + offset -= 1; + } + + if offset == 0 { + if reply.add(parent_ino, 2, fuser::FileType::Directory, "..") { + return Ok(()); + } + } else { + offset -= 1; + } + } + + const BASE_OFFSET: u64 = 3; + match underlying_dir_entries { + UnderlyingDirEntries::HexFolders { hex_folders } => { + let mut next_index = BASE_OFFSET + offset; + for (hex_bytes, file_node_index) in + hex_folders.iter().skip(offset as _) + { + let name = hex::encode(hex_bytes); + let ino = INodeType::HexFolder(*file_node_index).to_ino(); + + if reply.add( + ino, + next_index, + fuser::FileType::Directory, + name, + ) { + return Ok(()); + } + + next_index += 1; + } + } + UnderlyingDirEntries::Single { + filename, + file_node_index, + } => { + if offset == 0 { + let filename = filename.clone(); + let file_node_index = file_node_index.clone(); + + let Ok((attr, _)) = self.do_lookup( + INodeType::HexFolder(file_node_index).to_ino(), + &filename, + false, + ) else { + return Ok(()); + }; + + let ino = INodeType::FileNode(file_node_index).to_ino(); + + if reply.add(ino, BASE_OFFSET, attr.kind, filename) { + return Ok(()); + } + } + } + UnderlyingDirEntries::Backed { + dir, + last_offset, + pending, + parent, + } => { + let Some(Some(parent_node)) = + self.files.nodes.get_mut(parent.0) + else { + return Err(fuser::Errno::ENOENT); + }; + let mut parent_node = parent_node; + if parent_node.own_index != *parent { + self.abort.abort("do_read_dir: parent_node.own_index doesn't match index in fs.nodes"); + return Err(fuser::Errno::EIO); + } + + if offset != *last_offset { + *pending = None; + *last_offset = offset; + + #[cfg(target_os = "linux")] + if offset == 0 { + dir.rewind(); + } else { + dir.seek(offset as i64).map_err(to_fuser_errno)?; + } + #[cfg(not(target_os = "linux"))] + { + dir.rewind(); + for _ in 0..offset { + match dir.next() { + Some(entry) => { + _ = entry.map_err(to_fuser_errno)? + } + None => break, + } + } + } + } + + loop { + let entry = match pending.take() { + Some(entry) => entry, + None => match dir.next() { + Some(entry) => entry.map_err(to_fuser_errno)?, + None => break, + }, + }; + + // rustix only exposes d_off on Linux, elsewhere use the 1-based stream position + #[cfg(target_os = "linux")] + let offset = entry.offset() as u64; + #[cfg(not(target_os = "linux"))] + let offset = *last_offset + 1; + + let file_name = + OsStr::from_bytes(entry.file_name().to_bytes()); + + let dot_ino = if file_name == "." { + Some(folder_ino) + } else if file_name == ".." { + Some(parent_ino) + } else { + None + }; + if let Some(dot_ino) = dot_ino { + if reply.add( + dot_ino, + offset, + fuser::FileType::Directory, + file_name, + ) { + *pending = Some(entry); + return Ok(()); + } + *last_offset = offset; + continue; + } + + let file_type = to_fuser_filetype(entry.file_type()); + + let subfile_node_index = if let Some(subfile_node_index) = + parent_node.subfiles.get(file_name).copied() + { + subfile_node_index + } else { + let name: Arc = file_name.into(); + let initial_refcnt = 0; + let (subfile_node_index, _) = self.files.add_subfile( + *parent, + name.clone(), + initial_refcnt, + file_type, + ); + + let Some(Some(reborrowed_parent_node)) = + self.files.nodes.get_mut(parent.0) + else { + return Err(fuser::Errno::ENOENT); + }; + parent_node = reborrowed_parent_node; + parent_node.subfiles.insert(name, subfile_node_index); + subfile_node_index + }; + + let ino = INodeType::FileNode(subfile_node_index).to_ino(); + if reply.add(ino, offset, file_type, file_name) { + *pending = Some(entry); + return Ok(()); + } + *last_offset = offset; + } + } + } + + Ok(()) + } +} + +#[derive(Clone, Debug)] +struct FileSharingFS(Arc>); + +impl fuser::Filesystem for FileSharingFS { + fn init( + &mut self, + _req: &fuser::Request, + _config: &mut fuser::KernelConfig, + ) -> std::io::Result<()> { + Ok(()) + } + + fn lookup( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + reply: fuser::ReplyEntry, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("lookup(parent: {parent:x?}, name: {name:?})"); + + match fs.do_lookup(parent, name, true) { + Ok((attr, generation)) => reply.entry(&TTL, &attr, generation), + Err(errno) => reply.error(errno), + } + } + + fn forget(&self, _req: &fuser::Request, ino: fuser::INodeNo, nlookup: u64) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return; + } + + // todo: check that this forget logic actually works + // macfuse seems to have an issue and never issues a forget + // so i couldn't properly test this + + tracing::debug!("forget(ino: {ino:x?}, nlookup: {nlookup:?})"); + + let Some(inode_type) = INodeType::from_ino(ino) else { + return; + }; + + let file_node_index = match inode_type { + INodeType::Root => { + return; + } + INodeType::HexFolder(file_node_index) => file_node_index, + INodeType::FileNode(file_node_index) => file_node_index, + }; + + match fs.files.get_node_mut(file_node_index) { + Ok(node) => { + node.refcnt = node.refcnt.saturating_sub(nlookup as usize); + } + Err(_) => { + if let Some((refcnt, generation)) = + fs.files.node_index_pending_forget.get_mut(&file_node_index) + { + *refcnt = refcnt.saturating_sub(nlookup as usize); + if *refcnt == 0 { + let generation = *generation; + _ = fs + .files + .node_index_pending_forget + .remove(&file_node_index); + fs.files + .node_index_free_list + .push_back((file_node_index, generation)); + } + }; + } + } + } + + fn getattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: Option, + reply: fuser::ReplyAttr, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("getattr(ino: {ino:x?}, fh: {fh:?})"); + + // Handle existing fd + if let Some(fh) = fh + && let Some(data) = fs.file_handle_data.get(&fh.0) + && let Some(fd) = &data.underlying_fd + { + let stat = match rustix::fs::fstat(fd) { + Ok(stat) => stat, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + let attr = fs.create_file_attr(ino, stat); + return reply.attr(&TTL, &attr); + } + + // Handle without fd + let Some(inode_type) = INodeType::from_ino(ino) else { + return reply.error(fuser::Errno::ENOENT); + }; + + match inode_type { + INodeType::Root => { + let attr = fs.create_root_attr(); + return reply.attr(&TTL, &attr); + } + INodeType::HexFolder(file_node_index) => { + let attr = fs.create_hex_folder_attr(file_node_index); + return reply.attr(&TTL, &attr); + } + INodeType::FileNode(_) => { + let (dirfd, name) = match fs.files.open_parent_ino(ino, false) { + Ok(res) => res, + Err(errno) => return reply.error(errno), + }; + + let stat = match rustix::fs::statat( + dirfd, + &*name, + AtFlags::SYMLINK_NOFOLLOW, + ) { + Ok(stat) => stat, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + let attr = fs.create_file_attr(ino, stat); + return reply.attr(&TTL, &attr); + } + }; + } + + fn setattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + mode: Option, + _uid: Option, + _gid: Option, + size: Option, + atime: Option, + mtime: Option, + _ctime: Option, + fh: Option, + _crtime: Option, + _chgtime: Option, + _bkuptime: Option, + _flags: Option, + reply: fuser::ReplyAttr, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "setattr(ino: {ino:x?}, mode: {mode:?}, size: {size:?}, fh: {fh:?})" + ); + + let file = if let Some(fh) = fh + && let Some(data) = fs.file_handle_data.get(&fh.0) + && let Some(fd) = &data.underlying_fd + { + if !data.mutable { + return reply.error(fuser::Errno::EACCES); + } + fd.clone() + } else { + let access = if size.is_some() { + OFlags::RDWR + } else { + OFlags::RDONLY + }; + match fs.files.open_ino_and_check_mutable( + ino, + access | OFlags::NONBLOCK, + true, + ) { + Ok(file) => file, + Err(errno) => return reply.error(errno), + } + }; + + // Mode + if let Some(mode) = mode { + let mode = check_mode(mode); + + if let Err(errno) = rustix::fs::fchmod( + &file, + rustix::fs::Mode::from_raw_mode(mode as _), + ) { + return reply.error(to_fuser_errno(errno)); + } + } + + // uid and gid are ignored + + // Size + if let Some(size) = size { + if let Err(errno) = rustix::fs::ftruncate(&file, size) { + return reply.error(to_fuser_errno(errno)); + } + } + + // Times + if atime.is_some() || mtime.is_some() { + let times = rustix::fs::Timestamps { + last_access: time_to_timespec(atime), + last_modification: time_to_timespec(mtime), + }; + if let Err(errno) = rustix::fs::futimens(&file, ×) { + return reply.error(to_fuser_errno(errno)); + } + } + + let stat = match rustix::fs::fstat(file) { + Ok(stat) => stat, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + let attr = &fs.create_file_attr(ino, stat); + return reply.attr(&TTL, attr); + } + + fn readlink( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + reply: fuser::ReplyData, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("readlink(ino: {ino:x?})"); + + let (parent, name) = match fs.files.open_parent_ino(ino, false) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + match rustix::fs::readlinkat( + parent, + &*name, + std::mem::take(&mut fs.reuse_buffer), + ) { + Ok(target) => { + reply.data(target.as_bytes()); + fs.reuse_buffer = target.into_bytes_with_nul(); + return; + } + Err(errno) => return reply.error(to_fuser_errno(errno)), + } + } + + fn mknod( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + mode: u32, + _umask: u32, + #[cfg_attr(target_vendor = "apple", allow(unused))] rdev: u32, + reply: fuser::ReplyEntry, + ) { + let mode = check_mode(mode); + + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "mknod(parent: {parent:x?}, name: {name:?}, mode: {mode:#o})" + ); + + let file_type = rustix::fs::FileType::from_raw_mode(mode as _); + let mode = rustix::fs::Mode::from_raw_mode(mode as _); + + if file_type == rustix::fs::FileType::Unknown { + return reply.error(fuser::Errno::EINVAL); + } + + let parent_fd = match fs.files.open_ino_for_child(parent, name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + let result = match file_type { + rustix::fs::FileType::RegularFile => { + let flags = + O_DEFAULT | OFlags::RDONLY | OFlags::EXCL | OFlags::CREATE; + rustix::fs::openat(parent_fd, name, flags, mode).map(|_| ()) + } + rustix::fs::FileType::Directory => { + rustix::fs::mkdirat(parent_fd, name, mode) + } + _ => { + #[cfg(target_vendor = "apple")] + return reply.error(fuser::Errno::EINVAL); + #[cfg(not(target_vendor = "apple"))] + rustix::fs::mknodat(parent_fd, name, file_type, mode, rdev as _) + } + }; + + if let Err(errno) = result { + return reply.error(fuser::Errno::from_i32(errno.raw_os_error())); + } + + match fs.do_lookup(parent, name, true) { + Ok((attr, generation)) => reply.entry(&TTL, &attr, generation), + Err(errno) => reply.error(errno), + } + } + + fn mkdir( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + mode: u32, + _umask: u32, + reply: fuser::ReplyEntry, + ) { + let mode = check_mode(mode); + + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "mkdir(parent: {parent:x?}, name: {name:?}, mode: {mode:#o})" + ); + + let file_type = rustix::fs::FileType::from_raw_mode(mode as _); + let mode = rustix::fs::Mode::from_raw_mode(mode as _); + + if file_type != rustix::fs::FileType::Directory { + return reply.error(fuser::Errno::EINVAL); + } + + let parent_fd = match fs.files.open_ino_for_child(parent, name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + if let Err(errno) = rustix::fs::mkdirat(parent_fd, name, mode) { + return reply.error(to_fuser_errno(errno)); + } + + match fs.do_lookup(parent, name, true) { + Ok((attr, generation)) => reply.entry(&TTL, &attr, generation), + Err(errno) => reply.error(errno), + } + } + + fn unlink( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + reply: fuser::ReplyEmpty, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("unlink(parent: {parent:x?}, name: {name:?})"); + + let parent_fd = match fs.files.open_ino_for_child(parent, name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + // SYMLINK_NOFOLLOW isn't needed, unlinkat will delete symlinks by default + if let Err(errno) = + rustix::fs::unlinkat(parent_fd, name, AtFlags::empty()) + { + return reply.error(to_fuser_errno(errno)); + } + + match fs.files.try_remove_ino_child(parent, name) { + Ok(_) => return reply.ok(), + Err(errno) => return reply.error(errno), + } + } + + fn rmdir( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + reply: fuser::ReplyEmpty, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("rmdir(parent: {parent:x?}, name: {name:?})"); + + let parent_fd = match fs.files.open_ino_for_child(parent, name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + // SYMLINK_NOFOLLOW isn't needed, unlinkat will delete symlinks by default + if let Err(errno) = + rustix::fs::unlinkat(parent_fd, name, AtFlags::REMOVEDIR) + { + return reply.error(to_fuser_errno(errno)); + } + + match fs.files.try_remove_ino_child(parent, name) { + Ok(_) => return reply.ok(), + Err(errno) => return reply.error(errno), + } + } + + fn symlink( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + link_name: &std::ffi::OsStr, + target: &std::path::Path, + reply: fuser::ReplyEntry, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "symlink(parent: {parent:x?}, link_name: {link_name:?}, target: {target:?})" + ); + + let parent_fd = + match fs.files.open_ino_for_child(parent, link_name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + if let Err(errno) = rustix::fs::symlinkat(target, parent_fd, link_name) + { + return reply.error(to_fuser_errno(errno)); + } + + match fs.do_lookup(parent, link_name, true) { + Ok((attr, generation)) => reply.entry(&TTL, &attr, generation), + Err(errno) => reply.error(errno), + } + } + + fn rename( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + newparent: fuser::INodeNo, + newname: &std::ffi::OsStr, + fuser_flags: fuser::RenameFlags, + reply: fuser::ReplyEmpty, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "rename(parent: {parent:x?}, name: {name:?}, newparent: {newparent:x?}, newname: {newname:?}, flags: {fuser_flags:?})" + ); + + if newname == "." || newname == ".." { + // This should already be checked at the kernel level, but we + // do it here as well just to be sure + return reply.error(fuser::Errno::EINVAL); + } + + if parent == newparent && name == newname { + return reply.ok(); + } + + let Some(old_parent_node_type) = INodeType::from_ino(parent) else { + return reply.error(fuser::Errno::ENOENT); + }; + let Some(new_parent_node_type) = INodeType::from_ino(newparent) else { + return reply.error(fuser::Errno::ENOENT); + }; + + // Prevent renaming to a root file + // This can be dangerous, e.g. renaming ~/test.txt to ~/.zshrc + if matches!(new_parent_node_type, INodeType::HexFolder(_)) { + return reply.error(fuser::Errno::EACCES); + } + + let old_parent_fd = + match fs.files.open_ino_for_child(parent, name, true) { + Ok(old_parent_fd) => old_parent_fd, + Err(errno) => return reply.error(errno), + }; + + // Get from_node_index before the rename + let from_node_index = match old_parent_node_type { + INodeType::Root => return, + INodeType::HexFolder(file_node_index) => { + // child of hex folder must be file itself + file_node_index + } + INodeType::FileNode(parent_file_node_index) => { + match fs.files.get_or_create_child( + parent_file_node_index, + name, + false, + ) { + Ok((from_node_index, _, _)) => from_node_index, + Err(errno) => return reply.error(errno), + } + } + }; + + let rustix_flags = RenameFlags::from_bits_truncate(fuser_flags.bits()); + + // Handle simple case for renaming a file within the same directory + if parent == newparent { + let INodeType::FileNode(parent_node_index) = old_parent_node_type + else { + fs.abort("rename: same-directory rename with non-file parent"); + return reply.error(fuser::Errno::EIO); + }; + + let result = rustix::fs::renameat_with( + &old_parent_fd, + name, + &old_parent_fd, + newname, + rustix_flags, + ); + if let Err(errno) = result { + return reply.error(to_fuser_errno(errno)); + } + + let parent_node = match fs.files.get_node_mut(parent_node_index) { + Ok(node) => node, + Err(errno) => return reply.error(errno), + }; + parent_node.subfiles.shift_remove(name); + let replaced_node_index = + parent_node.subfiles.insert(newname.into(), from_node_index); + + if let Some(replaced_node_index) = replaced_node_index + && replaced_node_index != from_node_index + { + if rustix_flags.contains(RenameFlags::EXCHANGE) { + parent_node + .subfiles + .insert(name.into(), replaced_node_index); + match fs.files.get_node_mut(replaced_node_index) { + Ok(node) => node.filename = name.into(), + Err(errno) => return reply.error(errno), + } + } else if let Err(errno) = + fs.files.remove_node(replaced_node_index) + { + return reply.error(errno); + } + } + + match fs.files.get_node_mut(from_node_index) { + Ok(node) => node.filename = newname.into(), + Err(errno) => return reply.error(errno), + } + + return reply.ok(); + } + + let new_parent_fd = + match fs.files.open_ino_for_child(newparent, newname, true) { + Ok(new_parent_fd) => new_parent_fd, + Err(errno) => return reply.error(errno), + }; + + let result = rustix::fs::renameat_with( + old_parent_fd, + name, + new_parent_fd, + newname, + rustix_flags, + ); + if let Err(errno) = result { + return reply.error(to_fuser_errno(errno)); + } + + // Get to_node_index after the rename + let to_node_index = match new_parent_node_type { + INodeType::Root => { + fs.abort("rename: new parent was the root node, this shouldn't be possible"); + return reply.error(fuser::Errno::EIO); + } + INodeType::HexFolder(_) => { + // This should have been disallowed earlier, but error here as well + return reply.error(fuser::Errno::EACCES); + } + INodeType::FileNode(to_parent_node_index) => { + match fs.files.get_or_create_child( + to_parent_node_index, + newname, + false, + ) { + Ok((to_node_index, _, _)) => to_node_index, + Err(errno) => { + // Error encountered, let's just remove everything so we don't + // leave ourselves in an inconsistent state + _ = fs.files.try_remove_ino_child(parent, name); + _ = fs.files.try_remove_ino_child(newparent, newname); + return reply.error(errno); + } + } + } + }; + + // Apply side effects of the rename to our data structures + if from_node_index == to_node_index { + // Technically this shouldn't be possible since the move + // should result in to_node_index being a new node, but + // we handle it here anyways + if let Ok(node) = fs.files.get_node_mut(to_node_index) { + node.filename = newname.into(); + }; + } else { + if from_node_index.0 >= fs.files.nodes.len() { + fs.abort( + "rename: old_file_node_index was larger than node vec", + ); + return reply.error(fuser::Errno::EIO); + } + if to_node_index.0 >= fs.files.nodes.len() { + fs.abort( + "rename: new_file_node_index was larger than node vec", + ); + return reply.error(fuser::Errno::EIO); + } + + if let Err(errno) = fs.files.try_remove_ino_child(parent, name) { + fs.abort("rename: unable to remove old node"); + return reply.error(errno); + } + + // Move the new node to the previous node to maintain inode + let Ok([previous_node, new_node]) = fs + .files + .nodes + .get_disjoint_mut([from_node_index.0, to_node_index.0]) + else { + fs.abort("rename: from_node_index == to_node_index even though we should have checked this earlier"); + return reply.error(fuser::Errno::EIO); + }; + + if previous_node.is_some() { + fs.abort("rename: previous_node was still some even after calling remove_node"); + return reply.error(fuser::Errno::EIO); + } + + // Move new_node to previous_node, and replace new_node with None + std::mem::swap(previous_node, new_node); + + let Some(node) = previous_node else { + // previous_node now points to the new node + fs.abort( + "rename: node was none after being swapped with new_node", + ); + return reply.error(fuser::Errno::EIO); + }; + + node.own_index = from_node_index; + match &mut node.inner { + FileNodeInner::RootFile(root_file_node) => { + let hex = root_file_node.hex; + let Some(index_in_parent_hex) = + fs.files.hex_to_node_index.get_mut(&hex) + else { + fs.abort("rename: missing index in hex map"); + return reply.error(fuser::Errno::EIO); + }; + if *index_in_parent_hex != to_node_index { + fs.abort("rename: wrong node index in hex map"); + return reply.error(fuser::Errno::EIO); + } + *index_in_parent_hex = from_node_index; + } + FileNodeInner::Subfile(subfile_node) => { + let parent_index = subfile_node.parent; + let Ok(parent_node) = fs.files.get_node_mut(parent_index) + else { + fs.abort("rename: unable to find parent"); + return reply.error(fuser::Errno::EIO); + }; + let Some(index_in_parent_subfiles) = + parent_node.subfiles.get_mut(newname) + else { + fs.abort( + "rename: missing entry in parent's subfiles map", + ); + return reply.error(fuser::Errno::EIO); + }; + if *index_in_parent_subfiles != to_node_index { + fs.abort( + "rename: wrong node index in parent's subfile map", + ); + return reply.error(fuser::Errno::EIO); + } + *index_in_parent_subfiles = from_node_index; + } + } + } + + reply.ok(); + } + + fn link( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + newparent: fuser::INodeNo, + newname: &std::ffi::OsStr, + reply: fuser::ReplyEntry, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "link(ino: {ino:x?}, newparent: {newparent:x?}, newname: {newname:?})" + ); + + let (old_dirfd, old_path) = match fs.files.open_parent_ino(ino, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + let new_dirfd = + match fs.files.open_ino_for_child(newparent, newname, true) { + Ok(new_dirfd) => new_dirfd, + Err(errno) => return reply.error(errno), + }; + + if let Err(errno) = rustix::fs::linkat( + old_dirfd, + &*old_path, + new_dirfd, + newname, + AtFlags::SYMLINK_NOFOLLOW, + ) { + return reply.error(fuser::Errno::from_i32(errno.raw_os_error())); + } + + match fs.do_lookup(newparent, newname, true) { + Ok((attr, generation)) => reply.entry(&TTL, &attr, generation), + Err(errno) => reply.error(errno), + } + } + + fn open( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + flags: fuser::OpenFlags, + reply: fuser::ReplyOpen, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("open(ino: {ino:x?}, flags: {flags:?})"); + + let Some(inode_type) = INodeType::from_ino(ino) else { + return reply.error(fuser::Errno::ENOENT); + }; + + let underlying_fd = match inode_type { + INodeType::Root | INodeType::HexFolder(_) => None, + INodeType::FileNode(_) => { + let fd = match fs + .files + .open_ino(ino, OFlags::from_bits_truncate(flags.0 as _)) + { + Ok(fd) => fd, + Err(errno) => return reply.error(errno), + }; + + Some(fd) + } + }; + + let file_handle_data = FileHandleData { + opened_by: FileHandleOpenedBy::Open, + underlying_fd, + underlying_dir_entries: None, + mutable: flags.acc_mode() != fuser::OpenAccMode::O_RDONLY, + }; + + let file_handle = fs.push_file_handle_data(file_handle_data); + reply.opened(file_handle, fuser::FopenFlags::empty()); + } + + fn read( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + offset: u64, + size: u32, + flags: fuser::OpenFlags, + lock_owner: Option, + reply: fuser::ReplyData, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "read(ino: {ino:x?}, fh: {fh}, offset: {offset}, \ + size: {size}, flags: {flags:#x?}, lock_owner: {lock_owner:?})" + ); + + let Some(data) = fs.file_handle_data.get(&fh.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd) = data.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + if fs.reuse_buffer.len() < size as usize + 1 { + fs.reuse_buffer.resize(size as usize + 1, 0); + } + + let num_bytes = + match rustix::io::pread(fd, fs.reuse_buffer.as_mut_slice(), offset) + { + Ok(num_bytes) => num_bytes, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + reply.data(&fs.reuse_buffer[..num_bytes]); + } + + fn write( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + offset: u64, + data: &[u8], + write_flags: fuser::WriteFlags, + flags: fuser::OpenFlags, + lock_owner: Option, + reply: fuser::ReplyWrite, + ) { + let fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "write(ino: {ino:x?}, fh: {fh}, offset: {offset}, \ + data.len(): {}, write_flags: {write_flags:#x?}, flags: {flags:#x?}, \ + lock_owner: {lock_owner:?})", + data.len() + ); + + let Some(fh_data) = fs.file_handle_data.get(&fh.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd) = fh_data.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + let num_bytes = match rustix::io::pwrite(fd, data, offset) { + Ok(num_bytes) => num_bytes, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + reply.written(num_bytes as u32); + } + + fn flush( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + lock_owner: fuser::LockOwner, + reply: fuser::ReplyEmpty, + ) { + tracing::debug!( + "flush(ino: {ino:x?}, fh: {fh}, lock_owner: {lock_owner:?})" + ); + + // locking isn't supported, so we don't have anything to do + reply.ok(); + } + + fn release( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + flags: fuser::OpenFlags, + _lock_owner: Option, + _flush: bool, + reply: fuser::ReplyEmpty, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("release(ino: {ino:x?}, fh: {fh}, flags: {flags:?})"); + + if let Some(data) = fs.file_handle_data.get(&fh.0) { + if data.opened_by == FileHandleOpenedBy::Open { + fs.file_handle_data.remove(&fh.0); + } else { + tracing::warn!( + "release was called on a file handle opened by opendir()" + ); + return; + } + } + + reply.ok(); + } + + fn fsync( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + datasync: bool, + reply: fuser::ReplyEmpty, + ) { + let fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("fsync(ino: {ino:x?}, fh: {fh}, datasync: {datasync})"); + + let Some(fh_data) = fs.file_handle_data.get(&fh.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd) = fh_data.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + if fh_data.opened_by != FileHandleOpenedBy::Open { + return reply.error(fuser::Errno::EBADF); + } + + #[cfg(target_vendor = "apple")] + let result = rustix::fs::fsync(fd); + #[cfg(not(target_vendor = "apple"))] + let result = if datasync { + rustix::fs::fdatasync(fd) + } else { + rustix::fs::fsync(fd) + }; + + match result { + Ok(_) => reply.ok(), + Err(errno) => reply.error(to_fuser_errno(errno)), + } + } + + fn opendir( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + flags: fuser::OpenFlags, + reply: fuser::ReplyOpen, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("opendir(ino: {ino:x?}, flags: {flags:?})"); + + let Some(inode_type) = INodeType::from_ino(ino) else { + return reply.error(fuser::Errno::ENOENT); + }; + + if flags.acc_mode() != fuser::OpenAccMode::O_RDONLY { + return reply.error(fuser::Errno::EISDIR); + } + + let (underlying_fd, underlying_dir_entries) = match inode_type { + INodeType::Root => { + let dir_entries = UnderlyingDirEntries::HexFolders { + hex_folders: fs + .files + .hex_to_node_index + .iter() + .map(|(k, v)| (*k, *v)) + .collect(), + }; + (None, dir_entries) + } + INodeType::HexFolder(file_node_index) => { + let node = match fs.files.get_node(file_node_index) { + Ok(node) => node, + Err(errno) => return reply.error(errno), + }; + let dir_entries = UnderlyingDirEntries::Single { + filename: node.filename.clone(), + file_node_index, + }; + (None, dir_entries) + } + INodeType::FileNode(file_node_index) => { + let fd = match fs.files.open_ino( + ino, + OFlags::from_bits_truncate(flags.0 as _) + | OFlags::DIRECTORY, + ) { + Ok(fd) => fd, + Err(errno) => return reply.error(errno), + }; + + let dir = match rustix::fs::Dir::read_from(&fd) { + Ok(dir) => dir, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + let dir_entries = UnderlyingDirEntries::Backed { + dir, + last_offset: 0, + pending: None, + parent: file_node_index, + }; + + (Some(fd), dir_entries) + } + }; + + let file_handle_data = FileHandleData { + opened_by: FileHandleOpenedBy::Opendir, + underlying_fd, + underlying_dir_entries: Some(underlying_dir_entries), + mutable: false, + }; + + let file_handle = fs.push_file_handle_data(file_handle_data); + reply.opened(file_handle, fuser::FopenFlags::empty()); + } + + fn readdir( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + offset: u64, + mut reply: fuser::ReplyDirectory, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!("readdir(ino: {ino:x?}, fh: {fh:?}, offset: {offset})"); + + if let Err(errno) = fs.do_read_dir(ino, fh, offset, &mut reply) { + return reply.error(errno); + } else { + return reply.ok(); + } + } + + fn readdirplus( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + offset: u64, + reply: fuser::ReplyDirectoryPlus, + ) { + tracing::warn!( + "[Not Implemented] readdirplus(ino: {ino:x?}, fh: {fh}, offset: {offset})" + ); + reply.error(fuser::Errno::ENOSYS); + } + + fn releasedir( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + flags: fuser::OpenFlags, + reply: fuser::ReplyEmpty, + ) { + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "releasedir(ino: {ino:x?}, fh: {fh}, flags: {flags:?})" + ); + + if let Some(data) = fs.file_handle_data.get(&fh.0) { + if data.opened_by == FileHandleOpenedBy::Opendir { + fs.file_handle_data.remove(&fh.0); + } else { + tracing::warn!( + "releasedir was called on a file handle opened by open()" + ); + } + } + + reply.ok(); + } + + fn fsyncdir( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + datasync: bool, + reply: fuser::ReplyEmpty, + ) { + let fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "fsyncdir(ino: {ino:x?}, fh: {fh}, datasync: {datasync})" + ); + + let Some(fh_data) = fs.file_handle_data.get(&fh.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd) = fh_data.underlying_fd.clone() else { + // Nothing to sync for our synthetic directories + return reply.ok(); + }; + + if fh_data.opened_by != FileHandleOpenedBy::Opendir { + return reply.error(fuser::Errno::EBADF); + } + + #[cfg(target_vendor = "apple")] + let result = rustix::fs::fsync(fd); + #[cfg(not(target_vendor = "apple"))] + let result = if datasync { + rustix::fs::fdatasync(fd) + } else { + rustix::fs::fsync(fd) + }; + + match result { + Ok(_) => reply.ok(), + Err(errno) => reply.error(to_fuser_errno(errno)), + } + } + + fn statfs( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + reply: fuser::ReplyStatfs, + ) { + reply.statfs(0, 0, 0, 0, 0, 512, 255, 0); + } + + fn setxattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + name: &std::ffi::OsStr, + _value: &[u8], + flags: i32, + position: u32, + reply: fuser::ReplyEmpty, + ) { + tracing::warn!( + "[Not Implemented] setxattr(ino: {ino:x?}, name: {name:?}, \ + flags: {flags:#x?}, position: {position})" + ); + reply.error(fuser::Errno::ENOSYS); + } + + fn getxattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + name: &std::ffi::OsStr, + size: u32, + reply: fuser::ReplyXattr, + ) { + tracing::warn!( + "[Not Implemented] getxattr(ino: {ino:x?}, name: {name:?}, size: {size})" + ); + reply.error(fuser::Errno::ENOSYS); + } + + fn listxattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + size: u32, + reply: fuser::ReplyXattr, + ) { + tracing::warn!( + "[Not Implemented] listxattr(ino: {ino:x?}, size: {size})" + ); + reply.error(fuser::Errno::ENOSYS); + } + + fn removexattr( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + name: &std::ffi::OsStr, + reply: fuser::ReplyEmpty, + ) { + tracing::warn!( + "[Not Implemented] removexattr(ino: {ino:x?}, name: {name:?})" + ); + reply.error(fuser::Errno::ENOSYS); + } + + fn access( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _mask: fuser::AccessFlags, + reply: fuser::ReplyEmpty, + ) { + // We use fuser::MountOption::DefaultPermissions so this isn't necessary + return reply.error(fuser::Errno::ENOSYS); + } + + fn create( + &self, + _req: &fuser::Request, + parent: fuser::INodeNo, + name: &std::ffi::OsStr, + mode: u32, + umask: u32, + flags: i32, + reply: fuser::ReplyCreate, + ) { + let mode = check_mode(mode); + + let mut fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "create(parent: {parent:x?}, name: {name:?}, mode: {mode}, \ + umask: {umask:#x?}, flags: {flags:#x?})" + ); + + let file_type = rustix::fs::FileType::from_raw_mode(mode as _); + let mode = rustix::fs::Mode::from_raw_mode(mode as _); + + if file_type != rustix::fs::FileType::RegularFile { + return reply.error(fuser::Errno::EINVAL); + } + + let parent_fd = match fs.files.open_ino_for_child(parent, name, true) { + Ok(parent) => parent, + Err(errno) => return reply.error(errno), + }; + + let flags = + O_DEFAULT | OFlags::CREATE | OFlags::from_bits_truncate(flags as _); + let fh = match rustix::fs::openat(parent_fd, name, flags, mode) { + Ok(fd) => fs.push_file_handle_data(FileHandleData { + opened_by: FileHandleOpenedBy::Open, + underlying_fd: Some(Arc::new(fd)), + underlying_dir_entries: None, + mutable: (flags & OFlags::ACCMODE) != OFlags::RDONLY, + }), + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + match fs.do_lookup(parent, name, true) { + Ok((attr, generation)) => reply.created( + &TTL, + &attr, + generation, + fh, + fuser::FopenFlags::empty(), + ), + Err(errno) => reply.error(errno), + } + } + + fn getlk( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _fh: fuser::FileHandle, + _lock_owner: fuser::LockOwner, + _start: u64, + _end: u64, + _typ: i32, + _pid: u32, + reply: fuser::ReplyLock, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn setlk( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _fh: fuser::FileHandle, + _lock_owner: fuser::LockOwner, + _start: u64, + _end: u64, + _typ: i32, + _pid: u32, + _sleep: bool, + reply: fuser::ReplyEmpty, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn bmap( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _blocksize: u32, + _idx: u64, + reply: fuser::ReplyBmap, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn ioctl( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _fh: fuser::FileHandle, + _flags: fuser::IoctlFlags, + _cmd: u32, + _in_data: &[u8], + _out_size: u32, + reply: fuser::ReplyIoctl, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn poll( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _fh: fuser::FileHandle, + _ph: fuser::PollNotifier, + _events: fuser::PollEvents, + _flags: fuser::PollFlags, + reply: fuser::ReplyPoll, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn fallocate( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + _fh: fuser::FileHandle, + _offset: u64, + _length: u64, + _mode: i32, + reply: fuser::ReplyEmpty, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + fn lseek( + &self, + _req: &fuser::Request, + ino: fuser::INodeNo, + fh: fuser::FileHandle, + offset: i64, + whence: i32, + reply: fuser::ReplyLseek, + ) { + let fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "lseek(ino: {ino:x?}, fh: {fh}, \ + offset: {offset}, whence: {whence})" + ); + + let Some(data) = fs.file_handle_data.get(&fh.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd) = data.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + let seek_from = match whence { + libc::SEEK_SET => rustix::fs::SeekFrom::Start(offset as _), + libc::SEEK_CUR => rustix::fs::SeekFrom::Current(offset as _), + libc::SEEK_END => rustix::fs::SeekFrom::End(offset as _), + libc::SEEK_DATA => rustix::fs::SeekFrom::Data(offset as _), + libc::SEEK_HOLE => rustix::fs::SeekFrom::Hole(offset as _), + _ => { + return reply.error(fuser::Errno::EINVAL); + } + }; + + let new_offset = match rustix::fs::seek(fd, seek_from) { + Ok(num_bytes) => num_bytes, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + reply.offset(new_offset as _); + } + + #[cfg(not(target_os = "linux"))] + fn copy_file_range( + &self, + _req: &fuser::Request, + _ino_in: fuser::INodeNo, + _fh_in: fuser::FileHandle, + _offset_in: u64, + _ino_out: fuser::INodeNo, + _fh_out: fuser::FileHandle, + _offset_out: u64, + _len: u64, + _flags: fuser::CopyFileRangeFlags, + reply: fuser::ReplyWrite, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + #[cfg(target_os = "linux")] + fn copy_file_range( + &self, + _req: &fuser::Request, + ino_in: fuser::INodeNo, + fh_in: fuser::FileHandle, + mut offset_in: u64, + ino_out: fuser::INodeNo, + fh_out: fuser::FileHandle, + mut offset_out: u64, + len: u64, + flags: fuser::CopyFileRangeFlags, + reply: fuser::ReplyWrite, + ) { + let fs = self.0.lock(); + if fs.abort.is_aborted() { + return reply.error(fuser::Errno::EIO); + } + + tracing::debug!( + "copy_file_range(ino_in: {ino_in:x?}, fh_in: {fh_in}, \ + offset_in: {offset_in}, ino_out: {ino_out:x?}, fh_out: {fh_out}, \ + offset_out: {offset_out}, len: {len}, flags: {flags:?})" + ); + + let Some(fh_data_in) = fs.file_handle_data.get(&fh_in.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd_in) = fh_data_in.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fh_data_out) = fs.file_handle_data.get(&fh_out.0) else { + return reply.error(fuser::Errno::EBADF); + }; + + let Some(fd_out) = fh_data_out.underlying_fd.clone() else { + return reply.error(fuser::Errno::EBADF); + }; + + let result = rustix::fs::copy_file_range( + fd_in, + Some(&mut offset_in), + fd_out, + Some(&mut offset_out), + len as _, + ); + let num_bytes = match result { + Ok(num_bytes) => num_bytes, + Err(errno) => return reply.error(to_fuser_errno(errno)), + }; + + reply.written(num_bytes as _); + } + + #[cfg(target_vendor = "apple")] + fn setvolname( + &self, + _req: &fuser::Request, + _name: &std::ffi::OsStr, + reply: fuser::ReplyEmpty, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + #[cfg(target_vendor = "apple")] + fn exchange( + &self, + _req: &fuser::Request, + _parent: fuser::INodeNo, + _name: &std::ffi::OsStr, + _newparent: fuser::INodeNo, + _newname: &std::ffi::OsStr, + _options: u64, + reply: fuser::ReplyEmpty, + ) { + reply.error(fuser::Errno::ENOSYS); + } + + #[cfg(target_vendor = "apple")] + fn getxtimes( + &self, + _req: &fuser::Request, + _ino: fuser::INodeNo, + reply: fuser::ReplyXTimes, + ) { + reply.error(fuser::Errno::ENOSYS); + } +} + +fn i64_to_systemtime(time: i64) -> SystemTime { + if time > 0 { + SystemTime::UNIX_EPOCH + + Duration::from_secs(time.abs().max(i64::MIN + 1) as u64) + } else { + SystemTime::UNIX_EPOCH + - Duration::from_secs(time.abs().max(i64::MIN + 1) as u64) + } +} + +fn time_to_timespec( + time_or_now: Option, +) -> rustix::fs::Timespec { + match time_or_now { + Some(fuser::TimeOrNow::SpecificTime(system_time)) => { + let Ok(since) = system_time.duration_since(SystemTime::UNIX_EPOCH) + else { + return rustix::fs::Timespec { + tv_sec: 0, + tv_nsec: rustix::fs::UTIME_OMIT, + }; + }; + rustix::fs::Timespec { + tv_sec: since.as_secs() as _, + tv_nsec: since.subsec_nanos() as _, + } + } + Some(fuser::TimeOrNow::Now) => rustix::fs::Timespec { + tv_sec: 0, + tv_nsec: rustix::fs::UTIME_NOW, + }, + None => rustix::fs::Timespec { + tv_sec: 0, + tv_nsec: rustix::fs::UTIME_OMIT, + }, + } +} + +fn should_remove_on_error(err: fuser::Errno) -> bool { + err == fuser::Errno::ENOENT + || err == fuser::Errno::ENOTDIR + || err == fuser::Errno::ENAMETOOLONG +} + +fn to_fuser_errno(errno: rustix::io::Errno) -> fuser::Errno { + fuser::Errno::from_i32(errno.raw_os_error()) +} + +fn to_fuser_filetype(file_type: rustix::fs::FileType) -> fuser::FileType { + match file_type { + rustix::fs::FileType::RegularFile => fuser::FileType::RegularFile, + rustix::fs::FileType::Directory => fuser::FileType::Directory, + rustix::fs::FileType::Symlink => fuser::FileType::Symlink, + rustix::fs::FileType::Fifo => fuser::FileType::NamedPipe, + rustix::fs::FileType::Socket => fuser::FileType::Socket, + rustix::fs::FileType::CharacterDevice => fuser::FileType::CharDevice, + rustix::fs::FileType::BlockDevice => fuser::FileType::BlockDevice, + rustix::fs::FileType::Unknown => fuser::FileType::RegularFile, // Pretend any unknown file is a regular file + } +} + +fn check_mode(mut mode: u32) -> u32 { + mode &= !(libc::S_ISUID as u32); + mode &= !(libc::S_ISGID as u32); + mode +} diff --git a/packages/modrinth-sandbox/src/helper.rs b/packages/modrinth-sandbox/src/helper.rs new file mode 100644 index 00000000000..fc9171ef49b --- /dev/null +++ b/packages/modrinth-sandbox/src/helper.rs @@ -0,0 +1,70 @@ +//! Support for running sandbox setup operations in a helper process. +//! +//! Call [`run_default`] near the beginning of the executable, before parsing +//! application arguments or creating a [`crate::SandboxEnv`]. On Windows, the +//! sandbox may relaunch this helper with elevated privileges to configure +//! AppContainer ACLs and network isolation. +//! +//! [`crate::SandboxEnv::new`] relaunches the current executable by default. Use +//! [`crate::SandboxEnv::with_helper`] when another executable or additional +//! command arguments are required. + +use std::ffi::{OsStr, OsString}; + +use eyre::Result; + +use crate::backend; + +/// Creates the command used to run privileged sandbox setup operations. +/// +/// The resulting process must call [`run_default`] during startup. Arguments +/// describing the setup operation are appended to the command before launch. +pub type MakeHelper = fn() -> std::process::Command; + +pub const HELPER_ARG: &str = "--modrinth-sandbox-helper"; + +/// Handles a sandbox helper invocation for the default helper command. +/// +/// Returns `true` after handling a helper invocation and `false` during normal +/// application startup. When this returns `true`, the caller should exit +/// successfully without continuing application initialization. +pub fn run_default() -> Result { + let mut args = std::env::args_os(); + args.next(); // skip executable name + if args.next().as_deref() != Some(OsStr::new(HELPER_ARG)) { + return Ok(false); + } + run_with_args(args) +} + +/// Handles a sandbox helper invocation using the arguments provided. +/// +/// The argument list must not include the [`HELPER_ARG`]; if you don't want +/// to deal with this complexity, use [`run_default`]. +/// +/// Returns `true` after handling a helper invocation and `false` during normal +/// application startup. When this returns `true`, the caller should exit +/// successfully without continuing application initialization. +pub fn run_with_args(args: impl IntoIterator) -> Result { + backend::run_helper(args) +} + +/// Creates the default helper command by relaunching the current executable. +/// +/// The executable must call [`run_default`] during startup. +pub fn make_default() -> std::process::Command { + let current_exe = { + #[cfg(unix)] + { + std::path::PathBuf::from("/proc/self/exe") + } + #[cfg(windows)] + { + std::env::current_exe().expect("getting current exe") + } + }; + + let mut command = std::process::Command::new(current_exe); + command.arg(HELPER_ARG); + command +} diff --git a/packages/modrinth-sandbox/src/lib.rs b/packages/modrinth-sandbox/src/lib.rs new file mode 100644 index 00000000000..75312bc989a --- /dev/null +++ b/packages/modrinth-sandbox/src/lib.rs @@ -0,0 +1,328 @@ +#![doc = include_str!("../README.md")] + +pub mod api; +mod backend; +pub mod ffi; +#[cfg(target_os = "linux")] +pub mod file_sharing; +pub mod helper; +pub mod minecraft; +mod util; + +use std::{ + collections::{BTreeMap, BTreeSet}, + io::{PipeReader, PipeWriter}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use derive_more::Debug; +use eyre::Result; + +pub use backend::SandboxExitStatus; +pub use util::SandboxArg; + +use crate::{ + backend::{SandboxChildOp, SandboxHandleOp}, + helper::MakeHelper, +}; + +/// Allows spawning processes in a sandboxed environment, configured by +/// [`SandboxCommand`]. +/// +/// A [`SandboxEnv`] is not aware of Minecraft, Java, the JVM, or any other +/// game-specific details - it only manages the actual process sandboxing. +/// See the [`minecraft`] module for how to set up a sandbox for a Minecraft +/// instance specifically. +#[derive(Debug, Clone)] +#[debug("{imp:?}")] +pub struct SandboxEnv { + imp: Arc, +} + +impl SandboxEnv { + /// Creates the environment and initializes the required resources to perform + /// sandboxing. + /// + /// On most platforms, sandboxing is done using operating system primitives, in + /// which case creating the environment will always succeed. On other platforms, + /// sandboxing may require extra dependencies to be installed in the app + /// environment - if those are not fulfilled, this returns [`Err`]. + /// + /// # Backends + /// + /// ## Windows + /// + /// Uses the Windows [AppContainer] API for isolating the process from the host. + /// + /// ## macOS + /// + /// Uses macOS [Seatbelt] API. + /// + /// ## Linux + /// + /// Inside a Flatpak environment, this uses the [`org.freedesktop.portal.Flatpak`] + /// portal for spawning processes via the D-Bus session bus. + /// + /// Outside of a Flatpak environment, this uses the [Bubblewrap] sandboxing + /// tool via the command line (`bwrap` must be installed on the user's machine). + /// + /// # Helper command + /// + /// This uses [`helper::make_default`] to create the helper command. If you + /// need to customize how the helper process is launched, use + /// [`SandboxEnv::with_helper`]. + /// + /// Call [`helper::run_default`] near the start of the executable, before + /// creating a sandbox environment. See [`helper`] for details. + /// + /// # Errors + /// + /// Errors if the implementation cannot set up sandboxing. + /// + /// [AppContainer]: https://learn.microsoft.com/en-us/windows/win32/secauthz/appcontainer-isolation + /// [Seatbelt]: https://theapplewiki.com/wiki/Dev:Seatbelt + /// [`org.freedesktop.portal.Flatpak`]: https://docs.flatpak.org/en/latest/libflatpak-api-reference.html#gdbus-org.freedesktop.portal.Flatpak + /// [Bubblewrap]: https://github.com/containers/bubblewrap + pub async fn new() -> Result { + Self::with_helper(helper::make_default).await + } + + /// Creates the environment and initializes the required resources to perform + /// sandboxing, passing a custom function to make the helper command. + /// + /// See [`SandboxEnv::new`] for more details. + /// + /// `make_helper` must create a command whose process calls + /// [`helper::run_default`] during startup. See [`helper`] for details. + pub async fn with_helper(make_helper: MakeHelper) -> Result { + backend::create_env(make_helper).await.map(|imp| Self { + imp: Arc::from(imp), + }) + } + + /// Creates a [`SandboxEnv`] which performs no real sandboxing. + /// + /// This may be used to retain the safe API surface whether you're creating + /// a sandboxed or unsandboxed instance. + #[must_use] + pub fn noop() -> Self { + Self { + imp: Arc::new(backend::noop::NoSandbox), + } + } + + /// Spawn a sandboxed process and get a [`SandboxChild`] handle to it. + /// + /// This function is analogous to [`std::process::Command::spawn`], but + /// handles the complexity of sandboxing for you. See [`SandboxCommand`] on + /// what you can configure, such as what program to run, and what files are + /// exposed in the sandbox. + pub async fn spawn(&self, command: SandboxCommand) -> Result { + self.imp.spawn(command).await + } +} + +/// Configuration for launching a sandboxed process using [`SandboxEnv::spawn`]. +/// +/// This is a low-level configuration struct which is not aware of Minecraft, +/// Java, etc. If launching a Minecraft client, first create a command using +/// [`minecraft::setup_minecraft_command`], then customize it to your needs. +/// +/// # Implementation notes +/// +/// - Graphics and audio devices will always be passed to the child process when +/// possible. +/// - On Linux, you aren't allowed to mount any paths from the host under `/tmp` +/// since Flatpak doesn't support mounting those files. This applies to both +/// Bubblewrap and Flatpak, so your code stays portable across backends. +pub struct SandboxCommand { + /// Path to the executable to run. + pub executable: PathBuf, + /// Arguments passed to the executable. + pub args: Vec, + /// When spawning a process, ensure that each of these paths exists as a + /// directory on the host, automatically creating all parent directories. + pub ensure_dirs_exist: Vec, + /// Host paths mounted read-only at the same path in the sandbox. + pub read_only_paths: Vec, + /// Host paths mounted read-write at the same path in the sandbox. + pub read_write_paths: Vec, + /// What directory the executable is ran from. + pub working_directory: Option, + /// Names of environment variables copied from the host when present. + pub passthrough_environment: BTreeSet, + /// Environment variables explicitly set in the sandbox. + /// + /// These take precedence over passthrough variables with the same name. + pub extra_environment: BTreeMap, + /// Allow access to the host network namespace. + pub allow_network: bool, + /// Whether the program to run is a Java virtual machine. + /// + /// If set, performs some extra platform-specific setup to get the JVM to + /// work. + pub is_jvm: bool, + /// Whether the spawned child should terminate when the parent process + /// terminates. + pub die_with_parent: bool, + /// Default io behaviour for stdin. + pub stdin: SandboxStdio, + /// Default io behaviour for stdout. + pub stdout: SandboxStdio, + /// Default io behaviour for stderr. + pub stderr: SandboxStdio, + /// (Windows only) Stable, machine-facing identifier for the [AppContainer] + /// which this process runs in. + /// + /// Must remain stable and unique, and may be displayed to users, but don't + /// treat it as a localized string. + /// + /// [AppContainer]: https://learn.microsoft.com/en-us/windows/win32/secauthz/appcontainer-isolation + pub app_container_name: SandboxArg, + /// (Windows only) Human-friendly description of the [AppContainer] which + /// this process runs in. + /// + /// [AppContainer]: https://learn.microsoft.com/en-us/windows/win32/secauthz/appcontainer-isolation + pub app_container_description: SandboxArg, + /// Vec of callbacks to be run when the process starts + pub on_start: Vec>, + /// Vec of callbacks to be run when the process terminates or is dropped + pub on_finish: Vec>, +} + +/// Describes what to do with a standard I/O stream for a child process when +/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of +/// [`SandboxCommand`]. +/// +/// This is analogous to [`std::process::Stdio`]. +/// +/// [`stdin`]: SandboxCommand::stdin +/// [`stdout`]: SandboxCommand::stdout +/// [`stderr`]: SandboxCommand::stderr +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum SandboxStdio { + Null, + Inherit, + Pipe, +} + +/// Handle to a child process created by [`SandboxEnv::spawn`]. +/// +/// This is analogous to [`std::process::Child`], but because operating systems +/// expose different capabilities for child processes depending on how they're +/// spawned, this type is more limited in what you can do with it. +#[derive(Debug)] +#[debug("{imp:?}")] +pub struct SandboxChild { + /// Handle for writing to the child's standard input (stdin). + /// + /// Analogous to [`std::process::Child::stdin`]. + pub stdin: Option, + /// Handle for reading from the child's standard output (stdout). + /// + /// Analogous to [`std::process::Child::stdout`]. + pub stdout: Option, + /// Handle for reading from the child's standard error (stderr). + /// + /// Analogous to [`std::process::Child::stderr`]. + pub stderr: Option, + on_finish: Vec>, + handle: backend::SandboxHandle, + imp: backend::SandboxChild, +} + +impl SandboxChild { + pub fn id(&self) -> Option { + SandboxChildOp::id(&self.imp) + } + + /// Add a callback to be run when the process finishes or the struct is dropped + /// Requires one of the kill/wait/try_wait/etc. methods to be called + pub fn run_on_finish( + &mut self, + on_finish: Box, + ) { + self.on_finish.push(on_finish); + } + + /// Attempts to collect the exit status of the child if it has already + /// exited. + /// + /// This is analogous to [`std::process::Child::try_wait`]. + pub fn try_wait(&mut self) -> Result> { + let res = SandboxChildOp::try_wait(&mut self.imp); + if matches!(res, Ok(Some(_))) { + self.finish(); + } + res + } + + /// Waits for the child to exit completely, returning the status that it + /// exited with. This function will continue to have the same return value + /// after it has been called at least once. + /// + /// This is analogous to [`std::process::Child::wait`]. + /// + /// # Cancel safety + /// + /// This function is cancel safe. + pub async fn wait(&mut self) -> Result { + let res = SandboxChildOp::wait(&mut self.imp).await; + if res.is_ok() { + self.finish(); + } + res + } + + /// Forces the child process to exit. If the child has already exited, `Ok(())` + /// is returned. + /// + /// This is analogous to [`std::process::Child::kill`]. + pub async fn kill(&mut self) -> Result<()> { + let res = SandboxChildOp::kill(&mut self.imp).await; + self.finish(); + res + } + + pub fn get_sandbox_handle(&self) -> SandboxHandle { + SandboxHandle { + imp: self.handle.clone(), + } + } + + fn finish(&mut self) { + for on_finish in self.on_finish.drain(..) { + (on_finish)(); + } + } +} + +#[derive(Clone, Debug)] +pub enum ExposedPath { + Direct, + Proxied(PathBuf), +} + +#[derive(Clone, Debug)] +pub struct SandboxHandle { + imp: backend::SandboxHandle, +} + +impl SandboxHandle { + pub fn expose_path( + &self, + path: &Path, + writeable: bool, + ) -> eyre::Result { + self.imp.expose_path(path, writeable) + } + + pub fn is_path_readable(&self, path: &Path) -> bool { + self.imp.is_path_readable(path) + } + + pub fn is_path_writeable(&self, path: &Path) -> bool { + self.imp.is_path_writeable(path) + } +} diff --git a/packages/modrinth-sandbox/src/minecraft.rs b/packages/modrinth-sandbox/src/minecraft.rs new file mode 100644 index 00000000000..a45bb782877 --- /dev/null +++ b/packages/modrinth-sandbox/src/minecraft.rs @@ -0,0 +1,544 @@ +use std::{ + collections::BTreeMap, + ffi::OsString, + fs, + io::{ErrorKind, Write}, + path::{Path, PathBuf}, +}; + +use eyre::{Context, Result, ensure}; +use rand::Rng; +use sha1::{Digest, Sha1}; + +use crate::{ + SandboxChild, SandboxCommand, SandboxStdio, api::SandboxApiChild, + util::SandboxArg, +}; + +#[derive(Debug)] +pub struct MinecraftCommand { + /// Child reference to the sandbox API service, created using + /// [`SandboxApiService::start`] + /// + /// [`SandboxApiService::start`]: crate::api::SandboxApiService::start + pub sandbox_api_child: Option, + /// Path to the Java Runtime Environment on the host. + pub jre_path: PathBuf, + /// Optional Java agent JAR on the host. + pub java_agent: Option, + /// Complete Java classpath on the host, in classpath order. + pub classpath: Vec, + /// Path to the extracted native libraries on the host. + pub natives_path: PathBuf, + /// Path to the Minecraft assets directory on the host. + pub assets_path: PathBuf, + /// Optional version-specific logging configuration. + pub logging_config: Option, + /// Path to the Minecraft instance directory on the host. + pub instance_path: PathBuf, + /// Directory for persistent home, data, configuration, cache, and state, + /// shared across all game instances. Temporary launcher JARs are staged in + /// its `tmp` subdirectory and removed when the launched process exits. + pub persistent_dir: PathBuf, + /// Extra host directories exposed read-write at the same path in the + /// sandbox, such as folders the user has granted access to. + pub granted_paths: Vec, + /// JVM arguments which do not contain sandbox-managed paths. + /// + /// Classpath, Java agent, native-library, and logging arguments are generated + /// by [`create_command`]. + pub jvm_args: Vec, + /// Java main class to invoke. + pub main_class: SandboxArg, + /// Arguments passed to [`MinecraftCommand::main_class`]. + pub main_class_args: Vec, + /// Additional environment variables set for the sandboxed process. + pub extra_environment: BTreeMap, + /// Default io behaviour for stdin. + pub stdin: SandboxStdio, + /// Default io behaviour for stdout. + pub stdout: SandboxStdio, + /// Default io behaviour for stderr. + pub stderr: SandboxStdio, +} + +#[derive(Debug)] +pub struct MinecraftLoggingConfig { + /// Path to the logging configuration file on the host. + pub path: PathBuf, + /// JVM argument containing a `${path}` placeholder for the configuration + /// file's path inside the sandbox. + pub argument: String, +} + +const CLASSPATH_JVM_ARGUMENT: &str = "-cp"; +const JAVA_LIBRARY_PATH_JVM_ARGUMENT: &str = "-Djava.library.path"; +const JNA_TMPDIR_JVM_ARGUMENT: &str = "-Djna.tmpdir"; +const LWJGL_LIBRARY_EXTRACT_PATH_JVM_ARGUMENT: &str = + "-Dorg.lwjgl.system.SharedLibraryExtractPath"; +const NETTY_NATIVE_WORKDIR_JVM_ARGUMENT: &str = "-Dio.netty.native.workdir"; +const USER_HOME_JVM_ARGUMENT: &str = "-Duser.home"; +const LOGGING_CONFIG_JVM_ARGUMENT: &str = "-Dlog4j.configurationFile"; +const JAVA_AGENT_JVM_ARGUMENT: &str = "-javaagent"; + +/// JVM options generated by [`create_command`]. +/// +/// Entries are option names without their `=` or `:` separated values. +pub const JVM_ARGUMENTS: &[&str] = &[ + CLASSPATH_JVM_ARGUMENT, + JAVA_LIBRARY_PATH_JVM_ARGUMENT, + JNA_TMPDIR_JVM_ARGUMENT, + LWJGL_LIBRARY_EXTRACT_PATH_JVM_ARGUMENT, + NETTY_NATIVE_WORKDIR_JVM_ARGUMENT, + USER_HOME_JVM_ARGUMENT, + LOGGING_CONFIG_JVM_ARGUMENT, + JAVA_AGENT_JVM_ARGUMENT, +]; + +#[cfg(windows)] +const MINECRAFT_PASSTHROUGH_ENVIRONMENT: &[&str] = &[ + "COMPUTERNAME", + "HOME", + "HOMEDRIVE", + "HOMEPATH", + "HOSTNAME", + "NUMBER_OF_PROCESSORS", + "OS", + "PROCESSOR_ARCHITECTURE", + "PROCESSOR_IDENTIFIER", + "PROCESSOR_LEVEL", + "PROCESSOR_REVISION", + "PROGRAMDATA", + "PROGRAMFILES", + "PROGRAMFILES(X86)", + "PROGRAMW6432", + "PUBLIC", + "SYSTEMDRIVE", + "SYSTEMROOT", + "USERDOMAIN", + "APPDATA", + "LOCALAPPDATA", + "ALLUSERSPROFILE", + "PATH", + "PATHEXT", + "COMMONPROGRAMFILES", + "COMSPEC", + "DRIVERDATA", + "PROCESSOR_ARCHITECTURE", + "PROCESSOR_IDENTIFIER", + "PROCESSOR_LEVEL", + "SESSIONNAME", + "USERNAME", + "USERPROFILE", + "WINDIR", + "TEMP", +]; + +#[cfg(target_os = "macos")] +const MINECRAFT_PASSTHROUGH_ENVIRONMENT: &[&str] = &[ + "PATH", + "LANG", + "LANGUAGE", + "LC_ALL", + "LC_ADDRESS", + "LC_COLLATE", + "LC_CTYPE", + "LC_IDENTIFICATION", + "LC_MEASUREMENT", + "LC_MESSAGES", + "LC_MONETARY", + "LC_NAME", + "LC_NUMERIC", + "LC_PAPER", + "LC_TELEPHONE", + "LC_TIME", +]; + +#[cfg(target_os = "linux")] +const MINECRAFT_PASSTHROUGH_ENVIRONMENT: &[&str] = &[ + "PATH", + "LANG", + "LANGUAGE", + "LC_ALL", + "LC_ADDRESS", + "LC_COLLATE", + "LC_CTYPE", + "LC_IDENTIFICATION", + "LC_MEASUREMENT", + "LC_MESSAGES", + "LC_MONETARY", + "LC_NAME", + "LC_NUMERIC", + "LC_PAPER", + "LC_TELEPHONE", + "LC_TIME", + "GDMSESSION", + "DESKTOP_SESSION", + "DISPLAY", + "WAYLAND_DISPLAY", + "XDG_RUNTIME_DIR", + "XAUTHORITY", + "XDG_SESSION_TYPE", + "PIPEWIRE_REMOTE", + "PULSE_SERVER", + "TZ", + "DRI_PRIME", + "MESA_LOADER_DRIVER_OVERRIDE", + "MESA_VK_DEVICE_SELECT", + "MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE", + "LIBGL_ALWAYS_SOFTWARE", + "__GLX_VENDOR_LIBRARY_NAME", + "__NV_PRIME_RENDER_OFFLOAD", + "__NV_PRIME_RENDER_OFFLOAD_PROVIDER", + "__VK_LAYER_NV_optimus", + "__GL_THREADED_OPTIMIZATIONS", + "VK_DRIVER_FILES", + "VK_ICD_FILENAMES", + "VK_LAYER_PATH", + "VK_LOADER_DRIVERS_SELECT", + "VK_LOADER_DRIVERS_DISABLE", + "FREETYPE_PROPERTIES", + "ALSOFT_DRIVERS", + "SDL_AUDIODRIVER", + "GLFW_IM_MODULE", + "XMODIFIERS", + "SDL_IM_MODULE", +]; + +/// Creates unique launch staging storage under the configured root. +/// Keep the returned directory alive until the launched process exits. +pub fn create_launcher_temp_dir(root: &Path) -> Result { + fs::create_dir_all(root).with_context(|| { + format!("creating launcher staging root {}", root.display()) + })?; + tempfile::Builder::new() + .prefix("modrinth-minecraft-") + .tempdir_in(root) + .with_context(|| { + format!( + "creating Minecraft launcher staging storage in {}", + root.display() + ) + }) +} + +pub async fn setup_minecraft_command( + minecraft: MinecraftCommand, +) -> Result { + let Ok(instance_path) = minecraft.instance_path.canonicalize() else { + return Err(eyre::eyre!("Instance path could not be canonicalized")); + }; + + let java_path = { + #[cfg(unix)] + { + minecraft.jre_path.join("bin").join("java") + } + #[cfg(windows)] + { + minecraft.jre_path.join("bin").join("javaw.exe") + } + }; + + #[cfg(unix)] + let persistent_home = minecraft.persistent_dir.join("home"); + #[cfg(target_os = "linux")] + let persistent_data = minecraft.persistent_dir.join("data"); + #[cfg(target_os = "linux")] + let persistent_config = minecraft.persistent_dir.join("config"); + #[cfg(target_os = "linux")] + let persistent_cache = minecraft.persistent_dir.join("cache"); + #[cfg(target_os = "linux")] + let persistent_state = minecraft.persistent_dir.join("state"); + let skins_path = minecraft.assets_path.join("skins"); + let mut classpath = minecraft.classpath; + let mut read_only_paths = vec![ + minecraft.jre_path.clone(), + minecraft.natives_path.clone(), + minecraft.assets_path, + ]; + + // Some java installations will contain symlinks to external folders (e.g. arch symlinks conf, legal and man) + for folder in [ + "bin", "conf", "demo", "include", "jmods", "legal", "lib", "man", + ] { + let real_dir = minecraft.jre_path.join(folder).canonicalize(); + if let Ok(real_dir) = real_dir + && !real_dir.starts_with(&minecraft.jre_path) + { + read_only_paths.push(real_dir); + } + } + + read_only_paths.extend(classpath.clone()); + + let mut args = minecraft.jvm_args; + args.extend([ + jvm_path_argument( + JAVA_LIBRARY_PATH_JVM_ARGUMENT, + "=", + &minecraft.natives_path, + ) + .into(), + #[cfg(target_os = "linux")] + OsString::from(format!("{JNA_TMPDIR_JVM_ARGUMENT}=/tmp")).into(), + #[cfg(target_os = "linux")] + OsString::from(format!( + "{LWJGL_LIBRARY_EXTRACT_PATH_JVM_ARGUMENT}=/tmp" + )) + .into(), + #[cfg(target_os = "linux")] + OsString::from(format!("{NETTY_NATIVE_WORKDIR_JVM_ARGUMENT}=/tmp")) + .into(), + #[cfg(unix)] + jvm_path_argument(USER_HOME_JVM_ARGUMENT, "=", &persistent_home).into(), + ]); + + if let Some(java_agent) = minecraft.java_agent.clone() { + args.push( + jvm_path_argument(JAVA_AGENT_JVM_ARGUMENT, ":", &java_agent).into(), + ); + read_only_paths.push(java_agent); + } + + if let Some(logging_config) = minecraft.logging_config { + ensure!( + logging_config.argument.contains("${path}"), + "logging configuration argument must contain a `${{path}}` placeholder" + ); + read_only_paths.push(logging_config.path.clone()); + args.push( + replace_path_placeholder( + &logging_config.argument, + &logging_config.path, + ) + .into(), + ); + } + + let mut launcher_temp_keep_alive = None; + // Setup sandbox java agent + if let Some(child) = &minecraft.sandbox_api_child { + let launcher_temp_dir = minecraft.persistent_dir.join("tmp"); + let (agent_dir, sandbox_agent_path) = + tokio::task::spawn_blocking(move || { + let agent_dir = create_launcher_temp_dir(&launcher_temp_dir)?; + let path = create_sandbox_java_agent(agent_dir.path())?; + Ok::<_, eyre::Report>((agent_dir, path)) + }) + .await??; + launcher_temp_keep_alive = Some(agent_dir); + + classpath.push(sandbox_agent_path.clone()); + read_only_paths.push(sandbox_agent_path.clone()); + let port = child.get_port(); + + let mut agent_argument = OsString::new(); + agent_argument.push(JAVA_AGENT_JVM_ARGUMENT); + agent_argument.push(":"); + agent_argument.push(sandbox_agent_path.as_os_str()); + args.push(agent_argument.into()); + + args.push( + format!("-Dmodrinth.sandboxagent.secret={}", child.get_secret()) + .into(), + ); + args.push(format!("-Dmodrinth.sandboxagent.port={port}").into()); + args.push("-Dmodrinth.sandboxagent.transform.auth=true".into()); + + // Don't do desktop (openuri, file dialog, etc.) changes on macos + // macos's sandbox handles these correctly without any intervention + #[cfg(not(target_os = "macos"))] + { + args.push("-Dmodrinth.sandboxagent.transform.openuri=true".into()); + args.push("-Dmodrinth.sandboxagent.transform.dragdrop=true".into()); + args.push( + "-Dmodrinth.sandboxagent.transform.filedialog=true".into(), + ); + } + + args.push("-Drealms.environment=local".into()); + args.push("-Dminecraft.api.env=sandboxauth".into()); + + // used in 26.3 (authlib 10)+ + args.push(format!("-Dminecraft.api.discovery.host=http://127.0.0.1:{port}/sandboxauth/discovery").into()); + // used in 1.16 (authlib 2) - 26.2 (authlib 9) + args.push(format!("-Dminecraft.api.session.host=http://127.0.0.1:{port}/sandboxauth/session").into()); + // used in 1.16 (authlib 2) - 26.2 (authlib 9) + args.push(format!("-Dminecraft.api.services.host=http://127.0.0.1:{port}/sandboxauth/services").into()); + // used in 1.21.9 (authlib 7) - 26.2 (authlib 9) + args.push( + "-Dminecraft.api.profiles.host=https://api.mojang.com".into(), + ); + // used in 1.16 (authlib 2) - 1.20.3 (authlib 5) + args.push("-Dminecraft.api.account.host=https://api.mojang.com".into()); + // used in 1.16 (authlib 2) - 1.20.2 (authlib 4) + args.push( + "-Dminecraft.api.auth.host=https://authserver.mojang.com".into(), + ); + } + + args.push(CLASSPATH_JVM_ARGUMENT.into()); + args.push(std::env::join_paths(&classpath)?.into()); + args.push(minecraft.main_class); + args.extend(minecraft.main_class_args); + + let ensure_dirs_exist = vec![ + skins_path.clone(), + #[cfg(unix)] + persistent_home.clone(), + #[cfg(target_os = "linux")] + persistent_data.clone(), + #[cfg(target_os = "linux")] + persistent_config.clone(), + #[cfg(target_os = "linux")] + persistent_cache.clone(), + #[cfg(target_os = "linux")] + persistent_state.clone(), + ]; + + let mut extra_environment = minecraft.extra_environment; + extra_environment.extend([ + ("INSIDE_MODRINTH_SANDBOX".into(), "1".into()), + ("JAVA_HOME".into(), minecraft.jre_path.into()), + #[cfg(unix)] + ("HOME".into(), persistent_home.into()), + #[cfg(target_os = "linux")] + ("XDG_DATA_HOME".into(), persistent_data.into()), + #[cfg(target_os = "linux")] + ("XDG_CONFIG_HOME".into(), persistent_config.into()), + #[cfg(target_os = "linux")] + ("XDG_CACHE_HOME".into(), persistent_cache.into()), + #[cfg(target_os = "linux")] + ("XDG_STATE_HOME".into(), persistent_state.into()), + ]); + + read_only_paths.sort_unstable(); + read_only_paths.dedup(); + + let mut read_write_paths = vec![ + // .minecraft dir + instance_path.clone(), + // global persistent dirs for all mods + minecraft.persistent_dir, + // .minecraft assets/skins; assets/ is shared among instances, + // and so is the skin cache, but the game writes into the skin cache + skins_path, + ]; + read_write_paths.extend(minecraft.granted_paths); + read_write_paths.sort_unstable(); + read_write_paths.dedup(); + + let mut on_start: Vec> = + Vec::new(); + let mut on_finish: Vec> = Vec::new(); + if let Some(launcher_temp_dir) = launcher_temp_keep_alive { + on_finish.push(Box::new(move || drop(launcher_temp_dir))); + } + if let Some(sandbox_api_child) = minecraft.sandbox_api_child { + // Register handle + on_start.push(Box::new({ + let sandbox_api_child = sandbox_api_child.clone(); + move |child| { + sandbox_api_child + .set_sandbox_handle(child.get_sandbox_handle()); + } + })); + + // Keep sandbox api child alive until process dies + on_finish.push(Box::new(move || { + std::mem::drop(sandbox_api_child); + })); + } + + Ok(SandboxCommand { + executable: java_path, + args, + ensure_dirs_exist, + read_only_paths, + read_write_paths, + working_directory: Some(instance_path), + passthrough_environment: MINECRAFT_PASSTHROUGH_ENVIRONMENT + .iter() + .map(|s| SandboxArg::from(*s)) + .collect(), + extra_environment, + allow_network: true, + is_jvm: true, + die_with_parent: true, + stdin: minecraft.stdin, + stdout: minecraft.stdout, + stderr: minecraft.stderr, + app_container_name: "ModrinthMinecraftSandbox".into(), + app_container_description: + "Sandbox for Minecraft instances created by `modrinth-sandbox`" + .into(), + on_start, + on_finish, + }) +} + +fn create_sandbox_java_agent(agent_dir: &Path) -> eyre::Result { + const BYTES: &[u8] = + include_bytes!("../../modrinth-sandbox-agent/SandboxAgent.jar"); + let hash_bytes = Sha1::digest(BYTES); + let hash_str = hex::encode(hash_bytes); + + let path = agent_dir.join(format!("ModrinthSandboxAgent-{hash_str}.jar")); + + // Check that file exists and checksum matches + if !check_sha1_hash(&path, &hash_bytes)? { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + + let mut temp = path.clone(); + temp.add_extension(format!("{}", rand::rng().next_u32())); + temp.add_extension("new"); + + let mut temp_file = fs::File::create(&temp)?; + + temp_file.write_all(BYTES)?; + temp_file.flush()?; + temp_file.sync_all()?; + + drop(temp_file); + + if let Err(err) = fs::rename(&temp, &path) { + _ = fs::remove_file(&temp); + return Err(err.into()); + } + } + + Ok(path) +} + +fn check_sha1_hash(path: &Path, expected_hash: &[u8]) -> eyre::Result { + let contents = match fs::read(path) { + Err(err) if err.kind() == ErrorKind::NotFound => { + return Ok(false); + } + result => { + result.with_context(|| format!("reading {}", path.display()))? + } + }; + + Ok(expected_hash == &*Sha1::digest(&contents)) +} + +fn jvm_path_argument(argument: &str, separator: &str, path: &Path) -> OsString { + let mut result = OsString::from(argument); + result.push(separator); + result.push(path); + result +} + +fn replace_path_placeholder(argument: &str, path: &Path) -> OsString { + let (prefix, suffix) = argument + .split_once("${path}") + .expect("logging argument placeholder was validated"); + let mut result = OsString::from(prefix); + result.push(path); + result.push(suffix); + result +} diff --git a/packages/modrinth-sandbox/src/util/argument.rs b/packages/modrinth-sandbox/src/util/argument.rs new file mode 100644 index 00000000000..90185ca7528 --- /dev/null +++ b/packages/modrinth-sandbox/src/util/argument.rs @@ -0,0 +1,82 @@ +use std::{ + borrow::Cow, + ffi::{OsStr, OsString}, + path::{Path, PathBuf}, +}; + +/// Wrapper over Cow<'static OsStr> implementing conversions from str/String, OsStr/OsString and Path/PathBuf. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SandboxArg(Cow<'static, OsStr>); + +impl SandboxArg { + pub fn as_os_str(&self) -> &OsStr { + &self.0 + } + + pub fn into_os_string(self) -> OsString { + self.0.into_owned() + } +} + +// OsStr conversions +impl From> for SandboxArg { + fn from(value: Cow<'static, OsStr>) -> Self { + SandboxArg(value) + } +} + +impl From<&'static OsStr> for SandboxArg { + fn from(value: &'static OsStr) -> Self { + SandboxArg(Cow::Borrowed(value)) + } +} + +impl From for SandboxArg { + fn from(value: OsString) -> Self { + SandboxArg(Cow::Owned(value)) + } +} + +// str conversions +impl From> for SandboxArg { + fn from(value: Cow<'static, str>) -> Self { + SandboxArg(match value { + Cow::Borrowed(value) => Cow::Borrowed(OsStr::new(value)), + Cow::Owned(value) => Cow::Owned(value.into()), + }) + } +} + +impl From<&'static str> for SandboxArg { + fn from(value: &'static str) -> Self { + SandboxArg(Cow::Borrowed(OsStr::new(value))) + } +} + +impl From for SandboxArg { + fn from(value: String) -> Self { + SandboxArg(Cow::Owned(value.into())) + } +} + +// Path conversions +impl From> for SandboxArg { + fn from(value: Cow<'static, Path>) -> Self { + SandboxArg(match value { + Cow::Borrowed(value) => Cow::Borrowed(value.as_os_str()), + Cow::Owned(value) => Cow::Owned(value.into_os_string()), + }) + } +} + +impl From<&'static Path> for SandboxArg { + fn from(value: &'static Path) -> Self { + SandboxArg(Cow::Borrowed(value.as_os_str())) + } +} + +impl From for SandboxArg { + fn from(value: PathBuf) -> Self { + SandboxArg(Cow::Owned(value.into_os_string())) + } +} diff --git a/packages/modrinth-sandbox/src/util/mod.rs b/packages/modrinth-sandbox/src/util/mod.rs new file mode 100644 index 00000000000..d369781a22d --- /dev/null +++ b/packages/modrinth-sandbox/src/util/mod.rs @@ -0,0 +1,15 @@ +#![allow( + dead_code, + unused_imports, + reason = "some items are unused on some platforms" +)] + +mod argument; +mod path; +#[cfg(unix)] +mod raw_string_vec; + +pub use argument::SandboxArg; +pub use path::resolve_path; +#[cfg(unix)] +pub use raw_string_vec::RawStringVec; diff --git a/packages/modrinth-sandbox/src/util/path.rs b/packages/modrinth-sandbox/src/util/path.rs new file mode 100644 index 00000000000..c3e3b410070 --- /dev/null +++ b/packages/modrinth-sandbox/src/util/path.rs @@ -0,0 +1,24 @@ +use std::path::{Path, PathBuf}; + +use eyre::{Context, Result, eyre}; + +pub fn resolve_path(path: &Path) -> Result { + let path = path + .canonicalize() + .wrap_err_with(|| eyre!("executable file {path:?} doesn't exist"))?; + + debug_assert!(path.is_absolute()); + + #[cfg(windows)] + { + // Try to remove the \\?\ verbatim path prefix since it can break some applications + let encoded_bytes = path.as_os_str().as_encoded_bytes(); + if let Some(rest) = encoded_bytes.strip_prefix(b"\\\\?\\") { + return Ok(PathBuf::from(unsafe { + std::ffi::OsStr::from_encoded_bytes_unchecked(&rest) + })); + } + } + + Ok(path) +} diff --git a/packages/modrinth-sandbox/src/util/raw_string_vec.rs b/packages/modrinth-sandbox/src/util/raw_string_vec.rs new file mode 100644 index 00000000000..335c53ac15a --- /dev/null +++ b/packages/modrinth-sandbox/src/util/raw_string_vec.rs @@ -0,0 +1,54 @@ +use std::{ + ffi::{CString, OsString}, + os::unix::ffi::OsStringExt, +}; + +#[derive(Debug)] +pub struct RawStringVec(Vec<*mut libc::c_char>); + +impl RawStringVec { + pub fn with_capacity(capacity: usize) -> Self { + Self(Vec::with_capacity(capacity + 1)) + } + + pub fn push_c(&mut self, string: CString) { + self.0.push(string.into_raw()); + } + + pub fn push_os(&mut self, string: OsString) -> eyre::Result<()> { + self.push_c(CString::new(string.into_vec())?); + Ok(()) + } + + pub fn into_null_terminated_ptr(mut self) -> *const *mut libc::c_char { + assert!(self.0.last().unwrap().is_null()); + std::mem::take(&mut self.0).into_raw_parts().0 + } + + pub fn as_null_terminated_ptr(&self) -> *const *mut libc::c_char { + assert!(self.0.last().unwrap().is_null()); + self.0.as_ptr() + } + + pub fn ensure_null_terminated(&mut self) { + if let Some(last) = self.0.last() + && last.is_null() + { + return; + } + self.0.push(std::ptr::null_mut()); + } +} + +unsafe impl Send for RawStringVec {} +unsafe impl Sync for RawStringVec {} + +impl Drop for RawStringVec { + fn drop(&mut self) { + for ptr in self.0.drain(..) { + if !ptr.is_null() { + drop(unsafe { CString::from_raw(ptr) }); + } + } + } +} diff --git a/packages/ui/src/components/base/index.ts b/packages/ui/src/components/base/index.ts index 0195e2c1962..0e8751a1bb5 100644 --- a/packages/ui/src/components/base/index.ts +++ b/packages/ui/src/components/base/index.ts @@ -86,6 +86,7 @@ export { Textarea, } from './inputs' export { default as IntlFormatted } from './IntlFormatted.vue' +export { default as LargeRadioButton } from './LargeRadioButton.vue' export { default as LoadingBar } from './LoadingBar.vue' export { default as LoadingIndicator } from './LoadingIndicator.vue' export { default as ManySelect } from './ManySelect.vue'