@capgo/capacitor-updater 8.53.0 → 8.54.0
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/README.md +31 -15
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +192 -18
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +343 -30
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +82 -19
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +4 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +147 -29
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +10 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +34 -0
- package/dist/docs.json +34 -2
- package/dist/esm/definitions.d.ts +46 -2
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +112 -11
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +288 -56
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +59 -33
- package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +0 -19
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +20 -0
- package/package.json +1 -1
|
@@ -27,14 +27,12 @@ import androidx.work.PeriodicWorkRequest;
|
|
|
27
27
|
import androidx.work.WorkInfo;
|
|
28
28
|
import androidx.work.WorkManager;
|
|
29
29
|
import java.io.BufferedInputStream;
|
|
30
|
-
import java.io.BufferedReader;
|
|
31
30
|
import java.io.File;
|
|
32
31
|
import java.io.FileInputStream;
|
|
33
32
|
import java.io.FileNotFoundException;
|
|
34
33
|
import java.io.FileOutputStream;
|
|
35
34
|
import java.io.FilenameFilter;
|
|
36
35
|
import java.io.IOException;
|
|
37
|
-
import java.io.InputStreamReader;
|
|
38
36
|
import java.nio.charset.StandardCharsets;
|
|
39
37
|
import java.nio.file.Files;
|
|
40
38
|
import java.security.SecureRandom;
|
|
@@ -87,7 +85,6 @@ public class CapgoUpdater {
|
|
|
87
85
|
private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
|
|
88
86
|
private static final long DELETE_PACE_MS = 75L;
|
|
89
87
|
private final Object deleteLock = new Object();
|
|
90
|
-
private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
|
|
91
88
|
private static final String BACKGROUND_RUNNER_CONFIG_KEY = "BackgroundRunner";
|
|
92
89
|
private static final String BACKGROUND_RUNNER_WORKER_CLASS = "io.ionic.backgroundrunner.plugin.RunnerWorker";
|
|
93
90
|
|
|
@@ -120,6 +117,13 @@ public class CapgoUpdater {
|
|
|
120
117
|
public String publicKey = "";
|
|
121
118
|
public String deviceID = "";
|
|
122
119
|
public int timeout = 20000;
|
|
120
|
+
/** Refuse bundles whose version is below the native app version (versionBuild). Config builtinMinimum, default false. */
|
|
121
|
+
public volatile boolean builtinMinimum = false;
|
|
122
|
+
/**
|
|
123
|
+
* Require https for every URL the updater downloads from. Config httpsOnly, default true. Mirrors
|
|
124
|
+
* DownloadService.httpsOnly (the OkHttp interceptor); this field gates URLs before any network IO.
|
|
125
|
+
*/
|
|
126
|
+
public volatile boolean httpsOnly = true;
|
|
123
127
|
|
|
124
128
|
// Cached key ID calculated once from publicKey
|
|
125
129
|
private String cachedKeyId = "";
|
|
@@ -147,17 +151,33 @@ public class CapgoUpdater {
|
|
|
147
151
|
private final AtomicBoolean statsFlushInFlight = new AtomicBoolean(false);
|
|
148
152
|
private final AtomicBoolean statsStopped = new AtomicBoolean(false);
|
|
149
153
|
private static final long STATS_FLUSH_INTERVAL_MS = 1000;
|
|
154
|
+
private static volatile Long statsFlushIntervalOverrideMs = null;
|
|
155
|
+
private static volatile boolean statsFlushSchedulingDisabledForTests = false;
|
|
156
|
+
/** Unit tests only: runs after queue mutation and before the stats owner check. */
|
|
157
|
+
static volatile Runnable statsAdoptionBeforeOwnerCheckForTests = null;
|
|
150
158
|
private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
|
|
151
159
|
private static final int MAX_PENDING_STATS = 200;
|
|
160
|
+
// The live plugin instance owns the stats file. A headless worker hands its unsent events to it
|
|
161
|
+
// instead of writing the file; events handed over before the plugin claims ownership wait here.
|
|
162
|
+
private static final Object statsOwnerLock = new Object();
|
|
163
|
+
private static CapgoUpdater statsOwner = null;
|
|
164
|
+
private static final List<JSONObject> orphanedStats = new ArrayList<>();
|
|
152
165
|
|
|
153
166
|
private static final class QueuedStatsEvent {
|
|
154
167
|
|
|
155
168
|
private final JSONObject event;
|
|
156
169
|
private final Runnable onSent;
|
|
170
|
+
/** True when the event was loaded from the shared pending-stats file (not created by this instance). */
|
|
171
|
+
private final boolean restored;
|
|
157
172
|
|
|
158
173
|
private QueuedStatsEvent(final JSONObject event, final Runnable onSent) {
|
|
174
|
+
this(event, onSent, false);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private QueuedStatsEvent(final JSONObject event, final Runnable onSent, final boolean restored) {
|
|
159
178
|
this.event = event;
|
|
160
179
|
this.onSent = onSent;
|
|
180
|
+
this.restored = restored;
|
|
161
181
|
}
|
|
162
182
|
}
|
|
163
183
|
|
|
@@ -631,6 +651,96 @@ public class CapgoUpdater {
|
|
|
631
651
|
}
|
|
632
652
|
}
|
|
633
653
|
|
|
654
|
+
static boolean isHttpsUrl(final String url) {
|
|
655
|
+
if (url == null) {
|
|
656
|
+
return false;
|
|
657
|
+
}
|
|
658
|
+
final String trimmed = url.trim();
|
|
659
|
+
return trimmed.regionMatches(true, 0, "https://", 0, "https://".length());
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
static String httpsOnlyMessage(final String url) {
|
|
663
|
+
return "httpsOnly is enabled and " + url + " is not https";
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** httpsOnly gate for the zip url and every manifest download_url, run before any network IO. */
|
|
667
|
+
void requireHttpsUrls(final String url, final JSONArray manifest) throws IOException {
|
|
668
|
+
if (!this.httpsOnly) {
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (manifest == null || manifest.length() == 0) {
|
|
672
|
+
if (!isHttpsUrl(url)) {
|
|
673
|
+
logger.error(httpsOnlyMessage(url));
|
|
674
|
+
throw new IOException(httpsOnlyMessage(url));
|
|
675
|
+
}
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
for (int i = 0; i < manifest.length(); i++) {
|
|
679
|
+
final JSONObject entry = manifest.optJSONObject(i);
|
|
680
|
+
final String downloadUrl = entry == null ? null : entry.optString("download_url", "");
|
|
681
|
+
if (!isHttpsUrl(downloadUrl)) {
|
|
682
|
+
logger.error(httpsOnlyMessage(downloadUrl));
|
|
683
|
+
throw new IOException(httpsOnlyMessage(downloadUrl));
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
static String stripBuildMetadata(final String version) {
|
|
689
|
+
if (version == null) {
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
final int plus = version.indexOf('+');
|
|
693
|
+
return plus >= 0 ? version.substring(0, plus) : version;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** Compares major.minor.patch only (missing components count as 0); suffix and extra components are ignored. */
|
|
697
|
+
static int compareCoreVersion(final Version left, final Version right) {
|
|
698
|
+
for (int i = 0; i < 3; i++) {
|
|
699
|
+
final long a = i < left.getSubversionNumbers().size() ? left.getSubversionNumbers().get(i) : 0L;
|
|
700
|
+
final long b = i < right.getSubversionNumbers().size() ? right.getSubversionNumbers().get(i) : 0L;
|
|
701
|
+
if (a != b) {
|
|
702
|
+
return Long.compare(a, b);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
return 0;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
static boolean isParsableVersion(final Version version) {
|
|
709
|
+
return version != null && version.getOriginalString() != null && !version.getSubversionNumbers().isEmpty();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* builtinMinimum gate: a bundle may never roll the app below its native version. Skipped (debug log) when
|
|
714
|
+
* either version string does not parse, so unversioned bundles keep working.
|
|
715
|
+
*/
|
|
716
|
+
void requireVersionNotBelowBuiltin(final String version) throws IOException {
|
|
717
|
+
if (!this.builtinMinimum) {
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
// Build metadata (+...) never takes part in ordering.
|
|
721
|
+
final Version bundle = new Version(stripBuildMetadata(version));
|
|
722
|
+
final Version nativeVersion = new Version(stripBuildMetadata(this.versionBuild));
|
|
723
|
+
if (!isParsableVersion(bundle) || !isParsableVersion(nativeVersion)) {
|
|
724
|
+
logger.debug(
|
|
725
|
+
"builtinMinimum skipped: cannot parse bundle version '" + version + "' or native version '" + this.versionBuild + "'"
|
|
726
|
+
);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
// Only major.minor.patch matter: prerelease suffixes and a fourth component are not a rollback.
|
|
730
|
+
if (compareCoreVersion(bundle, nativeVersion) < 0) {
|
|
731
|
+
final String message = "Bundle version " + version + " is below native version " + this.versionBuild + " (builtinMinimum)";
|
|
732
|
+
logger.error(message);
|
|
733
|
+
this.sendStats("version_below_native", version);
|
|
734
|
+
throw new IOException(message);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** Pre-network download gates shared by every entry point: httpsOnly and builtinMinimum. */
|
|
739
|
+
void runPreDownloadSecurityGates(final String url, final String version, final JSONArray manifest) throws IOException {
|
|
740
|
+
this.requireHttpsUrls(url, manifest);
|
|
741
|
+
this.requireVersionNotBelowBuiltin(version);
|
|
742
|
+
}
|
|
743
|
+
|
|
634
744
|
static boolean containsPathTraversalSegment(final String relativePath) {
|
|
635
745
|
for (final String segment : relativePath.split("/")) {
|
|
636
746
|
if ("..".equals(segment)) {
|
|
@@ -819,7 +929,7 @@ public class CapgoUpdater {
|
|
|
819
929
|
continue;
|
|
820
930
|
}
|
|
821
931
|
try {
|
|
822
|
-
|
|
932
|
+
DownloadService.linkOrCopyImmutableFile(file, cacheFile);
|
|
823
933
|
} catch (IOException e) {
|
|
824
934
|
logger.debug("Delta cache copy failed: " + file.getPath());
|
|
825
935
|
}
|
|
@@ -1662,21 +1772,6 @@ public class CapgoUpdater {
|
|
|
1662
1772
|
return config == null ? null : config.label;
|
|
1663
1773
|
}
|
|
1664
1774
|
|
|
1665
|
-
private String readAssetAsString(final String assetPath) throws IOException {
|
|
1666
|
-
final StringBuilder buffer = new StringBuilder();
|
|
1667
|
-
try (
|
|
1668
|
-
final BufferedReader reader = new BufferedReader(
|
|
1669
|
-
new InputStreamReader(this.context().getAssets().open(assetPath), StandardCharsets.UTF_8)
|
|
1670
|
-
)
|
|
1671
|
-
) {
|
|
1672
|
-
String line;
|
|
1673
|
-
while ((line = reader.readLine()) != null) {
|
|
1674
|
-
buffer.append(line).append('\n');
|
|
1675
|
-
}
|
|
1676
|
-
}
|
|
1677
|
-
return buffer.toString();
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
1775
|
private void copyFileAtomically(final File source, final File dest) throws IOException {
|
|
1681
1776
|
final File parent = dest.getParentFile();
|
|
1682
1777
|
if (parent != null && !parent.exists() && !parent.mkdirs()) {
|
|
@@ -1735,7 +1830,9 @@ public class CapgoUpdater {
|
|
|
1735
1830
|
|
|
1736
1831
|
final BackgroundRunnerWorkConfig config;
|
|
1737
1832
|
try {
|
|
1738
|
-
config = getBackgroundRunnerWorkConfigFromConfig(
|
|
1833
|
+
config = getBackgroundRunnerWorkConfigFromConfig(
|
|
1834
|
+
InternalUtils.readAssetAsString(this.context(), InternalUtils.CAPACITOR_CONFIG_ASSET)
|
|
1835
|
+
);
|
|
1739
1836
|
} catch (IOException ignored) {
|
|
1740
1837
|
return;
|
|
1741
1838
|
}
|
|
@@ -1858,6 +1955,7 @@ public class CapgoUpdater {
|
|
|
1858
1955
|
if (manifest == null) {
|
|
1859
1956
|
this.requireBundleChecksum(checksum);
|
|
1860
1957
|
}
|
|
1958
|
+
this.runPreDownloadSecurityGates(url, version, manifest);
|
|
1861
1959
|
} catch (final IOException e) {
|
|
1862
1960
|
logger.error("Download blocked: " + e.getMessage());
|
|
1863
1961
|
return null;
|
|
@@ -1914,6 +2012,7 @@ public class CapgoUpdater {
|
|
|
1914
2012
|
public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
|
|
1915
2013
|
this.requireSessionKeyForEncryptedUpdate(sessionKey);
|
|
1916
2014
|
this.requireBundleChecksum(checksum);
|
|
2015
|
+
this.runPreDownloadSecurityGates(url, version, null);
|
|
1917
2016
|
this.runDownloadGate();
|
|
1918
2017
|
// Check for existing bundle with same version and clean up if in error state
|
|
1919
2018
|
BundleInfo existingBundle = this.getBundleInfoByName(version);
|
|
@@ -1971,6 +2070,7 @@ public class CapgoUpdater {
|
|
|
1971
2070
|
if (manifest == null) {
|
|
1972
2071
|
return download(url, version, sessionKey, checksum);
|
|
1973
2072
|
}
|
|
2073
|
+
this.runPreDownloadSecurityGates(url, version, manifest);
|
|
1974
2074
|
|
|
1975
2075
|
// Check for existing bundle with same version and clean up if in error state
|
|
1976
2076
|
BundleInfo existingBundle = this.getBundleInfoByName(version);
|
|
@@ -2278,6 +2378,13 @@ public class CapgoUpdater {
|
|
|
2278
2378
|
state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
|
|
2279
2379
|
|
|
2280
2380
|
this.editor.putString(this.CAP_SERVER_PATH, currentBundlePath);
|
|
2381
|
+
this.restoreResetStateRollbackTargets(state);
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
void restoreResetStateRollbackTargets(final ResetState state) {
|
|
2385
|
+
final String fallbackBundleId =
|
|
2386
|
+
state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
|
|
2387
|
+
|
|
2281
2388
|
this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
|
|
2282
2389
|
if (state.nextBundleId == null || state.nextBundleId.isEmpty()) {
|
|
2283
2390
|
this.editor.remove(NEXT_VERSION);
|
|
@@ -2287,6 +2394,13 @@ public class CapgoUpdater {
|
|
|
2287
2394
|
this.editor.commit();
|
|
2288
2395
|
}
|
|
2289
2396
|
|
|
2397
|
+
void preserveFallbackForWatchdog(final ResetState state) {
|
|
2398
|
+
final String fallbackBundleId =
|
|
2399
|
+
state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
|
|
2400
|
+
this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
|
|
2401
|
+
this.editor.commit();
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2290
2404
|
void prepareResetStateForTransition() {
|
|
2291
2405
|
this.setCurrentBundle(new File("public"));
|
|
2292
2406
|
this.setFallbackBundle(null);
|
|
@@ -2303,7 +2417,7 @@ public class CapgoUpdater {
|
|
|
2303
2417
|
}
|
|
2304
2418
|
|
|
2305
2419
|
boolean canSet(final BundleInfo bundle) {
|
|
2306
|
-
return bundle != null && (bundle.isBuiltin() || this.bundleExists(bundle.getId()));
|
|
2420
|
+
return bundle != null && !bundle.isErrorStatus() && (bundle.isBuiltin() || this.bundleExists(bundle.getId()));
|
|
2307
2421
|
}
|
|
2308
2422
|
|
|
2309
2423
|
public Boolean set(final BundleInfo bundle) {
|
|
@@ -3427,7 +3541,7 @@ public class CapgoUpdater {
|
|
|
3427
3541
|
if (statsQueue.size() >= MAX_PENDING_STATS) {
|
|
3428
3542
|
break;
|
|
3429
3543
|
}
|
|
3430
|
-
statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null));
|
|
3544
|
+
statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null, true));
|
|
3431
3545
|
}
|
|
3432
3546
|
}
|
|
3433
3547
|
if (backup.exists() && !backup.delete()) {
|
|
@@ -3449,10 +3563,198 @@ public class CapgoUpdater {
|
|
|
3449
3563
|
}
|
|
3450
3564
|
}
|
|
3451
3565
|
|
|
3566
|
+
/** Makes this instance the stats file owner and adopts events handed over before it loaded. */
|
|
3567
|
+
public void claimStatsOwnership() {
|
|
3568
|
+
final List<JSONObject> adopted;
|
|
3569
|
+
synchronized (statsOwnerLock) {
|
|
3570
|
+
statsOwner = this;
|
|
3571
|
+
adopted = new ArrayList<>(orphanedStats);
|
|
3572
|
+
orphanedStats.clear();
|
|
3573
|
+
}
|
|
3574
|
+
if (!adoptPendingStats(adopted)) {
|
|
3575
|
+
parkOrphanedStats(adopted);
|
|
3576
|
+
}
|
|
3577
|
+
}
|
|
3578
|
+
|
|
3579
|
+
public void releaseStatsOwnership() {
|
|
3580
|
+
synchronized (statsOwnerLock) {
|
|
3581
|
+
if (statsOwner == this) {
|
|
3582
|
+
statsOwner = null;
|
|
3583
|
+
}
|
|
3584
|
+
}
|
|
3585
|
+
}
|
|
3586
|
+
|
|
3587
|
+
/** Moves this instance's unsent events to the stats file owner (or parks them until one claims). */
|
|
3588
|
+
void handOverPendingStats() {
|
|
3589
|
+
// Stop first so a flush finishing later cannot requeue or persist what we hand over.
|
|
3590
|
+
statsStopped.set(true);
|
|
3591
|
+
final CapgoUpdater owner;
|
|
3592
|
+
synchronized (statsOwnerLock) {
|
|
3593
|
+
owner = statsOwner == this ? null : statsOwner;
|
|
3594
|
+
}
|
|
3595
|
+
final List<JSONObject> events = new ArrayList<>();
|
|
3596
|
+
synchronized (statsQueue) {
|
|
3597
|
+
collectHandoverEvents(statsInFlight, events, owner);
|
|
3598
|
+
statsInFlight.clear();
|
|
3599
|
+
collectHandoverEvents(statsQueue, events, owner);
|
|
3600
|
+
statsQueue.clear();
|
|
3601
|
+
}
|
|
3602
|
+
if (events.isEmpty()) {
|
|
3603
|
+
return;
|
|
3604
|
+
}
|
|
3605
|
+
// adoptPendingStats persists; never call it while holding statsOwnerLock (lock order).
|
|
3606
|
+
if (owner != null && owner.adoptPendingStats(events)) {
|
|
3607
|
+
return;
|
|
3608
|
+
}
|
|
3609
|
+
List<JSONObject> retryEvents = null;
|
|
3610
|
+
CapgoUpdater retryOwner = null;
|
|
3611
|
+
synchronized (statsOwnerLock) {
|
|
3612
|
+
addOrphanedStats(events);
|
|
3613
|
+
retryOwner = statsOwner == this ? null : statsOwner;
|
|
3614
|
+
if (retryOwner != null && !orphanedStats.isEmpty()) {
|
|
3615
|
+
retryEvents = new ArrayList<>(orphanedStats);
|
|
3616
|
+
orphanedStats.clear();
|
|
3617
|
+
}
|
|
3618
|
+
}
|
|
3619
|
+
if (retryOwner != null && retryEvents != null) {
|
|
3620
|
+
if (retryOwner.adoptPendingStats(retryEvents)) {
|
|
3621
|
+
return;
|
|
3622
|
+
}
|
|
3623
|
+
parkOrphanedStats(retryEvents);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
|
|
3627
|
+
private void collectHandoverEvents(final List<QueuedStatsEvent> source, final List<JSONObject> events, final CapgoUpdater owner) {
|
|
3628
|
+
for (final QueuedStatsEvent queued : source) {
|
|
3629
|
+
if (shouldHandOverQueuedEvent(queued, owner)) {
|
|
3630
|
+
events.add(queued.event);
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
|
|
3635
|
+
/**
|
|
3636
|
+
* Restored file events are not re-sent to an owner that shares the same pending-stats path
|
|
3637
|
+
* (the owner already loaded them from disk). They are still handed over when the paths differ.
|
|
3638
|
+
*/
|
|
3639
|
+
private boolean shouldHandOverQueuedEvent(final QueuedStatsEvent queued, final CapgoUpdater owner) {
|
|
3640
|
+
if (!queued.restored) {
|
|
3641
|
+
return true;
|
|
3642
|
+
}
|
|
3643
|
+
if (owner == null) {
|
|
3644
|
+
return true;
|
|
3645
|
+
}
|
|
3646
|
+
return !sharesPendingStatsFileWith(owner);
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
private boolean sharesPendingStatsFileWith(final CapgoUpdater other) {
|
|
3650
|
+
final File mine = pendingStatsFile();
|
|
3651
|
+
final File theirs = other.pendingStatsFile();
|
|
3652
|
+
return mine != null && theirs != null && mine.getAbsolutePath().equals(theirs.getAbsolutePath());
|
|
3653
|
+
}
|
|
3654
|
+
|
|
3655
|
+
private static void addOrphanedStats(final List<JSONObject> events) {
|
|
3656
|
+
orphanedStats.addAll(events);
|
|
3657
|
+
while (orphanedStats.size() > MAX_PENDING_STATS) {
|
|
3658
|
+
orphanedStats.remove(0);
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
|
|
3662
|
+
private static void parkOrphanedStats(final List<JSONObject> events) {
|
|
3663
|
+
synchronized (statsOwnerLock) {
|
|
3664
|
+
addOrphanedStats(events);
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
|
|
3668
|
+
/** Returns false (keeping nothing) when this instance has stopped and can no longer send the events. */
|
|
3669
|
+
private boolean adoptPendingStats(final List<JSONObject> events) {
|
|
3670
|
+
if (events.isEmpty()) {
|
|
3671
|
+
return true;
|
|
3672
|
+
}
|
|
3673
|
+
final List<QueuedStatsEvent> displaced = new ArrayList<>();
|
|
3674
|
+
final List<QueuedStatsEvent> adopted = new ArrayList<>();
|
|
3675
|
+
synchronized (statsQueue) {
|
|
3676
|
+
if (statsStopped.get()) {
|
|
3677
|
+
return false;
|
|
3678
|
+
}
|
|
3679
|
+
for (final JSONObject event : events) {
|
|
3680
|
+
while (statsQueue.size() >= MAX_PENDING_STATS) {
|
|
3681
|
+
final QueuedStatsEvent removed = statsQueue.remove(0);
|
|
3682
|
+
if (!adopted.contains(removed)) {
|
|
3683
|
+
displaced.add(removed);
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
final QueuedStatsEvent queued = new QueuedStatsEvent(event, null);
|
|
3687
|
+
statsQueue.add(queued);
|
|
3688
|
+
adopted.add(queued);
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
final Runnable beforeOwnerCheck = statsAdoptionBeforeOwnerCheckForTests;
|
|
3692
|
+
if (beforeOwnerCheck != null) {
|
|
3693
|
+
beforeOwnerCheck.run();
|
|
3694
|
+
}
|
|
3695
|
+
synchronized (statsOwnerLock) {
|
|
3696
|
+
if (statsOwner != null && statsOwner != this) {
|
|
3697
|
+
rollbackAdoptedEvents(adopted, displaced);
|
|
3698
|
+
return false;
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
persistStatsQueue();
|
|
3702
|
+
ensureStatsTimerStarted();
|
|
3703
|
+
return true;
|
|
3704
|
+
}
|
|
3705
|
+
|
|
3706
|
+
private void rollbackAdoptedEvents(final List<QueuedStatsEvent> adopted, final List<QueuedStatsEvent> displaced) {
|
|
3707
|
+
synchronized (statsQueue) {
|
|
3708
|
+
statsQueue.removeAll(adopted);
|
|
3709
|
+
if (!displaced.isEmpty()) {
|
|
3710
|
+
statsQueue.addAll(0, displaced);
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
|
|
3715
|
+
/** Unit tests only: disable scheduling or override the flush interval. */
|
|
3716
|
+
static void configureStatsFlushForTests(final Long intervalMs, final boolean schedulingEnabled) {
|
|
3717
|
+
statsFlushIntervalOverrideMs = intervalMs;
|
|
3718
|
+
statsFlushSchedulingDisabledForTests = !schedulingEnabled;
|
|
3719
|
+
}
|
|
3720
|
+
|
|
3721
|
+
/** Unit tests only: restore default stats flush scheduling. */
|
|
3722
|
+
static void resetStatsFlushForTests() {
|
|
3723
|
+
statsFlushIntervalOverrideMs = null;
|
|
3724
|
+
statsFlushSchedulingDisabledForTests = false;
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3452
3727
|
int pendingStatsCount() {
|
|
3453
3728
|
return statsQueue.size();
|
|
3454
3729
|
}
|
|
3455
3730
|
|
|
3731
|
+
void enqueuePendingStatsEventForTests(final String action) {
|
|
3732
|
+
try {
|
|
3733
|
+
final JSONObject json = new JSONObject();
|
|
3734
|
+
json.put("action", action);
|
|
3735
|
+
json.put("timestamp", 1);
|
|
3736
|
+
synchronized (statsQueue) {
|
|
3737
|
+
statsQueue.add(new QueuedStatsEvent(json, null));
|
|
3738
|
+
}
|
|
3739
|
+
} catch (final JSONException e) {
|
|
3740
|
+
throw new IllegalStateException(e);
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3744
|
+
List<String> pendingStatsActionsForTests() {
|
|
3745
|
+
final List<String> actions = new ArrayList<>();
|
|
3746
|
+
synchronized (statsQueue) {
|
|
3747
|
+
for (final QueuedStatsEvent queued : statsQueue) {
|
|
3748
|
+
try {
|
|
3749
|
+
actions.add(queued.event.getString("action"));
|
|
3750
|
+
} catch (final JSONException ignored) {
|
|
3751
|
+
actions.add("");
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
return actions;
|
|
3756
|
+
}
|
|
3757
|
+
|
|
3456
3758
|
public void persistPendingStats() {
|
|
3457
3759
|
persistStatsQueue();
|
|
3458
3760
|
}
|
|
@@ -3475,6 +3777,11 @@ public class CapgoUpdater {
|
|
|
3475
3777
|
return;
|
|
3476
3778
|
}
|
|
3477
3779
|
synchronized (pendingStatsPersistLock) {
|
|
3780
|
+
synchronized (statsOwnerLock) {
|
|
3781
|
+
if (statsOwner != null && statsOwner != this) {
|
|
3782
|
+
return;
|
|
3783
|
+
}
|
|
3784
|
+
}
|
|
3478
3785
|
if (statsStopped.get() && !force) {
|
|
3479
3786
|
return;
|
|
3480
3787
|
}
|
|
@@ -3566,16 +3873,12 @@ public class CapgoUpdater {
|
|
|
3566
3873
|
}
|
|
3567
3874
|
|
|
3568
3875
|
private synchronized void ensureStatsTimerStarted() {
|
|
3569
|
-
if (statsStopped.get()) {
|
|
3876
|
+
if (statsStopped.get() || statsFlushSchedulingDisabledForTests) {
|
|
3570
3877
|
return;
|
|
3571
3878
|
}
|
|
3879
|
+
final long intervalMs = statsFlushIntervalOverrideMs != null ? statsFlushIntervalOverrideMs : STATS_FLUSH_INTERVAL_MS;
|
|
3572
3880
|
if (statsFlushTask == null || statsFlushTask.isCancelled() || statsFlushTask.isDone()) {
|
|
3573
|
-
statsFlushTask = statsScheduler.scheduleAtFixedRate(
|
|
3574
|
-
this::flushStatsQueue,
|
|
3575
|
-
STATS_FLUSH_INTERVAL_MS,
|
|
3576
|
-
STATS_FLUSH_INTERVAL_MS,
|
|
3577
|
-
TimeUnit.MILLISECONDS
|
|
3578
|
-
);
|
|
3881
|
+
statsFlushTask = statsScheduler.scheduleAtFixedRate(this::flushStatsQueue, intervalMs, intervalMs, TimeUnit.MILLISECONDS);
|
|
3579
3882
|
}
|
|
3580
3883
|
}
|
|
3581
3884
|
|
|
@@ -3923,6 +4226,14 @@ public class CapgoUpdater {
|
|
|
3923
4226
|
* Should be called when the plugin is destroyed to prevent resource leaks.
|
|
3924
4227
|
*/
|
|
3925
4228
|
public void shutdown() {
|
|
4229
|
+
shutdown(true);
|
|
4230
|
+
}
|
|
4231
|
+
|
|
4232
|
+
/**
|
|
4233
|
+
* @param persistStats false when another live instance owns the stats file (headless worker
|
|
4234
|
+
* handing over to the plugin): writing this instance's queue would replace the newer file.
|
|
4235
|
+
*/
|
|
4236
|
+
public void shutdown(final boolean persistStats) {
|
|
3926
4237
|
statsStopped.set(true);
|
|
3927
4238
|
// Cancel the scheduled task
|
|
3928
4239
|
if (statsFlushTask != null) {
|
|
@@ -3931,7 +4242,9 @@ public class CapgoUpdater {
|
|
|
3931
4242
|
}
|
|
3932
4243
|
|
|
3933
4244
|
// Write once, then ignore later callbacks so they cannot delete a newer instance's file.
|
|
3934
|
-
|
|
4245
|
+
if (persistStats) {
|
|
4246
|
+
persistStatsQueue(true);
|
|
4247
|
+
}
|
|
3935
4248
|
|
|
3936
4249
|
// Shutdown the scheduler
|
|
3937
4250
|
statsScheduler.shutdown();
|
|
@@ -145,11 +145,69 @@ public class CryptoCipher {
|
|
|
145
145
|
|
|
146
146
|
public static void decryptFile(final File file, final String publicKey, final String ivSessionKey) throws IOException {
|
|
147
147
|
if (publicKey.isEmpty() || !isValidSessionKey(ivSessionKey)) {
|
|
148
|
-
if (logger != null)
|
|
149
|
-
logger.info("Encryption not set, no public key or session, ignored");
|
|
150
|
-
}
|
|
148
|
+
if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
|
|
151
149
|
return;
|
|
152
150
|
}
|
|
151
|
+
new DecryptionSession(publicKey, ivSessionKey).decryptFile(file);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// A manifest shares key setup, while each file still creates its own CBC cipher.
|
|
155
|
+
static final class DecryptionSession {
|
|
156
|
+
|
|
157
|
+
private final String publicKey;
|
|
158
|
+
private final String ivSessionKey;
|
|
159
|
+
private PreparedKey prepared;
|
|
160
|
+
private IOException failure;
|
|
161
|
+
|
|
162
|
+
DecryptionSession(String publicKey, String ivSessionKey) {
|
|
163
|
+
this.publicKey = publicKey;
|
|
164
|
+
this.ivSessionKey = ivSessionKey;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private synchronized PreparedKey key() throws IOException {
|
|
168
|
+
if (failure != null) throw new IOException(failure.getMessage(), failure);
|
|
169
|
+
if (prepared == null) {
|
|
170
|
+
try {
|
|
171
|
+
prepared = prepareDecryptionKey(publicKey, ivSessionKey);
|
|
172
|
+
} catch (IOException error) {
|
|
173
|
+
failure = error;
|
|
174
|
+
throw error;
|
|
175
|
+
} catch (RuntimeException error) {
|
|
176
|
+
// Malformed Base64 throws IllegalArgumentException: cache it like any other bad key.
|
|
177
|
+
failure = new IOException("AES file decryption failed: invalid session key", error);
|
|
178
|
+
throw failure;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return prepared;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
boolean isEncrypted() {
|
|
185
|
+
return publicKey != null && !publicKey.isEmpty();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
void decryptFile(File file) throws IOException {
|
|
189
|
+
if (!isEncrypted()) {
|
|
190
|
+
if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
PreparedKey key = key();
|
|
194
|
+
decryptAesFile(file, key.key, key.iv);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private static final class PreparedKey {
|
|
199
|
+
|
|
200
|
+
final SecretKey key;
|
|
201
|
+
final byte[] iv;
|
|
202
|
+
|
|
203
|
+
PreparedKey(SecretKey key, byte[] iv) {
|
|
204
|
+
this.key = key;
|
|
205
|
+
this.iv = iv;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private static PreparedKey prepareDecryptionKey(String publicKey, String ivSessionKey) throws IOException {
|
|
210
|
+
if (!isValidSessionKey(ivSessionKey)) throw new IOException("AES file decryption failed: session key is required");
|
|
153
211
|
// The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
|
|
154
212
|
if (!publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
|
|
155
213
|
if (logger != null) {
|
|
@@ -173,7 +231,7 @@ public class CryptoCipher {
|
|
|
173
231
|
}
|
|
174
232
|
|
|
175
233
|
SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
|
|
176
|
-
|
|
234
|
+
return new PreparedKey(sKey, iv);
|
|
177
235
|
} catch (GeneralSecurityException e) {
|
|
178
236
|
if (logger != null) {
|
|
179
237
|
logger.info("decryptFile fail");
|
|
@@ -395,27 +453,32 @@ public class CryptoCipher {
|
|
|
395
453
|
}
|
|
396
454
|
|
|
397
455
|
public static String calcChecksum(InputStream inputStream) {
|
|
398
|
-
final int BUFFER_SIZE = checksumBufferBytes();
|
|
399
|
-
MessageDigest digest;
|
|
400
456
|
try {
|
|
401
|
-
|
|
402
|
-
} catch (
|
|
403
|
-
logger.error("
|
|
457
|
+
return calcChecksumOrThrow(inputStream);
|
|
458
|
+
} catch (IOException error) {
|
|
459
|
+
logger.error("Cannot calculate checksum");
|
|
460
|
+
logger.debug("Error: " + error.getMessage());
|
|
404
461
|
return "";
|
|
405
462
|
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
static String calcChecksumOrThrow(File file) throws IOException {
|
|
466
|
+
try (FileInputStream input = new FileInputStream(file)) {
|
|
467
|
+
return calcChecksumOrThrow(input);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
406
470
|
|
|
471
|
+
static String calcChecksumOrThrow(InputStream input) throws IOException {
|
|
472
|
+
final MessageDigest digest;
|
|
407
473
|
try {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
digest.update(buffer, 0, length);
|
|
412
|
-
}
|
|
413
|
-
return digestToHex(digest);
|
|
414
|
-
} catch (IOException e) {
|
|
415
|
-
logger.error("Cannot calculate checksum");
|
|
416
|
-
logger.debug("Error: " + e.getMessage());
|
|
417
|
-
return "";
|
|
474
|
+
digest = MessageDigest.getInstance("SHA-256");
|
|
475
|
+
} catch (java.security.NoSuchAlgorithmException error) {
|
|
476
|
+
throw new IOException("SHA-256 algorithm not available", error);
|
|
418
477
|
}
|
|
478
|
+
byte[] buffer = new byte[checksumBufferBytes()];
|
|
479
|
+
int length;
|
|
480
|
+
while ((length = input.read(buffer)) != -1) digest.update(buffer, 0, length);
|
|
481
|
+
return digestToHex(digest);
|
|
419
482
|
}
|
|
420
483
|
|
|
421
484
|
static String digestToHex(MessageDigest digest) {
|