@capgo/capacitor-updater 9.0.0 → 9.0.2

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.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2406 -291
  4. package/android/build.gradle +37 -17
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +963 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2641 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +876 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1109 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,604 @@
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.net.http.HttpEngine;
10
+ import android.net.http.HttpException;
11
+ import android.net.http.NetworkException;
12
+ import android.net.http.UrlRequest;
13
+ import android.net.http.UrlResponseInfo;
14
+ import android.os.Build;
15
+ import androidx.annotation.NonNull;
16
+ import androidx.annotation.Nullable;
17
+ import androidx.annotation.RequiresExtension;
18
+ import java.io.File;
19
+ import java.io.IOException;
20
+ import java.io.InputStream;
21
+ import java.io.InterruptedIOException;
22
+ import java.net.ConnectException;
23
+ import java.net.SocketException;
24
+ import java.net.SocketTimeoutException;
25
+ import java.net.UnknownHostException;
26
+ import java.nio.ByteBuffer;
27
+ import java.util.concurrent.BlockingQueue;
28
+ import java.util.concurrent.ConcurrentHashMap;
29
+ import java.util.concurrent.Executor;
30
+ import java.util.concurrent.ExecutorService;
31
+ import java.util.concurrent.Executors;
32
+ import java.util.concurrent.LinkedBlockingQueue;
33
+ import java.util.concurrent.TimeUnit;
34
+ import java.util.concurrent.atomic.AtomicLong;
35
+ import okhttp3.Call;
36
+ import okhttp3.Headers;
37
+ import okhttp3.MediaType;
38
+ import okhttp3.Request;
39
+ import okhttp3.Response;
40
+ import okhttp3.ResponseBody;
41
+ import okio.Okio;
42
+
43
+ /**
44
+ * {@link Http3.Transport} on the platform HttpEngine. Uses the UrlRequest callback API rather than the engine's
45
+ * HttpURLConnection so every redirect hop goes through the updater's https policy, timeouts are enforced (the
46
+ * engine ignores connect timeouts), and the negotiated protocol can be logged.
47
+ */
48
+ @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
49
+ final class HttpEngineTransport implements Http3.Transport {
50
+
51
+ static final String STORAGE_DIR = "capgo_httpengine";
52
+ // Room for Alt-Svc, QUIC server info and host cache only: DISK_NO_HTTP never stores a response body.
53
+ private static final long STORAGE_BYTES = 1024 * 1024;
54
+ private static final int READ_BUFFER_BYTES = 32 * 1024;
55
+ // Poll slice so a cancelled OkHttp call (WorkManager stop) stops waiting promptly and a stall is seen within
56
+ // 50 ms of the stall window.
57
+ private static final long POLL_MS = 50;
58
+
59
+ private final HttpEngine engine;
60
+ private final Executor callbackExecutor;
61
+ private final Liveness liveness = new Liveness();
62
+
63
+ /** Time source and event wait. Tests replace it so stall timing never depends on thread scheduling. */
64
+ interface Clock {
65
+ long nanoTime();
66
+
67
+ /** Waits up to {@code timeoutMs} for the next event, null when none arrived. */
68
+ @Nullable
69
+ Object poll(@NonNull BlockingQueue<Object> events, long timeoutMs) throws InterruptedException;
70
+ }
71
+
72
+ static final Clock SYSTEM_CLOCK = new Clock() {
73
+ @Override
74
+ public long nanoTime() {
75
+ return System.nanoTime();
76
+ }
77
+
78
+ @Nullable
79
+ @Override
80
+ public Object poll(@NonNull BlockingQueue<Object> events, long timeoutMs) throws InterruptedException {
81
+ return events.poll(timeoutMs, TimeUnit.MILLISECONDS);
82
+ }
83
+ };
84
+
85
+ private HttpEngineTransport(HttpEngine engine, Executor callbackExecutor) {
86
+ this.engine = engine;
87
+ this.callbackExecutor = callbackExecutor;
88
+ }
89
+
90
+ @NonNull
91
+ static Http3.Transport create(@NonNull Context context, @Nullable Logger logger) {
92
+ // noBackupFilesDir: kept across launches (unlike a cache dir the OS may clear) and never restored onto
93
+ // another device or network by Auto Backup.
94
+ File storage = new File(context.getNoBackupFilesDir(), STORAGE_DIR);
95
+ if (!storage.isDirectory() && !storage.mkdirs()) {
96
+ throw new IllegalStateException("cannot create " + storage.getAbsolutePath());
97
+ }
98
+ HttpEngine engine = new HttpEngine.Builder(context)
99
+ .setStoragePath(storage.getAbsolutePath())
100
+ .setEnableHttpCache(HttpEngine.Builder.HTTP_CACHE_DISK_NO_HTTP, STORAGE_BYTES)
101
+ .setEnableQuic(true)
102
+ .setEnableHttp2(true)
103
+ .build();
104
+ ExecutorService executor = Executors.newSingleThreadExecutor((runnable) -> {
105
+ Thread thread = new Thread(runnable, "capgo-httpengine");
106
+ thread.setDaemon(true);
107
+ return thread;
108
+ });
109
+ return new HttpEngineTransport(engine, executor);
110
+ }
111
+
112
+ @NonNull
113
+ @Override
114
+ public Response execute(@NonNull Request request, int connectTimeoutMs, int readTimeoutMs, @Nullable Call call) throws IOException {
115
+ EngineCall engineCall = new EngineCall(request.url().toString(), call, liveness, Http3.STALL_MS);
116
+ UrlRequest.Builder builder = engine.newUrlRequestBuilder(request.url().toString(), callbackExecutor, engineCall);
117
+ builder.setHttpMethod("GET");
118
+ Headers headers = request.headers();
119
+ for (int i = 0; i < headers.size(); i++) {
120
+ builder.addHeader(headers.name(i), headers.value(i));
121
+ }
122
+ UrlRequest urlRequest = builder.build();
123
+ engineCall.start(urlRequest);
124
+ // OkHttp: connect timeout for the connection, then read timeout for the response headers.
125
+ UrlResponseInfo info = engineCall.awaitResponse(headerWaitBudgetMs(connectTimeoutMs, readTimeoutMs));
126
+ String negotiated = info.getNegotiatedProtocol();
127
+ Http3.logProtocol("HttpEngine", negotiated, request.url(), info.getHttpStatusCode());
128
+
129
+ Headers responseHeaders = Http3.responseHeaders(info.getHeaders().getAsList());
130
+ String contentType = responseHeaders.get("Content-Type");
131
+ String contentLength = responseHeaders.get("Content-Length");
132
+ long length = -1;
133
+ if (contentLength != null) {
134
+ try {
135
+ length = Long.parseLong(contentLength.trim());
136
+ } catch (NumberFormatException ignored) {}
137
+ }
138
+ String message = info.getHttpStatusText();
139
+ Request.Builder finalRequest = request.newBuilder().tag(Http3.ServedByEngine.class, Http3.ServedByEngine.TAG);
140
+ String finalUrl = info.getUrl();
141
+ if (finalUrl != null && !finalUrl.equals(request.url().toString())) {
142
+ okhttp3.HttpUrl parsed = okhttp3.HttpUrl.parse(finalUrl);
143
+ if (parsed != null) {
144
+ finalRequest.url(parsed);
145
+ }
146
+ }
147
+ InputStream body = engineCall.bodyStream(readTimeoutMs);
148
+ return new Response.Builder()
149
+ .request(finalRequest.build())
150
+ .protocol(Http3.protocolFor(negotiated))
151
+ .code(info.getHttpStatusCode())
152
+ .message(message != null ? message : "")
153
+ .headers(responseHeaders)
154
+ .body(ResponseBody.create(Okio.buffer(Okio.source(body)), contentType != null ? MediaType.parse(contentType) : null, length))
155
+ .build();
156
+ }
157
+
158
+ static IOException translate(@NonNull HttpException error) {
159
+ if (error instanceof NetworkException) {
160
+ return networkError(((NetworkException) error).getErrorCode(), error.getMessage(), error);
161
+ }
162
+ return new IOException("HttpEngine request failed: " + error.getMessage(), error);
163
+ }
164
+
165
+ /**
166
+ * Maps HttpEngine network errors onto the java.net exceptions OkHttp throws for the same failure, so the
167
+ * download retry logic ({@link DownloadService#isRetryableManifestError}) treats them the same way.
168
+ * TLS and any other engine error stay a plain IOException, which is not retried.
169
+ */
170
+ @NonNull
171
+ static IOException networkError(int errorCode, @Nullable String message, @Nullable Throwable cause) {
172
+ String text = "HttpEngine request failed: " + message;
173
+ IOException mapped;
174
+ switch (errorCode) {
175
+ case NetworkException.ERROR_HOSTNAME_NOT_RESOLVED:
176
+ mapped = new UnknownHostException(text);
177
+ break;
178
+ case NetworkException.ERROR_TIMED_OUT:
179
+ case NetworkException.ERROR_CONNECTION_TIMED_OUT:
180
+ mapped = new SocketTimeoutException(text);
181
+ break;
182
+ case NetworkException.ERROR_CONNECTION_REFUSED:
183
+ mapped = new ConnectException(text);
184
+ break;
185
+ case NetworkException.ERROR_INTERNET_DISCONNECTED:
186
+ case NetworkException.ERROR_NETWORK_CHANGED:
187
+ case NetworkException.ERROR_CONNECTION_CLOSED:
188
+ case NetworkException.ERROR_CONNECTION_RESET:
189
+ case NetworkException.ERROR_ADDRESS_UNREACHABLE:
190
+ case NetworkException.ERROR_QUIC_PROTOCOL_FAILED:
191
+ mapped = new SocketException(text);
192
+ break;
193
+ default:
194
+ return new IOException(text, cause);
195
+ }
196
+ if (cause != null) {
197
+ mapped.initCause(cause);
198
+ }
199
+ return mapped;
200
+ }
201
+
202
+ /** Longest wait for response headers, whatever the configured timeouts add up to (AGENTS.md: 10 minutes max). */
203
+ static final long MAX_HEADER_WAIT_MS = 600_000;
204
+
205
+ /** OkHttp waits connect timeout then read timeout for headers; the engine has one wait, so it gets the sum, capped. */
206
+ static long headerWaitBudgetMs(int connectTimeoutMs, int readTimeoutMs) {
207
+ // 0 means no timeout in OkHttp.
208
+ if (connectTimeoutMs <= 0 || readTimeoutMs <= 0) {
209
+ return 0;
210
+ }
211
+ return Math.min(MAX_HEADER_WAIT_MS, (long) connectTimeoutMs + (long) readTimeoutMs);
212
+ }
213
+
214
+ /** Wait for each body chunk: the read timeout, capped like the header wait (AGENTS.md: 10 minutes max). */
215
+ static int bodyReadTimeoutMs(int readTimeoutMs) {
216
+ // 0 means no timeout in OkHttp.
217
+ if (readTimeoutMs <= 0) {
218
+ return 0;
219
+ }
220
+ return (int) Math.min(MAX_HEADER_WAIT_MS, readTimeoutMs);
221
+ }
222
+
223
+ /**
224
+ * Last time any request on the shared engine got a callback (one engine, one picture of whether it is alive),
225
+ * and the last time per connection (scheme, host, port), which tells a request on a warm connection from one still setting up a new one.
226
+ */
227
+ static final class Liveness {
228
+
229
+ private final AtomicLong lastNanos = new AtomicLong();
230
+ // A handful of download hosts per process (update server, CDN, redirect targets), so this stays tiny.
231
+ private final ConcurrentHashMap<String, Long> hostNanos = new ConcurrentHashMap<>();
232
+ // False until the first callback: a new engine has not proven it is alive, so nothing can stall yet.
233
+ private volatile boolean seen;
234
+ final Clock clock;
235
+
236
+ Liveness() {
237
+ this(SYSTEM_CLOCK);
238
+ }
239
+
240
+ Liveness(@NonNull Clock clock) {
241
+ this.clock = clock;
242
+ }
243
+
244
+ void mark(@NonNull String host) {
245
+ long now = clock.nanoTime();
246
+ lastNanos.set(now);
247
+ hostNanos.put(host, now);
248
+ seen = true;
249
+ }
250
+
251
+ /** Last callback for a request to {@code host}, or null when the engine has not talked to it yet. */
252
+ @Nullable
253
+ Long lastNanos(@NonNull String host) {
254
+ return hostNanos.get(host);
255
+ }
256
+
257
+ boolean seen() {
258
+ return seen;
259
+ }
260
+
261
+ long lastNanos() {
262
+ return lastNanos.get();
263
+ }
264
+ }
265
+
266
+ /** Bridges the engine callbacks to a blocking response and body stream. */
267
+ static final class EngineCall implements UrlRequest.Callback {
268
+
269
+ private static final Object SUCCEEDED = new Object();
270
+
271
+ private static final class Started {
272
+
273
+ final UrlResponseInfo info;
274
+
275
+ Started(UrlResponseInfo info) {
276
+ this.info = info;
277
+ }
278
+ }
279
+
280
+ private static final class ReadDone {
281
+
282
+ final ByteBuffer buffer;
283
+
284
+ ReadDone(ByteBuffer buffer) {
285
+ this.buffer = buffer;
286
+ }
287
+ }
288
+
289
+ private static final class Failed {
290
+
291
+ final IOException error;
292
+
293
+ Failed(IOException error) {
294
+ this.error = error;
295
+ }
296
+ }
297
+
298
+ private final BlockingQueue<Object> events = new LinkedBlockingQueue<>();
299
+ private final String url;
300
+
301
+ @Nullable
302
+ private final Call call;
303
+
304
+ private volatile UrlRequest request;
305
+ private volatile String currentUrl;
306
+ // Warmth key of the current hop (scheme, host, port); see Http3.connectionKey.
307
+ private volatile String currentConnection;
308
+ // When the current hop started: set on each followed redirect, so a redirect target is judged warm or cold
309
+ // from the redirect, not from the start of the whole header wait. Guarded by the liveness monitor.
310
+ private long hopStartNanos;
311
+ private boolean redirected;
312
+ // Warm/cold verdict for the hop that started at warmHopStart, decided once from activity recorded before that
313
+ // hop: callbacks of the hop itself must never turn a cold hop warm mid-wait. Guarded by the liveness monitor.
314
+ private boolean warmDecided;
315
+ private long warmHopStart;
316
+ private boolean hopWarm;
317
+ private volatile IOException redirectError;
318
+
319
+ private final Liveness liveness;
320
+ private final long stallNanos;
321
+
322
+ EngineCall(String url, @Nullable Call call) {
323
+ this(url, call, new Liveness(), Http3.STALL_MS);
324
+ }
325
+
326
+ EngineCall(String url, @Nullable Call call, @NonNull Liveness liveness, long stallMs) {
327
+ this.url = url;
328
+ this.currentUrl = url;
329
+ this.currentConnection = Http3.connectionKey(url);
330
+ this.call = call;
331
+ this.liveness = liveness;
332
+ this.stallNanos = TimeUnit.MILLISECONDS.toNanos(stallMs);
333
+ }
334
+
335
+ void start(UrlRequest urlRequest) {
336
+ this.request = urlRequest;
337
+ urlRequest.start();
338
+ }
339
+
340
+ @Override
341
+ public void onRedirectReceived(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info, @NonNull String newLocationUrl) {
342
+ // Same monitor as the stall check, so it never sees a host mark without the matching global mark.
343
+ synchronized (liveness) {
344
+ liveness.mark(currentConnection);
345
+ }
346
+ IOException error = Http3.redirectError(currentUrl, newLocationUrl);
347
+ if (error != null) {
348
+ redirectError = error;
349
+ urlRequest.cancel();
350
+ return;
351
+ }
352
+ currentUrl = newLocationUrl;
353
+ synchronized (liveness) {
354
+ currentConnection = Http3.connectionKey(newLocationUrl);
355
+ hopStartNanos = liveness.clock.nanoTime();
356
+ redirected = true;
357
+ // Decide now, before the target can answer: only activity before the redirect counts.
358
+ decideHopWarmth(hopStartNanos);
359
+ }
360
+ urlRequest.followRedirect();
361
+ }
362
+
363
+ @Override
364
+ public void onResponseStarted(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info) {
365
+ publish(new Started(info));
366
+ }
367
+
368
+ @Override
369
+ public void onReadCompleted(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info, @NonNull ByteBuffer byteBuffer) {
370
+ publish(new ReadDone(byteBuffer));
371
+ }
372
+
373
+ @Override
374
+ public void onSucceeded(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info) {
375
+ publish(SUCCEEDED);
376
+ }
377
+
378
+ @Override
379
+ public void onFailed(@NonNull UrlRequest urlRequest, @Nullable UrlResponseInfo info, @NonNull HttpException error) {
380
+ publish(new Failed(translate(error)));
381
+ }
382
+
383
+ @Override
384
+ public void onCanceled(@NonNull UrlRequest urlRequest, @Nullable UrlResponseInfo info) {
385
+ IOException error = redirectError;
386
+ events.offer(new Failed(error != null ? error : new IOException("Canceled")));
387
+ }
388
+
389
+ /**
390
+ * Marks progress and queues an event under the liveness lock, so a stall decision either sees the event or
391
+ * finishes before it was published, never in between.
392
+ */
393
+ private void publish(@NonNull Object event) {
394
+ synchronized (liveness) {
395
+ liveness.mark(currentConnection);
396
+ events.offer(event);
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Next callback event, or null on timeout (0 waits forever). Cancels the request when OkHttp's call is.
402
+ * Throws {@link Http3.EngineStalledException} when the whole engine went silent for the stall window: always
403
+ * while waiting for headers (the caller can still retry on OkHttp) if the engine was busy just before, and
404
+ * while reading a body only once a stall is already confirmed, so a slow single body never trips it.
405
+ */
406
+ @Nullable
407
+ private Object next(long timeoutMs, boolean waitingForHeaders) throws IOException {
408
+ Clock clock = liveness.clock;
409
+ long start;
410
+ synchronized (liveness) {
411
+ start = clock.nanoTime();
412
+ // Decide the first hop's warmth with its boundary, under the lock: a mark from another request on this
413
+ // host between the two would otherwise replace the earlier activity the verdict needs. A followed
414
+ // redirect was already decided when it arrived.
415
+ if (!redirected) {
416
+ decideHopWarmth(start);
417
+ }
418
+ }
419
+ long deadline = timeoutMs > 0 ? start + TimeUnit.MILLISECONDS.toNanos(timeoutMs) : Long.MAX_VALUE;
420
+ try {
421
+ while (true) {
422
+ if (call != null && call.isCanceled()) {
423
+ cancel();
424
+ throw new IOException("Canceled");
425
+ }
426
+ // An event already queued is progress, even if this thread resumed late: hand it over instead
427
+ // of cancelling a request whose response already arrived.
428
+ Object ready = pollOrDetectStall(start, waitingForHeaders);
429
+ if (ready != null) {
430
+ return ready;
431
+ }
432
+ long remainingNanos;
433
+ synchronized (liveness) {
434
+ // Decide the deadline in nanoseconds and under the publish lock: a sub-millisecond budget is
435
+ // still a budget, and a callback published right at the deadline is handed over, not dropped.
436
+ remainingNanos = timeoutMs > 0 ? deadline - clock.nanoTime() : TimeUnit.MILLISECONDS.toNanos(POLL_MS);
437
+ if (remainingNanos <= 0) {
438
+ return events.poll();
439
+ }
440
+ }
441
+ // Round up so the last partial millisecond is waited for instead of read as zero.
442
+ long waitMs = Math.min(POLL_MS, Math.max(1, (remainingNanos + 999_999L) / 1_000_000L));
443
+ Object event = clock.poll(events, waitMs);
444
+ if (event != null) {
445
+ return event;
446
+ }
447
+ }
448
+ } catch (InterruptedException e) {
449
+ Thread.currentThread().interrupt();
450
+ cancel();
451
+ throw new InterruptedIOException("interrupted");
452
+ }
453
+ }
454
+
455
+ /**
456
+ * A queued event, else null when the engine is not stalled. The queue check and the stall decision run under
457
+ * the same lock as {@link #publish}, so a callback can never land between them and be dropped as a stall.
458
+ */
459
+ @Nullable
460
+ private Object pollOrDetectStall(long waitStartNanos, boolean waitingForHeaders) throws Http3.EngineStalledException {
461
+ long silentMs;
462
+ synchronized (liveness) {
463
+ Object ready = events.poll();
464
+ if (ready != null) {
465
+ return ready;
466
+ }
467
+ long now = liveness.clock.nanoTime();
468
+ boolean seen = liveness.seen();
469
+ long last = seen ? liveness.lastNanos() : waitStartNanos;
470
+ // Headers: only when the engine was talking to this same host right before this wait, so the request
471
+ // rides a warm connection. The first request of a process, a lone one after a quiet period, and one to
472
+ // a host the engine has not reached recently (a redirect target, another CDN) pay a full handshake
473
+ // that can take longer on a slow network, and keep the normal timeout instead of suspending HTTP/3.
474
+ // Judge the current hop: after a followed redirect (before or during this wait), the target must have
475
+ // been active within the stall window before the redirect, not merely at some point since. The verdict
476
+ // is fixed once per hop, so later callbacks cannot make a cold host warm. Silence and the deadline still
477
+ // count from the wait start.
478
+ long hopStart = redirected ? hopStartNanos : waitStartNanos;
479
+ if (!warmDecided || warmHopStart != hopStart) {
480
+ decideHopWarmth(hopStart);
481
+ }
482
+ boolean armed = waitingForHeaders ? hopWarm : Http3.isStallConfirmed(now);
483
+ long silentSince = last - waitStartNanos >= 0 ? last : waitStartNanos;
484
+ if (!armed || now - silentSince < stallNanos) {
485
+ return null;
486
+ }
487
+ silentMs = TimeUnit.NANOSECONDS.toMillis(now - silentSince);
488
+ }
489
+ // Outside the lock: cancelling posts onCanceled to the callback executor.
490
+ cancel();
491
+ throw new Http3.EngineStalledException("HttpEngine made no progress for " + silentMs + " ms on " + Http3.safeHost(url));
492
+ }
493
+
494
+ /** Caller holds the liveness monitor. Warm only for activity on currentConnection within the stall window before hopStart. */
495
+ private void decideHopWarmth(long hopStart) {
496
+ Long hostLast = liveness.lastNanos(currentConnection);
497
+ hopWarm = hostLast != null && hostLast - (hopStart - stallNanos) >= 0 && hopStart - hostLast >= 0;
498
+ warmHopStart = hopStart;
499
+ warmDecided = true;
500
+ }
501
+
502
+ UrlResponseInfo awaitResponse(long timeoutMs) throws IOException {
503
+ Object event = next(timeoutMs, true);
504
+ if (event instanceof Started) {
505
+ return ((Started) event).info;
506
+ }
507
+ if (event instanceof Failed) {
508
+ throw ((Failed) event).error;
509
+ }
510
+ cancel();
511
+ // No headers yet: the interceptor can still retry this request on OkHttp (see EngineHeaderTimeoutException).
512
+ throw new Http3.EngineHeaderTimeoutException("HttpEngine timeout waiting for response headers from " + Http3.safeHost(url));
513
+ }
514
+
515
+ InputStream bodyStream(int readTimeoutMs) {
516
+ return new BodyStream(readTimeoutMs);
517
+ }
518
+
519
+ void cancel() {
520
+ UrlRequest current = request;
521
+ if (current != null && !current.isDone()) {
522
+ current.cancel();
523
+ }
524
+ }
525
+
526
+ private final class BodyStream extends InputStream {
527
+
528
+ private final int readTimeoutMs;
529
+ private final ByteBuffer buffer = ByteBuffer.allocateDirect(READ_BUFFER_BYTES);
530
+ private boolean done;
531
+ private boolean closed;
532
+
533
+ BodyStream(int readTimeoutMs) {
534
+ this.readTimeoutMs = bodyReadTimeoutMs(readTimeoutMs);
535
+ buffer.limit(0);
536
+ }
537
+
538
+ @Override
539
+ public int read() throws IOException {
540
+ byte[] one = new byte[1];
541
+ int n = read(one, 0, 1);
542
+ return n == -1 ? -1 : one[0] & 0xff;
543
+ }
544
+
545
+ @Override
546
+ public int read(@NonNull byte[] target, int offset, int length) throws IOException {
547
+ if (closed) {
548
+ throw new IOException("closed");
549
+ }
550
+ if (length == 0) {
551
+ return 0;
552
+ }
553
+ while (!buffer.hasRemaining()) {
554
+ if (done) {
555
+ return -1;
556
+ }
557
+ buffer.clear();
558
+ request.read(buffer);
559
+ Object event = next(readTimeoutMs, false);
560
+ if (event instanceof ReadDone) {
561
+ buffer.flip();
562
+ } else if (event == SUCCEEDED) {
563
+ done = true;
564
+ buffer.limit(0);
565
+ } else if (event instanceof Failed) {
566
+ done = true;
567
+ buffer.limit(0);
568
+ throw ((Failed) event).error;
569
+ } else {
570
+ done = true;
571
+ buffer.limit(0);
572
+ cancel();
573
+ // The body timed out on the engine. Skip it for the cooldown so the caller's retry, which
574
+ // starts a new request and keeps its own partial-file and checksum checks, runs on OkHttp
575
+ // instead of waiting on the same engine again. Bytes already delivered stay from this
576
+ // response; nothing switches streams mid-body. One slow body is not a confirmed engine
577
+ // stall, so other bodies still streaming on the engine keep their normal read timeout.
578
+ Http3.suspendAfterBodyTimeout(liveness.clock.nanoTime());
579
+ throw new SocketTimeoutException("HttpEngine read timeout");
580
+ }
581
+ }
582
+ int count = Math.min(length, buffer.remaining());
583
+ buffer.get(target, offset, count);
584
+ return count;
585
+ }
586
+
587
+ @Override
588
+ public int available() {
589
+ return buffer.remaining();
590
+ }
591
+
592
+ @Override
593
+ public void close() {
594
+ if (closed) {
595
+ return;
596
+ }
597
+ closed = true;
598
+ if (!done) {
599
+ cancel();
600
+ }
601
+ }
602
+ }
603
+ }
604
+ }
@@ -0,0 +1,79 @@
1
+ package ee.forgr.capacitor_updater;
2
+
3
+ import android.content.Context;
4
+ import android.content.pm.PackageInfo;
5
+ import android.content.pm.PackageManager;
6
+ import android.os.Build;
7
+ import com.getcapacitor.JSObject;
8
+ import com.getcapacitor.util.JSONUtils;
9
+ import java.io.BufferedReader;
10
+ import java.io.IOException;
11
+ import java.io.InputStreamReader;
12
+ import java.nio.charset.StandardCharsets;
13
+ import java.util.Map;
14
+ import org.json.JSONException;
15
+ import org.json.JSONObject;
16
+
17
+ public class InternalUtils {
18
+
19
+ static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
20
+
21
+ /**
22
+ * Converts a Map to JSObject for proper bridge serialization.
23
+ */
24
+ public static JSObject mapToJSObject(Map<String, Object> map) {
25
+ JSObject jsObject = new JSObject();
26
+ for (Map.Entry<String, Object> entry : map.entrySet()) {
27
+ jsObject.put(entry.getKey(), entry.getValue());
28
+ }
29
+ return jsObject;
30
+ }
31
+
32
+ public static String getPackageName(PackageManager pm, String packageName) {
33
+ try {
34
+ PackageInfo pInfo = getPackageInfoInternal(pm, packageName);
35
+ return pInfo != null ? pInfo.packageName : null;
36
+ } catch (PackageManager.NameNotFoundException e) {
37
+ // Exception is handled internally, and null is returned to indicate the package name could not be retrieved
38
+ return null;
39
+ }
40
+ }
41
+
42
+ static String readAssetAsString(final Context context, final String assetPath) throws IOException {
43
+ final StringBuilder buffer = new StringBuilder();
44
+ try (
45
+ final BufferedReader reader = new BufferedReader(
46
+ new InputStreamReader(context.getAssets().open(assetPath), StandardCharsets.UTF_8)
47
+ )
48
+ ) {
49
+ String line;
50
+ while ((line = reader.readLine()) != null) {
51
+ buffer.append(line).append('\n');
52
+ }
53
+ }
54
+ return buffer.toString();
55
+ }
56
+
57
+ /** Replaces CapConfig.getString for root keys: Capacitor 9 removed it. */
58
+ public static String getRootConfigString(Context context, String key, String defaultValue) {
59
+ try {
60
+ return JSONUtils.getString(new JSONObject(readAssetAsString(context, CAPACITOR_CONFIG_ASSET)), key, defaultValue);
61
+ } catch (IOException | JSONException e) {
62
+ return defaultValue;
63
+ }
64
+ }
65
+
66
+ private static PackageInfo getPackageInfoInternal(PackageManager pm, String packageName) throws PackageManager.NameNotFoundException {
67
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
68
+ return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0));
69
+ } else {
70
+ return getPackageInfoLegacy(pm, packageName, (int) (long) 0);
71
+ }
72
+ }
73
+
74
+ @SuppressWarnings("deprecation")
75
+ private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, int flags)
76
+ throws PackageManager.NameNotFoundException {
77
+ return pm.getPackageInfo(packageName, flags);
78
+ }
79
+ }