diff --git a/garage_updates/LICENSE b/garage_updates/LICENSE new file mode 100644 index 0000000..72fab54 --- /dev/null +++ b/garage_updates/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 IMBENJI.NET LTD + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/garage_updates/analysis_options.yaml b/garage_updates/analysis_options.yaml new file mode 100644 index 0000000..a907916 --- /dev/null +++ b/garage_updates/analysis_options.yaml @@ -0,0 +1,6 @@ +include: package:flutter_lints/flutter.yaml + +linter: + rules: + # the SDK prints caught errors to console on purpose for debugging + avoid_print: false diff --git a/garage_updates/android/.gitignore b/garage_updates/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/garage_updates/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/garage_updates/android/build.gradle.kts b/garage_updates/android/build.gradle.kts new file mode 100644 index 0000000..87a6dd7 --- /dev/null +++ b/garage_updates/android/build.gradle.kts @@ -0,0 +1,58 @@ +group = "net.imbenji.garage_updates" +version = "1.0-SNAPSHOT" + +buildscript { + val kotlinVersion = "2.3.20" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:9.0.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "net.imbenji.garage_updates" + + compileSdk = 36 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + sourceSets { + getByName("main") { + java.srcDirs("src/main/kotlin") + } + } + + defaultConfig { + minSdk = 24 + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +dependencies { + // FileProvider, the only way to hand the installer a file since android 7 + implementation("androidx.core:core:1.13.1") +} diff --git a/garage_updates/android/settings.gradle.kts b/garage_updates/android/settings.gradle.kts new file mode 100644 index 0000000..0d6f0f4 --- /dev/null +++ b/garage_updates/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "garage_updates" diff --git a/garage_updates/android/src/main/AndroidManifest.xml b/garage_updates/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..fc6070e --- /dev/null +++ b/garage_updates/android/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + diff --git a/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt new file mode 100644 index 0000000..1cbe68d --- /dev/null +++ b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt @@ -0,0 +1,6 @@ +package net.imbenji.garage_updates + +import androidx.core.content.FileProvider + +// nothing in it. it exists so the manifest entry has a class name of its own +class GarageUpdatesFileProvider : FileProvider() diff --git a/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt new file mode 100644 index 0000000..a5e720d --- /dev/null +++ b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt @@ -0,0 +1,106 @@ +package net.imbenji.garage_updates + +import android.content.Context +import android.content.Intent +import android.os.Build +import android.util.Log +import androidx.core.content.FileProvider +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.plugin.common.MethodChannel.Result +import java.io.File + +// The android half of garage_updates. Two things dart cant do for itself: +// find out who installed the app, and hand an apk to the system installer. +// The installer always asks the person, theres no silent path and we dont +// want one. +class GarageUpdatesPlugin : FlutterPlugin, MethodCallHandler { + private lateinit var channel: MethodChannel + private lateinit var context: Context + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + context = binding.applicationContext + channel = MethodChannel(binding.binaryMessenger, "net.imbenji.garage_updates") + channel.setMethodCallHandler(this) + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + channel.setMethodCallHandler(null) + } + + override fun onMethodCall(call: MethodCall, result: Result) { + when (call.method) { + "info" -> result.success( + mapOf( + "installer" to installerPackageName(), + "cacheDir" to context.cacheDir.absolutePath, + ) + ) + + "installerPackageName" -> result.success(installerPackageName()) + + "install" -> { + val path = call.argument("path") + if (path == null) { + result.error("bad_args", "install needs a path", null) + return + } + install(File(path), result) + } + + else -> result.notImplemented() + } + } + + // "com.android.vending" for a play store install, null for a sideload + private fun installerPackageName(): String? { + val pm = context.packageManager + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + pm.getInstallSourceInfo(context.packageName).installingPackageName + } else { + @Suppress("DEPRECATION") + pm.getInstallerPackageName(context.packageName) + } + } catch (e: Exception) { + Log.e(TAG, "couldnt read the installer package name", e) + null + } + } + + private fun install(apk: File, result: Result) { + if (!apk.exists()) { + result.error("missing", "No apk at ${apk.path}", null) + return + } + + try { + val uri = FileProvider.getUriForFile( + context, + "${context.packageName}.garage_updates.files", + apk, + ) + + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + // the installer is another app, it needs lending the file + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + // we only have the application context, not an activity + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + + context.startActivity(intent) + result.success(null) + } catch (e: Exception) { + // an apk outside the shared cache folder lands here too + Log.e(TAG, "couldnt open the installer for ${apk.path}", e) + result.error("install_failed", e.message ?: "The installer could not be opened", null) + } + } + + companion object { + private const val TAG = "garage_updates" + } +} diff --git a/garage_updates/android/src/main/res/xml/garage_updates_paths.xml b/garage_updates/android/src/main/res/xml/garage_updates_paths.xml new file mode 100644 index 0000000..ea88c70 --- /dev/null +++ b/garage_updates/android/src/main/res/xml/garage_updates_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/garage_updates/example/lib/main.dart b/garage_updates/example/lib/main.dart new file mode 100644 index 0000000..0bb9d1e --- /dev/null +++ b/garage_updates/example/lib/main.dart @@ -0,0 +1,117 @@ +import "package:flutter/widgets.dart"; +import "package:garage_ui/garage_ui.dart"; +import "package:garage_updates/garage_updates.dart"; +import "package:go_router/go_router.dart"; + +// The whole integration is the one call at the top of main. Everything under +// it is just an app with a "restart to update" button, which is the only +// other thing an app has to do for itself. +// +// Run it with `flutter run` and the updater prints that this copy isnt an +// install and stays out of the way - it only ever touches a release build +// that the installer (or a previous update) put in place. + +Future main(List args) async { + // an app with helpers of its own (an agent, a tray) stops them here + GarageUpdater.instance.onBeforeRestart = () async { + print("about to restart into the new build"); + }; + + await GarageUpdater.launch( + args: args, + project: "proj_example", + build: 12, // the number after the + in pubspec's version + label: "v2610-1", + branding: const UpdaterBranding( + name: "Example App", + logo: Icon(LucideIcons.package), + ), + mode: UpdateMode.prompt, + ); + + runApp(const ExampleApp()); +} + +final _theme = ThemeData( + colorScheme: GarageSchemes.carbon, + density: const Density.product(), +); + +final _router = GoRouter( + routes: [ + GoRoute(path: "/", builder: (context, state) => const HomePage()), + ], +); + +class ExampleApp extends StatelessWidget { + const ExampleApp({super.key}); + + @override + Widget build(BuildContext context) { + return GarageApp.router(routerConfig: _router, theme: _theme, title: "Example App"); + } +} + +class HomePage extends StatefulWidget { + const HomePage({super.key}); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + String? _error; + + Future _restart() async { + try { + await GarageUpdater.instance.restartToUpdate(); + } on UpdateError catch (e) { + // a UAC prompt turned down, say. the update is still waiting + print("couldnt restart into the update: $e"); + if (mounted) setState(() => _error = e.message); + } + } + + @override + Widget build(BuildContext context) { + final updater = GarageUpdater.instance; + + return Scaffold( + child: Center( + child: ValueListenableBuilder( + valueListenable: updater.ready, + builder: (context, waiting, _) { + final latest = waiting?.latest; + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text("Example App ${updater.label}").large().semiBold(), + const Gap.sm(), + if (latest == null) + const Text("Up to date").muted() + else ...[ + Text("${latest.label} is ready to install").muted(), + const Gap.sm(), + + // the notes are the apps to show, the splash never does + if (latest.notes.isNotEmpty) Text(latest.notes).muted(), + const Gap.lg(), + Button( + style: const ButtonStyle.primary(), + onPressed: _restart, + child: const Text("Restart to update"), + ), + ], + if (_error != null) ...[ + const Gap.md(), + Text(_error!).muted(), + ], + ], + ); + }, + ), + ), + ); + } +} diff --git a/garage_updates/example/pubspec.yaml b/garage_updates/example/pubspec.yaml new file mode 100644 index 0000000..fd91331 --- /dev/null +++ b/garage_updates/example/pubspec.yaml @@ -0,0 +1,24 @@ +name: garage_updates_example +description: "Minimal example of an app that updates itself with garage_updates." +publish_to: 'none' +version: 0.1.0+12 + +environment: + sdk: ^3.10.0 + flutter: ">=3.5.0" + +dependencies: + flutter: + sdk: flutter + + garage_ui: + path: ../../garage_ui + garage_updates: + path: ../ + + go_router: ^14.6.2 + +dev_dependencies: + flutter_lints: ^6.0.0 + +flutter: diff --git a/garage_updates/lib/core.dart b/garage_updates/lib/core.dart new file mode 100644 index 0000000..ae1b274 --- /dev/null +++ b/garage_updates/lib/core.dart @@ -0,0 +1,20 @@ +// The updater without flutter: ask Garage for the newest release, download it +// with resume, check the sha256, install it and restart. +// +// A headless dart program (an agent, a cli) imports this one. A flutter app +// wants package:garage_updates/garage_updates.dart instead, which is this +// plus the splash. +// +// final engine = UpdateEngine.detect(project: "", build: 12); +// final info = await engine.check(); +// if (info.hasUpdate) { +// await engine.download(info.latest!); +// await engine.install(info.latest!); +// await engine.restart(args: args); +// } +// +// android isnt in here, installing an apk needs a platform channel. +library; + +export "src/core/models.dart"; +export "src/core/io.dart" if (dart.library.js_interop) "src/core/web.dart"; diff --git a/garage_updates/lib/garage_updates.dart b/garage_updates/lib/garage_updates.dart new file mode 100644 index 0000000..3ca38af --- /dev/null +++ b/garage_updates/lib/garage_updates.dart @@ -0,0 +1,25 @@ +// Auto updates for a flutter app, akin to Discord's. One call at the top of +// main and the rest happens on its own: +// +// Future main(List args) async { +// await GarageUpdater.launch( +// args: args, +// project: "", +// build: 12, +// label: "v2610-1", +// branding: UpdaterBranding(name: "Garage Stash", logo: "assets/logo.png"), +// ); +// runApp(const MyApp()); +// } +// +// While the app runs, GarageUpdater.instance.ready says when a newer build has +// been downloaded, and restartToUpdate() moves over to it. +// +// On the web every call is a no-op. +library; + +export "src/core/models.dart" + show UpdateInfo, UpdateRelease, UpdateAsset, UpdateStatus, UpdateError, UpdateDriver, DownloadProgress; +export "src/branding.dart" show UpdaterBranding, UpdateMode; +export "src/splash.dart" show UpdateSplash, UpdateSplashApp, SplashController, SplashStage; +export "src/updater.dart" show GarageUpdater; diff --git a/garage_updates/lib/src/branding.dart b/garage_updates/lib/src/branding.dart new file mode 100644 index 0000000..72e7aaf --- /dev/null +++ b/garage_updates/lib/src/branding.dart @@ -0,0 +1,39 @@ +import "package:flutter/widgets.dart"; +import "package:garage_ui/garage_ui.dart"; + +/// What happens to an update the app could carry on without. +enum UpdateMode { + /// found at launch = downloaded and installed there and then, behind the + /// splash. The app starts allready up to date + silent, + + /// never installed from the splash. Its fetched in the background and + /// `GarageUpdater.instance.ready` tells the app, which asks the person + prompt, +} + +/// Whose splash it is. +class UpdaterBranding { + const UpdaterBranding({required this.name, this.logo, this.theme}) + : assert( + logo == null || logo is Widget || logo is String || logo is ImageProvider, + "logo is an asset path, an ImageProvider or a Widget", + ); + + /// the developers name for the app, shown under the logo + final String name; + + /// an asset path ("assets/logo.png"), an [ImageProvider], or any widget + final Object? logo; + + /// the splash wears carbon at the product tier unless told otherwise + final ThemeData? theme; + + Widget? buildLogo() { + final l = logo; + if (l is Widget) return l; + if (l is String) return Image.asset(l); + if (l is ImageProvider) return Image(image: l); + return null; + } +} diff --git a/garage_updates/lib/src/core/client.dart b/garage_updates/lib/src/core/client.dart new file mode 100644 index 0000000..bf8f588 --- /dev/null +++ b/garage_updates/lib/src/core/client.dart @@ -0,0 +1,138 @@ +import "dart:async"; +import "dart:convert"; +import "dart:ffi" show Abi; +import "dart:io"; + +import "models.dart"; + +const kDefaultApiBase = "https://pay.imbenji.net/api"; + +/// Asks Garage what the newest release is. No sign in, one GET. +class UpdateClient { + UpdateClient({ + required this.project, + String apiBase = kDefaultApiBase, + HttpClient? httpClient, + this.timeout = const Duration(seconds: 20), + }) : apiBase = apiBase.endsWith("/") ? apiBase.substring(0, apiBase.length - 1) : apiBase, + _http = httpClient ?? HttpClient(); + + final String project; + final String apiBase; + final Duration timeout; + final HttpClient _http; + + Uri checkUri({required String platform, required String arch, required int build}) { + return Uri.parse("$apiBase/v1/updates/${Uri.encodeComponent(project)}").replace( + queryParameters: {"platform": platform, "arch": arch, "build": "$build"}, + ); + } + + /// `GET /v1/updates/:pid`. Throws [UpdateError] when the server cant be + /// reached or says no, a 200 with an odd body comes back as unknown. + Future check({ + required String platform, + required String arch, + required int build, + }) async { + final uri = checkUri(platform: platform, arch: arch, build: build); + + final HttpClientResponse res; + final String body; + try { + final req = await _http.getUrl(uri).timeout(timeout); + req.headers.set(HttpHeaders.acceptHeader, "application/json"); + res = await req.close().timeout(timeout); + body = await res.transform(utf8.decoder).join().timeout(timeout); + } on TimeoutException catch (e) { + print("[garage_updates] the update check timed out: $e"); + throw UpdateError("timeout", "The update check timed out"); + } catch (e, st) { + print("[garage_updates] the update check didnt get through: $e\n$st"); + throw UpdateError("network", "Couldn't reach the update server"); + } + + if (res.statusCode != 200) { + // the store api's errors are {"error": code, "message": ...} + var code = "http_${res.statusCode}"; + var message = "The update server answered ${res.statusCode}"; + try { + final j = jsonDecode(body); + if (j is Map) { + if (j["error"] is String) code = j["error"] as String; + if (j["message"] is String) message = j["message"] as String; + } + } catch (e) { + print("[garage_updates] update check ${res.statusCode} with a body that isnt json: $e"); + } + throw UpdateError(code, message); + } + + Object? json; + try { + json = jsonDecode(body); + } catch (e) { + print("[garage_updates] the update check answered something that isnt json: $e"); + return const UpdateInfo(status: UpdateStatus.unknown); + } + + final info = UpdateInfo.fromJson(json); + final latest = info.latest; + if (latest == null) return info; + + // hosted assets come back absolute, but dont fall over on a relative one + final resolved = _resolve(latest.asset.url); + if (resolved == latest.asset.url) return info; + return UpdateInfo( + status: info.status, + minimumBuild: info.minimumBuild, + latest: UpdateRelease( + label: latest.label, + build: latest.build, + notes: latest.notes, + publishedAt: latest.publishedAt, + asset: UpdateAsset( + url: resolved, + filename: latest.asset.filename, + format: latest.asset.format, + size: latest.asset.size, + sha256: latest.asset.sha256, + ), + ), + ); + } + + String _resolve(String url) { + final u = Uri.tryParse(url); + if (u == null || u.hasScheme) return url; + return Uri.parse("$apiBase/").resolve(url.startsWith("/") ? url.substring(1) : url).toString(); + } + + void close() => _http.close(force: true); +} + + +/// "windows" | "macos" | "android", or null where theres nothing to update +String? currentUpdatePlatform() { + if (Platform.isWindows) return "windows"; + if (Platform.isMacOS) return "macos"; + if (Platform.isAndroid) return "android"; + return null; +} + +/// The arch to ask for. The server falls back to `universal` by itself, so +/// this only has to be honest about the machine. +String currentUpdateArch() { + final abi = Abi.current(); + if (abi == Abi.windowsX64 || abi == Abi.macosX64 || abi == Abi.androidX64 || abi == Abi.linuxX64) { + return "x64"; + } + if (abi == Abi.windowsArm64 || + abi == Abi.macosArm64 || + abi == Abi.androidArm64 || + abi == Abi.linuxArm64) { + return "arm64"; + } + // 32 bit android and the like. only a universal asset can suit it + return "universal"; +} diff --git a/garage_updates/lib/src/core/downloader.dart b/garage_updates/lib/src/core/downloader.dart new file mode 100644 index 0000000..b6ccae2 --- /dev/null +++ b/garage_updates/lib/src/core/downloader.dart @@ -0,0 +1,276 @@ +import "dart:async"; +import "dart:convert"; +import "dart:io"; + +import "package:crypto/crypto.dart"; + +import "models.dart"; + +// Fetches one release asset into the staging folder. +// +// The bytes land in `update.part`, with a little json beside it saying which +// build + sha they belong to. A cut connection leaves both where they are and +// the next go asks for `Range: bytes=N-`. Only once the whole file hashes to +// what Garage recorded does it get its real name. + +const _partName = "update.part"; +const _metaName = "update.part.json"; + +class Downloader { + Downloader({ + HttpClient? httpClient, + this.quietTimeout = const Duration(seconds: 30), + this.retries = 3, + this.retryPause = const Duration(seconds: 2), + }) : _http = httpClient ?? HttpClient(); + + final HttpClient _http; + + /// how long the line may say nothing before we call it dead + final Duration quietTimeout; + + /// extra goes after the first, each one resuming + final int retries; + final Duration retryPause; + + static File partFile(Directory staging) => File(_join(staging.path, _partName)); + static File metaFile(Directory staging) => File(_join(staging.path, _metaName)); + + /// where a finished, verified download of [release] sits + static File finishedFile(Directory staging, UpdateRelease release) { + final ext = release.asset.format.isEmpty ? "bin" : release.asset.format; + return File(_join(staging.path, "update-${release.build}.$ext")); + } + + Future fetch({ + required UpdateRelease release, + required Directory staging, + DownloadProgress? onProgress, + }) async { + final asset = release.asset; + if (asset.sha256.isEmpty) { + // never install something we cant check + throw UpdateError("no_checksum", "The release has no checksum to verify against"); + } + + await staging.create(recursive: true); + final done = finishedFile(staging, release); + final part = partFile(staging); + final meta = metaFile(staging); + + if (await done.exists()) { + if (await sha256Of(done) == asset.sha256) { + onProgress?.call(await done.length(), await done.length()); + return done; + } + print("[garage_updates] ${done.path} doesnt match its checksum any more, fetching it again"); + await _remove(done); + } + await _sweep(staging, keep: done); + + if (!await _partIsOurs(meta, release)) { + if (await part.exists()) { + print("[garage_updates] throwing away a stale part file, it was for another build"); + } + await _remove(part); + await _writeMeta(meta, release); + } + + + var attempt = 0; + while (true) { + try { + await _pull(asset, part, onProgress); + break; + } on UpdateError catch (e) { + if (!_worthRetrying(e) || attempt >= retries) rethrow; + print("[garage_updates] download stopped (${e.message}), going again"); + } catch (e, st) { + // a cut connection, a quiet line. the part file stays for the resume + print("[garage_updates] download stopped: $e\n$st"); + if (attempt >= retries) { + throw UpdateError("download", "The download kept failing: $e"); + } + } + attempt++; + await Future.delayed(retryPause); + } + + final got = await sha256Of(part); + if (got != asset.sha256) { + print("[garage_updates] checksum mismatch, wanted ${asset.sha256} got $got"); + await _remove(part); + await _remove(meta); + throw UpdateError("checksum_mismatch", "The download didn't match its checksum"); + } + + await part.rename(done.path); + await _remove(meta); + return done; + } + + bool _worthRetrying(UpdateError e) => e.code == "restart" || e.code == "server"; + + Future _pull(UpdateAsset asset, File part, DownloadProgress? onProgress) async { + var have = await part.exists() ? await part.length() : 0; + + if (asset.size > 0 && have > asset.size) { + print("[garage_updates] the part file is bigger than the release, starting over"); + await _remove(part); + have = 0; + } + // all there allready, only the checksum left to do + if (asset.size > 0 && have == asset.size) { + onProgress?.call(have, asset.size); + return; + } + + final res = await _open(Uri.parse(asset.url), have); + var append = false; + + if (res.statusCode == HttpStatus.partialContent) { + final start = _rangeStart(res.headers.value(HttpHeaders.contentRangeHeader)); + if (start == have) { + append = true; + } else if (start == 0) { + have = 0; + } else { + await _drain(res); + await _remove(part); + throw UpdateError("restart", "The server resumed from the wrong place"); + } + } else if (res.statusCode == HttpStatus.ok) { + // it ignored the range and sent the lot. fine, start the file again + if (have > 0) print("[garage_updates] the server ignored the range, downloading from the top"); + have = 0; + } else if (res.statusCode == HttpStatus.requestedRangeNotSatisfiable) { + await _drain(res); + await _remove(part); + throw UpdateError("restart", "The server wouldn't resume the download"); + } else { + await _drain(res); + if (res.statusCode >= 500) { + throw UpdateError("server", "The download server answered ${res.statusCode}"); + } + throw UpdateError("http_${res.statusCode}", "The download was refused (${res.statusCode})"); + } + + int? total; + if (res.contentLength >= 0) { + total = have + res.contentLength; + } else if (asset.size > 0) { + total = asset.size; + } + + final out = await part.open(mode: append ? FileMode.writeOnlyAppend : FileMode.writeOnly); + var received = have; + try { + onProgress?.call(received, total); + await for (final chunk in res.timeout(quietTimeout)) { + await out.writeFrom(chunk); + received += chunk.length; + onProgress?.call(received, total); + } + } finally { + await out.close(); + } + + if (total != null && received < total) { + throw HttpException("the download ended early, $received of $total bytes"); + } + } + + // Walks the redirects by hand. A hosted download is a 302 to a presigned url + // that only lives a few minutes, so a resume has to start from the original + // link every time - which is why nothing here remembers where it ended up. + Future _open(Uri uri, int have) async { + for (var hop = 0; hop < 6; hop++) { + final req = await _http.getUrl(uri).timeout(quietTimeout); + req.followRedirects = false; + // dart asks for gzip by itself and unpacks it, which makes a nonsense + // of byte ranges + req.headers.removeAll(HttpHeaders.acceptEncodingHeader); + if (have > 0) req.headers.set(HttpHeaders.rangeHeader, "bytes=$have-"); + + final res = await req.close().timeout(quietTimeout); + final location = res.headers.value(HttpHeaders.locationHeader); + if (res.isRedirect || (_redirects.contains(res.statusCode) && location != null)) { + await _drain(res); + if (location == null) { + throw UpdateError("redirect", "The download redirected to nowhere"); + } + uri = uri.resolve(location); + continue; + } + return res; + } + throw UpdateError("redirect", "The download redirected too many times"); + } + + static const _redirects = {301, 302, 303, 307, 308}; + + int? _rangeStart(String? contentRange) { + // "bytes 100-999/1000" + if (contentRange == null) return null; + final m = RegExp(r"bytes\s+(\d+)-").firstMatch(contentRange); + return m == null ? null : int.tryParse(m.group(1)!); + } + + Future _drain(HttpClientResponse res) async { + try { + await res.drain().timeout(quietTimeout); + } catch (e) { + print("[garage_updates] couldnt drain a response we didnt want: $e"); + } + } + + Future _partIsOurs(File meta, UpdateRelease release) async { + if (!await meta.exists()) return false; + try { + final j = jsonDecode(await meta.readAsString()); + return j is Map && j["build"] == release.build && j["sha256"] == release.asset.sha256; + } catch (e) { + print("[garage_updates] unreadable part note, treating the part as stale: $e"); + return false; + } + } + + Future _writeMeta(File meta, UpdateRelease release) async { + await meta.writeAsString( + jsonEncode({"build": release.build, "sha256": release.asset.sha256}), + flush: true, + ); + } + + // finished downloads of other builds, nobody is going to install those now + Future _sweep(Directory staging, {required File keep}) async { + try { + await for (final e in staging.list()) { + if (e is! File || e.path == keep.path) continue; + final name = e.uri.pathSegments.last; + if (name.startsWith("update-")) await _remove(e); + } + } catch (e) { + print("[garage_updates] couldnt tidy the staging folder: $e"); + } + } + + void close() => _http.close(force: true); +} + +/// sha256 of a file as lower case hex, read as a stream so a big download +/// never sits in memory +Future sha256Of(File f) async { + final digest = await sha256.bind(f.openRead()).first; + return digest.toString(); +} + +Future _remove(File f) async { + try { + if (await f.exists()) await f.delete(); + } catch (e) { + print("[garage_updates] couldnt delete ${f.path}: $e"); + } +} + +String _join(String a, String b) => a.endsWith(Platform.pathSeparator) ? "$a$b" : "$a${Platform.pathSeparator}$b"; diff --git a/garage_updates/lib/src/core/engine.dart b/garage_updates/lib/src/core/engine.dart new file mode 100644 index 0000000..6e532a1 --- /dev/null +++ b/garage_updates/lib/src/core/engine.dart @@ -0,0 +1,184 @@ +import "dart:async"; +import "dart:io"; + +import "client.dart"; +import "downloader.dart"; +import "installer.dart"; +import "models.dart"; + +/// The whole updater with no flutter in it: check, download, install, +/// restart. The splash drives one of these, and so can a headless program. +/// +/// final engine = UpdateEngine.detect(project: "...", build: 12); +/// final info = await engine.check(); +/// if (info.hasUpdate) { +/// await engine.download(info.latest!); +/// await engine.install(info.latest!); +/// await engine.restart(args: args); +/// } +class UpdateEngine implements UpdateDriver { + UpdateEngine({ + required this.project, + required this.build, + String apiBase = kDefaultApiBase, + Installer? installer, + String? notInstalledReason, + UpdateClient? client, + Downloader? downloader, + String? arch, + void Function(int code)? exitProcess, + }) : _installer = installer, + notInstalledReason = installer != null ? null : (notInstalledReason ?? "no installer"), + client = client ?? UpdateClient(project: project, apiBase: apiBase), + downloader = downloader ?? Downloader(), + arch = arch ?? currentUpdateArch(), + _exit = exitProcess ?? exit; + + /// Looks at where this process is running from and builds the engine for + /// it. Somewhere the updater didnt put it = an engine that does nothing. + factory UpdateEngine.detect({ + required String project, + required int build, + String apiBase = kDefaultApiBase, + }) { + final found = detectInstall(); + return UpdateEngine( + project: project, + build: build, + apiBase: apiBase, + installer: found.installer, + notInstalledReason: found.reason, + ); + } + + final String project; + + /// the build this process is + final int build; + final String arch; + + final UpdateClient client; + final Downloader downloader; + final Installer? _installer; + final void Function(int code) _exit; + + @override + final String? notInstalledReason; + + @override + FutureOr Function()? onBeforeRestart; + + @override + bool get installed => _installer != null; + + Installer? get installer => _installer; + + bool _saidNotInstalled = false; + final Set _saidBlocked = {}; + + /// Says once why this copy wont be updated. Returns [installed]. + bool reportIfNotInstalled() { + if (installed) return true; + if (!_saidNotInstalled) { + _saidNotInstalled = true; + print("[garage_updates] not updating this copy: $notInstalledReason"); + } + return false; + } + + @override + Future noteStart() async { + final inst = _installer; + if (inst == null) return false; + return inst.noteStart(build); + } + + @override + Future check() async { + final inst = _installer; + if (inst == null) { + reportIfNotInstalled(); + return const UpdateInfo(status: UpdateStatus.unknown); + } + + final info = await client.check(platform: inst.platform, arch: arch, build: build); + final latest = info.latest; + if (latest == null) return info; + + if (latest.build <= build) { + // the server only offers newer ones, but never go backwards on its say so + return UpdateInfo(status: UpdateStatus.current, minimumBuild: info.minimumBuild); + } + + if (inst.blockedBuilds().contains(latest.build)) { + if (_saidBlocked.add(latest.build)) { + print("[garage_updates] build ${latest.build} failed to start on this machine before, not taking it again"); + } + // still required if it was, theres just nothing here that can be installed + return UpdateInfo( + status: info.isRequired ? UpdateStatus.required : UpdateStatus.current, + minimumBuild: info.minimumBuild, + ); + } + return info; + } + + @override + Future download(UpdateRelease release, {DownloadProgress? onProgress}) async { + final inst = _need(); + await downloader.fetch(release: release, staging: inst.staging, onProgress: onProgress); + } + + /// true when [release] is allready downloaded and verified + Future isDownloaded(UpdateRelease release) async { + final inst = _installer; + if (inst == null) return false; + return Downloader.finishedFile(inst.staging, release).exists(); + } + + @override + Future install(UpdateRelease release) async { + final inst = _need(); + final file = Downloader.finishedFile(inst.staging, release); + if (!await file.exists()) { + throw UpdateError("not_downloaded", "Build ${release.build} hasn't been downloaded"); + } + await inst.apply(file, release, runningBuild: build); + } + + @override + Future restart({List args = const []}) async { + final inst = _need(); + + final before = onBeforeRestart; + if (before != null) { + try { + await before(); + } catch (e, st) { + // the apps own tidy up going wrong shouldnt strand it on the old build + print("[garage_updates] onBeforeRestart threw, restarting anyway: $e\n$st"); + } + } + + await inst.relaunch(args); + if (inst.exitsOnRestart) _exit(0); + } + + @override + Future markHealthy() async { + await _installer?.markHealthy(); + } + + Installer _need() { + final inst = _installer; + if (inst == null) { + throw UpdateError("not_installed", "This copy of the app can't be updated: $notInstalledReason"); + } + return inst; + } + + void close() { + client.close(); + downloader.close(); + } +} diff --git a/garage_updates/lib/src/core/installer.dart b/garage_updates/lib/src/core/installer.dart new file mode 100644 index 0000000..923a035 --- /dev/null +++ b/garage_updates/lib/src/core/installer.dart @@ -0,0 +1,99 @@ +import "dart:io"; + +import "mac_installer.dart"; +import "models.dart"; +import "windows_installer.dart"; + +/// The part that differs per platform: where downloads go, how a verified +/// archive becomes the installed app, and how the app is started again. +abstract class Installer { + /// "windows" | "macos" | "android", what the check is asked for + String get platform; + + /// where the `.part` file and the finished download live + Directory get staging; + + /// builds that failed to start here and must not be offered again + List blockedBuilds(); + + /// Turns the verified [archive] into the installed app. Does not restart. + Future apply(File archive, UpdateRelease release, {required int runningBuild}); + + /// Starts the app again. The caller ends this process afterwards when + /// [exitsOnRestart] says so. + Future relaunch(List args); + + /// false on android, where the system installer does the restarting + bool get exitsOnRestart; + + /// Counts a start of [build]. true = the previous build was just put back + /// because this one kept dying, relaunch. + Future noteStart(int build); + + Future markHealthy(); +} + +typedef ProcessRunner = Future Function(String exe, List args); +typedef ProcessStarter = Future Function(String exe, List args); + +Future defaultRunner(String exe, List args) => Process.run(exe, args); + +Future defaultStarter(String exe, List args) async { + // detached, it has to outlive us + await Process.start(exe, args, mode: ProcessStartMode.detached); +} + +/// What [detectInstall] found. Exactly one of the two is set. +class InstallDetection { + const InstallDetection.found(Installer this.installer) : reason = null; + const InstallDetection.none(String this.reason) : installer = null; + + final Installer? installer; + + /// why this copy of the app isnt one we can update + final String? reason; +} + +/// Works out whether this process is running from somewhere the updater put +/// it. A dev build, `flutter run`, `dart run`, a folder that isnt +/// `app-`, a translocated or read only mac bundle: all "none", and the +/// updater then leaves the app completly alone. +InstallDetection detectInstall({ + String? executable, + Map? environment, + String? platform, + bool? product, +}) { + // debug + profile builds and anything run off the jit. a release build is + // the only thing that should ever get swapped + product ??= const bool.fromEnvironment("dart.vm.product"); + if (!product) return const InstallDetection.none("this isn't a release build"); + + final exe = executable ?? Platform.resolvedExecutable; + final env = environment ?? Platform.environment; + + switch (platform ?? Platform.operatingSystem) { + case "windows": + return WindowsInstaller.locate(exe, environment: env); + case "macos": + return MacInstaller.locate(exe, environment: env); + default: + return InstallDetection.none("no installer for ${platform ?? Platform.operatingSystem} here"); + } +} + +/// last bit of a path, whichever way the slashes lean +String baseName(String path) { + var p = path; + while (p.length > 1 && (p.endsWith("/") || p.endsWith("\\"))) { + p = p.substring(0, p.length - 1); + } + final cut = p.lastIndexOf(RegExp(r"[/\\]")); + return cut < 0 ? p : p.substring(cut + 1); +} + +String joinPath(String a, String b, [String? c]) { + final sep = Platform.pathSeparator; + final ab = a.endsWith(sep) ? "$a$b" : "$a$sep$b"; + return c == null ? ab : "$ab$sep$c"; +} diff --git a/garage_updates/lib/src/core/io.dart b/garage_updates/lib/src/core/io.dart new file mode 100644 index 0000000..017a824 --- /dev/null +++ b/garage_updates/lib/src/core/io.dart @@ -0,0 +1,12 @@ +// everything in core that needs dart:io. see core.dart + +export "client.dart"; +export "downloader.dart"; +export "engine.dart"; +export "installer.dart"; +export "mac_installer.dart"; +export "state.dart"; +export "windows_installer.dart"; + +/// false on the web, where theres nothing to update +const bool kUpdatesSupported = true; diff --git a/garage_updates/lib/src/core/mac_installer.dart b/garage_updates/lib/src/core/mac_installer.dart new file mode 100644 index 0000000..3d671a6 --- /dev/null +++ b/garage_updates/lib/src/core/mac_installer.dart @@ -0,0 +1,343 @@ +import "dart:convert"; +import "dart:io"; + +import "installer.dart"; +import "models.dart"; +import "state.dart"; + +// macOS. No stub here, the bundle is swapped where it stands: +// +// unpack the zip with ditto, move the running .app out to +// ~/Library/Application Support//garage_updates/previous.app, +// move the new one into its place, `open -n` it. +// +// A running app carries on fine after its bundle is moved, the files are +// still open. The fallback the windows stub does (3 starts that never get to +// markHealthy = go back) is done in here too, by noteStart(). + +const _maxFailedStarts = 3; + +class MacInstaller implements Installer { + MacInstaller({ + required this.bundle, + required this.bundleId, + required this.support, + ProcessRunner? run, + }) : _run = run ?? defaultRunner; + + /// the .app we are running out of + final Directory bundle; + final String bundleId; + + /// `~/Library/Application Support//garage_updates` + final Directory support; + + final ProcessRunner _run; + + late final StateFile state = StateFile(File(joinPath(support.path, "state.json"))); + + Directory get previousApp => Directory(joinPath(support.path, "previous.app")); + + static InstallDetection locate(String executable, {Map? environment}) { + final env = environment ?? Platform.environment; + + final bundle = _bundleOf(executable); + if (bundle == null) { + return InstallDetection.none("${baseName(executable)} isn't running from an app bundle"); + } + + final path = bundle.path; + if (path.contains("/AppTranslocation/")) { + // gatekeeper runs a quarantined app from a random read only mount untill + // its been moved by hand. nothing to swap there + return const InstallDetection.none("the app is translocated, move it to Applications first"); + } + if (path.contains("/Build/Products/") || path.contains("/DerivedData/")) { + return const InstallDetection.none("the app is running out of a build folder"); + } + if (!_writable(bundle.parent.path) || !_writable(path)) { + return InstallDetection.none("$path can't be replaced by this user"); + } + + final id = readBundleId(bundle); + if (id == null) { + return const InstallDetection.none("the bundle has no CFBundleIdentifier"); + } + + final home = env["HOME"]; + if (home == null || home.isEmpty) { + return const InstallDetection.none("no HOME to keep the update state in"); + } + + return InstallDetection.found(MacInstaller( + bundle: bundle, + bundleId: id, + support: Directory("$home/Library/Application Support/$id/garage_updates"), + )); + } + + // the OUTERMOST .app in the path. a helper in Contents/MacOS, or in a login + // item bundle nested inside, still belongs to the app around it + static Directory? _bundleOf(String executable) { + final parts = executable.split("/"); + for (var i = 0; i < parts.length - 1; i++) { + if (parts[i].endsWith(".app") && parts[i].length > 4) { + return Directory(parts.sublist(0, i + 1).join("/")); + } + } + return null; + } + + static bool _writable(String path) { + try { + return Process.runSync("/bin/test", ["-w", path]).exitCode == 0; + } catch (e) { + print("[garage_updates] couldnt check whether $path is writable: $e"); + return false; + } + } + + @override + String get platform => "macos"; + + @override + bool get exitsOnRestart => true; + + @override + Directory get staging => Directory(joinPath(support.path, "staging")); + + @override + List blockedBuilds() => state.read()?.blocked ?? const []; + + @override + Future apply(File archive, UpdateRelease release, {required int runningBuild}) async { + final unpack = Directory(joinPath(support.path, "unpack")); + await _wipe(unpack); + await unpack.create(recursive: true); + + try { + switch (release.asset.format) { + case "zip": + await _must("/usr/bin/ditto", ["-x", "-k", archive.path, unpack.path], "unpack the update"); + case "dmg": + await _fromDmg(archive, unpack); + default: + throw UpdateError("format", "A mac release has to be a zip or a dmg, not ${release.asset.format}"); + } + + final fresh = _findApp(unpack); + if (fresh == null) { + throw UpdateError("no_app", "There's no .app inside the update"); + } + + // dont let a mislabelled asset replace us with some other app + final freshId = readBundleId(fresh); + if (freshId != null && freshId != bundleId) { + throw UpdateError("wrong_app", "The update is for $freshId, this is $bundleId"); + } + + await _swap(fresh); + } finally { + await _wipe(unpack); + } + + state.update((s) { + // what we are running is the truth, whatever the file last thought + s.previous = runningBuild; + s.current = release.build; + s.failedStarts = 0; + }, createIfMissing: true); + + try { + if (archive.existsSync()) archive.deleteSync(); + } catch (e) { + print("[garage_updates] couldnt remove ${archive.path} after installing it: $e"); + } + } + + Future _swap(Directory fresh) async { + await _wipe(previousApp); + await support.create(recursive: true); + + await _move(bundle.path, previousApp.path); + try { + await _move(fresh.path, bundle.path); + } catch (e, st) { + print("[garage_updates] couldnt move the new bundle in, putting the old one back: $e\n$st"); + await _move(previousApp.path, bundle.path); + rethrow; + } + } + + Future _fromDmg(File dmg, Directory unpack) async { + final mount = Directory(joinPath(support.path, "mount")); + await _wipe(mount); + await mount.create(recursive: true); + + await _must( + "/usr/bin/hdiutil", + ["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mount.path, dmg.path], + "open the disk image", + ); + try { + final app = _findApp(mount); + if (app == null) throw UpdateError("no_app", "There's no .app inside the disk image"); + await _must( + "/usr/bin/ditto", + [app.path, joinPath(unpack.path, baseName(app.path))], + "copy the app off the disk image", + ); + } finally { + final res = await _run("/usr/bin/hdiutil", ["detach", mount.path, "-force"]); + if (res.exitCode != 0) { + print("[garage_updates] couldnt detach ${mount.path}: ${res.stderr}"); + } + await _wipe(mount); + } + } + + // top level, or one folder down (a zip of a folder holding the app) + Directory? _findApp(Directory dir) { + final found = []; + void look(Directory d, int depth) { + for (final e in d.listSync(followLinks: false)) { + if (e is! Directory) continue; + final name = baseName(e.path); + if (name == "__MACOSX") continue; + if (name.endsWith(".app")) { + found.add(e); + } else if (depth == 0) { + look(e, 1); + } + } + } + + look(dir, 0); + if (found.isEmpty) return null; + + final ours = baseName(bundle.path); + for (final f in found) { + if (baseName(f.path) == ours) return f; + } + return found.first; + } + + @override + Future relaunch(List args) async { + await _must( + "/usr/bin/open", + ["-n", bundle.path, if (args.isNotEmpty) ...["--args", ...args]], + "start the app again", + ); + } + + @override + Future noteStart(int build) async { + final s = state.read() ?? UpdateState(); + + if (s.current != build) { + // a build this file has never seen start. put there by hand, most likely + if (!previousApp.existsSync()) s.previous = null; + s.current = build; + s.failedStarts = 0; + } + + if (s.failedStarts >= _maxFailedStarts && s.previous != null && previousApp.existsSync()) { + print("[garage_updates] build $build failed to start ${s.failedStarts} times, going back to ${s.previous}"); + try { + await _swapBack(); + } catch (e, st) { + print("[garage_updates] couldnt put the previous build back: $e\n$st"); + return false; + } + + if (!s.blocked.contains(build)) s.blocked.add(build); + s.current = s.previous; + s.previous = null; + s.failedStarts = 0; + state.write(s); + return true; + } + + s.failedStarts++; + state.write(s); + return false; + } + + Future _swapBack() async { + final failed = Directory(joinPath(support.path, "failed.app")); + await _wipe(failed); + + await _move(bundle.path, failed.path); + try { + await _move(previousApp.path, bundle.path); + } catch (e) { + print("[garage_updates] the previous bundle wouldnt move back, restoring: $e"); + await _move(failed.path, bundle.path); + rethrow; + } + await _wipe(failed); + } + + @override + Future markHealthy() async { + final s = state.read(); + if (s != null && s.failedStarts == 0) return; + state.update((s) => s.failedStarts = 0, createIfMissing: true); + } + + + Future _move(String from, String to) async { + try { + await Directory(from).rename(to); + return; + } on FileSystemException catch (e) { + // another volume, rename cant cross those. mv copies when it has to + print("[garage_updates] rename $from -> $to failed (${e.osError?.message}), trying mv"); + } + await _must("/bin/mv", [from, to], "move ${baseName(from)}"); + } + + Future _must(String exe, List args, String what) async { + final res = await _run(exe, args); + if (res.exitCode != 0) { + print("[garage_updates] ${baseName(exe)} ${args.join(" ")} exited ${res.exitCode}\n${res.stdout}\n${res.stderr}"); + throw UpdateError("install_failed", "Couldn't $what"); + } + } + + Future _wipe(Directory d) async { + try { + if (await d.exists()) await d.delete(recursive: true); + } catch (e) { + print("[garage_updates] couldnt remove ${d.path}: $e"); + } + } +} + +/// CFBundleIdentifier out of a bundles Info.plist, null when there isnt one +String? readBundleId(Directory app) { + final plist = File("${app.path}/Contents/Info.plist"); + if (!plist.existsSync()) return null; + + try { + final text = utf8.decode(plist.readAsBytesSync(), allowMalformed: true); + if (!text.startsWith("bplist")) { + final m = RegExp(r"\s*CFBundleIdentifier\s*\s*([^<]+)").firstMatch(text); + if (m != null) return m.group(1)!.trim(); + } + + // a binary plist, or xml laid out some way the regex didnt expect + final res = Process.runSync( + "/usr/libexec/PlistBuddy", + ["-c", "Print :CFBundleIdentifier", plist.path], + ); + if (res.exitCode == 0) { + final id = (res.stdout as String).trim(); + if (id.isNotEmpty) return id; + } + } catch (e) { + print("[garage_updates] couldnt read ${plist.path}: $e"); + } + return null; +} diff --git a/garage_updates/lib/src/core/models.dart b/garage_updates/lib/src/core/models.dart new file mode 100644 index 0000000..63cee47 --- /dev/null +++ b/garage_updates/lib/src/core/models.dart @@ -0,0 +1,208 @@ +import "dart:async"; + +// The shapes the update check hands back, and the one interface the flutter +// half drives. Nothing in here touches dart:io, so it compiles for the web +// where the whole package is a no-op. + +enum UpdateStatus { + /// nothing newer for this platform + current, + + /// theres a newer build, the app may carry on without it + available, + + /// this build is below the projects minimum. the app must not start + required, + + /// the server couldnt tell (no build sent), or we couldnt read its answer + unknown, +} + +class UpdateAsset { + const UpdateAsset({ + required this.url, + required this.filename, + required this.format, + required this.size, + required this.sha256, + }); + + final String url; + final String filename; + + /// "zip" | "dmg" | "apk" + final String format; + final int size; + final String sha256; + + static UpdateAsset? fromJson(Object? raw) { + if (raw is! Map) return null; + final url = _str(raw["url"]); + if (url == null || url.isEmpty) return null; + + final filename = _str(raw["filename"]) ?? ""; + var format = (_str(raw["format"]) ?? "").toLowerCase(); + if (format.isEmpty) { + // older answers might not carry it, the filename says the same thing + final dot = filename.lastIndexOf("."); + if (dot >= 0) format = filename.substring(dot + 1).toLowerCase(); + } + + return UpdateAsset( + url: url, + filename: filename, + format: format, + size: _int(raw["size"]) ?? 0, + sha256: (_str(raw["sha256"]) ?? "").toLowerCase(), + ); + } + + Map toJson() => { + "url": url, + "filename": filename, + "format": format, + "size": size, + "sha256": sha256, + }; +} + +class UpdateRelease { + const UpdateRelease({ + required this.label, + required this.build, + required this.asset, + this.notes = "", + this.publishedAt, + }); + + final String label; + final int build; + final String notes; + final DateTime? publishedAt; + final UpdateAsset asset; + + static UpdateRelease? fromJson(Object? raw) { + if (raw is! Map) return null; + final build = _int(raw["build"]); + final asset = UpdateAsset.fromJson(raw["asset"]); + // a release we cant order or cant download is no use to anyone + if (build == null || asset == null) return null; + + final published = _str(raw["published_at"]); + return UpdateRelease( + label: _str(raw["label"]) ?? "", + build: build, + notes: _str(raw["notes"]) ?? "", + publishedAt: published == null ? null : DateTime.tryParse(published), + asset: asset, + ); + } + + Map toJson() => { + "label": label, + "build": build, + "notes": notes, + "published_at": publishedAt?.toUtc().toIso8601String(), + "asset": asset.toJson(), + }; +} + +class UpdateInfo { + const UpdateInfo({required this.status, this.minimumBuild, this.latest}); + + final UpdateStatus status; + final int? minimumBuild; + final UpdateRelease? latest; + + /// true when theres something to download + bool get hasUpdate => + latest != null && (status == UpdateStatus.available || status == UpdateStatus.required); + + bool get isRequired => status == UpdateStatus.required; + + /// Reads the body of `GET /v1/updates/:pid`. Never throws on a strange + /// shape, it just comes back as unknown. + factory UpdateInfo.fromJson(Object? raw) { + if (raw is! Map) return const UpdateInfo(status: UpdateStatus.unknown); + + final latest = UpdateRelease.fromJson(raw["latest"]); + var status = switch (_str(raw["status"])) { + "current" => UpdateStatus.current, + "available" => UpdateStatus.available, + "required" => UpdateStatus.required, + _ => UpdateStatus.unknown, + }; + + // says theres an update but didnt send one we can use + if (latest == null && (status == UpdateStatus.available || status == UpdateStatus.required)) { + print("[garage_updates] the check said ${status.name} but sent no usable release"); + status = UpdateStatus.unknown; + } + + return UpdateInfo( + status: status, + minimumBuild: _int(raw["minimum_build"]), + latest: latest, + ); + } + + UpdateInfo withStatus(UpdateStatus s) => + UpdateInfo(status: s, minimumBuild: minimumBuild, latest: latest); +} + + +/// Anything the updater gives up on. `code` is stable, `message` is for a log. +class UpdateError implements Exception { + UpdateError(this.code, this.message); + + final String code; + final String message; + + @override + String toString() => "UpdateError($code): $message"; +} + +/// bytes so far, and the total when we know it +typedef DownloadProgress = void Function(int received, int? total); + +/// What the splash and the background check drive. The real one is +/// `UpdateEngine` in core, the web gets none at all. +abstract class UpdateDriver { + /// false for a dev build, `flutter run`, a translocated mac bundle and so + /// on. When its false nothing else here does anything + bool get installed; + + /// why not, for the one line that gets printed + String? get notInstalledReason; + + /// Run right before the app is restarted into the new build, so an app can + /// stop its own helper processes first. + FutureOr Function()? onBeforeRestart; + + /// Counts this start. Comes back true when the last update kept failing to + /// start and the old build was put back - the caller should [restart]. + Future noteStart(); + + Future check(); + + /// Downloads + verifies. Safe to call again, it picks up where it stopped. + Future download(UpdateRelease release, {DownloadProgress? onProgress}); + + /// Installs what [download] fetched. Does not restart. + Future install(UpdateRelease release); + + /// Starts the app again and ends this process. On android the system + /// installer does the restarting, so this returns. + Future restart({List args = const []}); + + Future markHealthy(); +} + +String? _str(Object? v) => v is String ? v : null; + +int? _int(Object? v) { + if (v is int) return v; + if (v is double && v.isFinite) return v.toInt(); + if (v is String) return int.tryParse(v.trim()); + return null; +} diff --git a/garage_updates/lib/src/core/state.dart b/garage_updates/lib/src/core/state.dart new file mode 100644 index 0000000..74f1ded --- /dev/null +++ b/garage_updates/lib/src/core/state.dart @@ -0,0 +1,228 @@ +import "dart:convert"; +import "dart:io"; + +// `garage_updates.json` on windows (shared with the stub) and `state.json` on +// the mac. Same fields on both. + +class UpdateState { + UpdateState({ + this.exe, + this.current, + this.previous, + this.failedStarts = 0, + List? blocked, + Map? extra, + }) : blocked = blocked ?? [], + extra = extra ?? {}; + + /// the real exe inside a version folder. windows only + String? exe; + + int? current; + int? previous; + + /// starts of `current` that never reached markHealthy + int failedStarts; + + /// builds that failed 3 starts on this machine, never offered here again + List blocked; + + /// keys we dont know about. the stub may write more than we read, and + /// writing the file back must not lose them + Map extra; + + factory UpdateState.fromJson(Map j) { + final known = {"exe", "current", "previous", "failed_starts", "blocked"}; + final blocked = []; + final raw = j["blocked"]; + if (raw is List) { + for (final b in raw) { + final n = _int(b); + if (n != null && !blocked.contains(n)) blocked.add(n); + } + } + + return UpdateState( + exe: j["exe"] is String ? j["exe"] as String : null, + current: _int(j["current"]), + previous: _int(j["previous"]), + failedStarts: _int(j["failed_starts"]) ?? 0, + blocked: blocked, + extra: { + for (final e in j.entries) + if (e.key is String && !known.contains(e.key)) e.key as String: e.value, + }, + ); + } + + Map toJson() => { + ...extra, + if (exe != null) "exe": exe, + "current": current, + "previous": previous, + "failed_starts": failedStarts, + "blocked": blocked, + }; +} + +class StateFile { + StateFile(this.file); + + final File file; + + /// null when its missing, half written or not ours. Says which on the + /// console, never throws. + UpdateState? read() { + final j = _readObject(file); + return j == null ? null : UpdateState.fromJson(j); + } + + /// Write to a temp file beside it, then rename over the top, so a reader + /// never sees half a file. + bool write(UpdateState state) => _writeObject(file, state.toJson()); + + /// Read, change, write. Without [createIfMissing] it does nothing when the + /// file cant be read, rather than writing an empty state over whatever the + /// stub had in there. The mac owns its file so it passes true, a damaged + /// one just gets started again. + bool update(void Function(UpdateState s) change, {bool createIfMissing = false}) { + var state = read(); + if (state == null) { + if (!createIfMissing) return false; + state = UpdateState(); + } + change(state); + return write(state); + } +} + +/// What one person on the machine knows about the install, for when the +/// install itself is somewhere they cant write (Program Files). The stub +/// keeps it in `%LOCALAPPDATA%\\garage_updates.json` and it only +/// ever exists for an install like that. +class UserState { + UserState({ + this.failedStarts = 0, + List? blocked, + this.forCurrent, + this.runInstead, + }) : blocked = blocked ?? []; + + int failedStarts; + + /// builds that failed 3 starts for this user + List blocked; + + /// the `current` of the install the count was made against + int? forCurrent; + + /// the build the stub starts for this user instead of `current` + int? runInstead; + + factory UserState.fromJson(Map j) { + final blocked = []; + final raw = j["blocked"]; + if (raw is List) { + for (final b in raw) { + final n = _int(b); + if (n != null && !blocked.contains(n)) blocked.add(n); + } + } + final count = _int(j["failed_starts"]) ?? 0; + + return UserState( + failedStarts: count < 0 ? 0 : count, + blocked: blocked, + forCurrent: _int(j["for_current"]), + runInstead: _int(j["run_instead"]), + ); + } + + Map toJson() => { + "failed_starts": failedStarts, + "blocked": blocked, + "for_current": forCurrent, + "run_instead": runInstead, + }; + + /// The count and the build to run instead only mean anything for the + /// `current` they were made against. Once an update has gone in they start + /// again, what got blocked stays blocked. Same rule as the stub. + void settleFor(int? current) { + if (forCurrent == current) return; + forCurrent = current; + failedStarts = 0; + runInstead = null; + } +} + +class UserStateFile { + UserStateFile(this.file); + + final File file; + + UserState? read() { + final j = _readObject(file); + return j == null ? null : UserState.fromJson(j); + } + + bool write(UserState state) => _writeObject(file, state.toJson()); + + /// Same deal as [StateFile.update]. The app never passes + /// [createIfMissing], starting this file is the stubs job. + bool update(void Function(UserState s) change, {bool createIfMissing = false}) { + var state = read(); + if (state == null) { + if (!createIfMissing) return false; + state = UserState(); + } + change(state); + return write(state); + } +} + +Map? _readObject(File file) { + try { + if (!file.existsSync()) return null; + final text = file.readAsStringSync(); + if (text.trim().isEmpty) { + print("[garage_updates] ${file.path} is empty"); + return null; + } + final j = jsonDecode(text); + if (j is! Map) { + print("[garage_updates] ${file.path} isnt an object"); + return null; + } + return j; + } catch (e) { + // most likely caught mid write by the other side + print("[garage_updates] couldnt read ${file.path}: $e"); + return null; + } +} + +bool _writeObject(File file, Map json) { + final tmp = File("${file.path}.tmp"); + try { + file.parent.createSync(recursive: true); + tmp.writeAsStringSync(const JsonEncoder.withIndent(" ").convert(json), flush: true); + tmp.renameSync(file.path); + return true; + } catch (e, st) { + print("[garage_updates] couldnt write ${file.path}: $e\n$st"); + try { + if (tmp.existsSync()) tmp.deleteSync(); + } catch (e2) { + print("[garage_updates] and couldnt clear up ${tmp.path}: $e2"); + } + return false; + } +} + +int? _int(Object? v) { + if (v is int) return v; + if (v is double && v.isFinite) return v.toInt(); + if (v is String) return int.tryParse(v.trim()); + return null; +} diff --git a/garage_updates/lib/src/core/web.dart b/garage_updates/lib/src/core/web.dart new file mode 100644 index 0000000..9d8153b --- /dev/null +++ b/garage_updates/lib/src/core/web.dart @@ -0,0 +1,4 @@ +// the web's half of core: nothing. a site is updated by deploying it + +/// false on the web, where theres nothing to update +const bool kUpdatesSupported = false; diff --git a/garage_updates/lib/src/core/windows_installer.dart b/garage_updates/lib/src/core/windows_installer.dart new file mode 100644 index 0000000..83cb9c7 --- /dev/null +++ b/garage_updates/lib/src/core/windows_installer.dart @@ -0,0 +1,294 @@ +import "dart:io"; + +import "installer.dart"; +import "models.dart"; +import "state.dart"; + +// Windows. The app never unpacks anything itself, the stub in does: +// +// \.exe the stub +// \app-\... a version folder, we are running out of one +// \garage_updates.json state, the stubs and ours +// +// An install in Program Files cant be written by whoever is running the app, +// so there the stub keeps the count of starts in a file of the users own +// (see [UserState]). Everything read here is the two put together. +// +// All this side does is hand the stub a verified zip (`--garage-apply`), with +// a UAC prompt in front of it when is in Program Files, and then start +// the stub again so it launches the new folder. + +class WindowsInstaller implements Installer { + WindowsInstaller({ + required this.root, + required this.stub, + required this.runningFolderBuild, + Map? environment, + ProcessRunner? run, + ProcessStarter? start, + bool Function()? rootWritable, + }) : _env = environment ?? Platform.environment, + _run = run ?? defaultRunner, + _start = start ?? defaultStarter, + _rootWritableOverride = rootWritable; + + final Directory root; + final File stub; + + /// the number off the `app-` folder this process lives in + final int runningFolderBuild; + + final Map _env; + final ProcessRunner _run; + final ProcessStarter _start; + final bool Function()? _rootWritableOverride; + + late final StateFile state = StateFile(File(joinPath(root.path, "garage_updates.json"))); + + static final _versionFolder = RegExp(r"^app-(\d+)$"); + + static InstallDetection locate(String executable, {Map? environment}) { + final folder = File(executable).parent; + final m = _versionFolder.firstMatch(baseName(folder.path)); + if (m == null) { + return InstallDetection.none("${baseName(executable)} isn't running out of an app- folder"); + } + + final root = folder.parent; + final stateFile = File(joinPath(root.path, "garage_updates.json")); + if (!stateFile.existsSync()) { + return const InstallDetection.none("there's no garage_updates.json beside the version folder"); + } + + final stub = _findStub(root, StateFile(stateFile).read(), executable); + if (stub == null) { + return const InstallDetection.none("there's no stub exe beside the version folder"); + } + + return InstallDetection.found(WindowsInstaller( + root: root, + stub: stub, + runningFolderBuild: int.parse(m.group(1)!), + environment: environment, + )); + } + + // the stub carries the apps exe name. a helper (stash-agent.exe) isnt named + // after it, so the state file is asked first and our own name second + static File? _findStub(Directory root, UpdateState? state, String executable) { + final names = [ + if (state?.exe != null) baseName(state!.exe!), + baseName(executable), + ]; + for (final n in names) { + final f = File(joinPath(root.path, n)); + if (f.existsSync()) return f; + } + + try { + final exes = root + .listSync() + .whereType() + .where((f) => f.path.toLowerCase().endsWith(".exe")) + .toList(); + if (exes.length == 1) return exes.single; + } catch (e) { + print("[garage_updates] couldnt look for the stub in ${root.path}: $e"); + } + return null; + } + + @override + String get platform => "windows"; + + @override + bool get exitsOnRestart => true; + + /// "just me" installs are, Program Files isnt + bool get rootWritable { + final over = _rootWritableOverride; + if (over != null) return over(); + + final probe = File(joinPath(root.path, ".garage_updates_probe")); + try { + probe.writeAsStringSync(""); + probe.deleteSync(); + return true; + } on FileSystemException { + // the expected answer for Program Files, not worth a line in the log + return false; + } + } + + /// The installer may leave `app_id` in the state file, otherwise the + /// folders name does. + String get appId { + final id = state.read()?.extra["app_id"]; + // the stub wont make a folder out of one with these in, so neither do we + if (id is String && id.trim().isNotEmpty && !id.contains(RegExp("[\\\\/:*?\"<>|]"))) return id.trim(); + return baseName(root.path); + } + + /// `%LOCALAPPDATA%\\garage_updates.json`, the stubs count of starts + /// for this user when it couldnt write the one in root. The file is only + /// there for an install like that, we never make it. + UserStateFile? get userState { + final local = _env["LOCALAPPDATA"]; + if (local == null || local.isEmpty) return null; + return UserStateFile(File(joinPath(local, appId, "garage_updates.json"))); + } + + UserState? _mine(UpdateState? rootState) { + final mine = userState?.read(); + mine?.settleFor(rootState?.current); + return mine; + } + + + /// The build the stub starts for this user. `current`, unless that one + /// kept dying on them and the stub went back a build without being able to + /// say so in root. + int? get startsBuild { + final s = state.read(); + final other = _mine(s)?.runInstead; + if (other != null && other != s?.current && Directory(joinPath(root.path, "app-$other")).existsSync()) { + return other; + } + return s?.current; + } + + @override + Directory get staging { + if (rootWritable) return Directory(joinPath(root.path, "staging")); + + final local = _env["LOCALAPPDATA"]; + if (local == null || local.isEmpty) { + print("[garage_updates] no LOCALAPPDATA, staging in the temp folder"); + return Directory(joinPath(Directory.systemTemp.path, appId, "staging")); + } + return Directory(joinPath(local, appId, "staging")); + } + + @override + List blockedBuilds() { + final s = state.read(); + final out = [...?s?.blocked]; + // what failed for this user, on an install they cant write to + for (final b in _mine(s)?.blocked ?? const []) { + if (!out.contains(b)) out.add(b); + } + return out; + } + + @override + Future apply(File archive, UpdateRelease release, {required int runningBuild}) async { + if (release.asset.format != "zip") { + throw UpdateError("format", "A windows release has to be a zip, not ${release.asset.format}"); + } + + final args = ["--garage-apply", archive.path, "${release.build}"]; + final ProcessResult res; + if (rootWritable) { + res = await _run(stub.path, args); + } else { + // one UAC prompt. powershell is only the thing that can ask for it + res = await _run(powershellPath(_env), elevationArgs(stub.path, args)); + } + + if (res.exitCode != 0) { + print("[garage_updates] the stub exited ${res.exitCode}\n${res.stdout}\n${res.stderr}"); + if (res.exitCode == kElevationRefused) { + throw UpdateError("elevation_refused", "Administrator permission was not given"); + } + throw UpdateError("install_failed", "The update could not be installed (${res.exitCode})"); + } + + // belt and braces. a stub that said 0 but didnt move `current` would have + // us restart straight back into the old build, forever + final now = state.read(); + if (now != null && now.current != release.build) { + throw UpdateError("install_failed", "The update did not take, still on build ${now.current}"); + } + + try { + if (archive.existsSync()) archive.deleteSync(); + } catch (e) { + print("[garage_updates] couldnt remove ${archive.path} after installing it: $e"); + } + } + + @override + Future relaunch(List args) => _start(stub.path, args); + + /// the stub counts starts on windows, before it launches us + @override + Future noteStart(int build) async => false; + + @override + Future markHealthy() async { + final s = state.read(); + if (s != null && s.failedStarts != 0) state.update((s) => s.failedStarts = 0); + + // the stub counted in here instead if it couldnt write to root + final mine = userState; + final u = mine?.read(); + if (mine != null && u != null && u.failedStarts != 0) mine.update((u) => u.failedStarts = 0); + } +} + +/// ERROR_CANCELLED, what windows gives when the UAC prompt is turned down +const kElevationRefused = 1223; + +String powershellPath(Map env) { + final sys = env["SystemRoot"] ?? env["SYSTEMROOT"] ?? env["windir"]; + if (sys != null && sys.isNotEmpty) { + final full = "$sys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"; + if (File(full).existsSync()) return full; + } + return "powershell"; +} + +/// The powershell command line that runs [exe] elevated and passes its exit +/// code back out. Start-Process -Verb RunAs is ShellExecute "runas". +List elevationArgs(String exe, List args) { + final line = args.map(windowsQuoteArg).join(" "); + // without the try a refused prompt leaves $p null and powershell exits 0 + final script = "\$ErrorActionPreference = 'Stop'; " + "try { " + "\$p = Start-Process -FilePath ${powershellQuote(exe)} -ArgumentList ${powershellQuote(line)} " + "-Verb RunAs -Wait -PassThru -WindowStyle Hidden; " + "exit \$p.ExitCode " + "} catch { [Console]::Error.WriteLine(\$_); exit $kElevationRefused }"; + + return ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script]; +} + +/// a single quoted powershell string, nothing inside it is expanded +String powershellQuote(String s) => "'${s.replaceAll("'", "''")}'"; + +/// One argument the way CommandLineToArgvW wants it. Backslashes only matter +/// in front of a quote, which is the bit everyone gets wrong with a path that +/// ends in one. +String windowsQuoteArg(String arg) { + if (arg.isNotEmpty && !arg.contains(RegExp("[ \t\n\"]"))) return arg; + + final out = StringBuffer("\""); + var slashes = 0; + for (final ch in arg.split("")) { + if (ch == "\\") { + slashes++; + continue; + } + if (ch == "\"") { + out.write("\\" * (slashes * 2 + 1)); + out.write("\""); + } else { + out.write("\\" * slashes); + out.write(ch); + } + slashes = 0; + } + out.write("\\" * (slashes * 2)); + out.write("\""); + return out.toString(); +} diff --git a/garage_updates/lib/src/platform/android_installer.dart b/garage_updates/lib/src/platform/android_installer.dart new file mode 100644 index 0000000..7201821 --- /dev/null +++ b/garage_updates/lib/src/platform/android_installer.dart @@ -0,0 +1,83 @@ +import "dart:io"; + +import "package:flutter/foundation.dart"; +import "package:flutter/services.dart"; + +import "../core/installer.dart"; +import "../core/models.dart"; + +// Android. The apk is downloaded into the apps cache and handed to the system +// installer, which always asks. It also does the restarting, so theres no +// relaunch and no fallback here - a build that wont start is androids problem. + +const _channel = MethodChannel("net.imbenji.garage_updates"); + +const _playStore = "com.android.vending"; + +class AndroidInstaller implements Installer { + AndroidInstaller(this.cacheDir); + + final Directory cacheDir; + + static Future locate() async { + if (!kReleaseMode) { + // a debug apk is signed with the debug key, a release wouldnt install + // over it anyway + return const InstallDetection.none("this isn't a release build"); + } + + final Map? info; + try { + info = await _channel.invokeMapMethod("info"); + } catch (e, st) { + print("[garage_updates] couldnt ask android about the install: $e\n$st"); + return const InstallDetection.none("the garage_updates plugin didn't answer"); + } + + if (info?["installer"] == _playStore) { + return const InstallDetection.none("installed from the Play Store, which does the updating"); + } + + final cache = info?["cacheDir"]; + if (cache is! String || cache.isEmpty) { + return const InstallDetection.none("android gave no cache folder to download into"); + } + return InstallDetection.found(AndroidInstaller(Directory(cache))); + } + + @override + String get platform => "android"; + + @override + bool get exitsOnRestart => false; + + // has to match the cache-path in the plugins file provider xml + @override + Directory get staging => Directory("${cacheDir.path}/garage_updates"); + + @override + List blockedBuilds() => const []; + + @override + Future apply(File archive, UpdateRelease release, {required int runningBuild}) async { + if (release.asset.format != "apk") { + throw UpdateError("format", "An android release has to be an apk, not ${release.asset.format}"); + } + + try { + await _channel.invokeMethod("install", {"path": archive.path}); + } on PlatformException catch (e, st) { + print("[garage_updates] the system installer wouldnt open: $e\n$st"); + throw UpdateError("install_failed", e.message ?? "The installer could not be opened"); + } + } + + @override + Future relaunch(List args) async {} + + @override + Future noteStart(int build) async => false; + + @override + Future markHealthy() async {} +} diff --git a/garage_updates/lib/src/platform/driver.dart b/garage_updates/lib/src/platform/driver.dart new file mode 100644 index 0000000..557bf54 --- /dev/null +++ b/garage_updates/lib/src/platform/driver.dart @@ -0,0 +1 @@ +export "driver_io.dart" if (dart.library.js_interop) "driver_stub.dart"; diff --git a/garage_updates/lib/src/platform/driver_io.dart b/garage_updates/lib/src/platform/driver_io.dart new file mode 100644 index 0000000..47a4dfd --- /dev/null +++ b/garage_updates/lib/src/platform/driver_io.dart @@ -0,0 +1,31 @@ +import "dart:io"; + +import "../core/engine.dart"; +import "../core/models.dart"; +import "android_installer.dart"; + +/// The engine for whatever this is running on. null where the package has +/// nothing to do at all (linux, ios). +Future openDriver({ + required String project, + required int build, + required String apiBase, +}) async { + if (Platform.isWindows || Platform.isMacOS) { + return UpdateEngine.detect(project: project, build: build, apiBase: apiBase); + } + + if (Platform.isAndroid) { + // core cant do android, installing an apk goes through the plugin + final found = await AndroidInstaller.locate(); + return UpdateEngine( + project: project, + build: build, + apiBase: apiBase, + installer: found.installer, + notInstalledReason: found.reason, + ); + } + + return null; +} diff --git a/garage_updates/lib/src/platform/driver_stub.dart b/garage_updates/lib/src/platform/driver_stub.dart new file mode 100644 index 0000000..1021ecf --- /dev/null +++ b/garage_updates/lib/src/platform/driver_stub.dart @@ -0,0 +1,10 @@ +import "../core/models.dart"; + +// the web's half. nothing to update, so no driver + +Future openDriver({ + required String project, + required int build, + required String apiBase, +}) async => + null; diff --git a/garage_updates/lib/src/splash.dart b/garage_updates/lib/src/splash.dart new file mode 100644 index 0000000..282f222 --- /dev/null +++ b/garage_updates/lib/src/splash.dart @@ -0,0 +1,186 @@ +import "dart:async"; + +import "package:flutter/foundation.dart"; +import "package:flutter/widgets.dart"; +import "package:garage_ui/garage_ui.dart"; + +import "branding.dart"; + +// What's on screen before the app's own runApp. A fixed layout and nothing to +// configure but the logo and the name: logo, name, one status line, a bar, +// and when a required update wont go in, why and a Retry. + +enum SplashStage { checking, downloading, installing, starting } + +class SplashController extends ChangeNotifier { + SplashStage _stage = SplashStage.checking; + double? _progress; + String? _error; + Completer? _retry; + + SplashStage get stage => _stage; + + /// 0 to 1 while theres a number to show, null = busy + double? get progress => _progress; + + /// set when a required update failed. the Retry button shows with it + String? get error => _error; + + String get statusLine => switch (_stage) { + SplashStage.checking => "Checking for updates", + SplashStage.downloading => "Downloading update", + SplashStage.installing => "Installing", + SplashStage.starting => "Starting", + }; + + void show(SplashStage stage, {double? progress}) { + _stage = stage; + _progress = progress; + _error = null; + notifyListeners(); + } + + set progress(double? v) { + if (v == _progress) return; + _progress = v; + notifyListeners(); + } + + /// Puts the error up and waits for Retry to be pressed. + Future fail(String message) { + _error = message; + // a bar sweeping away under an error reads as still trying + _progress ??= 0; + final c = _retry = Completer(); + notifyListeners(); + return c.future; + } + + void retry() { + final c = _retry; + _retry = null; + _error = null; + notifyListeners(); + if (c != null && !c.isCompleted) c.complete(); + } +} + +class UpdateSplash extends StatelessWidget { + const UpdateSplash({required this.branding, required this.controller, super.key}); + + final UpdaterBranding branding; + final SplashController controller; + + @override + Widget build(BuildContext context) { + final density = GarageTheme.of(context).density; + final logo = branding.buildLogo(); + + return Scaffold( + child: Center( + child: SizedBox( + width: density.fontSize * 22, + child: ListenableBuilder( + listenable: controller, + builder: (context, _) { + final error = controller.error; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (logo != null) ...[ + SizedBox.square(dimension: density.controlHeight * 2, child: logo), + const Gap.lg(), + ], + Text(branding.name).large().semiBold(), + const Gap.sm(), + Text(controller.statusLine).muted(), + const Gap.lg(), + + // the bar has no width of its own, it takes the columns + SizedBox( + width: double.infinity, + child: LinearProgressIndicator(value: controller.progress), + ), + if (error != null) ...[ + const Gap.xl(), + Text(error).muted(), + const Gap.md(), + Button( + style: const ButtonStyle.outline(), + onPressed: controller.retry, + child: const Text("Retry"), + ), + ], + ], + ); + }, + ), + ), + ), + ); + } +} + + +/// The tiny app `launch` runs to get the splash on screen. The host app's own +/// runApp replaces it, and [onGone] is how the updater finds out it has. +class UpdateSplashApp extends StatefulWidget { + const UpdateSplashApp({ + required this.branding, + required this.controller, + this.onGone, + super.key, + }); + + final UpdaterBranding branding; + final SplashController controller; + final VoidCallback? onGone; + + static final defaultTheme = ThemeData( + colorScheme: GarageSchemes.carbon, + density: const Density.product(), + ); + + @override + State createState() => _UpdateSplashAppState(); +} + +class _UpdateSplashAppState extends State { + late final _delegate = _SplashDelegate( + (context) => UpdateSplash(branding: widget.branding, controller: widget.controller), + ); + late final _router = RouterConfig(routerDelegate: _delegate); + + @override + void dispose() { + _delegate.dispose(); + widget.onGone?.call(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return GarageApp.router( + routerConfig: _router, + theme: widget.branding.theme ?? UpdateSplashApp.defaultTheme, + title: widget.branding.name, + ); + } +} + +// one page and nowhere to go. GarageApp only comes as a router, and pulling +// go_router into every app that wants updates for this would be daft +class _SplashDelegate extends RouterDelegate with ChangeNotifier { + _SplashDelegate(this.builder); + + final WidgetBuilder builder; + + @override + Widget build(BuildContext context) => builder(context); + + @override + Future popRoute() => SynchronousFuture(false); + + @override + Future setNewRoutePath(Object configuration) => SynchronousFuture(null); +} diff --git a/garage_updates/lib/src/updater.dart b/garage_updates/lib/src/updater.dart new file mode 100644 index 0000000..bc3816b --- /dev/null +++ b/garage_updates/lib/src/updater.dart @@ -0,0 +1,322 @@ +import "dart:async"; + +import "package:flutter/foundation.dart"; +import "package:flutter/widgets.dart"; + +import "branding.dart"; +import "core/models.dart"; +import "platform/driver.dart"; +import "splash.dart"; + +const _defaultApiBase = "https://pay.imbenji.net/api"; + +/// how long the splash waits on the check before letting the app start +const _checkWait = Duration(seconds: 2); + +const _recheckEvery = Duration(hours: 6); + +/// after the apps first frame. long enough that a build which dies on the way +/// up doesnt get called healthy +const _healthyAfter = Duration(seconds: 3); + +class GarageUpdater { + GarageUpdater._(); + + /// There before [launch] is called, so an app can set [onBeforeRestart] + /// ahead of a restart that happens inside the splash. + static GarageUpdater get instance => _instance; + static GarageUpdater _instance = GarageUpdater._(); + + /// The one call, at the top of `main(List args)`. Completes when + /// the app should carry on to its own runApp. For a required update that + /// is never: it restarts into the new build instead. + static Future launch({ + required List args, + required String project, + required int build, + required String label, + required UpdaterBranding branding, + String apiBase = _defaultApiBase, + UpdateMode mode = UpdateMode.silent, + }) { + return instance.start( + args: args, + project: project, + build: build, + label: label, + branding: branding, + apiBase: apiBase, + mode: mode, + ); + } + + final ValueNotifier _ready = ValueNotifier(null); + + /// null untill a newer build has been downloaded and verified. Then + /// [restartToUpdate] moves over to it. + ValueListenable get ready => _ready; + + /// the same thing as a stream, for anyone who would rather await it + Stream get readyStream => _readyStream.stream; + final _readyStream = StreamController.broadcast(); + + /// The release notes of the newest build we know about. The splash never + /// shows these, they are for the app. + String? get notes => (_ready.value ?? _lastCheck)?.latest?.notes; + + /// what the last check that got an answer said + UpdateInfo? get lastCheck => _lastCheck; + + /// the label this build was launched with ("v2610-1") + String? get label => _label; + + /// Run right before the app is restarted into a new build. Stop helper + /// processes here. + FutureOr Function()? onBeforeRestart; + + UpdateDriver? _driver; + UpdateInfo? _lastCheck; + UpdateMode _mode = UpdateMode.silent; + List _args = const []; + String? _label; + bool _started = false; + bool _fetching = false; + Timer? _recheck; + Timer? _healthy; + + /// [launch] with the seams showing. [driver] and [show] are for tests. + @visibleForTesting + Future start({ + required List args, + required String project, + required int build, + required String label, + required UpdaterBranding branding, + String apiBase = _defaultApiBase, + UpdateMode mode = UpdateMode.silent, + UpdateDriver? driver, + void Function(Widget app)? show, + Duration checkWait = _checkWait, + }) async { + if (_started) { + print("[garage_updates] launch was called twice, ignoring the second"); + return; + } + _started = true; + _args = List.of(args); + _mode = mode; + _label = label; + + // a site is updated by deploying it + if (kIsWeb) return; + + var d = driver; + if (d == null) { + try { + d = await openDriver(project: project, build: build, apiBase: apiBase); + } catch (e, st) { + print("[garage_updates] couldnt set the updater up, starting without it: $e\n$st"); + return; + } + } + if (d == null) return; + + if (!d.installed) { + // a dev build, flutter run, a copy that isnt in the layout. hands off + print("[garage_updates] not updating this copy: ${d.notInstalledReason}"); + return; + } + + _driver = d; + d.onBeforeRestart = () => onBeforeRestart?.call(); + + try { + // the mac counts its own starts. true = the last update kept dying and + // the old build has just been put back + if (await d.noteStart()) { + await d.restart(args: _args); + } + } catch (e, st) { + print("[garage_updates] couldnt count this start: $e\n$st"); + } + + WidgetsFlutterBinding.ensureInitialized(); + final splash = SplashController(); + (show ?? runApp)(UpdateSplashApp( + branding: branding, + controller: splash, + onGone: _hostAppIsUp, + )); + + await _behindTheSplash(d, splash, checkWait); + + splash.show(SplashStage.starting); + _recheck = Timer.periodic(_recheckEvery, (_) => checkNow()); + } + + Future _behindTheSplash(UpdateDriver d, SplashController splash, Duration wait) async { + while (true) { + splash.show(SplashStage.checking); + + final UpdateInfo info; + final asking = d.check(); + try { + info = await asking.timeout(wait); + } on TimeoutException { + // no answer in time. the app starts, the answer is dealt with whenever + // it turns up + print("[garage_updates] no answer from the update check yet, starting the app"); + unawaited(asking.then(_gotLateAnswer, onError: (Object e, StackTrace st) { + print("[garage_updates] the update check failed: $e\n$st"); + })); + return; + } catch (e, st) { + print("[garage_updates] the update check failed, starting the app: $e\n$st"); + return; + } + + _lastCheck = info; + final latest = info.latest; + + if (info.isRequired) { + if (latest == null) { + // below the minimum, and the only newer build is blocked here + await splash.fail("This version can no longer be used, and the update can't be installed here."); + continue; + } + try { + await _fetchAndInstall(d, latest, splash); + await d.restart(args: _args); + } catch (e, st) { + print("[garage_updates] the required update failed: $e\n$st"); + await splash.fail(_sayWhy(e)); + continue; + } + + // only android gets here, its installer is a prompt over the top of us + await splash.fail("Install the update to continue."); + continue; + } + + if (latest == null || !info.hasUpdate) return; + + if (_mode == UpdateMode.prompt || defaultTargetPlatform == TargetPlatform.android) { + // android always asks, so its never sprung on someone at launch + unawaited(_fetchQuietly(info)); + return; + } + + try { + await _fetchAndInstall(d, latest, splash); + await d.restart(args: _args); + } catch (e, st) { + // not required, so its not worth keeping anyone out of the app over + print("[garage_updates] couldnt update at launch, starting the old build: $e\n$st"); + } + return; + } + } + + Future _fetchAndInstall(UpdateDriver d, UpdateRelease latest, SplashController splash) async { + splash.show(SplashStage.downloading, progress: 0); + await d.download(latest, onProgress: (got, total) { + splash.progress = (total == null || total <= 0) ? null : (got / total).clamp(0.0, 1.0); + }); + + splash.show(SplashStage.installing); + await d.install(latest); + splash.show(SplashStage.starting); + } + + String _sayWhy(Object e) { + if (e is UpdateError) return e.message; + return "The update could not be installed."; + } + + void _gotLateAnswer(UpdateInfo info) { + _lastCheck = info; + if (info.hasUpdate) unawaited(_fetchQuietly(info)); + } + + /// Asks again now, and fetches whatever is newer. Runs by itself every 6 + /// hours, an app can call it from a "check for updates" button. + Future checkNow() async { + final d = _driver; + if (d == null) return null; + + try { + final info = await d.check(); + _lastCheck = info; + if (info.hasUpdate) await _fetchQuietly(info); + return info; + } catch (e, st) { + print("[garage_updates] the background update check failed: $e\n$st"); + return null; + } + } + + Future _fetchQuietly(UpdateInfo info) async { + final d = _driver; + final latest = info.latest; + if (d == null || latest == null || _fetching) return; + if (_ready.value?.latest?.build == latest.build) return; + + _fetching = true; + try { + await d.download(latest); + _ready.value = info; + _readyStream.add(info); + } catch (e, st) { + // the part file is kept, the next check carries on from it + print("[garage_updates] the background download failed: $e\n$st"); + } finally { + _fetching = false; + } + } + + /// Installs the update that [ready] announced and restarts into it. Throws + /// an [UpdateError] when it wont go in (a UAC prompt turned down, say). + Future restartToUpdate() async { + final d = _driver; + final latest = _ready.value?.latest; + if (d == null || latest == null) { + print("[garage_updates] restartToUpdate with no update waiting, nothing to do"); + return; + } + + try { + await d.install(latest); + await d.restart(args: _args); + } catch (e, st) { + print("[garage_updates] couldnt restart into build ${latest.build}: $e\n$st"); + rethrow; + } + } + + /// Tells the updater this build starts fine, which stops it being rolled + /// back. Called for you a few seconds after the first frame. + Future markHealthy() async { + try { + await _driver?.markHealthy(); + } catch (e, st) { + print("[garage_updates] couldnt mark this build healthy: $e\n$st"); + } + } + + // the splash was just torn down, which is the host app's runApp taking over. + // its first frame is the next one + void _hostAppIsUp() { + WidgetsBinding.instance.addPostFrameCallback((_) { + _healthy?.cancel(); + _healthy = Timer(_healthyAfter, markHealthy); + }); + } + + /// Puts a fresh updater in [instance]. Tests only. + @visibleForTesting + static void reset() { + _instance._recheck?.cancel(); + _instance._healthy?.cancel(); + _instance = GarageUpdater._(); + } +} diff --git a/garage_updates/pubspec.yaml b/garage_updates/pubspec.yaml new file mode 100644 index 0000000..fab1f2b --- /dev/null +++ b/garage_updates/pubspec.yaml @@ -0,0 +1,37 @@ +name: garage_updates +description: "Auto updates for Garage apps — asks Garage for the newest release, downloads it with resume, checks the sha256, installs it beside the old one and restarts into it." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.10.0 + flutter: ">=3.5.0" + +dependencies: + flutter: + sdk: flutter + + # the splash is drawn with the design system, nothing of its own + garage_ui: + path: ../garage_ui + + # sha256 of the download, streamed off disk + crypto: ^3.0.6 + +dev_dependencies: + flutter_test: + sdk: flutter + + flutter_lints: ^6.0.0 + +flutter: + plugin: + platforms: + android: + package: net.imbenji.garage_updates + pluginClass: GarageUpdatesPlugin + + # no channel on windows. ffiPlugin only so the host app's build pulls in + # windows/CMakeLists.txt, which is where the stub exe gets built + windows: + ffiPlugin: true diff --git a/garage_updates/test/client_test.dart b/garage_updates/test/client_test.dart new file mode 100644 index 0000000..c548def --- /dev/null +++ b/garage_updates/test/client_test.dart @@ -0,0 +1,167 @@ +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_server.dart"; + +void main() { + late FakeServer server; + late UpdateClient client; + + setUp(() async { + server = await FakeServer.start(const []); + client = UpdateClient(project: "proj_1", apiBase: "${server.base}/", httpClient: HttpClient()); + }); + + tearDown(() async { + client.close(); + await server.close(); + }); + + Future check() => client.check(platform: "windows", arch: "x64", build: 12); + + Map latest({Object? build = 13}) => { + "label": "v2610-1", + "build": build, + "notes": "Fixed the thing", + "published_at": "2026-10-01T10:00:00Z", + "asset": { + "url": "https://cdn.example.com/app.zip", + "filename": "app.zip", + "format": "zip", + "size": 1234, + "sha256": "ABCDEF", + }, + }; + + test("asks the right url", () async { + server.updateBody = {"status": "current", "minimum_build": null, "latest": null}; + await check(); + + expect(server.log.single, "GET /v1/updates/proj_1"); + final uri = client.checkUri(platform: "macos", arch: "arm64", build: 7); + expect(uri.queryParameters, {"platform": "macos", "arch": "arm64", "build": "7"}); + // the trailing slash on apiBase didnt double up + expect(uri.path, "/v1/updates/proj_1"); + }); + + test("current", () async { + server.updateBody = {"status": "current", "minimum_build": 4, "latest": null}; + final info = await check(); + + expect(info.status, UpdateStatus.current); + expect(info.minimumBuild, 4); + expect(info.latest, isNull); + expect(info.hasUpdate, isFalse); + }); + + test("available", () async { + server.updateBody = {"status": "available", "minimum_build": null, "latest": latest()}; + final info = await check(); + + expect(info.status, UpdateStatus.available); + expect(info.hasUpdate, isTrue); + expect(info.isRequired, isFalse); + + final l = info.latest!; + expect(l.label, "v2610-1"); + expect(l.build, 13); + expect(l.notes, "Fixed the thing"); + expect(l.publishedAt, DateTime.utc(2026, 10, 1, 10)); + expect(l.asset.url, "https://cdn.example.com/app.zip"); + expect(l.asset.filename, "app.zip"); + expect(l.asset.format, "zip"); + expect(l.asset.size, 1234); + // lower cased, its compared against our own hex + expect(l.asset.sha256, "abcdef"); + }); + + test("required", () async { + server.updateBody = {"status": "required", "minimum_build": 13, "latest": latest()}; + final info = await check(); + + expect(info.status, UpdateStatus.required); + expect(info.isRequired, isTrue); + expect(info.minimumBuild, 13); + }); + + test("unknown", () async { + server.updateBody = {"status": "unknown", "minimum_build": null, "latest": null}; + expect((await check()).status, UpdateStatus.unknown); + }); + + test("a status we've never heard of is unknown", () async { + server.updateBody = {"status": "sideways", "latest": latest()}; + expect((await check()).status, UpdateStatus.unknown); + }); + + test("numbers as strings, missing keys and the wrong types are put up with", () async { + final l = latest(build: "13"); + (l["asset"] as Map)["size"] = "1234"; + (l["asset"] as Map).remove("format"); + l["notes"] = 42; + l.remove("published_at"); + server.updateBody = {"status": "available", "minimum_build": "9", "latest": l}; + + final info = await check(); + expect(info.minimumBuild, 9); + expect(info.latest!.build, 13); + expect(info.latest!.notes, ""); + expect(info.latest!.publishedAt, isNull); + expect(info.latest!.asset.size, 1234); + // worked out from the filename + expect(info.latest!.asset.format, "zip"); + }); + + test("available with nothing usable to download is unknown", () async { + final l = latest(); + l.remove("asset"); + server.updateBody = {"status": "available", "latest": l}; + final info = await check(); + + expect(info.status, UpdateStatus.unknown); + expect(info.hasUpdate, isFalse); + }); + + test("a body that isnt json, or isnt an object, is unknown", () async { + server.updateBody = "bad gateway"; + expect((await check()).status, UpdateStatus.unknown); + + server.updateBody = [1, 2, 3]; + expect((await check()).status, UpdateStatus.unknown); + }); + + test("a relative asset url is resolved against the api", () async { + final l = latest(); + (l["asset"] as Map)["url"] = "/v1/updates/proj_1/download/a1"; + server.updateBody = {"status": "available", "latest": l}; + + final info = await check(); + expect(info.latest!.asset.url, "${server.base}/v1/updates/proj_1/download/a1"); + }); + + test("an error status throws the store api's code", () async { + server.updateStatus = 404; + server.updateBody = {"error": "not_found", "message": "No such project"}; + + await expectLater( + check(), + throwsA(isA() + .having((e) => e.code, "code", "not_found") + .having((e) => e.message, "message", "No such project")), + ); + }); + + test("an error status with no json body still throws", () async { + server.updateStatus = 502; + server.updateBody = "bad gateway"; + + await expectLater(check(), throwsA(isA().having((e) => e.code, "code", "http_502"))); + }); + + test("a server that isnt there throws network", () async { + await server.close(); + await expectLater(check(), throwsA(isA().having((e) => e.code, "code", "network"))); + }); +} diff --git a/garage_updates/test/core_headless.dart b/garage_updates/test/core_headless.dart new file mode 100644 index 0000000..55b6cee --- /dev/null +++ b/garage_updates/test/core_headless.dart @@ -0,0 +1,36 @@ +// Not a flutter test, a plain dart program: +// +// dart run test/core_headless.dart +// +// It imports core and nothing else and runs on the standalone vm, which has +// no dart:ui. If core ever picked up a flutter import this wouldnt compile. + +import "dart:io"; + +import "package:garage_updates/core.dart"; + +Future main() async { + final engine = UpdateEngine.detect(project: "proj_headless", build: 1); + + // `dart run` is the jit, so this is a dev copy and the engine must sit still + if (engine.installed) { + stderr.writeln("FAIL: a dart run was taken for an install"); + exit(1); + } + engine.reportIfNotInstalled(); + + final info = await engine.check(); + if (info.status != UpdateStatus.unknown) { + stderr.writeln("FAIL: an engine with no install asked the server"); + exit(1); + } + + final state = StateFile(File("${Directory.systemTemp.path}/garage_updates_headless_missing.json")); + if (state.read() != null) { + stderr.writeln("FAIL: a missing state file read as something"); + exit(1); + } + + engine.close(); + print("core runs headless: supported=$kUpdatesSupported arch=${currentUpdateArch()} platform=${currentUpdatePlatform()}"); +} diff --git a/garage_updates/test/core_imports_test.dart b/garage_updates/test/core_imports_test.dart new file mode 100644 index 0000000..6be63bf --- /dev/null +++ b/garage_updates/test/core_imports_test.dart @@ -0,0 +1,85 @@ +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; + +// core.dart is for headless dart programs, so nothing it reaches may import +// flutter. This walks the imports from lib/core.dart (both sides of every +// conditional one) and checks. test/core_headless.dart is the other half: it +// actually runs core on the plain dart vm, which has no dart:ui to give. + +final _directive = RegExp(r'''^\s*(?:import|export)\s+([^;]+);''', multiLine: true); +final _uri = RegExp(r'''["']([^"']+)["']'''); + +Set _walk(File start) { + final seen = {}; + final uris = {}; + final queue = [start]; + + while (queue.isNotEmpty) { + final f = queue.removeLast(); + if (!seen.add(f.absolute.path)) continue; + + for (final d in _directive.allMatches(f.readAsStringSync())) { + for (final m in _uri.allMatches(d.group(1)!)) { + final uri = m.group(1)!; + if (uri.startsWith("dart:") || uri.startsWith("package:")) { + uris.add(uri); + } else { + queue.add(File.fromUri(f.absolute.uri.resolve(uri))); + } + } + } + } + return uris; +} + +void main() { + test("core.dart reaches no flutter", () { + final uris = _walk(File("lib/core.dart")); + + expect(uris, isNotEmpty); + expect(uris.where((u) => u.startsWith("package:flutter")), isEmpty); + expect(uris.where((u) => u.startsWith("package:garage_ui")), isEmpty); + expect(uris, isNot(contains("dart:ui"))); + + // and the only package it leans on at all + expect(uris.where((u) => u.startsWith("package:")).toSet(), {"package:crypto/crypto.dart"}); + }); + + test("core's web side reaches no dart:io", () { + final uris = { + ..._walk(File("lib/src/core/models.dart")), + ..._walk(File("lib/src/core/web.dart")), + }; + expect(uris, isNot(contains("dart:io"))); + expect(uris, isNot(contains("dart:ffi"))); + }); + + test("the flutter entry point reaches dart:io only behind a conditional import", () { + // everything garage_updates.dart can reach on the web: the stub side of + // each conditional import, never the io side + final seen = {}; + final uris = {}; + final queue = [File("lib/garage_updates.dart")]; + + while (queue.isNotEmpty) { + final f = queue.removeLast(); + if (!seen.add(f.absolute.path)) continue; + + for (final d in _directive.allMatches(f.readAsStringSync())) { + // of a conditional pair the last uri is the one the web gets + final uri = _uri.allMatches(d.group(1)!).last.group(1)!; + if (uri.startsWith("dart:") || uri.startsWith("package:")) { + uris.add(uri); + } else { + queue.add(File.fromUri(f.absolute.uri.resolve(uri))); + } + } + } + + expect(seen.where((p) => p.endsWith("driver_stub.dart")), isNotEmpty); + expect(seen.where((p) => p.endsWith("driver_io.dart")), isEmpty); + expect(uris, isNot(contains("dart:io"))); + expect(uris, isNot(contains("dart:ffi"))); + }); +} diff --git a/garage_updates/test/downloader_test.dart b/garage_updates/test/downloader_test.dart new file mode 100644 index 0000000..d5f3f0f --- /dev/null +++ b/garage_updates/test/downloader_test.dart @@ -0,0 +1,260 @@ +import "dart:convert"; +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_server.dart"; + +void main() { + late FakeServer server; + late Directory staging; + final data = noise(200 * 1024); + + Downloader make({int retries = 0}) => Downloader( + httpClient: HttpClient(), + retries: retries, + retryPause: const Duration(milliseconds: 10), + quietTimeout: const Duration(seconds: 5), + ); + + setUp(() async { + server = await FakeServer.start(data); + staging = Directory("${Directory.systemTemp.createTempSync("gu_dl_").path}/staging"); + }); + + tearDown(() async { + await server.close(); + if (staging.parent.existsSync()) staging.parent.deleteSync(recursive: true); + }); + + test("downloads, verifies and renames", () async { + final release = server.release(); + final seen = []; + int? total; + + final file = await make().fetch( + release: release, + staging: staging, + onProgress: (got, t) { + seen.add(got); + total = t; + }, + ); + + expect(file.path, Downloader.finishedFile(staging, release).path); + expect(file.path.endsWith("update-13.zip"), isTrue); + expect(file.readAsBytesSync(), data); + expect(seen.last, data.length); + expect(total, data.length); + + // nothing left lying about + expect(Downloader.partFile(staging).existsSync(), isFalse); + expect(Downloader.metaFile(staging).existsSync(), isFalse); + }); + + test("a cut connection keeps the part, and the next go resumes with Range", () async { + final release = server.release(); + server.cutsLeft = 1; + server.cutAfter = 50 * 1024; + + await expectLater( + make().fetch(release: release, staging: staging), + throwsA(isA().having((e) => e.code, "code", "download")), + ); + + final part = Downloader.partFile(staging); + expect(part.existsSync(), isTrue); + final had = part.lengthSync(); + expect(had, greaterThan(0)); + expect(had, lessThan(data.length)); + expect(Downloader.metaFile(staging).existsSync(), isTrue); + + int? firstProgress; + final file = await make().fetch( + release: release, + staging: staging, + onProgress: (got, _) => firstProgress ??= got, + ); + + expect(server.log, ["GET /blob", "GET /blob bytes=$had-"]); + expect(file.readAsBytesSync(), data); + // progress carried on from where it was, not from nought + expect(firstProgress, had); + }); + + test("retries by itself, resuming each time", () async { + final release = server.release(); + server.cutsLeft = 2; + server.cutAfter = 30 * 1024; + + final file = await make(retries: 3).fetch(release: release, staging: staging); + + expect(file.readAsBytesSync(), data); + expect(server.log.length, 3); + expect(server.log[0], "GET /blob"); + expect(server.log[1], startsWith("GET /blob bytes=")); + expect(server.log[2], startsWith("GET /blob bytes=")); + }); + + test("a 200 that ignored the range starts the file again", () async { + final release = server.release(); + server.cutsLeft = 1; + server.cutAfter = 50 * 1024; + await expectLater(make().fetch(release: release, staging: staging), throwsA(isA())); + + server.ignoreRange = true; + final file = await make().fetch(release: release, staging: staging); + + expect(server.log.last, startsWith("GET /blob bytes=")); + // not the old half with the whole file stuck on the end + expect(file.lengthSync(), data.length); + expect(file.readAsBytesSync(), data); + }); + + test("a hosted download follows the 302, and asks the original url again on resume", () async { + final release = server.release(path: "/hosted"); + server.cutsLeft = 1; + server.cutAfter = 40 * 1024; + + await expectLater(make().fetch(release: release, staging: staging), throwsA(isA())); + final had = Downloader.partFile(staging).lengthSync(); + + // the first presigned url is dead by now. going straight back to it would 403 + final file = await make().fetch(release: release, staging: staging); + + expect(server.log, [ + "GET /hosted", + "GET /blob", + "GET /hosted bytes=$had-", + "GET /blob bytes=$had-", + ]); + expect(file.readAsBytesSync(), data); + }); + + test("a checksum mismatch deletes the download and fails", () async { + final release = server.release(sha256: "0" * 64); + + await expectLater( + make(retries: 3).fetch(release: release, staging: staging), + throwsA(isA().having((e) => e.code, "code", "checksum_mismatch")), + ); + + expect(Downloader.partFile(staging).existsSync(), isFalse); + expect(Downloader.metaFile(staging).existsSync(), isFalse); + expect(Downloader.finishedFile(staging, release).existsSync(), isFalse); + // and it wasnt retried, the same bytes would come back + expect(server.log.length, 1); + }); + + test("a stale part for another build is thrown away", () async { + staging.createSync(recursive: true); + Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99)); + Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 12, "sha256": "f" * 64})); + + final file = await make().fetch(release: server.release(), staging: staging); + + // no Range, it didnt try to carry on from someone elses bytes + expect(server.log, ["GET /blob"]); + expect(file.readAsBytesSync(), data); + }); + + test("a part for the same build but another sha is stale too", () async { + staging.createSync(recursive: true); + Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99)); + Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 13, "sha256": "f" * 64})); + + await make().fetch(release: server.release(), staging: staging); + expect(server.log, ["GET /blob"]); + }); + + test("a part with no note beside it is stale", () async { + staging.createSync(recursive: true); + Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99)); + + final file = await make().fetch(release: server.release(), staging: staging); + expect(server.log, ["GET /blob"]); + expect(file.readAsBytesSync(), data); + }); + + test("a part that is allready whole only gets verified", () async { + final release = server.release(); + staging.createSync(recursive: true); + Downloader.partFile(staging).writeAsBytesSync(data); + Downloader.metaFile(staging) + .writeAsStringSync(jsonEncode({"build": release.build, "sha256": release.asset.sha256})); + + final file = await make().fetch(release: release, staging: staging); + expect(server.log, isEmpty); + expect(file.readAsBytesSync(), data); + }); + + test("a finished download is reused, and other builds' are swept", () async { + final release = server.release(); + await make().fetch(release: release, staging: staging); + File("${staging.path}/update-9.zip").writeAsStringSync("old"); + server.log.clear(); + + await make().fetch(release: release, staging: staging); + expect(server.log, isEmpty); + + // asking for a newer one clears the old finished files out + server.data = server.data.sublist(0, 1000); + final next = server.release(build: 14); + await make().fetch(release: next, staging: staging); + expect(File("${staging.path}/update-9.zip").existsSync(), isFalse); + expect(Downloader.finishedFile(staging, release).existsSync(), isFalse); + expect(Downloader.finishedFile(staging, next).existsSync(), isTrue); + }); + + test("a 404 fails without retrying", () async { + await expectLater( + make(retries: 3).fetch(release: server.release(path: "/gone"), staging: staging), + throwsA(isA().having((e) => e.code, "code", "http_404")), + ); + expect(server.log.length, 1); + }); + + test("a release with no checksum is refused", () async { + await expectLater( + make().fetch(release: server.release(sha256: ""), staging: staging), + throwsA(isA().having((e) => e.code, "code", "no_checksum")), + ); + expect(server.log, isEmpty); + }); + + test("a line that goes quiet times out", () async { + // accepts the connection and then says nothing at all + final silent = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final held = []; + silent.listen(held.add); + + final release = UpdateRelease( + label: "v13", + build: 13, + asset: UpdateAsset( + url: "http://127.0.0.1:${silent.port}/blob", + filename: "app.zip", + format: "zip", + size: data.length, + sha256: server.sha, + ), + ); + + final d = Downloader( + httpClient: HttpClient(), + retries: 0, + quietTimeout: const Duration(milliseconds: 300), + ); + await expectLater( + d.fetch(release: release, staging: staging), + throwsA(isA().having((e) => e.code, "code", "download")), + ); + + d.close(); + for (final s in held) { + s.destroy(); + } + await silent.close(); + }); +} diff --git a/garage_updates/test/engine_test.dart b/garage_updates/test/engine_test.dart new file mode 100644 index 0000000..282510a --- /dev/null +++ b/garage_updates/test/engine_test.dart @@ -0,0 +1,180 @@ +import "dart:convert"; +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_install.dart"; +import "support/fake_server.dart"; + +// the engine end to end against the pretend windows install: a real check, a +// real download off the fake server, the fake stub doing the installing + +void main() { + late FakeServer server; + late FakeWindowsInstall fake; + late UpdateEngine engine; + final exits = []; + + Map answer(String status, {int build = 13, int? minimum}) => { + "status": status, + "minimum_build": minimum, + "latest": server.release(build: build).toJson(), + }; + + setUp(() async { + exits.clear(); + server = await FakeServer.start(noise(64 * 1024)); + fake = FakeWindowsInstall.create(); + + final found = WindowsInstaller.locate(fake.exe.path, environment: const {}); + engine = UpdateEngine( + project: "proj_1", + build: 12, + installer: found.installer, + client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()), + downloader: Downloader(httpClient: HttpClient(), retries: 0), + arch: "x64", + exitProcess: exits.add, + ); + }); + + tearDown(() async { + engine.close(); + await server.close(); + fake.dispose(); + }); + + test("check, download, install, restart", () async { + server.updateBody = answer("available"); + final order = []; + engine.onBeforeRestart = () async { + // the stub has allready been run by the time the app is asked to tidy up + order.add("before restart, stub runs so far: ${fake.runs.length}"); + }; + + final info = await engine.check(); + expect(info.status, UpdateStatus.available); + expect(server.log.single, "GET /v1/updates/proj_1"); + + final latest = info.latest!; + expect(await engine.isDownloaded(latest), isFalse); + await engine.download(latest); + expect(await engine.isDownloaded(latest), isTrue); + + final zip = "${fake.root.path}/staging/update-13.zip"; + expect(File(zip).existsSync(), isTrue); + + await engine.install(latest); + expect(exits, isEmpty, reason: "installing must not restart by itself"); + + await engine.restart(args: ["--route=/x"]); + expect(exits, [0]); + expect(order, ["before restart, stub runs so far: 1"]); + + for (var i = 0; i < 100 && fake.runs.length < 2; i++) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(fake.runs, [ + ["--garage-apply", zip, "13"], + ["--route=/x"], + ]); + // the stub was handed the bytes the server sent + expect(File("${fake.root.path}/app-13/unpacked-from.zip").readAsBytesSync(), server.data); + }); + + test("an onBeforeRestart that throws doesnt stop the restart", () async { + engine.onBeforeRestart = () => throw StateError("the agent wouldnt stop"); + await engine.restart(); + expect(exits, [0]); + }); + + test("a build that failed to start here is never offered again", () async { + // 11 is in the fake installs blocked list + server.updateBody = answer("available", build: 11); + engine = UpdateEngine( + project: "proj_1", + build: 9, + installer: engine.installer, + client: engine.client, + downloader: engine.downloader, + arch: "x64", + exitProcess: exits.add, + ); + + final lines = await printsOf(() async { + final first = await engine.check(); + expect(first.status, UpdateStatus.current); + expect(first.latest, isNull); + expect(first.hasUpdate, isFalse); + await engine.check(); + }); + // said once, not every six hours for ever + expect(lines.where((l) => l.contains("failed to start on this machine")).length, 1); + }); + + test("a build that failed for this user on a read only install isnt offered to them again", () async { + // the stub went back to 12 for them. root still says 13 and blocks nothing + Directory("${fake.root.path}/app-13").createSync(); + fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [] }'); + for (var i = 0; i < 4; i++) { + fake.plainLaunch(readOnly: true); + } + + server.updateBody = answer("available", build: 13); + engine = UpdateEngine( + project: "proj_1", + build: 12, + installer: fake.installer(readOnly: true), + client: engine.client, + downloader: engine.downloader, + arch: "x64", + exitProcess: exits.add, + ); + + final info = await engine.check(); + expect(info.status, UpdateStatus.current); + expect(info.hasUpdate, isFalse); + + // the one after it is + server.updateBody = answer("available", build: 14); + expect((await engine.check()).latest!.build, 14); + }); + + test("a blocked build that is also required stays required, with nothing to install", () async { + server.updateBody = answer("required", build: 11, minimum: 11); + engine = UpdateEngine( + project: "proj_1", + build: 9, + installer: engine.installer, + client: engine.client, + downloader: engine.downloader, + arch: "x64", + ); + + final info = await engine.check(); + expect(info.status, UpdateStatus.required); + expect(info.latest, isNull); + }); + + test("an answer offering our own build, or an older one, is current", () async { + server.updateBody = answer("available", build: 12); + expect((await engine.check()).status, UpdateStatus.current); + + server.updateBody = answer("available", build: 5); + expect((await engine.check()).hasUpdate, isFalse); + }); + + test("install before download says so", () async { + await expectLater( + engine.install(server.release()), + throwsA(isA().having((e) => e.code, "code", "not_downloaded")), + ); + expect(fake.runs, isEmpty); + }); + + test("markHealthy reaches the state file", () async { + await engine.markHealthy(); + expect((jsonDecode(fake.stateFile.readAsStringSync()) as Map)["failed_starts"], 0); + }); +} diff --git a/garage_updates/test/mac_installer_test.dart b/garage_updates/test/mac_installer_test.dart new file mode 100644 index 0000000..d5a9082 --- /dev/null +++ b/garage_updates/test/mac_installer_test.dart @@ -0,0 +1,296 @@ +@TestOn("mac-os") +library; + +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_install.dart"; + +UpdateRelease _release(int build, {String format = "zip"}) => UpdateRelease( + label: "v$build", + build: build, + asset: UpdateAsset(url: "http://x/app.$format", filename: "app.$format", format: format, size: 3, sha256: "aa"), + ); + +void main() { + late Directory tmp; + late Directory apps; + late Directory bundle; + late MacInstaller mac; + + setUp(() { + // resolved, /var is a symlink to /private/var and the paths get compared + tmp = Directory(Directory.systemTemp.createTempSync("gu_mac_").resolveSymbolicLinksSync()); + apps = Directory("${tmp.path}/Applications")..createSync(); + bundle = makeApp(apps, marker: "build 12"); + mac = MacInstaller( + bundle: bundle, + bundleId: "net.imbenji.foo", + support: Directory("${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates"), + ); + }); + + tearDown(() { + Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]); + tmp.deleteSync(recursive: true); + }); + + // a zip of build [build], sitting in staging the way the downloader leaves it + File stagedZip(int build, {String id = "net.imbenji.foo", String name = "Foo.app"}) { + final src = Directory("${tmp.path}/src-$build")..createSync(); + final app = makeApp(src, marker: "build $build", id: id, name: name); + mac.staging.createSync(recursive: true); + return zipApp(app, File("${mac.staging.path}/update-$build.zip")); + } + + group("finding the install", () { + test("an exe inside a bundle finds it, its id and where the state goes", () { + final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path}); + expect(found.reason, isNull); + + final m = found.installer as MacInstaller; + expect(m.bundle.path, bundle.path); + expect(m.bundleId, "net.imbenji.foo"); + expect(m.support.path, "${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates"); + expect(m.state.file.path, endsWith("garage_updates/state.json")); + expect(m.previousApp.path, endsWith("garage_updates/previous.app")); + }); + + test("a helper nested in the bundle belongs to the outer app", () { + final helper = "${bundle.path}/Contents/Library/LoginItems/Helper.app/Contents/MacOS/Helper"; + final found = MacInstaller.locate(helper, environment: {"HOME": tmp.path}); + expect((found.installer as MacInstaller).bundle.path, bundle.path); + }); + + test("a bare executable is not an install", () { + final found = MacInstaller.locate("${tmp.path}/bin/dart", environment: {"HOME": tmp.path}); + expect(found.installer, isNull); + expect(found.reason, contains("app bundle")); + }); + + test("a translocated bundle is not an install", () { + final found = MacInstaller.locate( + "/private/var/folders/xx/T/AppTranslocation/ABCD-1234/d/Foo.app/Contents/MacOS/Foo", + environment: {"HOME": tmp.path}, + ); + expect(found.installer, isNull); + expect(found.reason, contains("translocated")); + }); + + test("a build folder is not an install", () { + final found = MacInstaller.locate( + "${tmp.path}/proj/build/macos/Build/Products/Release/Foo.app/Contents/MacOS/Foo", + environment: {"HOME": tmp.path}, + ); + expect(found.installer, isNull); + expect(found.reason, contains("build folder")); + }); + + test("a bundle in a folder we cant write to is not an install", () { + Process.runSync("/bin/chmod", ["555", apps.path]); + final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path}); + expect(found.installer, isNull); + expect(found.reason, contains("can't be replaced")); + }); + + test("reads the bundle id out of a binary plist too", () { + final plist = "${bundle.path}/Contents/Info.plist"; + final res = Process.runSync("/usr/bin/plutil", ["-convert", "binary1", plist]); + expect(res.exitCode, 0, reason: "${res.stderr}"); + expect(readBundleId(bundle), "net.imbenji.foo"); + }); + }); + + group("the swap", () { + test("unpacks with ditto, keeps the old bundle as previous.app, puts the new one in place", () async { + final zip = stagedZip(13); + await mac.noteStart(12); + + await mac.apply(zip, _release(13), runningBuild: 12); + + expect(markerOf(bundle), "build 13"); + expect(markerOf(mac.previousApp), "build 12"); + // still a bundle someone could run + expect(File("${bundle.path}/Contents/MacOS/Foo").existsSync(), isTrue); + expect(readBundleId(bundle), "net.imbenji.foo"); + + final s = mac.state.read()!; + expect(s.current, 13); + expect(s.previous, 12); + expect(s.failedStarts, 0); + + expect(zip.existsSync(), isFalse); + expect(Directory("${mac.support.path}/unpack").existsSync(), isFalse); + // and nothing else turned up beside the app + expect(apps.listSync().map((e) => e.uri.pathSegments.where((s) => s.isNotEmpty).last), ["Foo.app"]); + }); + + test("a second update replaces previous.app", () async { + await mac.apply(stagedZip(13), _release(13), runningBuild: 12); + await mac.apply(stagedZip(14), _release(14), runningBuild: 13); + + expect(markerOf(bundle), "build 14"); + expect(markerOf(mac.previousApp), "build 13"); + expect(mac.state.read()!.previous, 13); + }); + + test("an update for some other app is refused and nothing moves", () async { + final zip = stagedZip(13, id: "com.someone.else"); + + await expectLater( + mac.apply(zip, _release(13), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "wrong_app")), + ); + expect(markerOf(bundle), "build 12"); + expect(mac.previousApp.existsSync(), isFalse); + }); + + test("a zip with no app in it is refused and nothing moves", () async { + final junk = Directory("${tmp.path}/junk")..createSync(); + File("${junk.path}/readme.txt").writeAsStringSync("hello"); + mac.staging.createSync(recursive: true); + final zip = File("${mac.staging.path}/update-13.zip"); + Process.runSync("/usr/bin/ditto", ["-c", "-k", junk.path, zip.path]); + + await expectLater( + mac.apply(zip, _release(13), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "no_app")), + ); + expect(markerOf(bundle), "build 12"); + }); + + test("a file that isnt a zip at all fails cleanly", () async { + mac.staging.createSync(recursive: true); + final zip = File("${mac.staging.path}/update-13.zip")..writeAsStringSync("not a zip"); + + await expectLater( + mac.apply(zip, _release(13), runningBuild: 12), + throwsA(isA()), + ); + expect(markerOf(bundle), "build 12"); + }); + + test("the app inside can be one folder down, and named differently", () async { + final src = Directory("${tmp.path}/src/Foo 13")..createSync(recursive: true); + makeApp(src, marker: "build 13", name: "Foo Renamed.app"); + mac.staging.createSync(recursive: true); + final zip = File("${mac.staging.path}/update-13.zip"); + Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", src.path, zip.path]); + + await mac.apply(zip, _release(13), runningBuild: 12); + + // it goes where the running bundle was, under the running bundles name + expect(markerOf(bundle), "build 13"); + }); + + test("a dmg is mounted, copied out of and detached", () async { + final src = Directory("${tmp.path}/dmgsrc")..createSync(); + makeApp(src, marker: "build 13"); + mac.staging.createSync(recursive: true); + final dmg = File("${mac.staging.path}/update-13.dmg"); + final made = Process.runSync( + "/usr/bin/hdiutil", + ["create", "-srcfolder", src.path, "-volname", "Foo", "-format", "UDZO", "-ov", dmg.path], + ); + expect(made.exitCode, 0, reason: "${made.stderr}"); + + await mac.apply(dmg, _release(13, format: "dmg"), runningBuild: 12); + + expect(markerOf(bundle), "build 13"); + expect(markerOf(mac.previousApp), "build 12"); + expect(Directory("${mac.support.path}/mount").existsSync(), isFalse); + }); + }); + + group("the fallback", () { + test("three starts with no markHealthy and the fourth goes back", () async { + await mac.noteStart(12); + await mac.markHealthy(); + await mac.apply(stagedZip(13), _release(13), runningBuild: 12); + + expect(await mac.noteStart(13), isFalse); + expect(await mac.noteStart(13), isFalse); + expect(await mac.noteStart(13), isFalse); + expect(mac.state.read()!.failedStarts, 3); + expect(markerOf(bundle), "build 13"); + + expect(await mac.noteStart(13), isTrue); + + expect(markerOf(bundle), "build 12"); + expect(mac.previousApp.existsSync(), isFalse); + expect(Directory("${mac.support.path}/failed.app").existsSync(), isFalse); + + final s = mac.state.read()!; + expect(s.current, 12); + expect(s.previous, isNull); + expect(s.failedStarts, 0); + expect(s.blocked, [13]); + expect(mac.blockedBuilds(), [13]); + }); + + test("markHealthy stops the count", () async { + await mac.apply(stagedZip(13), _release(13), runningBuild: 12); + + for (var i = 0; i < 6; i++) { + expect(await mac.noteStart(13), isFalse); + await mac.markHealthy(); + } + expect(markerOf(bundle), "build 13"); + expect(mac.state.read()!.failedStarts, 0); + expect(mac.state.read()!.blocked, isEmpty); + }); + + test("with no previous.app theres nowhere to go back to", () async { + for (var i = 0; i < 6; i++) { + expect(await mac.noteStart(12), isFalse); + } + expect(markerOf(bundle), "build 12"); + expect(mac.state.read()!.blocked, isEmpty); + }); + + test("a build put there by hand starts its count from nought", () async { + mac.state.write(UpdateState(current: 12, previous: 9, failedStarts: 3)); + + // 13 was dragged into Applications, the file knows nothing about it + expect(await mac.noteStart(13), isFalse); + + final s = mac.state.read()!; + expect(s.current, 13); + expect(s.failedStarts, 1); + // no previous.app on disk, so no previous + expect(s.previous, isNull); + }); + + test("a damaged state file is started again rather than trusted", () async { + mac.support.createSync(recursive: true); + mac.state.file.writeAsStringSync('{ "current": 1'); + + expect(await mac.noteStart(12), isFalse); + expect(mac.state.read()!.current, 12); + expect(mac.state.read()!.failedStarts, 1); + }); + }); + + test("relaunch is open -n on the bundle, arguments after --args", () async { + final calls = >[]; + final m = MacInstaller( + bundle: bundle, + bundleId: "net.imbenji.foo", + support: mac.support, + run: (exe, args) async { + calls.add([exe, ...args]); + return ProcessResult(1, 0, "", ""); + }, + ); + + await m.relaunch(const []); + await m.relaunch(["--route=/settings"]); + + expect(calls, [ + ["/usr/bin/open", "-n", bundle.path], + ["/usr/bin/open", "-n", bundle.path, "--args", "--route=/settings"], + ]); + }); +} diff --git a/garage_updates/test/not_installed_test.dart b/garage_updates/test/not_installed_test.dart new file mode 100644 index 0000000..d5fdcde --- /dev/null +++ b/garage_updates/test/not_installed_test.dart @@ -0,0 +1,145 @@ +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_install.dart"; +import "support/fake_server.dart"; + +// the rule: a copy the updater didnt put there is left completly alone. no +// check, no download, nothing swapped, one line on the console. + +void main() { + group("detecting", () { + test("this very test run is not an install", () { + // flutter_tester off the jit, exactly the dev case + final found = detectInstall(); + expect(found.installer, isNull); + expect(found.reason, isNotNull); + }); + + test("a debug build is never an install, wherever it sits", () { + final fake = FakeWindowsInstall.create(); + addTearDown(fake.dispose); + + final found = detectInstall(executable: fake.exe.path, platform: "windows", product: false); + expect(found.installer, isNull); + expect(found.reason, contains("release build")); + + // the same place as a release build is one + expect(detectInstall(executable: fake.exe.path, platform: "windows", product: true).installer, isNotNull); + }); + + test("flutter run on windows", () { + final found = detectInstall( + executable: r"C:\src\app\build\windows\x64\runner\Debug\app.exe", + platform: "windows", + product: true, + ); + expect(found.installer, isNull); + expect(found.reason, contains("app-")); + }); + + test("a release exe run out of the build folder on windows", () { + final tmp = Directory.systemTemp.createTempSync("gu_dev_"); + addTearDown(() => tmp.deleteSync(recursive: true)); + final release = Directory("${tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true); + + final found = detectInstall(executable: "${release.path}/app.exe", platform: "windows", product: true); + expect(found.installer, isNull); + }); + + test("dart run / a bare binary on the mac", () { + final found = detectInstall( + executable: "/opt/homebrew/Cellar/dart/3.8.1/libexec/bin/dart", + platform: "macos", + product: true, + environment: const {"HOME": "/Users/someone"}, + ); + expect(found.installer, isNull); + expect(found.reason, contains("app bundle")); + }); + + test("flutter run on the mac", () { + final found = detectInstall( + executable: "/Users/someone/app/build/macos/Build/Products/Debug/App.app/Contents/MacOS/App", + platform: "macos", + product: true, + environment: const {"HOME": "/Users/someone"}, + ); + expect(found.installer, isNull); + expect(found.reason, contains("build folder")); + }); + + test("a platform core has no installer for", () { + final found = detectInstall(executable: "/usr/bin/app", platform: "linux", product: true); + expect(found.installer, isNull); + expect(found.reason, contains("linux")); + }); + }); + + group("an engine with no install", () { + late FakeServer server; + late UpdateEngine engine; + final exits = []; + + setUp(() async { + exits.clear(); + server = await FakeServer.start(noise(1024)); + server.updateBody = {"status": "required", "minimum_build": 99, "latest": server.release().toJson()}; + engine = UpdateEngine( + project: "proj_1", + build: 12, + notInstalledReason: "this isn't a release build", + client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()), + downloader: Downloader(httpClient: HttpClient(), retries: 0), + arch: "arm64", + exitProcess: exits.add, + ); + }); + + tearDown(() async { + engine.close(); + await server.close(); + }); + + test("says why once, and never asks the server", () async { + expect(engine.installed, isFalse); + expect(engine.notInstalledReason, "this isn't a release build"); + + final lines = await printsOf(() async { + expect((await engine.check()).status, UpdateStatus.unknown); + expect((await engine.check()).hasUpdate, isFalse); + expect(engine.reportIfNotInstalled(), isFalse); + }); + + expect(lines, ["[garage_updates] not updating this copy: this isn't a release build"]); + expect(server.log, isEmpty); + }); + + test("wont download, install or restart", () async { + final release = server.release(); + final notInstalled = throwsA(isA().having((e) => e.code, "code", "not_installed")); + + await expectLater(engine.download(release), notInstalled); + await expectLater(engine.install(release), notInstalled); + await expectLater(engine.restart(), notInstalled); + + expect(server.log, isEmpty); + expect(exits, isEmpty); + }); + + test("counting starts and markHealthy are quiet no-ops", () async { + expect(await engine.noteStart(), isFalse); + await engine.markHealthy(); + expect(await engine.isDownloaded(server.release()), isFalse); + }); + + test("detect() off a test run gives exactly this engine", () { + final e = UpdateEngine.detect(project: "proj_1", build: 12); + addTearDown(e.close); + expect(e.installed, isFalse); + expect(e.installer, isNull); + }); + }); +} diff --git a/garage_updates/test/splash_test.dart b/garage_updates/test/splash_test.dart new file mode 100644 index 0000000..dcd7755 --- /dev/null +++ b/garage_updates/test/splash_test.dart @@ -0,0 +1,117 @@ +import "package:flutter/widgets.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:garage_ui/garage_ui.dart"; +import "package:garage_updates/garage_updates.dart"; + +void main() { + const branding = UpdaterBranding( + name: "Garage Stash", + logo: SizedBox(key: Key("logo")), + ); + + Future pumpSplash(WidgetTester t, {UpdaterBranding b = branding, VoidCallback? onGone}) async { + final c = SplashController(); + await t.pumpWidget(UpdateSplashApp(branding: b, controller: c, onGone: onGone)); + return c; + } + + double? bar(WidgetTester t) => t.widget(find.byType(LinearProgressIndicator)).value; + + testWidgets("the logo, the name, one status line and a bar", (t) async { + await pumpSplash(t); + + expect(find.byKey(const Key("logo")), findsOneWidget); + expect(find.text("Garage Stash"), findsOneWidget); + expect(find.text("Checking for updates"), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + // nothing known yet, so the bar just sweeps + expect(bar(t), isNull); + + expect(find.text("Retry"), findsNothing); + expect(find.byType(Button), findsNothing); + }); + + testWidgets("each stage has its line", (t) async { + final c = await pumpSplash(t); + + c.show(SplashStage.downloading, progress: 0); + await t.pump(); + expect(find.text("Downloading update"), findsOneWidget); + expect(find.text("Checking for updates"), findsNothing); + expect(bar(t), 0); + + c.progress = 0.4; + await t.pump(); + expect(bar(t), 0.4); + + c.show(SplashStage.installing); + await t.pump(); + expect(find.text("Installing"), findsOneWidget); + expect(bar(t), isNull); + + c.show(SplashStage.starting); + await t.pump(); + expect(find.text("Starting"), findsOneWidget); + expect(find.text("Installing"), findsNothing); + }); + + testWidgets("a failure shows why and a Retry, and Retry clears it", (t) async { + final c = await pumpSplash(t); + c.show(SplashStage.downloading, progress: 0.3); + + var retried = false; + c.fail("The download didn't match its checksum").then((_) => retried = true); + await t.pump(); + + expect(find.text("The download didn't match its checksum"), findsOneWidget); + expect(find.text("Retry"), findsOneWidget); + // the stage it failed at is still what the status line says + expect(find.text("Downloading update"), findsOneWidget); + expect(bar(t), 0.3); + expect(retried, isFalse); + + await t.tap(find.text("Retry")); + await t.pump(); + + expect(retried, isTrue); + expect(find.text("Retry"), findsNothing); + expect(find.text("The download didn't match its checksum"), findsNothing); + }); + + testWidgets("a failure with nothing measured stops the bar sweeping", (t) async { + final c = await pumpSplash(t); + c.show(SplashStage.installing); + c.fail("The update could not be installed."); + await t.pump(); + + expect(bar(t), 0); + }); + + testWidgets("no logo is fine", (t) async { + await pumpSplash(t, b: const UpdaterBranding(name: "Plain")); + expect(find.text("Plain"), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + }); + + testWidgets("its drawn with the garage theme, carbon unless the developer says otherwise", (t) async { + await pumpSplash(t); + var theme = GarageTheme.of(t.element(find.byType(UpdateSplash))); + expect(theme.colorScheme, GarageSchemes.carbon); + + final light = ThemeData(colorScheme: GarageSchemes.light); + await t.pumpWidget(const SizedBox()); + await pumpSplash(t, b: UpdaterBranding(name: "Light", theme: light)); + theme = GarageTheme.of(t.element(find.byType(UpdateSplash))); + expect(theme.colorScheme, GarageSchemes.light); + }); + + testWidgets("the host app taking over is noticed", (t) async { + var gone = 0; + await pumpSplash(t, onGone: () => gone++); + expect(gone, 0); + + // what the apps own runApp does to us + await t.pumpWidget(const SizedBox()); + expect(gone, 1); + }); +} diff --git a/garage_updates/test/state_test.dart b/garage_updates/test/state_test.dart new file mode 100644 index 0000000..49a9db3 --- /dev/null +++ b/garage_updates/test/state_test.dart @@ -0,0 +1,159 @@ +import "dart:convert"; +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +void main() { + late Directory dir; + late StateFile state; + + setUp(() { + dir = Directory.systemTemp.createTempSync("gu_state_"); + state = StateFile(File("${dir.path}/garage_updates.json")); + }); + + tearDown(() => dir.deleteSync(recursive: true)); + + test("a missing file reads as null", () { + expect(state.read(), isNull); + }); + + test("reads what the stub writes", () { + state.file.writeAsStringSync( + '{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 2, "blocked": [11] }', + ); + final s = state.read()!; + + expect(s.exe, "garage_stash.exe"); + expect(s.current, 12); + expect(s.previous, 9); + expect(s.failedStarts, 2); + expect(s.blocked, [11]); + }); + + test("a half written file reads as null rather than throwing", () { + state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr'); + expect(state.read(), isNull); + + state.file.writeAsStringSync(""); + expect(state.read(), isNull); + + state.file.writeAsStringSync("[1, 2]"); + expect(state.read(), isNull); + }); + + test("missing and mistyped fields get sane defaults", () { + state.file.writeAsStringSync('{ "current": "12", "blocked": [11, "x", 11, 10.0], "failed_starts": null }'); + final s = state.read()!; + + expect(s.exe, isNull); + expect(s.current, 12); + expect(s.previous, isNull); + expect(s.failedStarts, 0); + expect(s.blocked, [11, 10]); + }); + + test("writing keeps the keys we dont know about", () { + state.file.writeAsStringSync('{ "exe": "a.exe", "current": 12, "app_id": "net.imbenji.stash", "later": {"x": 1} }'); + + expect(state.update((s) => s.failedStarts = 0), isTrue); + + final j = jsonDecode(state.file.readAsStringSync()) as Map; + expect(j["app_id"], "net.imbenji.stash"); + expect(j["later"], {"x": 1}); + expect(j["exe"], "a.exe"); + expect(j["current"], 12); + expect(j["previous"], isNull); + expect(j["failed_starts"], 0); + expect(j["blocked"], isEmpty); + }); + + test("the write is a replace, no temp file is left", () { + state.write(UpdateState(exe: "a.exe", current: 1)); + state.write(UpdateState(exe: "a.exe", current: 2, previous: 1, blocked: [3])); + + expect(dir.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]); + final s = state.read()!; + expect(s.current, 2); + expect(s.previous, 1); + expect(s.blocked, [3]); + }); + + test("update wont write over a file it couldnt read", () { + state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr'); + expect(state.update((s) => s.failedStarts = 0), isFalse); + expect(state.file.readAsStringSync(), '{ "exe": "garage_stash.exe", "curr'); + }); + + test("update can start a file that isnt there", () { + state = StateFile(File("${dir.path}/deeper/still/state.json")); + expect(state.update((s) => s.current = 5, createIfMissing: true), isTrue); + expect(state.read()!.current, 5); + }); + + group("the users file", () { + late UserStateFile mine; + + setUp(() => mine = UserStateFile(File("${dir.path}/local/garage_updates.json"))); + + test("reads what the stub writes", () { + mine.file.parent.createSync(); + mine.file.writeAsStringSync('{\n "failed_starts": 2,\n "blocked": [13, 13],\n "for_current": 14,\n "run_instead": null\n}\n'); + final u = mine.read()!; + + expect(u.failedStarts, 2); + expect(u.blocked, [13]); + expect(u.forCurrent, 14); + expect(u.runInstead, isNull); + }); + + test("missing, empty and half written all read as null", () { + expect(mine.read(), isNull); + + mine.file.parent.createSync(); + mine.file.writeAsStringSync(""); + expect(mine.read(), isNull); + + mine.file.writeAsStringSync('{ "failed_starts": 2, "bl'); + expect(mine.read(), isNull); + // and isnt written over + expect(mine.update((u) => u.failedStarts = 0), isFalse); + expect(mine.file.readAsStringSync(), '{ "failed_starts": 2, "bl'); + }); + + test("update doesnt start a file unless its told to", () { + expect(mine.update((u) => u.failedStarts = 0), isFalse); + expect(mine.file.existsSync(), isFalse); + + expect(mine.update((u) => u.failedStarts = 1, createIfMissing: true), isTrue); + expect(mine.file.parent.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]); + expect(jsonDecode(mine.file.readAsStringSync()), { + "failed_starts": 1, + "blocked": [], + "for_current": null, + "run_instead": null, + }); + }); + + test("the count is only good for the current it was made against", () { + final u = UserState(failedStarts: 2, blocked: [13], forCurrent: 13, runInstead: 12); + + u.settleFor(13); + expect(u.failedStarts, 2); + expect(u.runInstead, 12); + + u.settleFor(14); + expect(u.failedStarts, 0); + expect(u.runInstead, isNull); + expect(u.forCurrent, 14); + expect(u.blocked, [13]); + }); + }); + + test("a write that cant happen says false", () { + // a folder where the file should be + Directory(state.file.path).createSync(); + expect(state.write(UpdateState(current: 1)), isFalse); + }); +} diff --git a/garage_updates/test/support/fake_install.dart b/garage_updates/test/support/fake_install.dart new file mode 100644 index 0000000..78bd901 --- /dev/null +++ b/garage_updates/test/support/fake_install.dart @@ -0,0 +1,164 @@ +import "dart:io"; + +import "package:garage_updates/core.dart"; + +// A pretend windows install in a temp folder. The "stub" is a shell script +// with the stubs name: it writes down the arguments it was given, and for +// --garage-apply does the bookkeeping the real one would. + +const _stubScript = r'''#!/bin/sh +dir="$(cd "$(dirname "$0")" && pwd)" +printf '%s\n' "$@" >> "$dir/stub-args.txt" +echo "--" >> "$dir/stub-args.txt" + +if [ "$1" = "--garage-apply" ]; then + if [ -f "$dir/stub-exit" ]; then + exit "$(cat "$dir/stub-exit")" + fi + if [ ! -f "$dir/stub-lazy" ]; then + mkdir -p "$dir/app-$3" + cp "$2" "$dir/app-$3/unpacked-from.zip" + printf '{ "exe": "garage_stash.exe", "current": %s, "previous": 12, "failed_starts": 0, "blocked": [] }' "$3" > "$dir/garage_updates.json" + fi +fi +exit 0 +'''; + +class FakeWindowsInstall { + FakeWindowsInstall._(this.tmp); + + final Directory tmp; + + Directory get root => Directory("${tmp.path}/Garage Stash"); + Directory get versionFolder => Directory("${root.path}/app-12"); + File get stub => File("${root.path}/garage_stash.exe"); + File get exe => File("${versionFolder.path}/garage_stash.exe"); + File get stateFile => File("${root.path}/garage_updates.json"); + File get argsFile => File("${root.path}/stub-args.txt"); + + static FakeWindowsInstall create({String? state}) { + final f = FakeWindowsInstall._(Directory.systemTemp.createTempSync("gu_win_")); + f.versionFolder.createSync(recursive: true); + f.exe.writeAsStringSync("the real app, build 12"); + File("${f.versionFolder.path}/stash-agent.exe").writeAsStringSync("the agent"); + + f.stub.writeAsStringSync(_stubScript); + Process.runSync("/bin/chmod", ["+x", f.stub.path]); + + f.stateFile.writeAsStringSync( + state ?? '{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 1, "blocked": [11] }', + ); + return f; + } + + /// what LOCALAPPDATA is for an installer made by [installer] + Directory get local => Directory("${tmp.path}/Local"); + File get userStateFile => File("${local.path}/Garage Stash/garage_updates.json"); + + /// `readOnly` is an install in Program Files. Nothing is chmodded, the + /// installer is just told it cant write, and [plainLaunch] behaves the same + WindowsInstaller installer({bool readOnly = false}) => WindowsInstaller( + root: root, + stub: stub, + runningFolderBuild: 12, + environment: {"LOCALAPPDATA": local.path}, + rootWritable: () => !readOnly, + ); + + /// The stub being started with no flags, as far as the counting goes: the + /// same sums garage_stub.cpp does, in root when it can write there and in + /// the users own file when it cant. Returns the build it would start. + int plainLaunch({bool readOnly = false}) { + final state = StateFile(stateFile); + final s = state.read()!; + bool there(int? build) => build != null && Directory("${root.path}/app-$build").existsSync(); + + if (!readOnly) { + if (s.failedStarts >= 3 && there(s.previous)) { + if (!s.blocked.contains(s.current)) s.blocked.add(s.current!); + s.current = s.previous; + s.previous = null; + s.failedStarts = 0; + } + s.failedStarts++; + state.write(s); + return s.current!; + } + + final mine = UserStateFile(userStateFile); + final u = mine.read() ?? UserState(); + u.settleFor(s.current); + + if (u.runInstead != null) { + if (u.runInstead != s.current && there(u.runInstead)) return u.runInstead!; + u.runInstead = null; + u.failedStarts = 0; + } + + var run = s.current!; + if (u.failedStarts >= 3 && there(s.previous) && s.previous != s.current && !u.blocked.contains(s.previous)) { + if (!u.blocked.contains(s.current)) u.blocked.add(s.current!); + u.runInstead = s.previous; + u.failedStarts = 0; + run = s.previous!; + } + if (run == s.current) u.failedStarts++; + mine.write(u); + return run; + } + + + /// every run of the stub, as the list of arguments it got + List> get runs { + if (!argsFile.existsSync()) return []; + final out = >[]; + var cur = []; + for (final line in argsFile.readAsLinesSync()) { + if (line == "--") { + out.add(cur); + cur = []; + } else { + cur.add(line); + } + } + return out; + } + + void dispose() { + // a test may have made the root read only + Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]); + tmp.deleteSync(recursive: true); + } +} + +/// A pretend mac app. `Foo.app/Contents/{Info.plist, MacOS/Foo}` with a +/// marker file so a test can tell which build is sitting where. +Directory makeApp(Directory parent, {String name = "Foo.app", String id = "net.imbenji.foo", required String marker}) { + final app = Directory("${parent.path}/$name"); + Directory("${app.path}/Contents/MacOS").createSync(recursive: true); + Directory("${app.path}/Contents/Resources").createSync(recursive: true); + + File("${app.path}/Contents/Info.plist").writeAsStringSync(''' + + + + CFBundleExecutable + Foo + CFBundleIdentifier + $id + + +'''); + File("${app.path}/Contents/MacOS/Foo").writeAsStringSync("#!/bin/sh\necho $marker\n"); + File("${app.path}/Contents/Resources/marker.txt").writeAsStringSync(marker); + return app; +} + +String markerOf(Directory app) => File("${app.path}/Contents/Resources/marker.txt").readAsStringSync(); + +/// zips [app] the way a release would be, with the .app at the top +File zipApp(Directory app, File to) { + final res = Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, to.path]); + if (res.exitCode != 0) throw StateError("ditto couldnt zip ${app.path}: ${res.stderr}"); + return to; +} diff --git a/garage_updates/test/support/fake_server.dart b/garage_updates/test/support/fake_server.dart new file mode 100644 index 0000000..04ec10a --- /dev/null +++ b/garage_updates/test/support/fake_server.dart @@ -0,0 +1,154 @@ +import "dart:async"; +import "dart:convert"; +import "dart:io"; +import "dart:typed_data"; + +import "package:crypto/crypto.dart"; +import "package:garage_updates/core.dart"; + +/// A file server on loopback that can be told to misbehave. +class FakeServer { + FakeServer._(this._server, this.data); + + final HttpServer _server; + Uint8List data; + + /// "GET /blob bytes=100-" for every request, in order + final List log = []; + + /// send a plain 200 with the whole file whatever Range says + bool ignoreRange = false; + + /// how many of the next downloads to cut dead, and after how many bytes + int cutsLeft = 0; + int cutAfter = 0; + + /// the json `/v1/updates/` answers with, and the status it uses + Object? updateBody; + int updateStatus = 200; + + /// a /blob request without this sig gets a 403, like an expired presign + String? wantSig; + int _sig = 0; + + String get base => "http://127.0.0.1:${_server.port}"; + + static Future start(List data) async { + final s = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final fake = FakeServer._(s, Uint8List.fromList(data)); + s.listen(fake._handle); + return fake; + } + + Future close() => _server.close(force: true); + + String get sha => sha256.convert(data).toString(); + + UpdateRelease release({int build = 13, String path = "/blob", String format = "zip", String? sha256}) { + return UpdateRelease( + label: "v$build", + build: build, + notes: "notes for $build", + asset: UpdateAsset( + url: "$base$path", + filename: "app.$format", + format: format, + size: data.length, + sha256: sha256 ?? sha, + ), + ); + } + + Future _handle(HttpRequest req) async { + final range = req.headers.value(HttpHeaders.rangeHeader); + log.add("${req.method} ${req.uri.path}${range == null ? "" : " $range"}"); + + if (req.uri.path.startsWith("/v1/updates/")) { + req.response.statusCode = updateStatus; + req.response.headers.contentType = ContentType.json; + final body = updateBody; + req.response.write(body is String ? body : jsonEncode(body)); + await req.response.close(); + return; + } + + if (req.uri.path == "/hosted") { + // a fresh "presigned" url every time, the old ones stop working + wantSig = "s${++_sig}"; + req.response.statusCode = HttpStatus.found; + req.response.headers.set(HttpHeaders.locationHeader, "/blob?sig=$wantSig"); + await req.response.close(); + return; + } + + if (req.uri.path == "/gone") { + req.response.statusCode = HttpStatus.notFound; + await req.response.close(); + return; + } + + if (wantSig != null && req.uri.queryParameters["sig"] != wantSig) { + req.response.statusCode = HttpStatus.forbidden; + await req.response.close(); + return; + } + + var start = 0; + var status = "200 OK"; + final extra = []; + if (range != null && !ignoreRange) { + start = int.parse(RegExp(r"bytes=(\d+)-").firstMatch(range)!.group(1)!); + if (start >= data.length) { + req.response.statusCode = HttpStatus.requestedRangeNotSatisfiable; + await req.response.close(); + return; + } + status = "206 Partial Content"; + extra.add("Content-Range: bytes $start-${data.length - 1}/${data.length}"); + } + + final body = Uint8List.sublistView(data, start); + + // written by hand on the raw socket so it can be dropped mid body + final socket = await req.response.detachSocket(writeHeaders: false); + socket.write("HTTP/1.1 $status\r\n" + "Content-Length: ${body.length}\r\n" + "${extra.map((h) => "$h\r\n").join()}" + "Connection: close\r\n\r\n"); + + if (cutsLeft > 0) { + cutsLeft--; + socket.add(Uint8List.sublistView(body, 0, cutAfter.clamp(0, body.length))); + await socket.flush(); + socket.destroy(); + return; + } + + socket.add(body); + await socket.flush(); + await socket.close(); + } +} + +/// some bytes that arent all the same +List noise(int length, {int seed = 7}) { + var x = seed; + return List.generate(length, (_) { + x = (x * 1103515245 + 12345) & 0x7fffffff; + return x & 0xff; + }); +} + +/// runs [body] and hands back everything it printed +Future> printsOf(Future Function() body) async { + final lines = []; + await runZonedPrints(body, lines); + return lines; +} + +Future runZonedPrints(Future Function() body, List into) { + return runZoned( + body, + zoneSpecification: ZoneSpecification(print: (self, parent, zone, line) => into.add(line)), + ); +} diff --git a/garage_updates/test/updater_test.dart b/garage_updates/test/updater_test.dart new file mode 100644 index 0000000..b18ce9b --- /dev/null +++ b/garage_updates/test/updater_test.dart @@ -0,0 +1,415 @@ +import "dart:async"; + +import "package:flutter/foundation.dart"; +import "package:flutter/widgets.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:garage_ui/garage_ui.dart" show LinearProgressIndicator; +import "package:garage_updates/garage_updates.dart"; + +// GarageUpdater.launch against a driver that does whatever the test says + +class FakeDriver implements UpdateDriver { + FakeDriver({this.installed = true}); + + @override + bool installed; + + @override + String? get notInstalledReason => installed ? null : "this isn't a release build"; + + @override + FutureOr Function()? onBeforeRestart; + + final calls = []; + + /// what check() answers. a Completer to answer late, an error to throw + Object? answer; + + bool startsKeepFailing = false; + Object? downloadError; + Object? installError; + Completer? downloadGate; + + @override + Future noteStart() async { + calls.add("noteStart"); + return startsKeepFailing; + } + + @override + Future check() async { + calls.add("check"); + final a = answer; + if (a is Completer) return a.future; + if (a is UpdateInfo) return a; + throw a ?? StateError("no answer set"); + } + + @override + Future download(UpdateRelease release, {DownloadProgress? onProgress}) async { + calls.add("download ${release.build}"); + onProgress?.call(50, 100); + await downloadGate?.future; + final e = downloadError; + if (e != null) throw e; + onProgress?.call(100, 100); + } + + @override + Future install(UpdateRelease release) async { + calls.add("install ${release.build}"); + final e = installError; + if (e != null) throw e; + } + + @override + Future restart({List args = const []}) async { + await onBeforeRestart?.call(); + calls.add("restart ${args.join(" ")}".trim()); + } + + @override + Future markHealthy() async => calls.add("markHealthy"); +} + +const _release = UpdateRelease( + label: "v13", + build: 13, + notes: "Fixed the thing", + asset: UpdateAsset(url: "http://x/app.zip", filename: "app.zip", format: "zip", size: 100, sha256: "aa"), +); + +const _current = UpdateInfo(status: UpdateStatus.current); +const _available = UpdateInfo(status: UpdateStatus.available, latest: _release); +const _required = UpdateInfo(status: UpdateStatus.required, minimumBuild: 13, latest: _release); + +// the updater leaves a 6 hourly timer running, as it should. flutter_test +// counts timers the moment the body returns, before any tearDown, so the +// tidying has to happen in here +void updaterTest( + String name, + Future Function(WidgetTester t) body, { + TargetPlatform platform = TargetPlatform.macOS, +}) { + testWidgets(name, (t) async { + GarageUpdater.reset(); + // a flutter test says its android unless told otherwise + debugDefaultTargetPlatformOverride = platform; + try { + await body(t); + } finally { + // take the splash down first, that schedules the markHealthy timer + await t.pumpWidget(const SizedBox()); + await t.pump(); + GarageUpdater.reset(); + debugDefaultTargetPlatformOverride = null; + } + }); +} + +void main() { + + // starts the updater the way launch() does, with the splash going to the + // tester instead of runApp + ({Future done, bool Function() finished, Widget? Function() splash}) start( + FakeDriver driver, { + UpdateMode mode = UpdateMode.silent, + List args = const ["--route=/x"], + }) { + Widget? shown; + var finished = false; + final done = GarageUpdater.instance + .start( + args: args, + project: "proj_1", + build: 12, + label: "v12", + branding: const UpdaterBranding(name: "Garage Stash"), + mode: mode, + driver: driver, + show: (w) => shown = w, + ) + .then((_) => finished = true); + return (done: done, finished: () => finished, splash: () => shown); + } + + updaterTest("up to date: the splash shows, then the app carries on", (t) async { + final d = FakeDriver()..answer = _current; + final run = start(d); + await t.pump(); + + expect(run.splash(), isA()); + await t.pumpWidget(run.splash()!); + await t.pump(); + + expect(run.finished(), isTrue); + expect(find.text("Starting"), findsOneWidget); + expect(d.calls, ["noteStart", "check"]); + expect(GarageUpdater.instance.ready.value, isNull); + expect(GarageUpdater.instance.label, "v12"); + }); + + updaterTest("no answer in 2 seconds: the app starts, and the late answer is dealt with behind it", (t) async { + final late = Completer(); + final d = FakeDriver()..answer = late; + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + + await t.pump(const Duration(milliseconds: 1900)); + expect(run.finished(), isFalse); + expect(find.text("Checking for updates"), findsOneWidget); + + await t.pump(const Duration(milliseconds: 200)); + expect(run.finished(), isTrue); + expect(d.calls, ["noteStart", "check"]); + + final heard = []; + GarageUpdater.instance.readyStream.listen(heard.add); + + // the server finally answers, the app is long since up + late.complete(_available); + await t.pump(); + await t.pump(); + + expect(d.calls, ["noteStart", "check", "download 13"]); + expect(GarageUpdater.instance.ready.value, same(_available)); + expect(heard, [_available]); + expect(GarageUpdater.instance.notes, "Fixed the thing"); + // downloaded, not installed. thats the apps call now + expect(d.calls.where((c) => c.startsWith("install")), isEmpty); + }); + + updaterTest("a check that fails lets the app start", (t) async { + final d = FakeDriver()..answer = UpdateError("network", "Couldn't reach the update server"); + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + + expect(run.finished(), isTrue); + expect(find.text("Retry"), findsNothing); + }); + + updaterTest("silent + available: downloaded, installed and restarted behind the splash", (t) async { + final gate = Completer(); + final d = FakeDriver() + ..answer = _available + ..downloadGate = gate; + final stopped = []; + GarageUpdater.instance.onBeforeRestart = () => stopped.add("agent stopped"); + + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(find.text("Downloading update"), findsOneWidget); + expect(t.widget(find.byType(LinearProgressIndicator)).value, 0.5); + expect(run.finished(), isFalse); + + gate.complete(); + await t.pump(); + await t.pump(); + + expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]); + expect(stopped, ["agent stopped"]); + }); + + updaterTest("silent + available that fails: the old build starts anyway", (t) async { + final d = FakeDriver() + ..answer = _available + ..installError = UpdateError("install_failed", "The update could not be installed (3)"); + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(run.finished(), isTrue); + expect(find.text("Retry"), findsNothing); + expect(d.calls.where((c) => c.startsWith("restart")), isEmpty); + }); + + updaterTest("prompt + available: nothing is installed, ready fires, restartToUpdate applies it", (t) async { + final d = FakeDriver()..answer = _available; + final run = start(d, mode: UpdateMode.prompt); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(run.finished(), isTrue); + expect(d.calls, ["noteStart", "check", "download 13"]); + expect(GarageUpdater.instance.ready.value?.latest?.build, 13); + + await GarageUpdater.instance.restartToUpdate(); + expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]); + }); + + updaterTest("android never installs at launch unless it has to, its installer always asks", (t) async { + final d = FakeDriver()..answer = _available; + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(run.finished(), isTrue); + expect(d.calls, ["noteStart", "check", "download 13"]); + expect(GarageUpdater.instance.ready.value?.latest?.build, 13); + }, platform: TargetPlatform.android); + + updaterTest("required: the app is kept out, a failure offers Retry, and Retry goes again", (t) async { + final d = FakeDriver() + ..answer = _required + ..downloadError = UpdateError("checksum_mismatch", "The download didn't match its checksum"); + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(run.finished(), isFalse); + expect(find.text("The download didn't match its checksum"), findsOneWidget); + expect(find.text("Retry"), findsOneWidget); + + // still out, however long its left + await t.pump(const Duration(minutes: 10)); + expect(run.finished(), isFalse); + expect(d.calls.where((c) => c.startsWith("install")), isEmpty); + + d.downloadError = null; + await t.tap(find.text("Retry")); + await t.pump(); + await t.pump(); + await t.pump(); + + expect(d.calls, [ + "noteStart", + "check", + "download 13", + "check", + "download 13", + "install 13", + "restart --route=/x", + ]); + // a real restart ends the process. the fake comes back, which is androids + // case: the system installer is up and the app still must not start + expect(run.finished(), isFalse); + expect(find.text("Install the update to continue."), findsOneWidget); + }); + + updaterTest("required is required in prompt mode too", (t) async { + final d = FakeDriver()..answer = _required; + final run = start(d, mode: UpdateMode.prompt); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pump(); + + expect(d.calls, contains("install 13")); + expect(run.finished(), isFalse); + }); + + updaterTest("required with nothing installable says so and keeps the app out", (t) async { + final d = FakeDriver()..answer = const UpdateInfo(status: UpdateStatus.required, minimumBuild: 13); + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + + expect(run.finished(), isFalse); + expect(find.text("Retry"), findsOneWidget); + expect(d.calls.where((c) => c.startsWith("download")), isEmpty); + }); + + updaterTest("not installed in the layout: no splash, no check, nothing", (t) async { + final d = FakeDriver(installed: false); + final run = start(d); + await t.pump(); + + expect(run.finished(), isTrue); + expect(run.splash(), isNull); + expect(d.calls, isEmpty); + + // and the rest of the surface is safe to call + await GarageUpdater.instance.markHealthy(); + await GarageUpdater.instance.restartToUpdate(); + expect(await GarageUpdater.instance.checkNow(), isNull); + expect(d.calls, isEmpty); + expect(GarageUpdater.instance.ready.value, isNull); + expect(GarageUpdater.instance.notes, isNull); + }); + + updaterTest("a start that put the old build back restarts before anything else", (t) async { + final d = FakeDriver() + ..startsKeepFailing = true + ..answer = _current; + start(d); + await t.pump(); + + expect(d.calls.take(2), ["noteStart", "restart --route=/x"]); + }); + + updaterTest("markHealthy is called a few seconds after the host apps first frame", (t) async { + final d = FakeDriver()..answer = _current; + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + expect(run.finished(), isTrue); + + // sat on the splash, the app hasnt drawn anything of its own yet + await t.pump(const Duration(seconds: 10)); + expect(d.calls, isNot(contains("markHealthy"))); + + await t.pumpWidget(const SizedBox(key: Key("the host app"))); + await t.pump(const Duration(seconds: 2)); + expect(d.calls, isNot(contains("markHealthy"))); + + await t.pump(const Duration(seconds: 2)); + expect(d.calls, contains("markHealthy")); + }); + + updaterTest("checks again every 6 hours while the app runs", (t) async { + final d = FakeDriver()..answer = _current; + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + await t.pumpWidget(const SizedBox()); + + expect(d.calls.where((c) => c == "check").length, 1); + + await t.pump(const Duration(hours: 5, minutes: 59)); + expect(d.calls.where((c) => c == "check").length, 1); + + d.answer = _available; + await t.pump(const Duration(minutes: 2)); + await t.pump(); + + expect(d.calls.where((c) => c == "check").length, 2); + expect(d.calls, contains("download 13")); + expect(GarageUpdater.instance.ready.value?.latest?.build, 13); + + // the same build again in another 6 hours isnt fetched twice + await t.pump(const Duration(hours: 6, minutes: 1)); + await t.pump(); + expect(d.calls.where((c) => c == "download 13").length, 1); + }); + + updaterTest("launch twice is ignored the second time", (t) async { + final d = FakeDriver()..answer = _current; + final run = start(d); + await t.pump(); + await t.pumpWidget(run.splash()!); + await t.pump(); + + final again = start(FakeDriver()..answer = _required); + await t.pump(); + expect(again.finished(), isTrue); + expect(again.splash(), isNull); + }); +} diff --git a/garage_updates/test/windows_installer_test.dart b/garage_updates/test/windows_installer_test.dart new file mode 100644 index 0000000..323ddef --- /dev/null +++ b/garage_updates/test/windows_installer_test.dart @@ -0,0 +1,440 @@ +import "dart:convert"; +import "dart:io"; + +import "package:flutter_test/flutter_test.dart"; +import "package:garage_updates/core.dart"; + +import "support/fake_install.dart"; + +UpdateRelease _release(int build, {String format = "zip"}) => UpdateRelease( + label: "v$build", + build: build, + asset: UpdateAsset(url: "http://x/app.$format", filename: "app.$format", format: format, size: 3, sha256: "aa"), + ); + +void main() { + late FakeWindowsInstall fake; + + setUp(() => fake = FakeWindowsInstall.create()); + tearDown(() => fake.dispose()); + + WindowsInstaller locate([String? exe]) { + final found = WindowsInstaller.locate(exe ?? fake.exe.path, environment: const {}); + expect(found.reason, isNull); + return found.installer as WindowsInstaller; + } + + File zipIn(Directory staging) { + staging.createSync(recursive: true); + return File("${staging.path}/update-13.zip")..writeAsStringSync("zip"); + } + + group("finding the install", () { + test("an exe inside app- finds the root, the stub and the build", () { + final w = locate(); + + expect(w.root.path, fake.root.path); + expect(w.stub.path, fake.stub.path); + expect(w.runningFolderBuild, 12); + expect(w.rootWritable, isTrue); + expect(w.staging.path, "${fake.root.path}/staging"); + expect(w.blockedBuilds(), [11]); + // the writable probe cleaned up after itself + expect(File("${fake.root.path}/.garage_updates_probe").existsSync(), isFalse); + }); + + test("a helper exe finds the stub by the name in the state file", () { + final w = locate("${fake.versionFolder.path}/stash-agent.exe"); + expect(w.stub.path, fake.stub.path); + }); + + test("the stub is still found when the state file is half written", () { + fake.stateFile.writeAsStringSync('{ "exe": "garage_st'); + final w = locate(); + expect(w.stub.path, fake.stub.path); + expect(w.blockedBuilds(), isEmpty); + }); + + test("a folder that isnt app- is not an install", () { + final dev = Directory("${fake.tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true); + final found = WindowsInstaller.locate("${dev.path}/garage_stash.exe"); + + expect(found.installer, isNull); + expect(found.reason, contains("app-")); + }); + + test("app- with no state file beside it is not an install", () { + fake.stateFile.deleteSync(); + final found = WindowsInstaller.locate(fake.exe.path); + expect(found.installer, isNull); + expect(found.reason, contains("garage_updates.json")); + }); + + test("an old stub left in root by an update isnt taken for the stub", () { + // nothing to go on but whats in the folder: the state wont read and + // the stub isnt named after the exe that is asking + fake.stub.renameSync("${fake.root.path}/launcher.exe"); + File("${fake.root.path}/launcher.exe.old").writeAsStringSync("the stub before this one"); + File("${fake.root.path}/launcher.exe.old-412-99").writeAsStringSync("and one that wouldnt delete"); + fake.stateFile.writeAsStringSync('{ "exe": "garage_st'); + + final w = locate("${fake.versionFolder.path}/stash-agent.exe"); + expect(w.stub.path, "${fake.root.path}/launcher.exe"); + }); + + test("no stub, not an install", () { + fake.stub.deleteSync(); + final found = WindowsInstaller.locate(fake.exe.path); + expect(found.installer, isNull); + expect(found.reason, contains("stub")); + }); + }); + + group("applying", () { + test("runs the stub directly when the root is writable", () async { + final w = locate(); + final zip = zipIn(w.staging); + + await w.apply(zip, _release(13), runningBuild: 12); + + expect(fake.runs, [ + ["--garage-apply", zip.path, "13"], + ]); + expect(Directory("${fake.root.path}/app-13").existsSync(), isTrue); + expect(w.state.read()!.current, 13); + // the zip is spent + expect(zip.existsSync(), isFalse); + }); + + test("a path with spaces reaches the stub as one argument", () async { + final w = locate(); + // the root is "Garage Stash", so the zip path has a space in it allready + final zip = zipIn(w.staging); + expect(zip.path, contains(" ")); + + await w.apply(zip, _release(13), runningBuild: 12); + expect(fake.runs.single[1], zip.path); + }); + + test("a stub that exits non zero fails the install and keeps the zip", () async { + File("${fake.root.path}/stub-exit").writeAsStringSync("3"); + final w = locate(); + final zip = zipIn(w.staging); + + await expectLater( + w.apply(zip, _release(13), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "install_failed")), + ); + expect(zip.existsSync(), isTrue); + expect(w.state.read()!.current, 12); + }); + + test("a stub that says 0 without moving current is still a failure", () async { + File("${fake.root.path}/stub-lazy").writeAsStringSync(""); + final w = locate(); + + await expectLater( + w.apply(zipIn(w.staging), _release(13), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "install_failed")), + ); + }); + + test("anything but a zip is refused before the stub is run", () async { + final w = locate(); + await expectLater( + w.apply(zipIn(w.staging), _release(13, format: "dmg"), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "format")), + ); + expect(fake.runs, isEmpty); + }); + }); + + group("a root we cant write to", () { + test("a read only root is noticed", () { + Process.runSync("/bin/chmod", ["555", fake.root.path]); + final w = locate(); + expect(w.rootWritable, isFalse); + }); + + test("staging moves to LOCALAPPDATA, under app_id when the state has one", () { + final local = "${fake.tmp.path}/Local"; + var w = WindowsInstaller( + root: fake.root, + stub: fake.stub, + runningFolderBuild: 12, + environment: {"LOCALAPPDATA": local}, + rootWritable: () => false, + ); + // no app_id in the file, so the folders name + expect(w.staging.path, "$local/Garage Stash/staging"); + + fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 12, "app_id": "net.imbenji.stash" }'); + w = WindowsInstaller( + root: fake.root, + stub: fake.stub, + runningFolderBuild: 12, + environment: {"LOCALAPPDATA": local}, + rootWritable: () => false, + ); + expect(w.staging.path, "$local/net.imbenji.stash/staging"); + }); + + test("the stub is run elevated, through powershell", () async { + String? ranExe; + List? ranArgs; + + final w = WindowsInstaller( + root: fake.root, + stub: fake.stub, + runningFolderBuild: 12, + environment: {"LOCALAPPDATA": "${fake.tmp.path}/Local"}, + rootWritable: () => false, + run: (exe, args) async { + ranExe = exe; + ranArgs = args; + // the elevated stub did its job + fake.stateFile.writeAsStringSync(jsonEncode({"exe": "garage_stash.exe", "current": 13, "previous": 12})); + return ProcessResult(1, 0, "", ""); + }, + ); + final zip = zipIn(w.staging); + + await w.apply(zip, _release(13), runningBuild: 12); + + expect(ranExe, "powershell"); + expect(ranArgs!.sublist(0, ranArgs!.length - 1), + ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command"]); + + final script = ranArgs!.last; + expect(script, contains("Start-Process -FilePath '${fake.stub.path}'")); + expect(script, contains("-Verb RunAs")); + expect(script, contains("-Wait")); + // the zip path has a space, so its quoted inside the argument list + expect(script, contains("-ArgumentList '--garage-apply \"${zip.path}\" 13'")); + expect(script, contains("exit \$p.ExitCode")); + // the stub itself was never run unelevated + expect(fake.runs, isEmpty); + }); + + test("a UAC prompt turned down is its own error", () async { + final w = WindowsInstaller( + root: fake.root, + stub: fake.stub, + runningFolderBuild: 12, + environment: const {}, + rootWritable: () => false, + run: (exe, args) async => ProcessResult(1, kElevationRefused, "", "The operation was canceled by the user."), + ); + + await expectLater( + w.apply(zipIn(Directory("${fake.tmp.path}/st")), _release(13), runningBuild: 12), + throwsA(isA().having((e) => e.code, "code", "elevation_refused")), + ); + }); + }); + + group("starts counted for the user", () { + const state13 = '{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [11] }'; + + Map userJson() => jsonDecode(fake.userStateFile.readAsStringSync()) as Map; + + setUp(() { + Directory("${fake.root.path}/app-13").createSync(); + fake.stateFile.writeAsStringSync(state13); + }); + + test("the count goes in the users file, root is left as it was", () { + final w = fake.installer(readOnly: true); + expect(w.userState!.file.path, fake.userStateFile.path); + + expect(fake.plainLaunch(readOnly: true), 13); + expect(fake.plainLaunch(readOnly: true), 13); + + expect(userJson(), {"failed_starts": 2, "blocked": [], "for_current": 13, "run_instead": null}); + expect(fake.stateFile.readAsStringSync(), state13); + expect(w.startsBuild, 13); + expect(w.blockedBuilds(), [11]); + }); + + test("the users file goes under app_id when the state has one", () { + fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net.imbenji.stash" }'); + final w = fake.installer(readOnly: true); + expect(w.userState!.file.path, "${fake.local.path}/net.imbenji.stash/garage_updates.json"); + + // one that couldnt be a folder name is the same as none, as in the stub + fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net:imbenji" }'); + expect(w.userState!.file.path, fake.userStateFile.path); + }); + + test("markHealthy zeroes the users count and nothing else", () async { + final w = fake.installer(readOnly: true); + fake.plainLaunch(readOnly: true); + fake.plainLaunch(readOnly: true); + + await w.markHealthy(); + + expect(userJson(), {"failed_starts": 0, "blocked": [], "for_current": 13, "run_instead": null}); + expect(fake.stateFile.readAsStringSync(), state13); + expect(fake.local.listSync(recursive: true).whereType().map((f) => f.path), [fake.userStateFile.path]); + }); + + test("three starts that never got healthy: blocked for the user, the previous build runs instead", () { + final w = fake.installer(readOnly: true); + for (var i = 0; i < 3; i++) { + expect(fake.plainLaunch(readOnly: true), 13); + } + expect(w.startsBuild, 13); + + expect(fake.plainLaunch(readOnly: true), 12); + expect(userJson(), { + "failed_starts": 0, + "blocked": [13], + "for_current": 13, + "run_instead": 12, + }); + // and it stays there + expect(fake.plainLaunch(readOnly: true), 12); + + expect(w.startsBuild, 12); + expect(w.blockedBuilds(), [11, 13]); + // nobody else on the machine was moved + expect(fake.stateFile.readAsStringSync(), state13); + }); + + test("a build to run instead that has gone is not what we say is started", () { + fake.userStateFile.parent.createSync(recursive: true); + fake.userStateFile.writeAsStringSync('{ "failed_starts": 0, "blocked": [13], "for_current": 13, "run_instead": 10 }'); + + final w = fake.installer(readOnly: true); + expect(w.startsBuild, 13); + expect(fake.plainLaunch(readOnly: true), 13); + expect(userJson()["run_instead"], isNull); + }); + + test("an update going in starts the count again, what was blocked stays", () { + final w = fake.installer(readOnly: true); + for (var i = 0; i < 4; i++) { + fake.plainLaunch(readOnly: true); + } + expect(w.startsBuild, 12); + + // the elevated apply + Directory("${fake.root.path}/app-14").createSync(); + fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 14, "previous": 13, "failed_starts": 0, "blocked": [] }'); + + // before the stub has even been started again + expect(w.startsBuild, 14); + expect(w.blockedBuilds(), [13]); + + expect(fake.plainLaunch(readOnly: true), 14); + expect(userJson(), {"failed_starts": 1, "blocked": [13], "for_current": 14, "run_instead": null}); + }); + + test("a previous that allready failed the user is not gone back to", () { + fake.userStateFile.parent.createSync(recursive: true); + fake.userStateFile.writeAsStringSync('{ "failed_starts": 3, "blocked": [12], "for_current": 13, "run_instead": null }'); + + expect(fake.plainLaunch(readOnly: true), 13); + expect(userJson()["run_instead"], isNull); + expect(userJson()["blocked"], [12]); + }); + + test("a users file that is half written is read as none", () async { + fake.userStateFile.parent.createSync(recursive: true); + fake.userStateFile.writeAsStringSync('{ "failed_sta'); + + final w = fake.installer(readOnly: true); + expect(w.blockedBuilds(), [11]); + expect(w.startsBuild, 13); + await w.markHealthy(); + expect(fake.userStateFile.readAsStringSync(), '{ "failed_sta'); + }); + + test("a root that can be written never gets a users file", () async { + final w = fake.installer(); + + expect(fake.plainLaunch(), 13); + expect(fake.plainLaunch(), 13); + expect(w.state.read()!.failedStarts, 2); + expect(w.blockedBuilds(), [11]); + expect(w.startsBuild, 13); + await w.markHealthy(); + + expect(w.state.read()!.failedStarts, 0); + expect(fake.userStateFile.existsSync(), isFalse); + expect(fake.local.existsSync(), isFalse); + + // and falling back there is still the root file changing + for (var i = 0; i < 3; i++) { + fake.plainLaunch(); + } + expect(fake.plainLaunch(), 12); + final s = w.state.read()!; + expect(s.current, 12); + expect(s.blocked, [11, 13]); + expect(w.startsBuild, 12); + expect(fake.local.existsSync(), isFalse); + }); + }); + + group("quoting", () { + test("windows arguments", () { + expect(windowsQuoteArg("--garage-apply"), "--garage-apply"); + expect(windowsQuoteArg("13"), "13"); + expect(windowsQuoteArg(""), '""'); + expect(windowsQuoteArg(r"C:\Program Files\App\x.zip"), r'"C:\Program Files\App\x.zip"'); + // a trailing backslash would otherwise eat the closing quote + expect(windowsQuoteArg(r"C:\My Apps\"), r'"C:\My Apps\\"'); + expect(windowsQuoteArg(r'say "hi"'), r'"say \"hi\""'); + expect(windowsQuoteArg(r'a\"b c'), r'"a\\\"b c"'); + }); + + test("powershell strings", () { + expect(powershellQuote(r"C:\Users\O'Brien\app.exe"), r"'C:\Users\O''Brien\app.exe'"); + expect(powershellQuote(r"$env:x `n"), r"'$env:x `n'"); + }); + + test("the elevation script survives a quote in the path", () { + final args = elevationArgs(r"C:\Users\O'Brien\App\app.exe", ["--garage-apply", r"C:\Users\O'Brien\x.zip", "13"]); + expect(args.last, contains(r"-FilePath 'C:\Users\O''Brien\App\app.exe'")); + expect(args.last, contains(r"-ArgumentList '--garage-apply C:\Users\O''Brien\x.zip 13'")); + }); + }); + + test("relaunch starts the stub with the apps own arguments", () async { + final w = locate(); + await w.relaunch(["--route=/settings", "two words"]); + + // its detached, give it a moment to run + for (var i = 0; i < 100 && fake.runs.isEmpty; i++) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(fake.runs, [ + ["--route=/settings", "two words"], + ]); + }); + + test("markHealthy zeroes failed_starts and nothing else", () async { + final w = locate(); + await w.markHealthy(); + + final j = jsonDecode(fake.stateFile.readAsStringSync()) as Map; + expect(j["failed_starts"], 0); + expect(j["current"], 12); + expect(j["previous"], 9); + expect(j["blocked"], [11]); + expect(j["exe"], "garage_stash.exe"); + }); + + test("markHealthy leaves a half written state file alone", () async { + fake.stateFile.writeAsStringSync('{ "exe": "garage_st'); + await locate().markHealthy(); + expect(fake.stateFile.readAsStringSync(), '{ "exe": "garage_st'); + }); + + test("the stub counts starts on windows, not us", () async { + final w = locate(); + expect(await w.noteStart(12), isFalse); + expect(w.state.read()!.failedStarts, 1); + }); +} diff --git a/garage_updates/windows/CMakeLists.txt b/garage_updates/windows/CMakeLists.txt new file mode 100644 index 0000000..007eee9 --- /dev/null +++ b/garage_updates/windows/CMakeLists.txt @@ -0,0 +1,26 @@ +# garage_updates on windows is no plugin code at all, only the stub. the +# pubspec says ffiPlugin so that flutter adds this folder to the host apps +# build, and what comes out is garage_stub.exe sat beside the app. +cmake_minimum_required(VERSION 3.14) + +set(PROJECT_NAME "garage_updates") +project(${PROJECT_NAME} LANGUAGES CXX) + +cmake_policy(VERSION 3.14...3.25) + +# the host apps own icon, where flutter create puts it. an app that keeps it +# somewhere else sets GARAGE_STUB_ICON in its windows/CMakeLists.txt before +# generated_plugins.cmake is included +if(NOT GARAGE_STUB_ICON) + set(GARAGE_STUB_ICON "${CMAKE_SOURCE_DIR}/runner/resources/app_icon.ico") +endif() + +add_subdirectory("stub") + + +# flutter installs everything in this list next to the app exe. its meant for +# dlls but its install(FILES), so an exe goes along just the same +set(garage_updates_bundled_libraries + "$" + PARENT_SCOPE +) diff --git a/garage_updates/windows/stub/CMakeLists.txt b/garage_updates/windows/stub/CMakeLists.txt new file mode 100644 index 0000000..94eab1c --- /dev/null +++ b/garage_updates/windows/stub/CMakeLists.txt @@ -0,0 +1,71 @@ +# the stub exe. in a folder of its own so the runtime switch below stays off +# everything else in the build. +# +# two things can be set before this is added: +# GARAGE_STUB_ICON an .ico for it. shortcuts point at the stub, so this +# is the icon people see +# GARAGE_STUB_OUT_DIR where the exe goes, for a build that has to know +cmake_minimum_required(VERSION 3.14) + +# the stub sits on its own in . the vc runtime dlls, if the app ships +# them at all, are a folder down where it cant see them. so its linked static. +# flutters project() runs before its cmake_policy(), which leaves /MD sat in +# the flags and MSVC_RUNTIME_LIBRARY ignored, so both ways are covered +foreach(_flags + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_PROFILE CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_MINSIZEREL) + if(DEFINED ${_flags}) + string(REPLACE "/MDd" "/MTd" ${_flags} "${${_flags}}") + string(REPLACE "/MD" "/MT" ${_flags} "${${_flags}}") + endif() +endforeach() + +set(_stub_sources "garage_stub.cpp" "garage_common.h") +if(MSVC) + # as a source so the linker merges it. through the .rc it would collide with + # the manifest the linker makes itself + list(APPEND _stub_sources "garage_stub.exe.manifest") +endif() + + +set(GARAGE_STUB_ICON_LINE "") +if(GARAGE_STUB_ICON AND EXISTS "${GARAGE_STUB_ICON}") + # forward slashes. a backslash inside an .rc string is an escape + file(TO_CMAKE_PATH "${GARAGE_STUB_ICON}" _stub_icon) + set(GARAGE_STUB_ICON_LINE "1 ICON \"${_stub_icon}\"") +else() + message(STATUS "garage_updates: no icon for the stub, it gets the plain windows one") +endif() + +# with msvc and no icon there would be nothing in the .rc at all, so it stays out +if(GARAGE_STUB_ICON_LINE OR NOT MSVC) + set(GARAGE_STUB_MANIFEST_FILE "${CMAKE_CURRENT_SOURCE_DIR}/garage_stub.exe.manifest") + configure_file("garage_stub.rc.in" "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc" @ONLY) + list(APPEND _stub_sources "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc") + if(NOT MSVC) + set_property(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/garage_stub.rc" APPEND PROPERTY + COMPILE_DEFINITIONS GARAGE_RC_MANIFEST) + endif() +endif() + +add_executable(garage_stub WIN32 ${_stub_sources}) +target_compile_features(garage_stub PRIVATE cxx_std_17) +target_compile_definitions(garage_stub PRIVATE UNICODE _UNICODE) +set_target_properties(garage_stub PROPERTIES + OUTPUT_NAME "garage_stub" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +if(MSVC) + # no APPLY_STANDARD_SETTINGS. thats /WX, and this has never been through msvc + target_compile_options(garage_stub PRIVATE /W4 /EHsc /utf-8) +endif() +if(MINGW) + # mingw only looks for wWinMain when its told to + target_link_options(garage_stub PRIVATE -municode "-Wl,--subsystem,windows") +endif() +target_link_libraries(garage_stub PRIVATE user32 shell32 advapi32) + +if(GARAGE_STUB_OUT_DIR) + # the empty genex stops visual studio adding a Release\ on the end + set_target_properties(garage_stub PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${GARAGE_STUB_OUT_DIR}$<0:>") +endif() diff --git a/garage_updates/windows/stub/garage_common.h b/garage_updates/windows/stub/garage_common.h new file mode 100644 index 0000000..1e01031 --- /dev/null +++ b/garage_updates/windows/stub/garage_common.h @@ -0,0 +1,652 @@ +// the bits the stub and the installer both need. header only and everything +// is inline, so whichever of the two doesnt call a function doesnt get told +// off about it. +// +// nothing in here logs. it leaves GetLastError alone for the caller to report. + +#pragma once + +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif + +#include +#include +#include +#include + +namespace garage { + +inline std::wstring widen(const std::string& s) { + if (s.empty()) return L""; + int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0); + if (n <= 0) return L""; + std::wstring w((size_t)n, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), &w[0], n); + return w; +} + +inline std::string narrow(const std::wstring& w) { + if (w.empty()) return ""; + int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), nullptr, 0, nullptr, nullptr); + if (n <= 0) return ""; + std::string s((size_t)n, '\0'); + WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), &s[0], n, nullptr, nullptr); + return s; +} + +inline std::wstring num(long long v) { + return std::to_wstring(v); +} + +// "5 Access is denied". winhttp keeps its own messages in its dll +inline std::wstring win_error(DWORD code) { + wchar_t buf[512]; + DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + HMODULE from = nullptr; + if (code >= 12000 && code < 12200) { + from = GetModuleHandleW(L"winhttp.dll"); + if (from) flags |= FORMAT_MESSAGE_FROM_HMODULE; + } + DWORD n = FormatMessageW(flags, from, code, 0, buf, ARRAYSIZE(buf), nullptr); + while (n > 0 && (buf[n - 1] == L'\r' || buf[n - 1] == L'\n' || buf[n - 1] == L' ' || buf[n - 1] == L'.')) n--; + std::wstring out = num(code); + if (n > 0) { + out += L" "; + out.append(buf, n); + } + return out; +} + + +// ---- paths ---- + +// only long ones get the prefix. with it on nothing is normalised any more, +// so short paths are better off without +inline std::wstring lp(const std::wstring& p) { + if (p.size() < 240) return p; + if (p.compare(0, 4, L"\\\\?\\") == 0) return p; + if (p.compare(0, 2, L"\\\\") == 0) return L"\\\\?\\UNC\\" + p.substr(2); + if (p.size() > 2 && p[1] == L':') return L"\\\\?\\" + p; + return p; +} + +inline std::wstring join(const std::wstring& a, const std::wstring& b) { + if (a.empty()) return b; + wchar_t last = a[a.size() - 1]; + if (last == L'\\' || last == L'/') return a + b; + return a + L"\\" + b; +} + +inline std::wstring parent(const std::wstring& p) { + size_t at = p.find_last_of(L"\\/"); + if (at == std::wstring::npos) return L""; + return p.substr(0, at); +} + +inline std::wstring leaf(const std::wstring& p) { + size_t at = p.find_last_of(L"\\/"); + if (at == std::wstring::npos) return p; + return p.substr(at + 1); +} + +inline bool exists(const std::wstring& p) { + return GetFileAttributesW(lp(p).c_str()) != INVALID_FILE_ATTRIBUTES; +} + +inline bool is_dir(const std::wstring& p) { + DWORD a = GetFileAttributesW(lp(p).c_str()); + return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY) != 0; +} + +inline std::wstring absolute(const std::wstring& p) { + DWORD need = GetFullPathNameW(p.c_str(), 0, nullptr, nullptr); + if (need == 0) return p; + std::wstring out((size_t)need, L'\0'); + DWORD got = GetFullPathNameW(p.c_str(), need, &out[0], nullptr); + if (got == 0 || got >= need) return p; + out.resize(got); + return out; +} + +inline long long file_size(const std::wstring& p) { + WIN32_FILE_ATTRIBUTE_DATA info; + if (!GetFileAttributesExW(lp(p).c_str(), GetFileExInfoStandard, &info)) return -1; + return ((long long)info.nFileSizeHigh << 32) | (long long)info.nFileSizeLow; +} + +inline bool same_text(const std::wstring& a, const std::wstring& b) { + return CompareStringOrdinal(a.data(), (int)a.size(), b.data(), (int)b.size(), TRUE) == CSTR_EQUAL; +} + +inline bool starts_with(const std::wstring& s, const std::wstring& prefix) { + if (s.size() < prefix.size()) return false; + return CompareStringOrdinal(s.data(), (int)prefix.size(), prefix.data(), (int)prefix.size(), TRUE) == CSTR_EQUAL; +} + +inline bool is_ascii(const std::wstring& s) { + for (size_t i = 0; i < s.size(); i++) { + if (s[i] > 126 || s[i] < 32) return false; + } + return true; +} + +// deletes a folder and whats in it. keeps going past things it cant delete +// and hands back the first error, the caller says what to do about it +inline bool remove_tree(const std::wstring& dir, DWORD* firstError) { + bool clean = true; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd); + if (find != INVALID_HANDLE_VALUE) { + do { + std::wstring name = fd.cFileName; + if (name == L"." || name == L"..") continue; + std::wstring full = join(dir, name); + bool isDir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; + bool isLink = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; + + if (isDir && !isLink) { + if (!remove_tree(full, firstError)) clean = false; + continue; + } + if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { + SetFileAttributesW(lp(full).c_str(), fd.dwFileAttributes & ~(DWORD)FILE_ATTRIBUTE_READONLY); + } + // a junction is taken away as a folder, never walked in to + BOOL gone = isDir ? RemoveDirectoryW(lp(full).c_str()) : DeleteFileW(lp(full).c_str()); + if (!gone) { + if (firstError && *firstError == 0) *firstError = GetLastError(); + clean = false; + } + } while (FindNextFileW(find, &fd)); + FindClose(find); + } + + if (!RemoveDirectoryW(lp(dir).c_str())) { + DWORD err = GetLastError(); + if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) { + if (firstError && *firstError == 0) *firstError = err; + clean = false; + } + } + return clean; +} + +inline bool read_file(const std::wstring& path, std::string& out, size_t cap) { + out.clear(); + HANDLE h = INVALID_HANDLE_VALUE; + // the other side may be half way through swapping it + for (int i = 0; i < 10; i++) { + h = CreateFileW(lp(path).c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h != INVALID_HANDLE_VALUE) break; + if (GetLastError() != ERROR_SHARING_VIOLATION) return false; + Sleep(20); + } + if (h == INVALID_HANDLE_VALUE) return false; + + char chunk[4096]; + DWORD got = 0; + bool ok = true; + for (;;) { + if (!ReadFile(h, chunk, sizeof(chunk), &got, nullptr)) { ok = false; break; } + if (got == 0) break; + out.append(chunk, got); + if (out.size() > cap) break; + } + DWORD err = GetLastError(); + CloseHandle(h); + SetLastError(err); + return ok; +} + +// temp file beside it, then swapped in. a reader sees the old one or the new +// one and never half of either +inline bool write_atomic(const std::wstring& path, const std::string& bytes) { + std::wstring tmp = path + L".tmp" + num((long long)GetCurrentProcessId()); + HANDLE h = CreateFileW(lp(tmp).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + + DWORD wrote = 0; + bool ok = WriteFile(h, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr) && wrote == (DWORD)bytes.size(); + if (ok) FlushFileBuffers(h); + DWORD err = GetLastError(); + CloseHandle(h); + if (!ok) { + DeleteFileW(lp(tmp).c_str()); + SetLastError(err); + return false; + } + + for (int i = 0; i < 20; i++) { + if (MoveFileExW(lp(tmp).c_str(), lp(path).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + return true; + } + err = GetLastError(); + // somebody has it open to read. they wont for long + if (err != ERROR_SHARING_VIOLATION && err != ERROR_ACCESS_DENIED) break; + Sleep(25); + } + DeleteFileW(lp(tmp).c_str()); + SetLastError(err); + return false; +} + + +// ---- json ---- +// small, but a real parser. objects, arrays, strings, whole numbers, the +// three words. a number with a fraction keeps the part before the dot. + +struct JVal { + enum Kind { Null, Bool, Num, Str, Arr, Obj }; + Kind kind = Null; + bool b = false; + long long n = 0; + std::string s; + std::vector keys; + std::vector items; + + const JVal* get(const char* key) const { + if (kind != Obj) return nullptr; + for (size_t i = 0; i < keys.size(); i++) { + if (keys[i] == key) return &items[i]; + } + return nullptr; + } + std::string str(const char* key) const { + const JVal* v = get(key); + return v && v->kind == Str ? v->s : std::string(); + } + long long number(const char* key, long long fallback) const { + const JVal* v = get(key); + return v && v->kind == Num ? v->n : fallback; + } +}; + +struct JParser { + const char* p; + const char* end; + int depth; +}; + +inline void j_ws(JParser& j) { + while (j.p < j.end && (*j.p == ' ' || *j.p == '\t' || *j.p == '\r' || *j.p == '\n')) j.p++; +} + +inline void j_utf8(std::string& out, unsigned long cp) { + if (cp < 0x80) { + out += (char)cp; + } else if (cp < 0x800) { + out += (char)(0xC0 | (cp >> 6)); + out += (char)(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + out += (char)(0xE0 | (cp >> 12)); + out += (char)(0x80 | ((cp >> 6) & 0x3F)); + out += (char)(0x80 | (cp & 0x3F)); + } else { + out += (char)(0xF0 | (cp >> 18)); + out += (char)(0x80 | ((cp >> 12) & 0x3F)); + out += (char)(0x80 | ((cp >> 6) & 0x3F)); + out += (char)(0x80 | (cp & 0x3F)); + } +} + +inline bool j_hex4(JParser& j, unsigned long& out) { + if (j.end - j.p < 4) return false; + out = 0; + for (int i = 0; i < 4; i++) { + char c = *j.p++; + out <<= 4; + if (c >= '0' && c <= '9') out |= (unsigned long)(c - '0'); + else if (c >= 'a' && c <= 'f') out |= (unsigned long)(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') out |= (unsigned long)(c - 'A' + 10); + else return false; + } + return true; +} + +inline bool j_string(JParser& j, std::string& out) { + if (j.p >= j.end || *j.p != '"') return false; + j.p++; + while (j.p < j.end) { + char c = *j.p++; + if (c == '"') return true; + if (c != '\\') { out += c; continue; } + if (j.p >= j.end) return false; + char e = *j.p++; + switch (e) { + case 'n': out += '\n'; break; + case 't': out += '\t'; break; + case 'r': out += '\r'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'u': { + unsigned long cp = 0; + if (!j_hex4(j, cp)) return false; + // two of them make one character above the bmp + if (cp >= 0xD800 && cp < 0xDC00 && j.end - j.p >= 6 && j.p[0] == '\\' && j.p[1] == 'u') { + JParser look = j; + look.p += 2; + unsigned long low = 0; + if (j_hex4(look, low) && low >= 0xDC00 && low < 0xE000) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); + j.p = look.p; + } + } + j_utf8(out, cp); + break; + } + default: out += e; break; + } + } + return false; +} + +inline bool j_word(JParser& j, const char* word) { + size_t n = strlen(word); + if ((size_t)(j.end - j.p) < n || strncmp(j.p, word, n) != 0) return false; + j.p += n; + return true; +} + +inline bool j_value(JParser& j, JVal& out) { + j_ws(j); + if (j.p >= j.end) return false; + char c = *j.p; + + if (c == '"') { + out.kind = JVal::Str; + return j_string(j, out.s); + } + if (c == '{' || c == '[') { + bool isObj = c == '{'; + char close = isObj ? '}' : ']'; + out.kind = isObj ? JVal::Obj : JVal::Arr; + if (++j.depth > 32) return false; + j.p++; + j_ws(j); + if (j.p < j.end && *j.p == close) { j.p++; j.depth--; return true; } + for (;;) { + if (isObj) { + j_ws(j); + std::string key; + if (!j_string(j, key)) return false; + j_ws(j); + if (j.p >= j.end || *j.p != ':') return false; + j.p++; + out.keys.push_back(key); + } + out.items.push_back(JVal()); + if (!j_value(j, out.items.back())) return false; + j_ws(j); + if (j.p >= j.end) return false; + if (*j.p == ',') { j.p++; continue; } + if (*j.p == close) { j.p++; j.depth--; return true; } + return false; + } + } + if (c == '-' || (c >= '0' && c <= '9')) { + bool neg = c == '-'; + if (neg) j.p++; + if (j.p >= j.end || *j.p < '0' || *j.p > '9') return false; + long long v = 0; + while (j.p < j.end && *j.p >= '0' && *j.p <= '9') { + if (v < 900000000000000000LL) v = v * 10 + (*j.p - '0'); + j.p++; + } + // whatever comes after the whole part is stepped over + while (j.p < j.end && (*j.p == '.' || *j.p == 'e' || *j.p == 'E' || *j.p == '+' || *j.p == '-' || + (*j.p >= '0' && *j.p <= '9'))) { + j.p++; + } + out.kind = JVal::Num; + out.n = neg ? -v : v; + return true; + } + if (j_word(j, "true")) { out.kind = JVal::Bool; out.b = true; return true; } + if (j_word(j, "false")) { out.kind = JVal::Bool; out.b = false; return true; } + if (j_word(j, "null")) { out.kind = JVal::Null; return true; } + return false; +} + +inline bool json_parse(const std::string& text, JVal& out) { + JParser j; + j.p = text.data(); + j.end = text.data() + text.size(); + j.depth = 0; + // some editors put a bom on the front + if (text.size() >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB && + (unsigned char)text[2] == 0xBF) { + j.p += 3; + } + if (!j_value(j, out)) return false; + j_ws(j); + return j.p == j.end; +} + +inline std::string json_quote(const std::string& s) { + static const char hex[] = "0123456789abcdef"; + std::string out = "\""; + for (size_t i = 0; i < s.size(); i++) { + unsigned char c = (unsigned char)s[i]; + if (c == '"' || c == '\\') { + out += '\\'; + out += (char)c; + } else if (c < 0x20) { + out += "\\u00"; + out += hex[c >> 4]; + out += hex[c & 15]; + } else { + out += (char)c; + } + } + out += '"'; + return out; +} + +inline std::string json_print(const JVal& v) { + switch (v.kind) { + case JVal::Null: return "null"; + case JVal::Bool: return v.b ? "true" : "false"; + case JVal::Num: return std::to_string(v.n); + case JVal::Str: return json_quote(v.s); + default: break; + } + bool isObj = v.kind == JVal::Obj; + std::string out = isObj ? "{" : "["; + for (size_t i = 0; i < v.items.size(); i++) { + if (i > 0) out += ", "; + if (isObj) out += json_quote(v.keys[i]) + ": "; + out += json_print(v.items[i]); + } + out += isObj ? "}" : "]"; + return out; +} + + +// ---- garage_updates.json ---- + +struct State { + std::wstring exe; + long long current = -1; // -1 is "there isnt one" + long long previous = -1; + long long failedStarts = 0; + std::vector blocked; + // anything else thats in the file (the dart side keeps app_id in there). + // not ours, so it goes back out the way it came in + std::vector extraKeys; + std::vector extraVals; + + std::wstring extra(const char* key) const { + for (size_t i = 0; i < extraKeys.size(); i++) { + if (extraKeys[i] == key && extraVals[i].kind == JVal::Str) return widen(extraVals[i].s); + } + return L""; + } + void set_extra(const char* key, const std::wstring& value) { + JVal v; + v.kind = JVal::Str; + v.s = narrow(value); + for (size_t i = 0; i < extraKeys.size(); i++) { + if (extraKeys[i] == key) { extraVals[i] = v; return; } + } + extraKeys.push_back(key); + extraVals.push_back(v); + } + + bool is_blocked(long long build) const { + for (size_t i = 0; i < blocked.size(); i++) { + if (blocked[i] == build) return true; + } + return false; + } +}; + +inline bool parse_state(const std::string& text, State& st) { + JVal root; + if (!json_parse(text, root) || root.kind != JVal::Obj) return false; + st = State(); + st.exe = widen(root.str("exe")); + st.current = root.number("current", -1); + st.previous = root.number("previous", -1); + st.failedStarts = root.number("failed_starts", 0); + if (st.failedStarts < 0) st.failedStarts = 0; + const JVal* blocked = root.get("blocked"); + if (blocked && blocked->kind == JVal::Arr) { + for (size_t i = 0; i < blocked->items.size(); i++) { + if (blocked->items[i].kind == JVal::Num) st.blocked.push_back(blocked->items[i].n); + } + } + + for (size_t i = 0; i < root.keys.size(); i++) { + const std::string& k = root.keys[i]; + if (k == "exe" || k == "current" || k == "previous" || k == "failed_starts" || k == "blocked") continue; + st.extraKeys.push_back(k); + st.extraVals.push_back(root.items[i]); + } + return true; +} + +inline std::string print_build(long long build) { + return build > 0 ? std::to_string(build) : std::string("null"); +} + +inline std::string print_state(const State& st) { + std::string out = "{\n"; + out += " \"exe\": " + json_quote(narrow(st.exe)) + ",\n"; + out += " \"current\": " + print_build(st.current) + ",\n"; + out += " \"previous\": " + print_build(st.previous) + ",\n"; + out += " \"failed_starts\": " + std::to_string(st.failedStarts) + ",\n"; + out += " \"blocked\": ["; + for (size_t i = 0; i < st.blocked.size(); i++) { + if (i > 0) out += ", "; + out += std::to_string(st.blocked[i]); + } + out += "]"; + for (size_t i = 0; i < st.extraKeys.size(); i++) { + out += ",\n " + json_quote(st.extraKeys[i]) + ": " + json_print(st.extraVals[i]); + } + out += "\n}\n"; + return out; +} + +inline std::wstring state_path(const std::wstring& root) { + return join(root, L"garage_updates.json"); +} + +inline std::wstring version_dir(const std::wstring& root, long long build) { + return join(root, L"app-" + num(build)); +} + +// "app-12" and nothing else. a half unpacked folder has a different name on +// purpose so it never gets past this +inline bool parse_version_name(const std::wstring& name, long long& build) { + if (name.size() < 5 || name.size() > 4 + 17) return false; + if (name.compare(0, 4, L"app-") != 0) return false; + long long v = 0; + for (size_t i = 4; i < name.size(); i++) { + if (name[i] < L'0' || name[i] > L'9') return false; + v = v * 10 + (name[i] - L'0'); + } + if (v <= 0) return false; + build = v; + return true; +} + +inline std::vector list_versions(const std::wstring& root) { + std::vector out; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(root, L"app-*")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) return out; + do { + long long build = 0; + if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && parse_version_name(fd.cFileName, build)) { + out.push_back(build); + } + } while (FindNextFileW(find, &fd)); + FindClose(find); + return out; +} + + +// ---- processes ---- + +// one argument, quoted so that CommandLineToArgvW on the other end gives +// back exactly this +inline std::wstring quote_arg(const std::wstring& arg) { + if (!arg.empty() && arg.find_first_of(L" \t\"") == std::wstring::npos) return arg; + std::wstring out = L"\""; + size_t slashes = 0; + for (size_t i = 0; i < arg.size(); i++) { + wchar_t c = arg[i]; + if (c == L'\\') { + slashes++; + continue; + } + if (c == L'"') { + out.append(slashes * 2 + 1, L'\\'); + } else { + out.append(slashes, L'\\'); + } + slashes = 0; + out += c; + } + // the ones at the very end sit in front of our closing quote + out.append(slashes * 2, L'\\'); + out += L"\""; + return out; +} + +// runs something with no window and waits for it. `output` (may be null) gets +// its stdout and stderr and has to be an inheritable handle +inline bool run_wait(const std::wstring& exe, const std::wstring& args, const std::wstring& cwd, + HANDLE output, DWORD& exitCode) { + std::wstring cmd = quote_arg(exe); + if (!args.empty()) cmd += L" " + args; + + STARTUPINFOW si = {}; + si.cb = sizeof(si); + if (output) { + si.dwFlags |= STARTF_USESTDHANDLES; + si.hStdOutput = output; + si.hStdError = output; + } + PROCESS_INFORMATION pi = {}; + if (!CreateProcessW(exe.c_str(), &cmd[0], nullptr, nullptr, output ? TRUE : FALSE, + CREATE_NO_WINDOW, nullptr, cwd.empty() ? nullptr : cwd.c_str(), &si, &pi)) { + return false; + } + WaitForSingleObject(pi.hProcess, INFINITE); + exitCode = 1; + GetExitCodeProcess(pi.hProcess, &exitCode); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return true; +} + +} // namespace garage diff --git a/garage_updates/windows/stub/garage_stub.cpp b/garage_updates/windows/stub/garage_stub.cpp new file mode 100644 index 0000000..362746a --- /dev/null +++ b/garage_updates/windows/stub/garage_stub.cpp @@ -0,0 +1,1354 @@ +// the stub. shortcuts, the uninstall entry and start-at-login all point at +// this, and it lives in under the apps own exe name. +// +// \.exe us. every build carries a garage_stub.exe and +// apply swaps us for it when its a different one +// \app-\... a whole build of the app +// \garage_updates.json which build to start. the dart side writes it too +// +// when is program files the person starting the app cant write that +// file, so the count of starts is kept for them in +// %LOCALAPPDATA%\\garage_updates.json instead. +// +// no flags start the current build, count the start, fall back to +// the previous build when this one keeps dying +// --garage-exec start some other exe out of the current build +// --garage-apply unpack a zip as a new build and make it current +// --garage-uninstall take the whole install away +// +// anything else on the command line belongs to the app and goes through as it +// came. there is no window and nothing waits on the app once its started. + +#include "garage_common.h" + +#include +#include + +using namespace garage; + +// what the dart side sees. 0 is the only good one +enum ExitCode { + kOk = 0, + kBadArgs = 10, + kNoSelf = 11, // couldnt work out where we are + kNoVersion = 12, // no app- folder that can be started + kNoExe = 13, // dont know which exe in the folder is the app + kCantStart = 14, + kExecMissing = 15, // --garage-exec asked for something that isnt there, or isnt inside the folder + + kNotWritable = 20, // apply needs to be run elevated + kZipMissing = 21, + kNoTar = 22, + kTarFailed = 23, + kBadPackage = 24, // unpacked fine but the apps exe isnt in it + kCantPlace = 25, // couldnt move the folder in to place + kStateWrite = 26, + kBusy = 27, // another apply is running + kNoTemp = 28, + + kCancelled = 30, + kNoElevation = 31, + kLeftovers = 32, // uninstall couldnt remove everything + kNotAnInstall = 33, +}; + +static std::wstring g_self; +static std::wstring g_root; +// %LOCALAPPDATA%\\ is where the log goes when is read only +static std::wstring g_appId; + + +// ---- the log ---- + +static std::wstring env(const wchar_t* name) { + DWORD need = GetEnvironmentVariableW(name, nullptr, 0); + if (need == 0) return L""; + std::wstring out((size_t)need, L'\0'); + DWORD got = GetEnvironmentVariableW(name, &out[0], need); + if (got == 0 || got >= need) return L""; + out.resize(got); + return out; +} + +static std::wstring local_dir() { + std::wstring local = env(L"LOCALAPPDATA"); + if (local.empty()) return L""; + return join(local, g_appId.empty() ? leaf(g_root) : g_appId); +} + +static bool append_to(const std::wstring& path, const std::string& bytes) { + // it only ever gets failures, but a machine that fails every start + // shouldnt fill the disk with them + if (file_size(path) > 256 * 1024) { + MoveFileExW(lp(path).c_str(), lp(path + L".old").c_str(), MOVEFILE_REPLACE_EXISTING); + } + HANDLE h = CreateFileW(lp(path).c_str(), FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD wrote = 0; + BOOL ok = WriteFile(h, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr); + CloseHandle(h); + return ok != FALSE; +} + +static void log_line(const std::wstring& msg) { + SYSTEMTIME t; + GetLocalTime(&t); + wchar_t stamp[64]; + wsprintfW(stamp, L"%04d-%02d-%02d %02d:%02d:%02d [%lu] ", t.wYear, t.wMonth, t.wDay, + t.wHour, t.wMinute, t.wSecond, GetCurrentProcessId()); + std::wstring line = stamp + msg; + OutputDebugStringW((L"garage_stub: " + line + L"\n").c_str()); + + std::string bytes = narrow(line) + "\r\n"; + + // whoever started us with a pipe (the dart side does) gets it as well + HANDLE err = GetStdHandle(STD_ERROR_HANDLE); + if (err && err != INVALID_HANDLE_VALUE) { + DWORD wrote = 0; + WriteFile(err, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr); + } + + if (!g_root.empty() && append_to(join(g_root, L"garage_updates.log"), bytes)) return; + + // program files. the user cant write there, so it goes beside their own stuff + std::wstring dir = local_dir(); + if (dir.empty()) return; + CreateDirectoryW(lp(dir).c_str(), nullptr); + if (!append_to(join(dir, L"garage_updates.log"), bytes)) { + OutputDebugStringW(L"garage_stub: and the log couldnt be written either\n"); + } +} + +static void log_fail(const std::wstring& what, DWORD err) { + log_line(what + L" (win32 " + win_error(err) + L")"); +} + + +// ---- the command line ---- +// read off the raw string, not argv. what the app is owed has to reach it +// exactly as it was typed, and re-quoting an argv never quite manages that. + +static bool is_space(wchar_t c) { + return c == L' ' || c == L'\t'; +} + +// the program name has its own rule: a quoted one ends at the next quote and +// backslashes mean nothing +static const wchar_t* skip_program(const wchar_t* p) { + if (*p == L'"') { + p++; + while (*p && *p != L'"') p++; + if (*p) p++; + } else { + while (*p && !is_space(*p)) p++; + } + while (is_space(*p)) p++; + return p; +} + +// one argument, read the way the c runtime reads it. leaves p on the next one +static bool next_arg(const wchar_t*& p, std::wstring& out) { + out.clear(); + while (is_space(*p)) p++; + if (!*p) return false; + + bool quoted = false; + for (;;) { + size_t slashes = 0; + while (*p == L'\\') { p++; slashes++; } + + if (*p == L'"') { + out.append(slashes / 2, L'\\'); + if (slashes % 2) { + out += L'"'; + p++; + } else if (quoted && p[1] == L'"') { + out += L'"'; + p += 2; + } else { + quoted = !quoted; + p++; + } + continue; + } + + out.append(slashes, L'\\'); + if (!*p || (!quoted && is_space(*p))) break; + out += *p++; + } + while (is_space(*p)) p++; + return true; +} + + +// ---- locks ---- +// two of us can be started at once (a double click, a login item and a +// shortcut). a mutex named after the root keeps them off the state file +// together. theres nowhere to put a lock file when root is read only. + +static HANDLE lock_named(const wchar_t* what, DWORD waitMs) { + std::wstring lower = g_root; + if (!lower.empty()) CharLowerBuffW(&lower[0], (DWORD)lower.size()); + unsigned long long h = 1469598103934665603ULL; + for (size_t i = 0; i < lower.size(); i++) { + h ^= (unsigned long long)lower[i]; + h *= 1099511628211ULL; + } + wchar_t name[96]; + wsprintfW(name, L"Local\\garage_updates-%s-%08x%08x", what, (unsigned)(h >> 32), (unsigned)(h & 0xffffffffULL)); + + HANDLE m = CreateMutexW(nullptr, FALSE, name); + if (!m) { + log_fail(std::wstring(L"couldnt make the ") + what + L" lock", GetLastError()); + return nullptr; + } + DWORD got = WaitForSingleObject(m, waitMs); + // abandoned is the last holder dying with it. its ours now all the same + if (got == WAIT_OBJECT_0 || got == WAIT_ABANDONED) return m; + + log_fail(std::wstring(L"gave up waiting for the ") + what + L" lock", got == WAIT_TIMEOUT ? (DWORD)WAIT_TIMEOUT : GetLastError()); + CloseHandle(m); + return nullptr; +} + +static void unlock(HANDLE m) { + if (!m) return; + ReleaseMutex(m); + CloseHandle(m); +} + + +// ---- state ---- + +static bool safe_exe_name(const std::wstring& name) { + if (name.empty()) return false; + return name.find_first_of(L"\\/:") == std::wstring::npos && name != L"." && name != L".."; +} + +static bool can_start(const State& st, long long build) { + if (build <= 0) return false; + std::wstring dir = version_dir(g_root, build); + if (!is_dir(dir)) return false; + return st.exe.empty() || exists(join(dir, st.exe)); +} + +// for when the state file doesnt say. our own name first, the stub is put in +// root under the apps exe name. failing that, the only exe in there +static std::wstring guess_exe(const std::wstring& dir) { + std::wstring mine = leaf(g_self); + if (!same_text(mine, L"garage_stub.exe") && exists(join(dir, mine))) return mine; + + std::wstring only; + int count = 0; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(dir, L"*.exe")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) return L""; + do { + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; + if (same_text(fd.cFileName, L"garage_stub.exe")) continue; + only = fd.cFileName; + count++; + } while (FindNextFileW(find, &fd)); + FindClose(find); + return count == 1 ? only : L""; +} + +static bool read_state(State& st) { + std::wstring path = state_path(g_root); + std::string text; + if (!read_file(path, text, 1024 * 1024)) { + DWORD err = GetLastError(); + if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) log_fail(L"couldnt read " + path, err); + st = State(); + return false; + } + if (!parse_state(text, st)) { + log_line(path + L" isnt json we understand, going by the folders instead"); + st = State(); + return false; + } + if (!st.exe.empty() && !safe_exe_name(st.exe)) { + log_line(L"the exe in the state file has a path in it, ignoring it: " + st.exe); + st.exe.clear(); + } + return true; +} + +static bool save_state(const State& st) { + return write_atomic(state_path(g_root), print_state(st)); +} + +// makes the state agree with whats on disk: a current that can be started and +// an exe name. `quiet` is for apply on a first install, where having nothing +// yet is the normal case +static int settle(State& st, bool quiet) { + if (!can_start(st, st.current)) { + long long was = st.current; + long long pick = -1; + if (st.previous != st.current && can_start(st, st.previous)) { + pick = st.previous; + } else { + std::vector have = list_versions(g_root); + for (size_t i = 0; i < have.size(); i++) { + if (have[i] > pick && !st.is_blocked(have[i]) && can_start(st, have[i])) pick = have[i]; + } + } + if (pick <= 0) { + if (!quiet) log_line(L"theres no app- folder in " + g_root + L" that can be started"); + return kNoVersion; + } + if (!quiet) { + log_line(L"the state file says build " + num(was) + L" which isnt there, using build " + num(pick)); + } + st.current = pick; + st.failedStarts = 0; + } + if (st.previous == st.current) st.previous = -1; + + if (st.exe.empty()) { + st.exe = guess_exe(version_dir(g_root, st.current)); + if (st.exe.empty()) { + if (!quiet) log_line(L"dont know which exe in " + version_dir(g_root, st.current) + L" is the app"); + return kNoExe; + } + } + return kOk; +} + + +// ---- the users own half ---- +// nobody but an admin can write to an install in program files, so the count +// of starts cant go in the state file there. it goes in a file of the users +// own, and falling back is "start the previous build for this user" rather +// than changing what current is for everybody. + +struct UserState { + long long failedStarts = 0; + std::vector blocked; + long long forCurrent = -1; // the current the count was made against + long long runInstead = -1; // started for this user in place of current + + bool is_blocked(long long build) const { + for (size_t i = 0; i < blocked.size(); i++) { + if (blocked[i] == build) return true; + } + return false; + } +}; + +static std::wstring user_state_path() { + std::wstring dir = local_dir(); + if (dir.empty()) return L""; + return join(dir, L"garage_updates.json"); +} + +// a missing one or one that wont parse is the same as a new one +static void read_user_state(UserState& us) { + us = UserState(); + std::wstring path = user_state_path(); + std::string text; + if (!read_file(path, text, 1024 * 1024)) { + DWORD err = GetLastError(); + if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) log_fail(L"couldnt read " + path, err); + return; + } + JVal root; + if (!json_parse(text, root) || root.kind != JVal::Obj) { + log_line(path + L" isnt json we understand, starting it again"); + return; + } + us.failedStarts = root.number("failed_starts", 0); + if (us.failedStarts < 0) us.failedStarts = 0; + us.forCurrent = root.number("for_current", -1); + us.runInstead = root.number("run_instead", -1); + const JVal* blocked = root.get("blocked"); + if (blocked && blocked->kind == JVal::Arr) { + for (size_t i = 0; i < blocked->items.size(); i++) { + if (blocked->items[i].kind == JVal::Num && !us.is_blocked(blocked->items[i].n)) { + us.blocked.push_back(blocked->items[i].n); + } + } + } +} + +static bool save_user_state(const UserState& us) { + std::wstring dir = local_dir(); + if (!CreateDirectoryW(lp(dir).c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) return false; + + std::string out = "{\n"; + out += " \"failed_starts\": " + std::to_string(us.failedStarts) + ",\n"; + out += " \"blocked\": ["; + for (size_t i = 0; i < us.blocked.size(); i++) { + if (i > 0) out += ", "; + out += std::to_string(us.blocked[i]); + } + out += "],\n"; + out += " \"for_current\": " + print_build(us.forCurrent) + ",\n"; + out += " \"run_instead\": " + print_build(us.runInstead) + "\n}\n"; + return write_atomic(user_state_path(), out); +} + +// counts a start for this user, root being somewhere they cant write. hands +// back the build to start, which isnt current once current has failed them +// three times. the dart side reads the same file by the same rules +static long long count_for_user(const State& st) { + if (local_dir().empty()) { + log_line(L"theres no LOCALAPPDATA to count starts in, this start isnt counted"); + return st.current; + } + + UserState us; + read_user_state(us); + if (us.forCurrent != st.current) { + // an update went in since. what was counted was the build before it + us.forCurrent = st.current; + us.failedStarts = 0; + us.runInstead = -1; + } + + if (us.runInstead > 0) { + // nothing is counted while on this one, theres no further back to go + if (us.runInstead != st.current && can_start(st, us.runInstead)) return us.runInstead; + + log_line(L"build " + num(us.runInstead) + L" that this user was put back on isnt there any more, starting build " + + num(st.current)); + us.runInstead = -1; + us.failedStarts = 0; + } + + long long run = st.current; + if (us.failedStarts >= 3) { + // a previous that allready failed this user is no better + bool back = st.previous > 0 && st.previous != st.current && !us.is_blocked(st.previous) && + can_start(st, st.previous); + if (back) { + log_line(L"build " + num(st.current) + L" didnt stay up " + num(us.failedStarts) + + L" times in a row for this user, blocking it for them and starting build " + num(st.previous)); + if (!us.is_blocked(st.current)) us.blocked.push_back(st.current); + us.runInstead = st.previous; + us.failedStarts = 0; + run = st.previous; + } else { + log_line(L"build " + num(st.current) + L" keeps failing to start for this user and theres nothing to go back to"); + } + } + if (run == st.current && us.failedStarts < 1000) us.failedStarts++; + + if (!save_user_state(us)) { + log_fail(L"couldnt write " + user_state_path() + L", this start isnt counted", GetLastError()); + } + return run; +} + + +// ---- whats running ---- + +struct Running { + DWORD pid; + std::wstring path; +}; + +// every process we are allowed to ask the path of. the ones we arent belong +// to the system or somebody else, and none of those are the app +static std::vector running() { + std::vector out; + HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snap == INVALID_HANDLE_VALUE) { + log_fail(L"couldnt list whats running", GetLastError()); + return out; + } + PROCESSENTRY32W pe = {}; + pe.dwSize = sizeof(pe); + if (Process32FirstW(snap, &pe)) { + do { + if (pe.th32ProcessID == 0 || pe.th32ProcessID == GetCurrentProcessId()) continue; + HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ProcessID); + if (!proc) continue; + + wchar_t image[2048]; + DWORD len = ARRAYSIZE(image); + if (QueryFullProcessImageNameW(proc, 0, image, &len)) { + Running r; + r.pid = pe.th32ProcessID; + r.path.assign(image, len); + out.push_back(r); + } + CloseHandle(proc); + } while (Process32NextW(snap, &pe)); + } + CloseHandle(snap); + return out; +} + +static bool is_running(const std::wstring& exe) { + std::vector all = running(); + for (size_t i = 0; i < all.size(); i++) { + if (same_text(all[i].path, exe)) return true; + } + return false; +} + + +// ---- starting things ---- + +static bool usable(HANDLE h) { + return h != nullptr && h != INVALID_HANDLE_VALUE; +} + +// `rest` is the raw tail of our own command line and is passed on as it is +static bool start_child(const std::wstring& exe, const std::wstring& cwd, const wchar_t* rest) { + std::wstring cmd = quote_arg(exe); + if (rest && *rest) { + cmd += L" "; + cmd += rest; + } + + // so the app can find its way back without counting folders + SetEnvironmentVariableW(L"GARAGE_UPDATES_ROOT", g_root.c_str()); + SetEnvironmentVariableW(L"GARAGE_UPDATES_STUB", g_self.c_str()); + + STARTUPINFOW mine = {}; + mine.cb = sizeof(mine); + GetStartupInfoW(&mine); + + STARTUPINFOW si = {}; + si.cb = sizeof(si); + // a shortcut set to "run minimised" means the app, not us + if (mine.dwFlags & STARTF_USESHOWWINDOW) { + si.dwFlags |= STARTF_USESHOWWINDOW; + si.wShowWindow = mine.wShowWindow; + } + HANDLE in = GetStdHandle(STD_INPUT_HANDLE); + HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE err = GetStdHandle(STD_ERROR_HANDLE); + BOOL inherit = FALSE; + if (usable(in) || usable(out) || usable(err)) { + // started with pipes. theyre the childs pipes really + si.dwFlags |= STARTF_USESTDHANDLES; + si.hStdInput = in; + si.hStdOutput = out; + si.hStdError = err; + inherit = TRUE; + } + + PROCESS_INFORMATION pi = {}; + if (CreateProcessW(exe.c_str(), &cmd[0], nullptr, nullptr, inherit, 0, nullptr, cwd.c_str(), &si, &pi)) { + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return true; + } + + DWORD why = GetLastError(); + if (why != ERROR_ELEVATION_REQUIRED) { + SetLastError(why); + return false; + } + + // the apps manifest wants admin. CreateProcess wont ask, the shell will + SHELLEXECUTEINFOW sx = {}; + sx.cbSize = sizeof(sx); + sx.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI; + sx.lpFile = exe.c_str(); + sx.lpParameters = rest; + sx.lpDirectory = cwd.c_str(); + sx.nShow = (mine.dwFlags & STARTF_USESHOWWINDOW) ? mine.wShowWindow : SW_SHOWNORMAL; + return ShellExecuteExW(&sx) != FALSE; +} + +static void tell_user(const std::wstring& text) { + std::wstring title = leaf(g_root); + if (title.empty()) title = L"Garage"; + MessageBoxW(nullptr, text.c_str(), title.c_str(), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); +} + +// apply swaps the stub by renaming the running one out of the way, and a +// running exe cant be deleted. so what it leaves gets cleared up by whoever +// comes along next +static void sweep_old_stubs() { + std::wstring prefix = leaf(g_self) + L".old"; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(g_root, prefix + L"*")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) return; + do { + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; + if (!starts_with(fd.cFileName, prefix)) continue; + std::wstring full = join(g_root, fd.cFileName); + if (!DeleteFileW(lp(full).c_str())) log_fail(L"couldnt delete the old stub " + full, GetLastError()); + } while (FindNextFileW(find, &fd)); + FindClose(find); +} + +static int run_app(const wchar_t* rest) { + HANDLE lock = lock_named(L"state", 5000); + // no lock is not a reason to leave somebody with a dead shortcut + + State st; + bool hadFile = read_state(st); + int rc = settle(st, false); + if (rc != kOk) { + unlock(lock); + tell_user(L"This app could not be started because its files are missing. Installing it again will fix that."); + return rc; + } + + // a second click on the shortcut while the app is up. that one hands over + // to the window thats allready there and goes away without ever saying + // its healthy, so counting it would walk a perfectly good build on to + // the block list + bool allreadyUp = is_running(join(version_dir(g_root, st.current), st.exe)); + + const State asRead = st; + long long run = st.current; + + if (!allreadyUp && st.failedStarts >= 3) { + if (st.previous > 0 && st.previous != st.current && can_start(st, st.previous)) { + log_line(L"build " + num(st.current) + L" didnt stay up " + num(st.failedStarts) + + L" times in a row, blocking it and going back to build " + num(st.previous)); + if (!st.is_blocked(st.current)) st.blocked.push_back(st.current); + st.current = st.previous; + st.previous = -1; + st.failedStarts = 0; + } else { + log_line(L"build " + num(st.current) + L" keeps failing to start and theres nothing to go back to"); + } + } + + if (!allreadyUp) { + if (st.failedStarts < 1000) st.failedStarts++; + if (save_state(st)) { + run = st.current; + sweep_old_stubs(); + } else { + // program files, for anybody who isnt elevated. nothing above + // happened then, and the start is counted for the user instead + DWORD err = GetLastError(); + if (err != ERROR_ACCESS_DENIED) { + log_fail(hadFile ? L"couldnt write the state file, counting this start for the user instead" + : L"couldnt write a new state file, counting this start for the user instead", err); + } + st = asRead; + run = count_for_user(st); + } + } + unlock(lock); + + + std::wstring dir = version_dir(g_root, run); + std::wstring exe = join(dir, st.exe); + if (start_child(exe, dir, rest)) return kOk; + + DWORD err = GetLastError(); + log_fail(L"couldnt start " + exe, err); + + // not counted as three strikes, it may only be a virus scanner holding the + // file. the count above still goes up, so a build that is truely broken + // gets blocked the normal way + long long other = run == st.current ? st.previous : st.current; + if (other > 0 && other != run && can_start(st, other)) { + std::wstring oldDir = version_dir(g_root, other); + std::wstring oldExe = join(oldDir, st.exe); + if (start_child(oldExe, oldDir, rest)) { + log_line(L"started build " + num(other) + L" for now instead"); + return kOk; + } + log_fail(L"couldnt start " + oldExe + L" either", GetLastError()); + } + + tell_user(L"This app could not be started (" + win_error(err) + L")."); + return kCantStart; +} + +static int run_exec(const wchar_t* p) { + std::wstring rel; + if (!next_arg(p, rel) || rel.empty()) { + log_line(L"--garage-exec needs the exe to start"); + return kBadArgs; + } + for (size_t i = 0; i < rel.size(); i++) { + if (rel[i] == L'/') rel[i] = L'\\'; + } + + // it has to stay inside the version folder + bool inside = rel[0] != L'\\' && rel.find(L':') == std::wstring::npos; + size_t from = 0; + while (inside && from <= rel.size()) { + size_t to = rel.find(L'\\', from); + if (to == std::wstring::npos) to = rel.size(); + if (rel.compare(from, to - from, L"..") == 0) inside = false; + from = to + 1; + } + if (!inside) { + log_line(L"--garage-exec was given a path that leaves the version folder: " + rel); + return kExecMissing; + } + + State st; + read_state(st); + int rc = settle(st, false); + // not knowing the apps own exe doesnt matter here, we were told which one + if (rc != kOk && rc != kNoExe) return rc; + + std::wstring dir = version_dir(g_root, st.current); + std::wstring exe = join(dir, rel); + if (!exists(exe)) { + log_fail(L"--garage-exec: no " + exe, GetLastError()); + return kExecMissing; + } + if (!start_child(exe, dir, p)) { + log_fail(L"--garage-exec: couldnt start " + exe, GetLastError()); + return kCantStart; + } + return kOk; +} + + +// ---- apply ---- + +static bool move_retry(const std::wstring& from, const std::wstring& to) { + DWORD err = 0; + // a scanner likes to open everything thats just been written + for (int i = 0; i < 15; i++) { + if (MoveFileExW(lp(from).c_str(), lp(to).c_str(), 0)) return true; + err = GetLastError(); + if (err != ERROR_ACCESS_DENIED && err != ERROR_SHARING_VIOLATION) break; + Sleep(200); + } + SetLastError(err); + return false; +} + +// things a run that died left in root. they all start with a dot +static void sweep_leftovers() { + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(g_root, L".*")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) return; + do { + std::wstring name = fd.cFileName; + if (name.compare(0, 8, L".unpack-") != 0 && name.compare(0, 7, L".trash-") != 0) continue; + std::wstring full = join(g_root, name); + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + DWORD err = 0; + if (!remove_tree(full, &err)) log_fail(L"couldnt clear out " + full, err); + } else if (!DeleteFileW(lp(full).c_str())) { + log_fail(L"couldnt delete " + full, GetLastError()); + } + } while (FindNextFileW(find, &fd)); + FindClose(find); +} + +// renamed first, deleted second. the rename is the test: it fails when +// anything inside is still running, and then nothing has been touched +static bool discard_dir(const std::wstring& dir, const std::wstring& tag) { + std::wstring trash = join(g_root, L".trash-" + tag + L"-" + num((long long)GetTickCount())); + if (!MoveFileExW(lp(dir).c_str(), lp(trash).c_str(), 0)) return false; + DWORD err = 0; + if (!remove_tree(trash, &err)) { + // its out of the way at least. the next apply sweeps it + log_fail(L"couldnt finish deleting " + trash, err); + } + return true; +} + +// tar.exe takes its arguments in the ansi code page, so a path with anything +// else in it turns to question marks. this finds a way to say the zip in +// plain ascii: relative to root, or through a hard link in root +static std::wstring zip_for_tar(const std::wstring& zip, std::wstring& link) { + link.clear(); + std::wstring prefix = g_root + L"\\"; + if (starts_with(zip, prefix) && is_ascii(zip.substr(prefix.size()))) return zip.substr(prefix.size()); + if (is_ascii(zip)) return zip; + + std::wstring name = L".unpack-" + num((long long)GetCurrentProcessId()) + L".zip"; + if (CreateHardLinkW(lp(join(g_root, name)).c_str(), lp(zip).c_str(), nullptr)) { + link = join(g_root, name); + return name; + } + log_fail(L"couldnt link " + zip + L" in to root, handing tar the real path and hoping", GetLastError()); + return zip; +} + +static int unpack(const std::wstring& zip, const std::wstring& tmpName) { + wchar_t sys[MAX_PATH]; + UINT n = GetSystemDirectoryW(sys, ARRAYSIZE(sys)); + if (n == 0 || n >= ARRAYSIZE(sys)) { + log_fail(L"couldnt find the system folder", GetLastError()); + return kNoTar; + } + std::wstring tar = join(sys, L"tar.exe"); + if (!exists(tar)) { + log_fail(L"theres no " + tar + L". it comes with windows 10 1803 and later, this one is older", GetLastError()); + return kNoTar; + } + + // what tar has to say goes in a file, and from there in to the log + std::wstring notes = join(g_root, tmpName + L".txt"); + SECURITY_ATTRIBUTES sa = {}; + sa.nLength = sizeof(sa); + sa.bInheritHandle = TRUE; + HANDLE out = CreateFileW(lp(notes).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (out == INVALID_HANDLE_VALUE) { + log_fail(L"couldnt make " + notes + L", unpacking without tars output", GetLastError()); + out = nullptr; + } + + std::wstring link; + std::wstring args = L"-xf " + quote_arg(zip_for_tar(zip, link)) + L" -C " + tmpName; + DWORD code = 1; + // run from root, so the folder to unpack in to is a bare ascii name + bool ran = run_wait(tar, args, g_root, out, code); + DWORD err = GetLastError(); + if (out) CloseHandle(out); + if (!link.empty()) DeleteFileW(lp(link).c_str()); + + std::string said; + read_file(notes, said, 4000); + DeleteFileW(lp(notes).c_str()); + + if (!ran) { + log_fail(L"couldnt run " + tar, err); + return kTarFailed; + } + if (code != 0) { + log_line(L"tar couldnt unpack " + zip + L", it exited " + num((long long)code) + L": " + widen(said)); + return kTarFailed; + } + return kOk; +} + +// a zip of the Release folder itself has everything one level down, and how +// many levels depends on what made it. follow single folders untill theres +// something beside them +static std::wstring content_dir(const std::wstring& top) { + std::wstring dir = top; + for (int depth = 0; depth < 8; depth++) { + std::wstring only; + int dirs = 0, files = 0; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) break; + do { + std::wstring name = fd.cFileName; + if (name == L"." || name == L"..") continue; + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + dirs++; + only = name; + } else { + files++; + } + } while (FindNextFileW(find, &fd)); + FindClose(find); + + if (files != 0 || dirs != 1) break; + dir = join(dir, only); + } + return dir; +} + +static void remove_old_versions(const State& st) { + std::vector have = list_versions(g_root); + for (size_t i = 0; i < have.size(); i++) { + if (have[i] == st.current || have[i] == st.previous) continue; + std::wstring dir = version_dir(g_root, have[i]); + if (!discard_dir(dir, num(have[i]))) { + // something out of it is still running. it goes next time + log_fail(L"left " + dir + L" where it is, its in use", GetLastError()); + } + } +} + +// every build has the stub it was built with in it, as garage_stub.exe. when +// thats not the one in root any more, root gets it. we are the one in root +// and a running exe cant be written over, but it can be renamed +static void refresh_stub(long long build) { + std::wstring fresh = join(version_dir(g_root, build), L"garage_stub.exe"); + if (!exists(fresh)) return; + + std::string theirs, ours; + const size_t cap = 64 * 1024 * 1024; + if (!read_file(fresh, theirs, cap)) { + log_fail(L"couldnt read " + fresh + L", keeping the stub thats here", GetLastError()); + return; + } + if (!read_file(g_self, ours, cap)) { + log_fail(L"couldnt read " + g_self + L" to compare it, keeping the stub thats here", GetLastError()); + return; + } + if (theirs == ours) return; + + // half a file in root would be the end of the install + if (theirs.size() < 1024 || theirs.size() > cap || theirs[0] != 'M' || theirs[1] != 'Z') { + log_line(fresh + L" doesnt look like an exe, keeping the stub thats here"); + return; + } + + std::wstring old = g_self + L".old"; + if (exists(old) && !DeleteFileW(lp(old).c_str())) { + log_fail(L"couldnt delete " + old + L", using another name", GetLastError()); + old += L"-" + num((long long)GetCurrentProcessId()) + L"-" + num((long long)GetTickCount()); + } + if (!move_retry(g_self, old)) { + log_fail(L"couldnt move the stub out of the way, keeping it", GetLastError()); + return; + } + if (!CopyFileW(lp(fresh).c_str(), lp(g_self).c_str(), TRUE)) { + log_fail(L"couldnt copy " + fresh + L" to " + g_self + L", putting the old stub back", GetLastError()); + if (!MoveFileExW(lp(old).c_str(), lp(g_self).c_str(), MOVEFILE_REPLACE_EXISTING)) { + log_fail(L"and the old stub wouldnt go back. it is at " + old + L" and has to be renamed by hand", GetLastError()); + } + return; + } + // `old` is us and stays till the next start + log_line(L"the stub is now the one out of build " + num(build)); +} + +static int apply_locked(const std::wstring& zip, long long build) { + sweep_leftovers(); + sweep_old_stubs(); + + std::wstring tmpName = L".unpack-" + num(build) + L"-" + num((long long)GetCurrentProcessId()); + std::wstring tmp = join(g_root, tmpName); + if (!CreateDirectoryW(lp(tmp).c_str(), nullptr)) { + DWORD err = GetLastError(); + log_fail(L"couldnt make " + tmp, err); + return err == ERROR_ACCESS_DENIED ? kNotWritable : kNoTemp; + } + + State st; + read_state(st); + bool installed = settle(st, true) == kOk; + std::wstring target = version_dir(g_root, build); + + if (installed && st.current == build) { + // asked twice, or the installer run again over itself. the folder is + // the one thats running so it stays as it is + RemoveDirectoryW(lp(tmp).c_str()); + st.failedStarts = 0; + if (!save_state(st)) { + log_fail(L"build " + num(build) + L" is allready current but the state file couldnt be written", GetLastError()); + return kStateWrite; + } + return kOk; + } + + if (exists(target) && !discard_dir(target, num(build))) { + log_fail(L"theres an old " + target + L" in the way and it wont move", GetLastError()); + RemoveDirectoryW(lp(tmp).c_str()); + return kCantPlace; + } + + int rc = unpack(zip, tmpName); + DWORD cleanErr = 0; + if (rc != kOk) { + if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); + return rc; + } + + std::wstring content = content_dir(tmp); + std::wstring exe = st.exe.empty() ? guess_exe(content) : st.exe; + if (exe.empty() || !exists(join(content, exe))) { + log_line(L"unpacked " + zip + L" but " + (exe.empty() ? std::wstring(L"an app exe") : exe) + + L" isnt in it, so its not a build of this app"); + if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); + return exe.empty() ? kNoExe : kBadPackage; + } + + if (!move_retry(content, target)) { + log_fail(L"couldnt move " + content + L" to " + target, GetLastError()); + if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); + return kCantPlace; + } + // whats left is the shell of folders the build was sitting inside + if (content != tmp && !remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); + + + HANDLE lock = lock_named(L"state", 5000); + // read again, the app may have written to it while tar was busy + State now; + read_state(now); + bool hadCurrent = settle(now, true) == kOk && now.current != build; + now.exe = exe; + now.previous = hadCurrent ? now.current : -1; + now.current = build; + now.failedStarts = 0; + // being told to install it outranks an old block + for (size_t i = 0; i < now.blocked.size();) { + if (now.blocked[i] == build) now.blocked.erase(now.blocked.begin() + (ptrdiff_t)i); + else i++; + } + bool saved = save_state(now); + DWORD saveErr = GetLastError(); + unlock(lock); + if (!saved) { + log_fail(L"build " + num(build) + L" is unpacked but the state file couldnt be written", saveErr); + return kStateWrite; + } + + // never a reason to fail, the build is in either way + refresh_stub(build); + + remove_old_versions(now); + log_line(L"build " + num(build) + L" is in, previous is " + (now.previous > 0 ? num(now.previous) : std::wstring(L"none"))); + return kOk; +} + +static int run_apply(const wchar_t* p) { + std::wstring zipArg, buildArg; + if (!next_arg(p, zipArg) || !next_arg(p, buildArg)) { + log_line(L"--garage-apply needs a zip and a build number"); + return kBadArgs; + } + long long build = 0; + if (!parse_version_name(L"app-" + buildArg, build)) { + log_line(L"--garage-apply: \"" + buildArg + L"\" isnt a build number"); + return kBadArgs; + } + + std::wstring zip = absolute(zipArg); + if (file_size(zip) < 0) { + log_fail(L"--garage-apply: no " + zip, GetLastError()); + return kZipMissing; + } + + // one at a time. the second one in waits for the first, it doesnt race it + HANDLE lock = lock_named(L"apply", 120000); + if (!lock) return kBusy; + int rc = apply_locked(zip, build); + unlock(lock); + return rc; +} + + +// ---- uninstall ---- +// the installer leaves what it made in the uninstall entry: the shortcuts as +// GarageShortcuts. so the entry is found by its InstallLocation being us, and +// it says the rest. + +static const wchar_t* kUninstallKey = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + +struct Entry { + bool found = false; + HKEY hive = nullptr; + std::wstring key; + std::wstring name; + std::vector shortcuts; +}; + +static std::wstring reg_text(HKEY key, const wchar_t* sub, const wchar_t* value, DWORD kind) { + DWORD bytes = 0; + if (RegGetValueW(key, sub, value, kind, nullptr, nullptr, &bytes) != ERROR_SUCCESS || bytes < sizeof(wchar_t)) { + return L""; + } + std::wstring out(bytes / sizeof(wchar_t) + 1, L'\0'); + bytes = (DWORD)(out.size() * sizeof(wchar_t)); + if (RegGetValueW(key, sub, value, kind, nullptr, &out[0], &bytes) != ERROR_SUCCESS) return L""; + out.resize(bytes / sizeof(wchar_t)); + return out; +} + +static std::wstring trim_slash(std::wstring p) { + while (!p.empty() && (p[p.size() - 1] == L'\\' || p[p.size() - 1] == L'/' || p[p.size() - 1] == L'\0')) { + p.resize(p.size() - 1); + } + return p; +} + +static bool find_entry(HKEY hive, Entry& out) { + HKEY all = nullptr; + LSTATUS rc = RegOpenKeyExW(hive, kUninstallKey, 0, KEY_READ | KEY_WOW64_64KEY, &all); + if (rc != ERROR_SUCCESS) { + if (rc != ERROR_FILE_NOT_FOUND) log_fail(L"couldnt open the uninstall list", (DWORD)rc); + return false; + } + wchar_t sub[256]; + for (DWORD i = 0;; i++) { + DWORD len = ARRAYSIZE(sub); + rc = RegEnumKeyExW(all, i, sub, &len, nullptr, nullptr, nullptr, nullptr); + if (rc == ERROR_NO_MORE_ITEMS) break; + if (rc != ERROR_SUCCESS) continue; + + std::wstring where = trim_slash(reg_text(all, sub, L"InstallLocation", RRF_RT_REG_SZ)); + if (where.empty() || !same_text(where, g_root)) continue; + + out.found = true; + out.hive = hive; + out.key = std::wstring(kUninstallKey) + L"\\" + sub; + out.name = trim_slash(reg_text(all, sub, L"DisplayName", RRF_RT_REG_SZ)); + + std::wstring multi = reg_text(all, sub, L"GarageShortcuts", RRF_RT_REG_MULTI_SZ); + size_t from = 0; + while (from < multi.size()) { + size_t to = multi.find(L'\0', from); + if (to == std::wstring::npos) to = multi.size(); + if (to > from) out.shortcuts.push_back(multi.substr(from, to - from)); + from = to + 1; + } + break; + } + RegCloseKey(all); + return out.found; +} + +static bool root_writable() { + std::wstring probe = join(g_root, L".probe-" + num((long long)GetCurrentProcessId())); + HANDLE h = CreateFileW(lp(probe).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + CloseHandle(h); + return true; +} + +static bool can_delete_entry(const Entry& entry) { + if (!entry.found) return true; + HKEY k = nullptr; + if (RegOpenKeyExW(entry.hive, entry.key.c_str(), 0, DELETE | KEY_SET_VALUE | KEY_WOW64_64KEY, &k) != ERROR_SUCCESS) { + return false; + } + RegCloseKey(k); + return true; +} + +// anything running out of root has its files locked, and the stash agent has +// no window for anybody to close. so theyre stopped +static void stop_running() { + std::wstring prefix = g_root + L"\\"; + std::vector all = running(); + for (size_t i = 0; i < all.size(); i++) { + // the one thing in root itself is the stub, which may be the + // un-elevated us waiting on the elevated us + if (!starts_with(all[i].path, prefix) || same_text(all[i].path, g_self)) continue; + + HANDLE proc = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, all[i].pid); + if (!proc) { + log_fail(L"couldnt open " + all[i].path + L" to stop it", GetLastError()); + continue; + } + if (!TerminateProcess(proc, 1)) { + log_fail(L"couldnt stop " + all[i].path, GetLastError()); + } else { + WaitForSingleObject(proc, 5000); + } + CloseHandle(proc); + } +} + +// we cant delete ourselves while running. cmd waits a couple of seconds and +// does it, then takes root away if its empty by then. the paths go through +// the environment so nothing in them (a %, an &) gets read as part of the +// command +static void delete_self_later() { + wchar_t sys[MAX_PATH]; + UINT n = GetSystemDirectoryW(sys, ARRAYSIZE(sys)); + if (n == 0 || n >= ARRAYSIZE(sys)) { + log_fail(L"couldnt find the system folder, the stub is left behind", GetLastError()); + return; + } + SetEnvironmentVariableW(L"GARAGE_RM_EXE", g_self.c_str()); + SetEnvironmentVariableW(L"GARAGE_RM_DIR", g_root.c_str()); + + std::wstring cmd = join(sys, L"cmd.exe"); + std::wstring line = quote_arg(cmd) + + L" /d /s /c \"ping -n 3 127.0.0.1 >nul" + L" & del /f /q \"%GARAGE_RM_EXE%\" >nul 2>&1" + L" & ping -n 4 127.0.0.1 >nul" + L" & (if exist \"%GARAGE_RM_EXE%\" del /f /q \"%GARAGE_RM_EXE%\" >nul 2>&1)" + L" & rd \"%GARAGE_RM_DIR%\" >nul 2>&1\""; + + STARTUPINFOW si = {}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi = {}; + // started in system32. if it sat in root, root could never be removed + if (!CreateProcessW(cmd.c_str(), &line[0], nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, sys, &si, &pi)) { + log_fail(L"couldnt start cmd to remove the stub, its left behind", GetLastError()); + return; + } + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); +} + +static int run_uninstall(const wchar_t* p) { + bool quiet = false, elevated = false; + std::wstring a; + while (next_arg(p, a)) { + if (a == L"--quiet") quiet = true; + if (a == L"--elevated") elevated = true; + } + + Entry entry; + if (!find_entry(HKEY_CURRENT_USER, entry)) find_entry(HKEY_LOCAL_MACHINE, entry); + + // a copy of the stub run from the desktop mustnt go deleting whats around it + if (!entry.found && !exists(state_path(g_root))) { + log_line(L"--garage-uninstall: " + g_root + L" isnt an install, not touching it"); + return kNotAnInstall; + } + + std::wstring name = entry.name.empty() ? leaf(g_root) : entry.name; + if (!quiet) { + std::wstring ask = L"Remove " + name + L" and all of its files from this PC?"; + if (MessageBoxW(nullptr, ask.c_str(), name.c_str(), MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND) != IDYES) { + return kCancelled; + } + } + + if (!root_writable() || !can_delete_entry(entry)) { + if (elevated) { + log_fail(L"--garage-uninstall: elevated and still cant write to " + g_root, GetLastError()); + return kNoElevation; + } + // an "everyone" install. settings starts the uninstaller as the user + SHELLEXECUTEINFOW sx = {}; + sx.cbSize = sizeof(sx); + sx.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC; + sx.lpVerb = L"runas"; + sx.lpFile = g_self.c_str(); + sx.lpParameters = L"--garage-uninstall --quiet --elevated"; + sx.nShow = SW_HIDE; + if (!ShellExecuteExW(&sx) || !sx.hProcess) { + DWORD err = GetLastError(); + log_fail(L"--garage-uninstall: couldnt get administrator permission", err); + return err == ERROR_CANCELLED ? kCancelled : kNoElevation; + } + WaitForSingleObject(sx.hProcess, INFINITE); + DWORD code = (DWORD)kNoElevation; + GetExitCodeProcess(sx.hProcess, &code); + CloseHandle(sx.hProcess); + if (code != 0 && !quiet) { + tell_user(name + L" could not be removed completely. Close it and try again."); + } + return (int)code; + } + + + stop_running(); + + // the files first. if some wont go, the entry and the shortcuts stay so + // it can be tried again from the same place + bool clean = true; + std::vector have = list_versions(g_root); + for (size_t i = 0; i < have.size(); i++) { + std::wstring dir = version_dir(g_root, have[i]); + DWORD err = 0; + if (!remove_tree(dir, &err)) { + log_fail(L"--garage-uninstall: couldnt remove " + dir, err); + clean = false; + } + } + if (!clean) { + if (!quiet) tell_user(name + L" could not be removed completely. Close it and try again."); + return kLeftovers; + } + + sweep_leftovers(); + sweep_old_stubs(); + State st; + read_state(st); + std::wstring appId = st.extra("app_id"); + + std::wstring staging = join(g_root, L"staging"); + DWORD err = 0; + if (exists(staging) && !remove_tree(staging, &err)) log_fail(L"--garage-uninstall: couldnt remove " + staging, err); + + // downloads for an "everyone" install go here instead. only that folder, + // whatever else the app keeps beside it is the users + std::wstring local = env(L"LOCALAPPDATA"); + if (!local.empty()) { + std::wstring mine = join(local, appId.empty() ? leaf(g_root) : appId); + std::wstring theirs = join(mine, L"staging"); + err = 0; + if (exists(theirs) && !remove_tree(theirs, &err)) log_fail(L"--garage-uninstall: couldnt remove " + theirs, err); + DeleteFileW(lp(join(mine, L"garage_updates.log")).c_str()); + DeleteFileW(lp(join(mine, L"garage_updates.log.old")).c_str()); + // the count of starts, when it was kept out here + std::wstring counts = join(mine, L"garage_updates.json"); + if (exists(counts) && !DeleteFileW(lp(counts).c_str())) { + log_fail(L"--garage-uninstall: couldnt delete " + counts, GetLastError()); + } + // only goes if that left it empty + RemoveDirectoryW(lp(mine).c_str()); + } + + for (size_t i = 0; i < entry.shortcuts.size(); i++) { + const std::wstring& lnk = entry.shortcuts[i]; + // its a list out of the registry. only ever delete a shortcut off it + if (lnk.size() < 5 || !same_text(lnk.substr(lnk.size() - 4), L".lnk")) continue; + if (!DeleteFileW(lp(lnk).c_str())) { + DWORD why = GetLastError(); + if (why != ERROR_FILE_NOT_FOUND && why != ERROR_PATH_NOT_FOUND) { + log_fail(L"--garage-uninstall: couldnt delete " + lnk, why); + clean = false; + } + } + } + + if (entry.found) { + LSTATUS rc = RegDeleteKeyExW(entry.hive, entry.key.c_str(), KEY_WOW64_64KEY, 0); + if (rc != ERROR_SUCCESS && rc != ERROR_FILE_NOT_FOUND) { + log_fail(L"--garage-uninstall: couldnt remove the uninstall entry", (DWORD)rc); + clean = false; + } + } + + std::wstring statePath = state_path(g_root); + if (exists(statePath) && !DeleteFileW(lp(statePath).c_str())) { + log_fail(L"--garage-uninstall: couldnt delete " + statePath, GetLastError()); + clean = false; + } + + // the log goes last and only when theres nothing in it worth keeping + if (clean) { + DeleteFileW(lp(join(g_root, L"garage_updates.log")).c_str()); + DeleteFileW(lp(join(g_root, L"garage_updates.log.old")).c_str()); + } + delete_self_later(); + return clean ? kOk : kLeftovers; +} + + +static bool find_self() { + std::wstring buf(512, L'\0'); + for (;;) { + DWORD n = GetModuleFileNameW(nullptr, &buf[0], (DWORD)buf.size()); + if (n == 0) return false; + if (n < buf.size()) { + buf.resize(n); + break; + } + if (buf.size() > 40000) return false; + buf.resize(buf.size() * 2); + } + // started through a \\?\ path. nothing after us wants the prefix + if (buf.compare(0, 8, L"\\\\?\\UNC\\") == 0) buf = L"\\\\" + buf.substr(8); + else if (buf.compare(0, 4, L"\\\\?\\") == 0) buf = buf.substr(4); + + g_self = buf; + g_root = parent(buf); + return !g_root.empty(); +} + +int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { + if (!find_self()) { + log_fail(L"couldnt work out where the stub is", GetLastError()); + return kNoSelf; + } + + // only for where the fallback log goes, so a state file that wont read is + // not worth a word here. whoever needs it properly says so + std::string text; + State peek; + if (read_file(state_path(g_root), text, 1024 * 1024) && parse_state(text, peek)) g_appId = peek.extra("app_id"); + if (g_appId.find_first_of(L"\\/:*?\"<>|") != std::wstring::npos) g_appId.clear(); + + + const wchar_t* rest = skip_program(GetCommandLineW()); + const wchar_t* after = rest; + std::wstring first; + if (next_arg(after, first)) { + if (first == L"--garage-exec") return run_exec(after); + if (first == L"--garage-apply") return run_apply(after); + if (first == L"--garage-uninstall") return run_uninstall(after); + } + return run_app(rest); +} diff --git a/garage_updates/windows/stub/garage_stub.exe.manifest b/garage_updates/windows/stub/garage_stub.exe.manifest new file mode 100644 index 0000000..7bbef11 --- /dev/null +++ b/garage_updates/windows/stub/garage_stub.exe.manifest @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + PerMonitorV2 + true + + + diff --git a/garage_updates/windows/stub/garage_stub.rc.in b/garage_updates/windows/stub/garage_stub.rc.in new file mode 100644 index 0000000..84d84e3 --- /dev/null +++ b/garage_updates/windows/stub/garage_stub.rc.in @@ -0,0 +1,9 @@ +// the stub is what the shortcuts point at, so it wears the apps icon +#pragma code_page(65001) + +@GARAGE_STUB_ICON_LINE@ + +// msvc gets the manifest handed to the linker instead, two of them collide +#ifdef GARAGE_RC_MANIFEST +1 24 "@GARAGE_STUB_MANIFEST_FILE@" +#endif diff --git a/garage_updates/windows_installer/CMakeLists.txt b/garage_updates/windows_installer/CMakeLists.txt new file mode 100644 index 0000000..8d85f6c --- /dev/null +++ b/garage_updates/windows_installer/CMakeLists.txt @@ -0,0 +1,114 @@ +# the first-time installer for an app that uses garage_updates. built once by +# the developer, per app: +# +# cmake -S . -B build -A x64 -DGARAGE_APP_NAME="Garage Stash" -DGARAGE_APP_ID=net.imbenji.stash +# -DGARAGE_PROJECT_ID= -DGARAGE_EXE_NAME=garage_stash.exe -DGARAGE_ICON=C:/.../app_icon.ico +# cmake --build build --config Release +# +# and out comes "-Setup.exe" with the stub inside it. build_installer.bat +# does the same with shorter flags. +cmake_minimum_required(VERSION 3.15) +project(garage_installer LANGUAGES CXX) + +# static runtime, its handed to people who have nothing installed yet +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + +set(GARAGE_APP_NAME "" CACHE STRING "The apps name as people see it") +set(GARAGE_APP_ID "" CACHE STRING "A stable id, e.g. net.imbenji.stash. Names the uninstall entry") +set(GARAGE_PROJECT_ID "" CACHE STRING "The Garage project the releases are published on") +set(GARAGE_EXE_NAME "" CACHE STRING "The apps exe inside a build, e.g. garage_stash.exe") +set(GARAGE_API_BASE "https://pay.imbenji.net/api" CACHE STRING "Where the update check goes") +set(GARAGE_PUBLISHER "" CACHE STRING "Shown in Installed apps. Optional") +set(GARAGE_ICON "" CACHE FILEPATH "An .ico for the installer, the stub and the shortcuts. Optional") +set(GARAGE_DEFAULT_LOCATION "me" CACHE STRING "me (LocalAppData) or everyone (Program Files)") +option(GARAGE_SHOW_CHOICE "Ask just me / everyone. Off goes with the default without asking" ON) +option(GARAGE_DESKTOP_SHORTCUT "A desktop shortcut as well as the start menu one" OFF) + +foreach(_needed GARAGE_APP_NAME GARAGE_APP_ID GARAGE_PROJECT_ID GARAGE_EXE_NAME) + if("${${_needed}}" STREQUAL "") + message(FATAL_ERROR "${_needed} has to be set, e.g. -D${_needed}=...") + endif() +endforeach() +if(NOT GARAGE_EXE_NAME MATCHES "\\.exe$") + message(FATAL_ERROR "GARAGE_EXE_NAME is the file name with .exe on it, got \"${GARAGE_EXE_NAME}\"") +endif() +if(GARAGE_APP_ID MATCHES "[\\\\/:*?\"<>| ]") + message(FATAL_ERROR "GARAGE_APP_ID ends up as a folder and a registry key, keep it to letters, digits, dots and dashes") +endif() +if(NOT GARAGE_DEFAULT_LOCATION MATCHES "^(me|everyone)$") + message(FATAL_ERROR "GARAGE_DEFAULT_LOCATION is me or everyone, got \"${GARAGE_DEFAULT_LOCATION}\"") +endif() +if(GARAGE_ICON AND NOT EXISTS "${GARAGE_ICON}") + message(FATAL_ERROR "GARAGE_ICON: theres no ${GARAGE_ICON}") +endif() + + +# these land inside L"..." in a header +foreach(_text GARAGE_APP_NAME GARAGE_APP_ID GARAGE_PROJECT_ID GARAGE_EXE_NAME GARAGE_API_BASE GARAGE_PUBLISHER) + string(REPLACE "\\" "\\\\" ${_text}_C "${${_text}}") + string(REPLACE "\"" "\\\"" ${_text}_C "${${_text}_C}") +endforeach() +# no slash on the end, the code puts its own on +string(REGEX REPLACE "/+$" "" GARAGE_API_BASE_C "${GARAGE_API_BASE_C}") + +set(GARAGE_DEFAULT_EVERYONE_C 0) +if(GARAGE_DEFAULT_LOCATION STREQUAL "everyone") + set(GARAGE_DEFAULT_EVERYONE_C 1) +endif() +set(GARAGE_SHOW_CHOICE_C 0) +if(GARAGE_SHOW_CHOICE) + set(GARAGE_SHOW_CHOICE_C 1) +endif() +set(GARAGE_DESKTOP_SHORTCUT_C 0) +if(GARAGE_DESKTOP_SHORTCUT) + set(GARAGE_DESKTOP_SHORTCUT_C 1) +endif() + +set(_generated "${CMAKE_CURRENT_BINARY_DIR}/generated") +configure_file("installer_config.h.in" "${_generated}/installer_config.h" @ONLY) + + +# the stub is the plugins one, built here with this apps icon on it and put +# somewhere the .rc can name +set(_stub_dir "${CMAKE_CURRENT_SOURCE_DIR}/../windows/stub") +set(GARAGE_STUB_ICON "${GARAGE_ICON}") +set(GARAGE_STUB_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/stub_out") +add_subdirectory("${_stub_dir}" "${CMAKE_CURRENT_BINARY_DIR}/stub") +set(GARAGE_STUB_FILE "${GARAGE_STUB_OUT_DIR}/garage_stub.exe") + +set(GARAGE_ICON_LINE "") +if(GARAGE_ICON) + file(TO_CMAKE_PATH "${GARAGE_ICON}" _icon) + set(GARAGE_ICON_LINE "1 ICON \"${_icon}\"") +endif() +set(GARAGE_MANIFEST_FILE "${CMAKE_CURRENT_SOURCE_DIR}/installer.exe.manifest") +configure_file("installer.rc.in" "${_generated}/installer.rc" @ONLY) + +set(_sources "installer.cpp" "${_generated}/installer_config.h" "${_generated}/installer.rc") +if(MSVC) + list(APPEND _sources "installer.exe.manifest") +endif() + +add_executable(garage_installer WIN32 ${_sources}) +target_compile_features(garage_installer PRIVATE cxx_std_17) +target_compile_definitions(garage_installer PRIVATE UNICODE _UNICODE) +target_include_directories(garage_installer PRIVATE "${_generated}" "${_stub_dir}") +if(MSVC) + target_compile_options(garage_installer PRIVATE /W4 /EHsc /utf-8) +else() + # not msvc, so nothing merges the manifest for us. it goes in through the .rc + set_property(SOURCE "${_generated}/installer.rc" APPEND PROPERTY COMPILE_DEFINITIONS GARAGE_RC_MANIFEST) +endif() +if(MINGW) + target_link_options(garage_installer PRIVATE -municode "-Wl,--subsystem,windows") +endif() +target_link_libraries(garage_installer PRIVATE + user32 shell32 advapi32 ole32 uuid comctl32 winhttp bcrypt) + +# the .rc pulls the stub in as a file, which cmake cant see for itself +add_dependencies(garage_installer garage_stub) +set_property(SOURCE "${_generated}/installer.rc" APPEND PROPERTY OBJECT_DEPENDS "${GARAGE_STUB_FILE}") + +# the name with whatever a file name cant have taken out +string(REGEX REPLACE "[\\\\/:*?\"<>|]" "" _file_name "${GARAGE_APP_NAME}") +set_target_properties(garage_installer PROPERTIES OUTPUT_NAME "${_file_name}-Setup") diff --git a/garage_updates/windows_installer/build_installer.bat b/garage_updates/windows_installer/build_installer.bat new file mode 100644 index 0000000..f93f959 --- /dev/null +++ b/garage_updates/windows_installer/build_installer.bat @@ -0,0 +1,82 @@ +@echo off +setlocal + +rem builds "-Setup.exe" for one app. needs cmake and visual studio's +rem c++ tools, the same things flutter build windows needs. +rem +rem build_installer.bat --name "Garage Stash" --id net.imbenji.stash ^ +rem --project --exe garage_stash.exe ^ +rem --icon C:\path\app_icon.ico +rem +rem optional: +rem --api where the update check goes (default pay.imbenji.net/api) +rem --publisher "" shown in Installed apps +rem --default me^|everyone which one is ticked to begin with (default me) +rem --hide-choice dont ask, go with the default +rem --desktop a desktop shortcut as well +rem --arch x64^|arm64 default x64 +rem --out where the exe is put (default: the folder youre in) + +set "HERE=%~dp0" +set "NAME=" +set "ID=" +set "PROJECT=" +set "EXE=" +set "ICON=" +set "API=https://pay.imbenji.net/api" +set "PUBLISHER=" +set "LOCATION=me" +set "CHOICE=ON" +set "DESKTOP=OFF" +set "ARCH=x64" +set "OUT=%CD%" + +:args +if "%~1"=="" goto run +if /i "%~1"=="--name" ( set "NAME=%~2" & shift & shift & goto args ) +if /i "%~1"=="--id" ( set "ID=%~2" & shift & shift & goto args ) +if /i "%~1"=="--project" ( set "PROJECT=%~2" & shift & shift & goto args ) +if /i "%~1"=="--exe" ( set "EXE=%~2" & shift & shift & goto args ) +if /i "%~1"=="--icon" ( set "ICON=%~f2" & shift & shift & goto args ) +if /i "%~1"=="--api" ( set "API=%~2" & shift & shift & goto args ) +if /i "%~1"=="--publisher" ( set "PUBLISHER=%~2" & shift & shift & goto args ) +if /i "%~1"=="--default" ( set "LOCATION=%~2" & shift & shift & goto args ) +if /i "%~1"=="--arch" ( set "ARCH=%~2" & shift & shift & goto args ) +if /i "%~1"=="--out" ( set "OUT=%~f2" & shift & shift & goto args ) +if /i "%~1"=="--hide-choice" ( set "CHOICE=OFF" & shift & goto args ) +if /i "%~1"=="--desktop" ( set "DESKTOP=ON" & shift & goto args ) +echo build_installer: dont know what "%~1" is +exit /b 2 + +:run +if "%NAME%"=="" ( echo build_installer: --name is needed & exit /b 2 ) +if "%ID%"=="" ( echo build_installer: --id is needed & exit /b 2 ) +if "%PROJECT%"=="" ( echo build_installer: --project is needed & exit /b 2 ) +if "%EXE%"=="" ( echo build_installer: --exe is needed & exit /b 2 ) + +set "VSARCH=x64" +if /i "%ARCH%"=="arm64" set "VSARCH=ARM64" + +rem one build folder per app and arch, so two apps dont share a cache +set "BUILD=%HERE%build\%ID%-%ARCH%" + +rem cmake wants forward slashes in a path it is going to paste in to an .rc +if defined ICON set "ICON=%ICON:\=/%" + +cmake -S "%HERE%." -B "%BUILD%" -A %VSARCH% ^ + "-DGARAGE_APP_NAME=%NAME%" "-DGARAGE_APP_ID=%ID%" "-DGARAGE_PROJECT_ID=%PROJECT%" ^ + "-DGARAGE_EXE_NAME=%EXE%" "-DGARAGE_API_BASE=%API%" "-DGARAGE_PUBLISHER=%PUBLISHER%" ^ + "-DGARAGE_ICON=%ICON%" "-DGARAGE_DEFAULT_LOCATION=%LOCATION%" ^ + -DGARAGE_SHOW_CHOICE=%CHOICE% -DGARAGE_DESKTOP_SHORTCUT=%DESKTOP% +if errorlevel 1 ( echo build_installer: cmake couldnt set the build up & exit /b 1 ) + +cmake --build "%BUILD%" --config Release +if errorlevel 1 ( echo build_installer: the build failed & exit /b 1 ) + +if not exist "%OUT%" mkdir "%OUT%" +copy /y "%BUILD%\Release\*-Setup.exe" "%OUT%\" >nul +if errorlevel 1 ( echo build_installer: built, but couldnt copy the exe out of %BUILD%\Release & exit /b 1 ) + +echo. +echo the installer is in %OUT% +endlocal diff --git a/garage_updates/windows_installer/installer.cpp b/garage_updates/windows_installer/installer.cpp new file mode 100644 index 0000000..f4ee555 --- /dev/null +++ b/garage_updates/windows_installer/installer.cpp @@ -0,0 +1,1107 @@ +// the first-time installer. one exe, nothing beside it: the stub rides along +// as a resource and everything else comes from garage. +// +// asks who its for (if the developer left that on), asks garage what the +// newest windows build is, downloads it, checks the sha256, puts the stub in +// and has the stub unpack the zip, so theres one bit of code that knows +// how a version folder is made. then a start menu shortcut, an entry in +// "installed apps", and the app is started. +// +// who its for decides where it goes: +// just me %LOCALAPPDATA%\Programs\, nothing needs admin, ever +// everyone %ProgramFiles%\, and we start ourselves again elevated +// +// the window is a task dialog. windows lays it out and draws it, theres no +// layout code in here to get wrong on somebody elses dpi. + +#include "garage_common.h" +#include "installer_config.h" + +#include +#include +#include +#include +#include +#include + +using namespace garage; + +enum { kExitOk = 0, kExitFailed = 1, kExitCancelled = 2 }; + +enum { ID_INSTALL = 1001 }; +enum { RADIO_ME = 2001, RADIO_EVERYONE = 2002 }; +enum Page { PAGE_CHOICE, PAGE_PROGRESS, PAGE_ERROR }; + +static const wchar_t* kAppName = GARAGE_APP_NAME; +static const wchar_t* kPublisher = GARAGE_PUBLISHER; +static const wchar_t* kUserAgent = L"garage_updates-installer/1"; + +static bool g_everyone = GARAGE_DEFAULT_EVERYONE != 0; +static bool g_showChoice = GARAGE_SHOW_CHOICE != 0; +static bool g_desktopShortcut = GARAGE_DESKTOP_SHORTCUT != 0; +// started by ourselves through the uac prompt. the one that asked is still +// there waiting, and its the one that starts the app afterwards +static bool g_elevatedChild = false; + +static Page g_page = PAGE_CHOICE; +static int g_exit = kExitCancelled; +static HANDLE g_child = nullptr; +static HICON g_icon = nullptr; + +static HANDLE g_worker = nullptr; +static volatile LONG g_cancel = 0; +static bool g_marquee = false; +static std::wstring g_shown; + +// what the worker thread has to say to the window. the window reads it on a timer +static CRITICAL_SECTION g_lock; +static struct { + std::wstring status; + int permille = -1; // -1 is "no idea how long", the bar just slides + bool done = false; + bool ok = false; + std::wstring error; +} g_progress; + +static std::wstring g_logDir; + + +// ---- small things ---- + +static void log_line(const std::wstring& msg) { + OutputDebugStringW((L"garage_setup: " + msg + L"\n").c_str()); + if (g_logDir.empty()) return; + + SYSTEMTIME t; + GetLocalTime(&t); + wchar_t stamp[48]; + wsprintfW(stamp, L"%04d-%02d-%02d %02d:%02d:%02d ", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); + std::string bytes = narrow(stamp + msg) + "\r\n"; + + HANDLE h = CreateFileW(lp(join(g_logDir, L"setup.log")).c_str(), FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + OutputDebugStringW(L"garage_setup: and the log couldnt be opened\n"); + return; + } + DWORD wrote = 0; + WriteFile(h, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr); + CloseHandle(h); +} + +static void log_fail(const std::wstring& what, DWORD err) { + log_line(what + L" (win32 " + win_error(err) + L")"); +} + +static bool cancelled() { + return InterlockedCompareExchange(&g_cancel, 0, 0) != 0; +} + +static void set_status(const std::wstring& status, int permille) { + EnterCriticalSection(&g_lock); + g_progress.status = status; + g_progress.permille = permille; + LeaveCriticalSection(&g_lock); +} + +static std::wstring shell_folder(int csidl) { + wchar_t buf[MAX_PATH]; + HRESULT hr = SHGetFolderPathW(nullptr, csidl | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, buf); + if (FAILED(hr)) { + log_fail(L"couldnt find shell folder " + num(csidl), (DWORD)hr); + return L""; + } + return buf; +} + +// the app name is a folder name and a shortcut name as well +static std::wstring file_safe(const std::wstring& name) { + std::wstring out; + for (size_t i = 0; i < name.size(); i++) { + wchar_t c = name[i]; + if (c < 32 || wcschr(L"\\/:*?\"<>|", c)) continue; + out += c; + } + while (!out.empty() && (out[out.size() - 1] == L' ' || out[out.size() - 1] == L'.')) out.resize(out.size() - 1); + return out.empty() ? std::wstring(L"App") : out; +} + +static std::wstring install_root(bool everyone) { + std::wstring base = everyone ? shell_folder(CSIDL_PROGRAM_FILES) + : join(shell_folder(CSIDL_LOCAL_APPDATA), L"Programs"); + return join(base, file_safe(kAppName)); +} + +static bool is_admin() { + HANDLE token = nullptr; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false; + TOKEN_ELEVATION info = {}; + DWORD size = 0; + BOOL ok = GetTokenInformation(token, TokenElevation, &info, sizeof(info), &size); + CloseHandle(token); + return ok && info.TokenIsElevated != 0; +} + +// the machine, not us. an x64 build of this runs fine on an arm64 pc and +// should still ask for the arm64 app +static const wchar_t* native_arch() { + typedef BOOL (WINAPI *Wow64Fn)(HANDLE, USHORT*, USHORT*); + HMODULE k32 = GetModuleHandleW(L"kernel32.dll"); + Wow64Fn fn = k32 ? (Wow64Fn)(void*)GetProcAddress(k32, "IsWow64Process2") : nullptr; + USHORT process = 0, machine = 0; + if (fn && fn(GetCurrentProcess(), &process, &machine)) { + return machine == 0xAA64 ? L"arm64" : L"x64"; + } +#if defined(_M_ARM64) || defined(__aarch64__) + return L"arm64"; +#else + return L"x64"; +#endif +} + + +// ---- http ---- + +struct Http { + HINTERNET session = nullptr; + HINTERNET conn = nullptr; + HINTERNET req = nullptr; + DWORD status = 0; +}; + +static void http_end(Http& h) { + DWORD keep = GetLastError(); + if (h.req) WinHttpCloseHandle(h.req); + if (h.conn) WinHttpCloseHandle(h.conn); + if (h.session) WinHttpCloseHandle(h.session); + h = Http(); + SetLastError(keep); +} + +// sends a GET and reads as far as the status. redirects are followed by +// winhttp, and it carries the Range header along to wherever they lead +static bool http_begin(Http& h, const std::wstring& url, long long from) { + URL_COMPONENTS u = {}; + u.dwStructSize = sizeof(u); + u.dwSchemeLength = (DWORD)-1; + u.dwHostNameLength = (DWORD)-1; + u.dwUrlPathLength = (DWORD)-1; + u.dwExtraInfoLength = (DWORD)-1; + if (!WinHttpCrackUrl(url.c_str(), 0, 0, &u)) return false; + + std::wstring host(u.lpszHostName, u.dwHostNameLength); + std::wstring path(u.lpszUrlPath, u.dwUrlPathLength); + if (u.lpszExtraInfo) path.append(u.lpszExtraInfo, u.dwExtraInfoLength); + if (path.empty()) path = L"/"; + bool secure = u.nScheme == INTERNET_SCHEME_HTTPS; + + h.session = WinHttpOpen(kUserAgent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, 0); + if (!h.session) { + // windows before 8.1 doesnt know that one + h.session = WinHttpOpen(kUserAgent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, 0); + } + if (!h.session) return false; + + DWORD tls = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; +#ifdef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 + DWORD newer = tls | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; + if (!WinHttpSetOption(h.session, WINHTTP_OPTION_SECURE_PROTOCOLS, &newer, sizeof(newer))) +#endif + { + if (!WinHttpSetOption(h.session, WINHTTP_OPTION_SECURE_PROTOCOLS, &tls, sizeof(tls))) { + log_fail(L"couldnt pick the tls versions, using what windows defaults to", GetLastError()); + } + } + WinHttpSetTimeouts(h.session, 15000, 15000, 30000, 30000); + + h.conn = WinHttpConnect(h.session, host.c_str(), u.nPort, 0); + if (!h.conn) { http_end(h); return false; } + + h.req = WinHttpOpenRequest(h.conn, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, + WINHTTP_DEFAULT_ACCEPT_TYPES, secure ? WINHTTP_FLAG_SECURE : 0); + if (!h.req) { http_end(h); return false; } + + if (from > 0) { + std::wstring range = L"Range: bytes=" + num(from) + L"-"; + if (!WinHttpAddRequestHeaders(h.req, range.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD)) { + http_end(h); + return false; + } + } + + if (!WinHttpSendRequest(h.req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || + !WinHttpReceiveResponse(h.req, nullptr)) { + http_end(h); + return false; + } + + DWORD size = sizeof(h.status); + if (!WinHttpQueryHeaders(h.req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, &h.status, &size, WINHTTP_NO_HEADER_INDEX)) { + http_end(h); + return false; + } + return true; +} + +static std::wstring http_header(Http& h, DWORD which) { + wchar_t buf[256]; + DWORD size = sizeof(buf); + if (!WinHttpQueryHeaders(h.req, which, WINHTTP_HEADER_NAME_BY_INDEX, buf, &size, WINHTTP_NO_HEADER_INDEX)) { + return L""; + } + return std::wstring(buf, size / sizeof(wchar_t)); +} + +static bool http_text(const std::wstring& url, DWORD& status, std::string& body) { + Http h; + if (!http_begin(h, url, 0)) return false; + status = h.status; + body.clear(); + char chunk[8192]; + for (;;) { + DWORD got = 0; + if (!WinHttpReadData(h.req, chunk, sizeof(chunk), &got)) { + http_end(h); + return false; + } + if (got == 0) break; + body.append(chunk, got); + // its a few hundred bytes of json. anything like this isnt it + if (body.size() > 1024 * 1024) break; + } + http_end(h); + return true; +} + + +// ---- the release ---- + +struct Release { + long long build = 0; + std::wstring label; + std::wstring url; + std::wstring sha256; + long long size = 0; +}; + +static bool ask_garage(const wchar_t* arch, Release& out, bool& none, std::wstring& error) { + none = false; + std::wstring url = std::wstring(GARAGE_API_BASE) + L"/v1/updates/" + GARAGE_PROJECT_ID + + L"?platform=windows&arch=" + arch; + DWORD status = 0; + std::string body; + if (!http_text(url, status, body)) { + DWORD err = GetLastError(); + log_fail(L"couldnt ask " + url, err); + error = L"Could not reach the download server. Check your internet connection.\n\n(" + win_error(err) + L")"; + return false; + } + + JVal json; + bool parsed = json_parse(body, json) && json.kind == JVal::Obj; + if (status != 200 || !parsed) { + std::wstring said = parsed ? widen(json.str("message")) : L""; + log_line(url + L" answered " + num(status) + L": " + widen(body.substr(0, 400))); + error = L"The download server gave an answer that makes no sense (" + num(status) + L")."; + if (!said.empty()) error += L"\n\n" + said; + return false; + } + + const JVal* latest = json.get("latest"); + const JVal* asset = latest ? latest->get("asset") : nullptr; + if (!latest || latest->kind != JVal::Obj || !asset || asset->kind != JVal::Obj) { + none = true; + return false; + } + + out.build = latest->number("build", 0); + out.label = widen(latest->str("label")); + out.url = widen(asset->str("url")); + out.sha256 = widen(asset->str("sha256")); + out.size = asset->number("size", 0); + std::string format = asset->str("format"); + + if (format != "zip") { + log_line(L"the windows asset of build " + num(out.build) + L" is a " + widen(format) + L", it has to be a zip"); + error = L"The newest release is not in a form this installer can use."; + return false; + } + bool http = out.url.compare(0, 8, L"https://") == 0 || out.url.compare(0, 7, L"http://") == 0; + if (out.build <= 0 || !http || out.sha256.size() != 64) { + log_line(L"the release that came back is missing things: " + widen(body.substr(0, 400))); + error = L"The download server gave an answer that makes no sense."; + return false; + } + return true; +} + +// one go at it. true is "the whole file is there". false with `again` set is +// "ask once more, itll carry on from where this got to" +static bool download_once(const Release& rel, const std::wstring& part, bool& again, std::wstring& error) { + again = false; + long long have = file_size(part); + if (have < 0) have = 0; + if (rel.size > 0 && have == rel.size) return true; + if (rel.size > 0 && have > rel.size) { + // not ours, or a different build that got the same name + DeleteFileW(lp(part).c_str()); + have = 0; + } + + Http h; + if (!http_begin(h, rel.url, have)) { + DWORD err = GetLastError(); + log_fail(L"couldnt start the download", err); + error = L"The download could not be started. Check your internet connection.\n\n(" + win_error(err) + L")"; + again = true; + return false; + } + + bool append = false; + if (h.status == 206 && have > 0) { + // "bytes 1000-1999/2000". if it isnt carrying on from where we are, start over + std::wstring range = http_header(h, WINHTTP_QUERY_CONTENT_RANGE); + std::wstring want = L"bytes " + num(have) + L"-"; + append = range.compare(0, want.size(), want) == 0; + if (!append) { + log_line(L"asked to resume at " + num(have) + L" and got \"" + range + L"\", starting again"); + http_end(h); + DeleteFileW(lp(part).c_str()); + again = true; + return false; + } + } else if (h.status == 416) { + // what we have is longer than the file is + http_end(h); + DeleteFileW(lp(part).c_str()); + again = true; + return false; + } else if (h.status != 200) { + log_line(L"the download answered " + num(h.status)); + error = L"The download server refused the download (" + num(h.status) + L")."; + again = h.status >= 500; + http_end(h); + return false; + } else { + // a plain 200 is the whole file from the top, whatever we asked for + have = 0; + } + + HANDLE file = CreateFileW(lp(part).c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, + append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + DWORD err = GetLastError(); + log_fail(L"couldnt open " + part, err); + error = L"The download could not be saved.\n\n(" + win_error(err) + L")"; + http_end(h); + return false; + } + LARGE_INTEGER zero = {}; + SetFilePointerEx(file, zero, nullptr, FILE_END); + + long long total = rel.size; + std::vector buf(64 * 1024); + bool ok = true; + for (;;) { + if (cancelled()) { ok = false; break; } + + DWORD got = 0; + if (!WinHttpReadData(h.req, &buf[0], (DWORD)buf.size(), &got)) { + DWORD err = GetLastError(); + log_fail(L"the download broke off at " + num(have), err); + error = L"The download was interrupted.\n\n(" + win_error(err) + L")"; + again = true; + ok = false; + break; + } + if (got == 0) break; + + DWORD wrote = 0; + if (!WriteFile(file, &buf[0], got, &wrote, nullptr) || wrote != got) { + DWORD err = GetLastError(); + log_fail(L"couldnt write to " + part, err); + error = L"The download could not be saved. The disk may be full.\n\n(" + win_error(err) + L")"; + ok = false; + break; + } + have += got; + if (total > 0) { + int permille = (int)((have * 1000) / total); + set_status(L"Downloading\x2026 " + num(have / (1024 * 1024)) + L" of " + num(total / (1024 * 1024)) + L" MB", + permille > 1000 ? 1000 : permille); + } else { + set_status(L"Downloading\x2026 " + num(have / (1024 * 1024)) + L" MB", -1); + } + } + CloseHandle(file); + http_end(h); + if (!ok) return false; + + if (total > 0 && have < total) { + // the server hung up early without it being an error + log_line(L"the download stopped at " + num(have) + L" of " + num(total)); + error = L"The download was interrupted."; + again = true; + return false; + } + return true; +} + +static bool download(const Release& rel, const std::wstring& part, std::wstring& error) { + for (int attempt = 0; attempt < 5; attempt++) { + bool again = false; + if (download_once(rel, part, again, error)) return true; + if (cancelled() || !again) return false; + // a breath, then carry on from where it stopped. the Retry button is + // for when this runs out + Sleep(1500); + } + return false; +} + +static bool sha256_file(const std::wstring& path, std::wstring& hex) { + hex.clear(); + HANDLE file = CreateFileW(lp(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (file == INVALID_HANDLE_VALUE) { + log_fail(L"couldnt open " + path + L" to check it", GetLastError()); + return false; + } + + BCRYPT_ALG_HANDLE alg = nullptr; + BCRYPT_HASH_HANDLE hash = nullptr; + BYTE digest[32]; + bool ok = false; + LONG rc = BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, 0); + if (rc >= 0) rc = BCryptCreateHash(alg, &hash, nullptr, 0, nullptr, 0, 0); + if (rc >= 0) { + std::vector buf(256 * 1024); + long long total = file_size(path), done = 0; + for (;;) { + DWORD got = 0; + if (!ReadFile(file, &buf[0], (DWORD)buf.size(), &got, nullptr)) { + log_fail(L"couldnt read " + path + L" to check it", GetLastError()); + rc = -1; + break; + } + if (got == 0) break; + rc = BCryptHashData(hash, &buf[0], got, 0); + if (rc < 0) break; + done += got; + if (total > 0) set_status(L"Checking the download\x2026", (int)((done * 1000) / total)); + } + if (rc >= 0) rc = BCryptFinishHash(hash, digest, sizeof(digest), 0); + ok = rc >= 0; + } + if (!ok) log_line(L"sha256 didnt work, ntstatus " + num((long long)rc)); + if (hash) BCryptDestroyHash(hash); + if (alg) BCryptCloseAlgorithmProvider(alg, 0); + CloseHandle(file); + if (!ok) return false; + + static const wchar_t digits[] = L"0123456789abcdef"; + for (size_t i = 0; i < sizeof(digest); i++) { + hex += digits[digest[i] >> 4]; + hex += digits[digest[i] & 15]; + } + return true; +} + + +// ---- laying it out ---- + +// the stub comes out of our own resources and goes in under the apps exe name +static bool write_stub(const std::wstring& to) { + HMODULE me = GetModuleHandleW(nullptr); + HRSRC res = FindResourceW(me, L"STUB", RT_RCDATA); + HGLOBAL mem = res ? LoadResource(me, res) : nullptr; + const void* bytes = mem ? LockResource(mem) : nullptr; + DWORD size = res ? SizeofResource(me, res) : 0; + if (!bytes || size == 0) { + log_fail(L"the stub isnt inside this installer, it was built wrong", GetLastError()); + return false; + } + + std::wstring fresh = to + L".new"; + HANDLE h = CreateFileW(lp(fresh).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + log_fail(L"couldnt make " + fresh, GetLastError()); + return false; + } + DWORD wrote = 0; + bool ok = WriteFile(h, bytes, size, &wrote, nullptr) && wrote == size; + DWORD err = GetLastError(); + CloseHandle(h); + if (!ok) { + log_fail(L"couldnt write " + fresh, err); + DeleteFileW(lp(fresh).c_str()); + return false; + } + + // installing over the top of one thats there. the old stub is only ever + // running for the moment it takes to start the app + for (int i = 0; i < 15; i++) { + if (MoveFileExW(lp(fresh).c_str(), lp(to).c_str(), MOVEFILE_REPLACE_EXISTING)) return true; + err = GetLastError(); + Sleep(300); + } + log_fail(L"couldnt put the stub at " + to, err); + DeleteFileW(lp(fresh).c_str()); + return false; +} + +static bool make_shortcut(const std::wstring& lnk, const std::wstring& target, const std::wstring& dir) { + IShellLinkW* link = nullptr; + HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (void**)&link); + if (FAILED(hr) || !link) { + log_fail(L"couldnt make a shortcut object for " + lnk, (DWORD)hr); + return false; + } + link->SetPath(target.c_str()); + link->SetWorkingDirectory(dir.c_str()); + link->SetDescription(kAppName); + link->SetIconLocation(target.c_str(), 0); + + IPersistFile* file = nullptr; + hr = link->QueryInterface(IID_IPersistFile, (void**)&file); + if (SUCCEEDED(hr) && file) { + hr = file->Save(lnk.c_str(), TRUE); + file->Release(); + } + link->Release(); + if (FAILED(hr)) { + log_fail(L"couldnt save " + lnk, (DWORD)hr); + return false; + } + return true; +} + +static long long folder_size(const std::wstring& dir) { + long long total = 0; + WIN32_FIND_DATAW fd; + HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd); + if (find == INVALID_HANDLE_VALUE) return 0; + do { + std::wstring name = fd.cFileName; + if (name == L"." || name == L"..") continue; + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) total += folder_size(join(dir, name)); + } else { + total += ((long long)fd.nFileSizeHigh << 32) | (long long)fd.nFileSizeLow; + } + } while (FindNextFileW(find, &fd)); + FindClose(find); + return total; +} + +static bool reg_text(HKEY key, const wchar_t* name, const std::wstring& value) { + LSTATUS rc = RegSetValueExW(key, name, 0, REG_SZ, (const BYTE*)value.c_str(), + (DWORD)((value.size() + 1) * sizeof(wchar_t))); + if (rc != ERROR_SUCCESS) log_fail(std::wstring(L"couldnt set ") + name + L" on the uninstall entry", (DWORD)rc); + return rc == ERROR_SUCCESS; +} + +static bool reg_number(HKEY key, const wchar_t* name, DWORD value) { + LSTATUS rc = RegSetValueExW(key, name, 0, REG_DWORD, (const BYTE*)&value, sizeof(value)); + if (rc != ERROR_SUCCESS) log_fail(std::wstring(L"couldnt set ") + name + L" on the uninstall entry", (DWORD)rc); + return rc == ERROR_SUCCESS; +} + +// the line in "installed apps". its also where the stub finds out what to +// take away again: it looks for the entry whose InstallLocation is its own +// folder and deletes the shortcuts listed in GarageShortcuts +static bool write_uninstall_entry(const std::wstring& root, const std::wstring& stub, const Release& rel, + const std::vector& shortcuts) { + std::wstring path = std::wstring(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\") + GARAGE_APP_ID; + HKEY key = nullptr; + LSTATUS rc = RegCreateKeyExW(g_everyone ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER, path.c_str(), 0, nullptr, 0, + KEY_WRITE | KEY_WOW64_64KEY, nullptr, &key, nullptr); + if (rc != ERROR_SUCCESS) { + log_fail(L"couldnt make the uninstall entry", (DWORD)rc); + return false; + } + + SYSTEMTIME t; + GetLocalTime(&t); + wchar_t date[16]; + wsprintfW(date, L"%04d%02d%02d", t.wYear, t.wMonth, t.wDay); + + std::wstring multi; + for (size_t i = 0; i < shortcuts.size(); i++) { + multi += shortcuts[i]; + multi += L'\0'; + } + multi += L'\0'; + + bool ok = true; + ok = reg_text(key, L"DisplayName", kAppName) && ok; + ok = reg_text(key, L"DisplayVersion", rel.label.empty() ? num(rel.build) : rel.label) && ok; + ok = reg_text(key, L"DisplayIcon", stub) && ok; + ok = reg_text(key, L"InstallLocation", root) && ok; + ok = reg_text(key, L"InstallDate", date) && ok; + ok = reg_text(key, L"UninstallString", quote_arg(stub) + L" --garage-uninstall") && ok; + ok = reg_text(key, L"QuietUninstallString", quote_arg(stub) + L" --garage-uninstall --quiet") && ok; + if (kPublisher[0]) ok = reg_text(key, L"Publisher", kPublisher) && ok; + ok = reg_number(key, L"NoModify", 1) && ok; + ok = reg_number(key, L"NoRepair", 1) && ok; + ok = reg_number(key, L"EstimatedSize", (DWORD)(folder_size(version_dir(root, rel.build)) / 1024)) && ok; + + rc = RegSetValueExW(key, L"GarageShortcuts", 0, REG_MULTI_SZ, (const BYTE*)multi.data(), + (DWORD)(multi.size() * sizeof(wchar_t))); + if (rc != ERROR_SUCCESS) { + log_fail(L"couldnt set GarageShortcuts on the uninstall entry", (DWORD)rc); + ok = false; + } + RegCloseKey(key); + return ok; +} + +static std::wstring g_errorText; + +static bool fail(const std::wstring& text) { + g_errorText = text; + return false; +} + +// everything, start to finish. runs on the worker thread +static bool install() { + std::wstring error; + + set_status(L"Looking for the newest version\x2026", -1); + const wchar_t* arch = native_arch(); + Release rel; + bool none = false; + if (!ask_garage(arch, rel, none, error)) { + if (!none) return fail(error); + // nothing built for arm. the x64 one runs there all the same + bool found = false; + if (lstrcmpW(arch, L"arm64") == 0) { + found = ask_garage(L"x64", rel, none, error); + if (!found && !none) return fail(error); + } + if (!found) { + log_line(std::wstring(L"garage has no published windows release for ") + arch); + return fail(std::wstring(kAppName) + L" has not been released for Windows yet."); + } + } + if (cancelled()) return false; + + + std::wstring zip = join(g_logDir, num(rel.build) + L".zip"); + std::wstring part = zip + L".part"; + if (!exists(zip)) { + set_status(L"Downloading\x2026", rel.size > 0 ? 0 : -1); + if (!download(rel, part, error)) return fail(error); + if (cancelled()) return false; + if (!MoveFileExW(lp(part).c_str(), lp(zip).c_str(), MOVEFILE_REPLACE_EXISTING)) { + DWORD err = GetLastError(); + log_fail(L"couldnt rename " + part, err); + return fail(L"The download could not be saved.\n\n(" + win_error(err) + L")"); + } + } + + set_status(L"Checking the download\x2026", 0); + std::wstring sum; + if (!sha256_file(zip, sum)) return fail(L"The download could not be checked."); + if (!same_text(sum, rel.sha256)) { + log_line(L"sha256 of the download is " + sum + L", garage says " + rel.sha256); + // no good to anybody. Retry starts it from nothing + DeleteFileW(lp(zip).c_str()); + return fail(L"The download arrived damaged. Try again."); + } + if (cancelled()) return false; + + + set_status(L"Installing\x2026", -1); + std::wstring root = install_root(g_everyone); + int made = SHCreateDirectoryExW(nullptr, root.c_str(), nullptr); + if (made != ERROR_SUCCESS && made != ERROR_ALREADY_EXISTS && made != ERROR_FILE_EXISTS) { + log_fail(L"couldnt make " + root, (DWORD)made); + return fail(L"The install folder could not be made.\n\n" + root + L"\n(" + win_error((DWORD)made) + L")"); + } + + std::wstring stub = join(root, GARAGE_EXE_NAME); + if (!write_stub(stub)) return fail(L"The app could not be copied in to place.\n\n" + root); + + // the stub needs to know which exe in the zip is the app before its + // unpacked anything. whatever else is in an old state file stays + State st; + std::string text; + if (read_file(state_path(root), text, 1024 * 1024) && !parse_state(text, st)) { + log_line(L"the state file in " + root + L" wont read, writing a new one"); + st = State(); + } + st.exe = GARAGE_EXE_NAME; + st.set_extra("app_id", GARAGE_APP_ID); + if (!write_atomic(state_path(root), print_state(st))) { + DWORD err = GetLastError(); + log_fail(L"couldnt write " + state_path(root), err); + return fail(L"The install folder could not be written to.\n\n" + root + L"\n(" + win_error(err) + L")"); + } + + DWORD code = 1; + if (!run_wait(stub, L"--garage-apply " + quote_arg(zip) + L" " + num(rel.build), root, nullptr, code)) { + DWORD err = GetLastError(); + log_fail(L"couldnt run " + stub, err); + return fail(L"The app could not be unpacked.\n\n(" + win_error(err) + L")"); + } + if (code != 0) { + log_line(L"the stub couldnt unpack build " + num(rel.build) + L", it exited " + num(code)); + return fail(L"The app could not be unpacked (code " + num(code) + L").\n\nDetails are in " + + join(root, L"garage_updates.log")); + } + + + // from here its in and it runs. a shortcut that wont save is logged and + // lived with, its not worth telling somebody the install failed over + std::vector shortcuts; + HRESULT com = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + std::wstring lnkName = file_safe(kAppName) + L".lnk"; + std::wstring programs = shell_folder(g_everyone ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS); + if (!programs.empty() && make_shortcut(join(programs, lnkName), stub, root)) { + shortcuts.push_back(join(programs, lnkName)); + } + if (g_desktopShortcut) { + std::wstring desktop = shell_folder(g_everyone ? CSIDL_COMMON_DESKTOPDIRECTORY : CSIDL_DESKTOPDIRECTORY); + if (!desktop.empty() && make_shortcut(join(desktop, lnkName), stub, root)) { + shortcuts.push_back(join(desktop, lnkName)); + } + } + if (SUCCEEDED(com)) CoUninitialize(); + + if (!write_uninstall_entry(root, stub, rel, shortcuts)) { + log_line(L"the uninstall entry is missing or half there, the app is installed all the same"); + } + + if (!DeleteFileW(lp(zip).c_str())) log_fail(L"couldnt delete " + zip, GetLastError()); + return true; +} + +static DWORD WINAPI install_thread(LPVOID) { + g_errorText.clear(); + bool ok = install(); + + EnterCriticalSection(&g_lock); + g_progress.ok = ok; + g_progress.error = g_errorText; + g_progress.done = true; + LeaveCriticalSection(&g_lock); + return 0; +} + +static bool start_app() { + std::wstring root = install_root(g_everyone); + std::wstring stub = join(root, GARAGE_EXE_NAME); + std::wstring cmd = quote_arg(stub); + STARTUPINFOW si = {}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi = {}; + if (!CreateProcessW(stub.c_str(), &cmd[0], nullptr, nullptr, FALSE, 0, nullptr, root.c_str(), &si, &pi)) { + log_fail(L"installed, but couldnt start " + stub, GetLastError()); + return false; + } + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return true; +} + +// ourselves again, behind the uac prompt. the handle comes back so whoever +// asked can wait for it +static bool relaunch_elevated(HWND owner) { + wchar_t self[MAX_PATH * 4]; + DWORD n = GetModuleFileNameW(nullptr, self, ARRAYSIZE(self)); + if (n == 0 || n >= ARRAYSIZE(self)) { + log_fail(L"couldnt find our own exe to elevate", GetLastError()); + return false; + } + SHELLEXECUTEINFOW sx = {}; + sx.cbSize = sizeof(sx); + sx.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC; + sx.hwnd = owner; + sx.lpVerb = L"runas"; + sx.lpFile = self; + sx.lpParameters = L"--everyone --elevated"; + sx.nShow = SW_SHOWNORMAL; + if (!ShellExecuteExW(&sx) || !sx.hProcess) { + log_fail(L"the administrator prompt was turned down, or didnt come up", GetLastError()); + return false; + } + g_child = sx.hProcess; + return true; +} + + +// ---- the window ---- + +static std::wstring g_title, g_heading, g_body; +static TASKDIALOGCONFIG g_cfg; +static TASKDIALOG_BUTTON g_buttons[1]; +static TASKDIALOG_BUTTON g_radios[2]; + +static HRESULT CALLBACK dialog_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp, LONG_PTR data); + +// fills g_cfg for a page. everything it points at is a global, the dialog +// holds on to the pointers +static void fill_page(Page page) { + g_page = page; + g_cfg = TASKDIALOGCONFIG(); + g_cfg.cbSize = sizeof(g_cfg); + g_cfg.hInstance = GetModuleHandleW(nullptr); + g_cfg.pfCallback = dialog_proc; + g_cfg.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_CAN_BE_MINIMIZED; + g_title = std::wstring(kAppName) + L" Setup"; + g_cfg.pszWindowTitle = g_title.c_str(); + + if (page == PAGE_ERROR) { + g_cfg.pszMainIcon = TD_ERROR_ICON; + } else if (g_icon) { + g_cfg.dwFlags |= TDF_USE_HICON_MAIN; + g_cfg.hMainIcon = g_icon; + } + + switch (page) { + case PAGE_CHOICE: + g_heading = std::wstring(L"Install ") + kAppName; + g_body = L"Who should be able to use it?"; + g_buttons[0].nButtonID = ID_INSTALL; + g_buttons[0].pszButtonText = L"Install"; + g_radios[0].nButtonID = RADIO_ME; + g_radios[0].pszButtonText = L"Just me"; + g_radios[1].nButtonID = RADIO_EVERYONE; + g_radios[1].pszButtonText = L"Everyone on this PC"; + g_cfg.pButtons = g_buttons; + g_cfg.cButtons = 1; + g_cfg.pRadioButtons = g_radios; + g_cfg.cRadioButtons = 2; + g_cfg.nDefaultRadioButton = g_everyone ? RADIO_EVERYONE : RADIO_ME; + g_cfg.nDefaultButton = ID_INSTALL; + g_cfg.dwCommonButtons = TDCBF_CANCEL_BUTTON; + break; + + case PAGE_PROGRESS: + g_heading = std::wstring(L"Installing ") + kAppName; + g_body = L"Getting ready\x2026"; + g_cfg.dwFlags |= TDF_SHOW_PROGRESS_BAR | TDF_CALLBACK_TIMER; + g_cfg.dwCommonButtons = TDCBF_CANCEL_BUTTON; + break; + + case PAGE_ERROR: + g_heading = std::wstring(kAppName) + L" could not be installed"; + g_cfg.dwCommonButtons = TDCBF_RETRY_BUTTON | TDCBF_CLOSE_BUTTON; + g_cfg.nDefaultButton = IDRETRY; + break; + } + g_cfg.pszMainInstruction = g_heading.c_str(); + g_cfg.pszContent = g_body.c_str(); +} + +static void go_to(HWND hwnd, Page page) { + fill_page(page); + SendMessageW(hwnd, TDM_NAVIGATE_PAGE, 0, (LPARAM)&g_cfg); +} + +static void set_body(HWND hwnd, const std::wstring& text) { + g_body = text; + SendMessageW(hwnd, TDM_SET_ELEMENT_TEXT, TDE_CONTENT, (LPARAM)g_body.c_str()); +} + +static void show_shield(HWND hwnd) { + SendMessageW(hwnd, TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE, ID_INSTALL, g_everyone && !is_admin()); +} + +static void set_marquee(HWND hwnd, bool on) { + g_marquee = on; + SendMessageW(hwnd, TDM_SET_MARQUEE_PROGRESS_BAR, on, 0); + SendMessageW(hwnd, TDM_SET_PROGRESS_BAR_MARQUEE, on, 0); +} + +static void start_worker(HWND hwnd) { + EnterCriticalSection(&g_lock); + g_progress.status = g_body; + g_progress.permille = -1; + g_progress.done = false; + g_progress.ok = false; + g_progress.error.clear(); + LeaveCriticalSection(&g_lock); + InterlockedExchange(&g_cancel, 0); + g_shown = g_body; + + SendMessageW(hwnd, TDM_SET_PROGRESS_BAR_RANGE, 0, MAKELPARAM(0, 1000)); + set_marquee(hwnd, true); + + g_worker = CreateThread(nullptr, 0, install_thread, nullptr, 0, nullptr); + if (!g_worker) { + log_fail(L"couldnt start the install thread", GetLastError()); + g_body = L"Windows would not start the install. Try again."; + go_to(hwnd, PAGE_ERROR); + } +} + +// five times a second while the progress page is up +static void on_tick(HWND hwnd) { + if (!g_worker) return; + + EnterCriticalSection(&g_lock); + std::wstring status = g_progress.status; + int permille = g_progress.permille; + bool done = g_progress.done, ok = g_progress.ok; + std::wstring error = g_progress.error; + LeaveCriticalSection(&g_lock); + + if (!done) { + if (cancelled()) return; + if (status != g_shown) { + g_shown = status; + set_body(hwnd, status); + } + if (permille < 0) { + if (!g_marquee) set_marquee(hwnd, true); + } else { + if (g_marquee) set_marquee(hwnd, false); + SendMessageW(hwnd, TDM_SET_PROGRESS_BAR_POS, (WPARAM)permille, 0); + } + return; + } + + WaitForSingleObject(g_worker, INFINITE); + CloseHandle(g_worker); + g_worker = nullptr; + + if (ok || cancelled()) { + g_exit = ok ? kExitOk : kExitCancelled; + // with the worker gone a click on cancel is let through, which is + // how a task dialog gets closed from the inside + SendMessageW(hwnd, TDM_CLICK_BUTTON, IDCANCEL, 0); + return; + } + g_body = error.empty() ? std::wstring(L"Something went wrong.") : error; + go_to(hwnd, PAGE_ERROR); +} + +// S_OK lets the click close the dialog, S_FALSE keeps it open +static HRESULT on_button(HWND hwnd, int id) { + switch (g_page) { + case PAGE_CHOICE: + if (id != ID_INSTALL) { + g_exit = kExitCancelled; + return S_OK; + } + if (g_everyone && !is_admin()) { + if (relaunch_elevated(hwnd)) return S_OK; + set_body(hwnd, L"Installing for everyone needs an administrator to allow it. " + L"Choose Just me to install without one."); + return S_FALSE; + } + go_to(hwnd, PAGE_PROGRESS); + return S_FALSE; + + case PAGE_PROGRESS: + if (!g_worker) return S_OK; + // the worker is told, and the timer closes us once its let go + InterlockedExchange(&g_cancel, 1); + set_body(hwnd, L"Cancelling\x2026"); + return S_FALSE; + + case PAGE_ERROR: + if (id == IDRETRY) { + go_to(hwnd, PAGE_PROGRESS); + return S_FALSE; + } + g_exit = kExitFailed; + return S_OK; + } + return S_OK; +} + +static HRESULT CALLBACK dialog_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM, LONG_PTR) { + switch (msg) { + case TDN_CREATED: + case TDN_NAVIGATED: + if (g_page == PAGE_CHOICE) show_shield(hwnd); + if (g_page == PAGE_PROGRESS) start_worker(hwnd); + break; + case TDN_RADIO_BUTTON_CLICKED: + g_everyone = (int)wp == RADIO_EVERYONE; + show_shield(hwnd); + break; + case TDN_TIMER: + on_tick(hwnd); + break; + case TDN_BUTTON_CLICKED: + return on_button(hwnd, (int)wp); + } + return S_OK; +} + +static void complain(const std::wstring& text) { + MessageBoxW(nullptr, text.c_str(), (std::wstring(kAppName) + L" Setup").c_str(), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); +} + +int WINAPI wWinMain(HINSTANCE inst, HINSTANCE, PWSTR, int) { + InitializeCriticalSection(&g_lock); + + wchar_t temp[MAX_PATH + 2]; + DWORD n = GetTempPathW(ARRAYSIZE(temp), temp); + if (n > 0 && n < ARRAYSIZE(temp)) { + g_logDir = join(temp, std::wstring(GARAGE_APP_ID) + L"-setup"); + if (!CreateDirectoryW(lp(g_logDir).c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) { + DWORD err = GetLastError(); + g_logDir = std::wstring(temp); + log_fail(L"couldnt make a folder in temp, using temp itself", err); + } + } else { + complain(L"Windows has no temporary folder to download to."); + return kExitFailed; + } + + int argc = 0; + wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); + for (int i = 1; argv && i < argc; i++) { + if (lstrcmpW(argv[i], L"--everyone") == 0) g_everyone = true; + if (lstrcmpW(argv[i], L"--just-me") == 0) g_everyone = false; + if (lstrcmpW(argv[i], L"--elevated") == 0) g_elevatedChild = true; + } + if (argv) LocalFree(argv); + + g_icon = LoadIconW(inst, MAKEINTRESOURCEW(1)); + + bool choose = g_showChoice && !g_elevatedChild; + if (!choose && g_everyone && !is_admin()) { + // nothing to ask and its going in program files, so straight to the prompt + if (!relaunch_elevated(nullptr)) { + complain(std::wstring(kAppName) + L" is installed for everyone on this PC, which needs an administrator to allow it."); + return kExitCancelled; + } + } + + if (!g_child) { + fill_page(choose ? PAGE_CHOICE : PAGE_PROGRESS); + int pressed = 0; + HRESULT hr = TaskDialogIndirect(&g_cfg, &pressed, nullptr, nullptr); + if (FAILED(hr)) { + log_fail(L"the setup window wouldnt open", (DWORD)hr); + complain(L"The setup window could not be opened."); + return kExitFailed; + } + } + + if (g_child) { + // the elevated one has its own window and its own retry. we only + // want to know how it ended + WaitForSingleObject(g_child, INFINITE); + DWORD code = (DWORD)kExitFailed; + GetExitCodeProcess(g_child, &code); + CloseHandle(g_child); + g_exit = (int)code; + } + + // an elevated copy doesnt start the app, or the app would run as admin. + // the one that asked for it does, back down here as the user + if (g_exit == kExitOk && !g_elevatedChild) start_app(); + + DeleteCriticalSection(&g_lock); + return g_exit; +} diff --git a/garage_updates/windows_installer/installer.exe.manifest b/garage_updates/windows_installer/installer.exe.manifest new file mode 100644 index 0000000..9e11af9 --- /dev/null +++ b/garage_updates/windows_installer/installer.exe.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + PerMonitorV2 + true + + + diff --git a/garage_updates/windows_installer/installer.rc.in b/garage_updates/windows_installer/installer.rc.in new file mode 100644 index 0000000..d373844 --- /dev/null +++ b/garage_updates/windows_installer/installer.rc.in @@ -0,0 +1,12 @@ +// made by cmake. the icon, the stub and (not for msvc) the manifest +#pragma code_page(65001) + +@GARAGE_ICON_LINE@ + +// the stub, whole. its written out as \.exe +STUB RCDATA "@GARAGE_STUB_FILE@" + +// msvc gets the manifest handed to the linker instead, two of them collide +#ifdef GARAGE_RC_MANIFEST +1 24 "@GARAGE_MANIFEST_FILE@" +#endif diff --git a/garage_updates/windows_installer/installer_config.h.in b/garage_updates/windows_installer/installer_config.h.in new file mode 100644 index 0000000..22ac114 --- /dev/null +++ b/garage_updates/windows_installer/installer_config.h.in @@ -0,0 +1,24 @@ +// made by cmake from the values the installer was built with. dont edit the +// copy in the build folder, it gets written over. +#pragma once + +// what people see: the window, the shortcut, the folder, "installed apps" +#define GARAGE_APP_NAME L"@GARAGE_APP_NAME_C@" + +// the key of the uninstall entry, and the folder under %LOCALAPPDATA% that +// downloads go to when the install itself is read only +#define GARAGE_APP_ID L"@GARAGE_APP_ID_C@" + +#define GARAGE_PROJECT_ID L"@GARAGE_PROJECT_ID_C@" +#define GARAGE_API_BASE L"@GARAGE_API_BASE_C@" + +// the apps exe inside a build. the stub goes in root under the same name +#define GARAGE_EXE_NAME L"@GARAGE_EXE_NAME_C@" + +#define GARAGE_PUBLISHER L"@GARAGE_PUBLISHER_C@" + +// 1 is "everyone on this pc" (program files), 0 is "just me" +#define GARAGE_DEFAULT_EVERYONE @GARAGE_DEFAULT_EVERYONE_C@ +// 0 never asks and goes with the default +#define GARAGE_SHOW_CHOICE @GARAGE_SHOW_CHOICE_C@ +#define GARAGE_DESKTOP_SHORTCUT @GARAGE_DESKTOP_SHORTCUT_C@