@capgo/capacitor-updater 8.54.2 → 9.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CapgoCapacitorUpdater.podspec +2 -2
- package/Package.swift +3 -4
- package/README.md +162 -417
- package/android/build.gradle +7 -7
- package/android/consumer-rules.pro +48 -0
- package/android/proguard-rules.pro +1 -23
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
- package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
- package/dist/docs.json +44 -566
- package/dist/esm/definitions.d.ts +97 -215
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
- package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
- package/package.json +15 -13
|
@@ -24,10 +24,28 @@ import java.util.concurrent.TimeoutException;
|
|
|
24
24
|
|
|
25
25
|
public class DownloadWorkerManager {
|
|
26
26
|
|
|
27
|
-
private static Logger logger;
|
|
27
|
+
private static volatile Logger logger;
|
|
28
|
+
private static final Object LOGGER_LOCK = new Object();
|
|
28
29
|
|
|
29
30
|
public static void setLogger(Logger loggerInstance) {
|
|
30
|
-
|
|
31
|
+
synchronized (LOGGER_LOCK) {
|
|
32
|
+
logger = loggerInstance;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
public static void setLoggerIfAbsent(Logger loggerInstance) {
|
|
37
|
+
if (loggerInstance == null) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
synchronized (LOGGER_LOCK) {
|
|
41
|
+
if (logger == null) {
|
|
42
|
+
logger = loggerInstance;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
public static Logger getLogger() {
|
|
48
|
+
return logger;
|
|
31
49
|
}
|
|
32
50
|
|
|
33
51
|
private static volatile boolean isInitialized = false;
|
|
@@ -111,6 +129,8 @@ public class DownloadWorkerManager {
|
|
|
111
129
|
.putString(DownloadService.DEFAULT_CHANNEL, defaultChannel)
|
|
112
130
|
.putBoolean(DownloadService.IS_PROD, isProd)
|
|
113
131
|
.putBoolean(DownloadService.IS_EMULATOR, isEmulator)
|
|
132
|
+
// A job WorkManager resumes in a fresh process runs before any config is loaded.
|
|
133
|
+
.putBoolean(DownloadService.HTTP3, Http3.isEnabled())
|
|
114
134
|
.build();
|
|
115
135
|
|
|
116
136
|
// Create network constraints - be more lenient on emulators
|
|
@@ -25,6 +25,7 @@ import androidx.work.WorkerParameters;
|
|
|
25
25
|
import com.getcapacitor.CapConfig;
|
|
26
26
|
import com.getcapacitor.PluginConfig;
|
|
27
27
|
import com.getcapacitor.plugin.WebView;
|
|
28
|
+
import java.io.IOException;
|
|
28
29
|
import java.util.Map;
|
|
29
30
|
import java.util.concurrent.CountDownLatch;
|
|
30
31
|
import java.util.concurrent.TimeUnit;
|
|
@@ -71,19 +72,28 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
71
72
|
@NonNull
|
|
72
73
|
@Override
|
|
73
74
|
public Result doWork() {
|
|
74
|
-
final
|
|
75
|
+
final Context context = getApplicationContext();
|
|
76
|
+
final Logger logger;
|
|
75
77
|
try {
|
|
76
|
-
final
|
|
77
|
-
|
|
78
|
+
final PluginConfig config = CapConfig.loadDefault(context).getPluginConfiguration("CapacitorUpdater");
|
|
79
|
+
final boolean osLogging = config.getBoolean("osLogging", true);
|
|
80
|
+
logger = new Logger("CapgoUpdater", new Logger.Options(osLogging));
|
|
81
|
+
try {
|
|
82
|
+
final String status = run(context, logger);
|
|
83
|
+
logger.info("Headless update check finished: " + status);
|
|
84
|
+
} catch (final Exception e) {
|
|
85
|
+
logger.error("Headless update check failed: " + e.getMessage());
|
|
86
|
+
}
|
|
78
87
|
} catch (final Exception e) {
|
|
79
|
-
|
|
88
|
+
final Logger fallback = new Logger("CapgoUpdater", new Logger.Options(true));
|
|
89
|
+
fallback.error("Headless update check skipped: invalid Capacitor config (" + e.getMessage() + ")");
|
|
80
90
|
}
|
|
81
91
|
// Never retry: the next launch or push runs a fresh check.
|
|
82
92
|
return Result.success();
|
|
83
93
|
}
|
|
84
94
|
|
|
85
95
|
static String run(final Context context, final Logger logger) throws PackageManager.NameNotFoundException {
|
|
86
|
-
if (CapacitorUpdaterPlugin.
|
|
96
|
+
if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
|
|
87
97
|
// The running plugin instance owns downloads and installs in this process.
|
|
88
98
|
return "handed_over";
|
|
89
99
|
}
|
|
@@ -132,7 +142,7 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
132
142
|
}
|
|
133
143
|
}
|
|
134
144
|
};
|
|
135
|
-
configure(updater, context, config, prefs, packageInfo, versionCode);
|
|
145
|
+
configure(updater, context, config, prefs, packageInfo, versionCode, logger);
|
|
136
146
|
try {
|
|
137
147
|
String updateUrl = config.getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault);
|
|
138
148
|
if (config.getBoolean("persistModifyUrl", false) && prefs.contains(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY)) {
|
|
@@ -173,11 +183,9 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
173
183
|
if (existing != null && existing.isErrorStatus()) {
|
|
174
184
|
return "failed";
|
|
175
185
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
180
|
-
return "downloaded";
|
|
186
|
+
final String reused = reuseDownloadedBundle(updater, existing, version, setNext, logger);
|
|
187
|
+
if (reused != null) {
|
|
188
|
+
return reused;
|
|
181
189
|
}
|
|
182
190
|
|
|
183
191
|
// downloadBackground returns null when it refuses the download (blocked encryption, gate,
|
|
@@ -192,7 +200,7 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
192
200
|
// the app meanwhile, its plugin instance takes over the download (it restarts downloads it
|
|
193
201
|
// does not observe), so stop waiting.
|
|
194
202
|
while (!finished.await(1, TimeUnit.SECONDS)) {
|
|
195
|
-
if (CapacitorUpdaterPlugin.
|
|
203
|
+
if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
|
|
196
204
|
return "handed_over";
|
|
197
205
|
}
|
|
198
206
|
if (System.currentTimeMillis() > deadline) {
|
|
@@ -207,11 +215,13 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
207
215
|
} finally {
|
|
208
216
|
// Once the plugin instance is up it owns the stats file: hand it our unsent events
|
|
209
217
|
// instead of overwriting its newer file.
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
218
|
+
synchronized (CapacitorUpdaterPlugin.INSTANCE_LOADED_LOCK) {
|
|
219
|
+
if (CapacitorUpdaterPlugin.instanceLoaded) {
|
|
220
|
+
updater.handOverPendingStats();
|
|
221
|
+
updater.shutdown(false);
|
|
222
|
+
} else {
|
|
223
|
+
updater.shutdown(true);
|
|
224
|
+
}
|
|
215
225
|
}
|
|
216
226
|
}
|
|
217
227
|
}
|
|
@@ -221,7 +231,7 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
221
231
|
* it is the same as installing on a background transition. Delay conditions keep it as next.
|
|
222
232
|
*/
|
|
223
233
|
static boolean applyIfNoUi(final CapgoUpdater updater, final BundleInfo bundle, final Logger logger) {
|
|
224
|
-
if (CapacitorUpdaterPlugin.
|
|
234
|
+
if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
|
|
225
235
|
return false;
|
|
226
236
|
}
|
|
227
237
|
final String delays = updater.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
|
|
@@ -237,6 +247,20 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
237
247
|
return false;
|
|
238
248
|
}
|
|
239
249
|
|
|
250
|
+
/**
|
|
251
|
+
* When builtinMinimum is on, refuse an existing downloaded bundle whose version is below the native build.
|
|
252
|
+
* Shared by tests and {@link #run} so removing the guard breaks a unit test.
|
|
253
|
+
*/
|
|
254
|
+
static boolean builtinMinimumBlocksExistingBundle(final CapgoUpdater updater, final String bundleVersion, final Logger logger) {
|
|
255
|
+
try {
|
|
256
|
+
updater.requireVersionNotBelowBuiltin(bundleVersion);
|
|
257
|
+
return false;
|
|
258
|
+
} catch (final IOException e) {
|
|
259
|
+
logger.error(e.getMessage() == null ? "Download blocked" : e.getMessage());
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
240
264
|
static JSONArray manifestOf(final Map<String, Object> latest) {
|
|
241
265
|
final Object manifest = latest.get("manifest");
|
|
242
266
|
if (manifest instanceof JSONArray) {
|
|
@@ -268,14 +292,41 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
268
292
|
return packageManager.getPackageInfo(context.getPackageName(), 0);
|
|
269
293
|
}
|
|
270
294
|
|
|
271
|
-
/**
|
|
295
|
+
/**
|
|
296
|
+
* Reuses a bundle already downloaded for {@code version}: queues it, and installs it when no UI runs, after
|
|
297
|
+
* the same builtinMinimum gate a fresh download goes through. Returns null when there is nothing to reuse.
|
|
298
|
+
*/
|
|
299
|
+
static String reuseDownloadedBundle(
|
|
300
|
+
final CapgoUpdater updater,
|
|
301
|
+
final BundleInfo existing,
|
|
302
|
+
final String version,
|
|
303
|
+
final boolean setNext,
|
|
304
|
+
final Logger logger
|
|
305
|
+
) {
|
|
306
|
+
if (existing == null || !existing.isDownloaded() || BundleStatus.DOWNLOADING == existing.getStatus()) {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
if (builtinMinimumBlocksExistingBundle(updater, version, logger)) {
|
|
310
|
+
if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
|
|
311
|
+
updater.handOverPendingStats();
|
|
312
|
+
}
|
|
313
|
+
return "skipped";
|
|
314
|
+
}
|
|
315
|
+
if (setNext && updater.setNextBundle(existing.getId())) {
|
|
316
|
+
return applyIfNoUi(updater, existing, logger) ? "installed" : "queued";
|
|
317
|
+
}
|
|
318
|
+
return "downloaded";
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Mirrors the identity, URL and builtinMinimum setup of CapacitorUpdaterPlugin#load. */
|
|
272
322
|
private static void configure(
|
|
273
323
|
final CapgoUpdater updater,
|
|
274
324
|
final Context context,
|
|
275
325
|
final PluginConfig config,
|
|
276
326
|
final SharedPreferences prefs,
|
|
277
327
|
final PackageInfo packageInfo,
|
|
278
|
-
final String versionCode
|
|
328
|
+
final String versionCode,
|
|
329
|
+
final Logger headlessLogger
|
|
279
330
|
) {
|
|
280
331
|
updater.appContext = context;
|
|
281
332
|
updater.prefs = prefs;
|
|
@@ -294,6 +345,16 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
294
345
|
appId = InternalUtils.getRootConfigString(context, "appId", appId);
|
|
295
346
|
updater.appId = config.getString("appId", appId);
|
|
296
347
|
updater.setPublicKey(config.getString("publicKey", ""));
|
|
348
|
+
// Same default as CapacitorUpdaterPlugin#load: on unless the app opts out.
|
|
349
|
+
updater.builtinMinimum = config.getBoolean("builtinMinimum", true);
|
|
350
|
+
|
|
351
|
+
DownloadService.setAllowHttpsToHttpRedirect(config.getBoolean("allowHttpsToHttpRedirect", false));
|
|
352
|
+
Http3.setEnabled(config.getBoolean("http3", true));
|
|
353
|
+
final boolean httpsOnly = config.getBoolean("httpsOnly", true);
|
|
354
|
+
updater.httpsOnly = httpsOnly;
|
|
355
|
+
DownloadService.setHttpsOnly(httpsOnly);
|
|
356
|
+
DownloadService.setLoggerIfAbsent(headlessLogger);
|
|
357
|
+
DownloadWorkerManager.setLoggerIfAbsent(headlessLogger);
|
|
297
358
|
|
|
298
359
|
final boolean persistModifyUrl = config.getBoolean("persistModifyUrl", false);
|
|
299
360
|
updater.statsUrl = config.getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault);
|
|
@@ -307,7 +368,7 @@ public class HeadlessUpdateWorker extends Worker {
|
|
|
307
368
|
updater.defaultChannel =
|
|
308
369
|
storedDefaultChannel != null && !storedDefaultChannel.isEmpty() ? storedDefaultChannel : config.getString("defaultChannel", "");
|
|
309
370
|
|
|
310
|
-
if (config.getBoolean("persistCustomId",
|
|
371
|
+
if (config.getBoolean("persistCustomId", true)) {
|
|
311
372
|
final String storedCustomId = prefs.getString(CapacitorUpdaterPlugin.CUSTOM_ID_PREF_KEY, "");
|
|
312
373
|
if (storedCustomId != null && !storedCustomId.isEmpty()) {
|
|
313
374
|
updater.customId = storedCustomId;
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
3
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
5
|
+
*/
|
|
6
|
+
package ee.forgr.capacitor_updater;
|
|
7
|
+
|
|
8
|
+
import android.content.Context;
|
|
9
|
+
import android.os.Build;
|
|
10
|
+
import android.os.ext.SdkExtensions;
|
|
11
|
+
import androidx.annotation.NonNull;
|
|
12
|
+
import androidx.annotation.Nullable;
|
|
13
|
+
import java.io.IOException;
|
|
14
|
+
import java.net.SocketTimeoutException;
|
|
15
|
+
import java.util.List;
|
|
16
|
+
import java.util.Locale;
|
|
17
|
+
import java.util.Map;
|
|
18
|
+
import java.util.concurrent.TimeUnit;
|
|
19
|
+
import okhttp3.Call;
|
|
20
|
+
import okhttp3.Headers;
|
|
21
|
+
import okhttp3.HttpUrl;
|
|
22
|
+
import okhttp3.Interceptor;
|
|
23
|
+
import okhttp3.Protocol;
|
|
24
|
+
import okhttp3.Request;
|
|
25
|
+
import okhttp3.Response;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* HTTP/3 for bundle and manifest downloads.
|
|
29
|
+
*
|
|
30
|
+
* <p>Where the device has the platform {@code android.net.http.HttpEngine} (Android 14+, or Android 12 and 13
|
|
31
|
+
* with the S extension at level 7), https downloads tagged with {@link #markDownload} run on one shared engine.
|
|
32
|
+
* The engine speaks HTTP/3 when the server advertises it through Alt-Svc and falls back to HTTP/2 on its own when
|
|
33
|
+
* QUIC is blocked. Its storage path and {@code HTTP_CACHE_DISK_NO_HTTP} cache keep the Alt-Svc entries across
|
|
34
|
+
* launches without caching any response, so the next process goes straight to HTTP/3 (finding from
|
|
35
|
+
* https://github.com/Cap-go/capacitor-updater/issues/1027, credit autopylotben).
|
|
36
|
+
*
|
|
37
|
+
* <p>Everything else stays on OkHttp: API calls, requests with a body, plain http, devices without HttpEngine,
|
|
38
|
+
* an engine that failed to start, and apps that set {@code http3: false}.
|
|
39
|
+
*/
|
|
40
|
+
final class Http3 {
|
|
41
|
+
|
|
42
|
+
/** Request tag for downloads allowed to run on HttpEngine. */
|
|
43
|
+
static final class Download {
|
|
44
|
+
|
|
45
|
+
static final Download TAG = new Download();
|
|
46
|
+
|
|
47
|
+
private Download() {}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Runs one tagged download outside OkHttp's network stack. */
|
|
51
|
+
interface Transport {
|
|
52
|
+
@NonNull
|
|
53
|
+
Response execute(@NonNull Request request, int connectTimeoutMs, int readTimeoutMs, @Nullable Call call) throws IOException;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface TransportFactory {
|
|
57
|
+
@NonNull
|
|
58
|
+
Transport create(@NonNull Context context, @Nullable Logger logger);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The engine made no progress at all (no callback for any request) for {@link #STALL_MS} while a download
|
|
63
|
+
* waited on it. Seen on an Android 16 emulator (HttpEngine 133): right after a large receive burst the QUIC session
|
|
64
|
+
* stops answering, and the engine only gives up on it after its own 6 to 40 s timeout.
|
|
65
|
+
*/
|
|
66
|
+
static final class EngineStalledException extends SocketTimeoutException {
|
|
67
|
+
|
|
68
|
+
EngineStalledException(String message) {
|
|
69
|
+
super(message);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* How long the whole engine may stay silent, while downloads wait on it, before they move to OkHttp. A live
|
|
75
|
+
* connection with requests in flight answers in a few round trips, far below this.
|
|
76
|
+
*/
|
|
77
|
+
static final long STALL_MS = 500;
|
|
78
|
+
/** After a stall, new downloads skip the engine for this long instead of each paying the stall again. */
|
|
79
|
+
static final long STALL_COOLDOWN_MS = 60_000;
|
|
80
|
+
|
|
81
|
+
private static volatile Transport transport;
|
|
82
|
+
private static volatile boolean enabled = true;
|
|
83
|
+
// System.nanoTime() until which downloads skip the engine after a stall; only read while stalledOnce is true.
|
|
84
|
+
private static volatile long suspendedUntilNanos;
|
|
85
|
+
private static volatile boolean stalledOnce;
|
|
86
|
+
// True once the plugin or the headless worker applied the http3 config in this process.
|
|
87
|
+
private static volatile boolean configured;
|
|
88
|
+
// Guards the configured check plus the enabled write, kept apart from init() so it never waits on engine setup.
|
|
89
|
+
private static final Object OPTION_LOCK = new Object();
|
|
90
|
+
private static boolean initialized;
|
|
91
|
+
|
|
92
|
+
private Http3() {}
|
|
93
|
+
|
|
94
|
+
/** The http3 config value, applied by plugin load and the headless worker. Wins over saved job values. */
|
|
95
|
+
static void setEnabled(boolean value) {
|
|
96
|
+
synchronized (OPTION_LOCK) {
|
|
97
|
+
enabled = value;
|
|
98
|
+
configured = true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The http3 value saved with a WorkManager job. Only used when this process has not loaded the config yet
|
|
104
|
+
* (a job resumed in a fresh process), so a stale job never overrides the current config.
|
|
105
|
+
*/
|
|
106
|
+
static void restoreSavedOption(boolean value) {
|
|
107
|
+
synchronized (OPTION_LOCK) {
|
|
108
|
+
if (!configured) {
|
|
109
|
+
enabled = value;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
static boolean isEnabled() {
|
|
115
|
+
return enabled;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** HttpEngine is public API from 34, and ships to 31-33 through the S extension at level 7. */
|
|
119
|
+
static boolean isHttpEngineAvailable(int sdkInt, int sExtensionVersion) {
|
|
120
|
+
return sdkInt >= 34 || (sdkInt >= 31 && sExtensionVersion >= 7);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private static int sExtensionVersion() {
|
|
124
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
return SdkExtensions.getExtensionVersion(Build.VERSION_CODES.S);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Builds the shared engine once per process. Safe to call before every download. */
|
|
131
|
+
static void init(@NonNull Context context, @Nullable Logger logger) {
|
|
132
|
+
if (transport != null || !enabled) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
int sdkInt = Build.VERSION.SDK_INT;
|
|
136
|
+
int extension;
|
|
137
|
+
try {
|
|
138
|
+
extension = sExtensionVersion();
|
|
139
|
+
} catch (RuntimeException e) {
|
|
140
|
+
extension = 0;
|
|
141
|
+
}
|
|
142
|
+
init(context, logger, sdkInt, extension, HttpEngineTransport::create);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
static synchronized void init(
|
|
146
|
+
@NonNull Context context,
|
|
147
|
+
@Nullable Logger logger,
|
|
148
|
+
int sdkInt,
|
|
149
|
+
int sExtensionVersion,
|
|
150
|
+
@NonNull TransportFactory factory
|
|
151
|
+
) {
|
|
152
|
+
if (initialized || !enabled) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
initialized = true;
|
|
156
|
+
if (!isHttpEngineAvailable(sdkInt, sExtensionVersion)) {
|
|
157
|
+
debug(logger, "HttpEngine not available (API " + sdkInt + "), downloads stay on OkHttp");
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
transport = factory.create(context.getApplicationContext() != null ? context.getApplicationContext() : context, logger);
|
|
162
|
+
debug(logger, "HttpEngine ready, HTTP/3 enabled for bundle downloads");
|
|
163
|
+
} catch (RuntimeException | LinkageError e) {
|
|
164
|
+
// LinkageError: a device that reports the extension but cannot load the engine classes.
|
|
165
|
+
transport = null;
|
|
166
|
+
if (logger != null) {
|
|
167
|
+
logger.warn("HttpEngine failed to start, downloads stay on OkHttp: " + e.getMessage());
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
@Nullable
|
|
173
|
+
static Transport transport() {
|
|
174
|
+
return transport;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Called when the engine stalled: downloads use OkHttp for {@link #STALL_COOLDOWN_MS}. */
|
|
178
|
+
static void suspendAfterStall(long nowNanos) {
|
|
179
|
+
suspendedUntilNanos = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
|
|
180
|
+
stalledOnce = true;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
static boolean isSuspended(long nowNanos) {
|
|
184
|
+
return stalledOnce && nowNanos - suspendedUntilNanos < 0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Test hook: forget the engine so the next init() starts over. */
|
|
188
|
+
static synchronized void resetForTest() {
|
|
189
|
+
transport = null;
|
|
190
|
+
initialized = false;
|
|
191
|
+
stalledOnce = false;
|
|
192
|
+
synchronized (OPTION_LOCK) {
|
|
193
|
+
enabled = true;
|
|
194
|
+
configured = false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
@NonNull
|
|
199
|
+
static Request.Builder markDownload(@NonNull Request.Builder builder) {
|
|
200
|
+
return builder.tag(Download.class, Download.TAG);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
static boolean shouldUseEngine(@NonNull Request request) {
|
|
204
|
+
return (
|
|
205
|
+
enabled &&
|
|
206
|
+
request.tag(Download.class) != null &&
|
|
207
|
+
"GET".equals(request.method()) &&
|
|
208
|
+
request.body() == null &&
|
|
209
|
+
// HTTP/3 only exists over TLS, so plain http (local dev servers) keeps the OkHttp path.
|
|
210
|
+
request.isHttps() &&
|
|
211
|
+
!isSuspended(System.nanoTime())
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Last application interceptor on the shared client, so User-Agent and the httpsOnly gate already ran.
|
|
217
|
+
* The engine follows redirects itself, and checks every hop with {@link #redirectError}.
|
|
218
|
+
*/
|
|
219
|
+
static final class EngineInterceptor implements Interceptor {
|
|
220
|
+
|
|
221
|
+
@NonNull
|
|
222
|
+
@Override
|
|
223
|
+
public Response intercept(@NonNull Chain chain) throws IOException {
|
|
224
|
+
Request request = chain.request();
|
|
225
|
+
Transport current = transport;
|
|
226
|
+
if (current == null || !shouldUseEngine(request)) {
|
|
227
|
+
Response response = chain.proceed(request);
|
|
228
|
+
if (request.tag(Download.class) != null) {
|
|
229
|
+
logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
|
|
230
|
+
}
|
|
231
|
+
return response;
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
return current.execute(request, chain.connectTimeoutMillis(), chain.readTimeoutMillis(), chain.call());
|
|
235
|
+
} catch (EngineStalledException stall) {
|
|
236
|
+
// No response headers yet, so nothing reached the caller: retry this download on OkHttp right away.
|
|
237
|
+
suspendAfterStall(System.nanoTime());
|
|
238
|
+
Logger logger = DownloadService.logger();
|
|
239
|
+
if (logger != null) {
|
|
240
|
+
logger.warn("HttpEngine stalled, download moved to OkHttp: " + stall.getMessage());
|
|
241
|
+
}
|
|
242
|
+
Response response = chain.proceed(request);
|
|
243
|
+
logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
|
|
244
|
+
return response;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Maps HttpEngine's ALPN name (h3, h2, http/1.1, quic/1+spdy/3...) to the closest OkHttp protocol. */
|
|
250
|
+
@NonNull
|
|
251
|
+
static Protocol protocolFor(@Nullable String negotiated) {
|
|
252
|
+
if (negotiated == null) {
|
|
253
|
+
return Protocol.HTTP_1_1;
|
|
254
|
+
}
|
|
255
|
+
String value = negotiated.toLowerCase(Locale.ROOT);
|
|
256
|
+
if (value.startsWith("h3") || value.startsWith("quic")) {
|
|
257
|
+
return Protocol.QUIC;
|
|
258
|
+
}
|
|
259
|
+
if (value.equals("h2")) {
|
|
260
|
+
return Protocol.HTTP_2;
|
|
261
|
+
}
|
|
262
|
+
if (value.equals("http/1.0")) {
|
|
263
|
+
return Protocol.HTTP_1_0;
|
|
264
|
+
}
|
|
265
|
+
return Protocol.HTTP_1_1;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* HttpEngine always negotiates gzip/br and hands back the decoded body, but keeps the encoded headers. Drop
|
|
270
|
+
* Content-Encoding and Content-Length then, as OkHttp does after transparent gzip, so callers see an unknown
|
|
271
|
+
* length instead of a wrong one (the checksum still verifies the bytes).
|
|
272
|
+
*/
|
|
273
|
+
@NonNull
|
|
274
|
+
static Headers responseHeaders(@NonNull List<Map.Entry<String, String>> fields) {
|
|
275
|
+
boolean decoded = false;
|
|
276
|
+
for (Map.Entry<String, String> field : fields) {
|
|
277
|
+
if (field.getKey() != null && field.getKey().equalsIgnoreCase("Content-Encoding") && isContentCoding(field.getValue())) {
|
|
278
|
+
decoded = true;
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
Headers.Builder headers = new Headers.Builder();
|
|
283
|
+
for (Map.Entry<String, String> field : fields) {
|
|
284
|
+
String name = field.getKey();
|
|
285
|
+
if (name == null || field.getValue() == null) {
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (decoded && (name.equalsIgnoreCase("Content-Encoding") || name.equalsIgnoreCase("Content-Length"))) {
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
headers.addUnsafeNonAscii(name, field.getValue());
|
|
292
|
+
}
|
|
293
|
+
return headers.build();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** {@code identity} (or an empty value) means no coding was applied, so the Content-Length stays valid. */
|
|
297
|
+
private static boolean isContentCoding(@Nullable String value) {
|
|
298
|
+
if (value == null) {
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
String coding = value.trim();
|
|
302
|
+
return !coding.isEmpty() && !coding.equalsIgnoreCase("identity");
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Host only, for log and error messages: a signed download URL carries credentials in its query. */
|
|
306
|
+
@NonNull
|
|
307
|
+
static String safeHost(@Nullable String url) {
|
|
308
|
+
HttpUrl parsed = url == null ? null : HttpUrl.parse(url);
|
|
309
|
+
return parsed != null ? parsed.host() : "unknown host";
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Same policy as the shared client's network interceptor, for redirects the engine follows itself. */
|
|
313
|
+
@Nullable
|
|
314
|
+
static IOException redirectError(@Nullable String from, @Nullable String to) {
|
|
315
|
+
return redirectError(from, to, DownloadService.httpsOnly, DownloadService.isAllowHttpsToHttpRedirect());
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
@Nullable
|
|
319
|
+
static IOException redirectError(@Nullable String from, @Nullable String to, boolean httpsOnly, boolean allowHttpsToHttp) {
|
|
320
|
+
HttpUrl target = to == null ? null : HttpUrl.parse(to);
|
|
321
|
+
if (target == null) {
|
|
322
|
+
return new IOException("Invalid redirect location");
|
|
323
|
+
}
|
|
324
|
+
if (httpsOnly && !target.isHttps()) {
|
|
325
|
+
return new IOException(CapgoUpdater.httpsOnlyMessage(to));
|
|
326
|
+
}
|
|
327
|
+
HttpUrl source = from == null ? null : HttpUrl.parse(from);
|
|
328
|
+
if (source != null && source.isHttps() && !target.isHttps() && !allowHttpsToHttp) {
|
|
329
|
+
return new DownloadService.BlockedRedirectException();
|
|
330
|
+
}
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
static void logProtocol(String transportName, @Nullable String protocol, @NonNull HttpUrl url, int code) {
|
|
335
|
+
Logger logger = DownloadService.logger();
|
|
336
|
+
if (logger != null) {
|
|
337
|
+
logger.debug(
|
|
338
|
+
"Download protocol " +
|
|
339
|
+
(protocol == null || protocol.isEmpty() ? "unknown" : protocol) +
|
|
340
|
+
" via " +
|
|
341
|
+
transportName +
|
|
342
|
+
" (HTTP " +
|
|
343
|
+
code +
|
|
344
|
+
") " +
|
|
345
|
+
url.host() +
|
|
346
|
+
url.encodedPath()
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private static void debug(@Nullable Logger logger, String message) {
|
|
352
|
+
if (logger != null) {
|
|
353
|
+
logger.debug(message);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|