Repository navigation
Expand file tree
/
Copy pathDownloadTask.java
More file actions
802 lines (745 loc) Β· 35.4 KB
/
Copy pathDownloadTask.java
File metadata and controls
802 lines (745 loc) Β· 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
package cn.reactnative.modules.update;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import org.json.JSONObject;
import org.json.JSONTokener;
class DownloadTask implements Runnable {
// Bundle delta entry inside a patch archive, stored encoded.
private static final String BUNDLE_DELTA_ENTRY =
Texts.BUNDLE_DELTA_ENTRY;
// Resume sidecars are a few hundred bytes of JSON.
private static final long MAX_SIDECAR_BYTES = 64 * 1024;
// When the server does not report Content-Length we cannot key progress
// events on percentage change, so throttle by bytes to avoid flooding the
// bridge (e.g. a 20MB chunked download would otherwise emit ~5000 events).
private static final long PROGRESS_BYTES_THRESHOLD = 256 * 1024;
// Explicit timeouts: the default client has no call timeout, so a
// slow-dripping connection could occupy the single-threaded download
// executor indefinitely and starve queued tasks. The call timeout is a
// generous upper bound sized for large full-package downloads.
private static final OkHttpClient HTTP_CLIENT = HttpClients.base().newBuilder()
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.callTimeout(10, java.util.concurrent.TimeUnit.MINUTES)
.build();
// Two-phase install (cpp/patch_core/install_record.h): all unpack/patch
// work happens in <hash>.staging; the final <hash> directory only ever
// appears through an atomic rename after the completion record was
// written, so a crash or failure can never leave a half-installed
// directory that looks like a version.
private File stagingDirectory() {
return InstallRecord.stagingDirectoryFor(params.unzipDirectory);
}
// SHA-256 of the downloaded archive, recorded in the install record.
private String artifactSha256 = "";
// The archive digest computed while its bytes streamed to disk (a resumed
// transfer first hashes the prefix already on disk); null when this task
// did not stream the whole file itself and it must be hashed from disk.
private String streamedArchiveSha256;
// Digest of the bundle computed while a full package was extracted;
// null when the bundle was produced some other way (patch tasks).
private String stagedBundleSha256;
/** What a staged patch archive declared, as the native core consumes it. */
private static final class PatchArchiveContents {
final String[] entryNames;
// The raw __diff.json bytes (UTF-8): parsed only by the native core
// (cpp/patch_core/patch_manifest.h), never here.
final byte[] manifestJson;
PatchArchiveContents(ArrayList<String> entryNames, byte[] manifestJson) {
this.entryNames = entryNames.toArray(new String[0]);
this.manifestJson = manifestJson;
}
}
private final Context context;
private final DownloadTaskParams params;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final BundledResourceCopier bundledResourceCopier;
private String hash;
// Set once downloadFile() returns: failures after this point in a patch
// task are patch-application failures, not download failures.
private boolean downloadPhaseCompleted = false;
DownloadTask(Context context, DownloadTaskParams params) {
this.context = context.getApplicationContext();
this.params = params;
this.bundledResourceCopier = new BundledResourceCopier(this.context);
}
private void postProgress(final long received, final long total) {
// Cross-platform progress contract: unknown length is reported as
// total=0, never a raw -1 (OkHttp's contentLength for chunked/gzip).
final long normalizedTotal = total > 0 ? total : 0;
mainHandler.post(() -> {
WritableMap progress = Arguments.createMap();
progress.putDouble("received", received);
progress.putDouble("total", normalizedTotal);
progress.putString("hash", hash);
UpdateEventEmitter.sendEvent("RCTPushyDownloadProgress", progress);
});
}
// Sidecar next to the archive recording what a partial download belongs
// to (url + validators + total). An archive without a matching sidecar is
// untrusted and restarted from zero; the pair is deleted together with
// the archive once it is consumed or classified as poisoned.
private static File resumeSidecarFile(File archive) {
return new File(archive.getPath() + ".resume");
}
static void deleteResumeSidecar(File archive) {
File sidecar = resumeSidecarFile(archive);
if (sidecar.exists() && !sidecar.delete() && BuildConfig.DEBUG) {
Log.w(Texts.LOG_TAG, "Failed to delete resume sidecar " + sidecar);
}
}
private JSONObject readResumeMeta(File sidecar, String url) {
if (!sidecar.isFile()) {
return null;
}
try {
JSONObject meta = (JSONObject) new JSONTokener(
UpdateFileUtils.readSmallUtf8(sidecar, MAX_SIDECAR_BYTES)).nextValue();
if (url.equals(meta.optString("url"))) {
return meta;
}
} catch (Throwable e) {
// A corrupt sidecar simply means "cannot resume".
}
return null;
}
private void writeResumeMeta(
File sidecar, String url, Response response, JSONObject previousMeta, long total
) {
try {
JSONObject meta = new JSONObject();
meta.put("url", url);
String etag = response.header("ETag");
String lastModified = response.header("Last-Modified");
if (etag == null && previousMeta != null) {
etag = previousMeta.optString("etag", null);
}
if (lastModified == null && previousMeta != null) {
lastModified = previousMeta.optString("lastModified", null);
}
if (etag != null) {
meta.put("etag", etag);
}
if (lastModified != null) {
meta.put("lastModified", lastModified);
}
if (total > 0) {
meta.put("total", total);
}
UpdateFileUtils.ensureParentDirectory(sidecar);
try (java.io.FileOutputStream out = new java.io.FileOutputStream(sidecar)) {
out.write(meta.toString().getBytes(StandardCharsets.UTF_8));
}
} catch (Throwable e) {
// Non-fatal: without a sidecar the next attempt starts from zero.
Log.w(Texts.LOG_TAG, "Failed to persist resume sidecar: " + e);
}
}
private void downloadFile() throws IOException {
this.hash = params.hash;
streamedArchiveSha256 = null;
String url = params.url;
File writePath = params.targetFile;
File sidecar = resumeSidecarFile(writePath);
UpdateFileUtils.ensureParentDirectory(writePath);
// Cross-launch resume (NATIVE_CHECKUPDATE_DESIGN Β§11.4): a brick gets
// a few hundred milliseconds per launch plus a bounded crash-rescue
// window, so every partial byte must survive process death and count.
long resumeOffset = 0;
JSONObject resumeMeta = readResumeMeta(sidecar, url);
if (resumeMeta != null && writePath.isFile() && writePath.length() > 0) {
long knownTotal = resumeMeta.optLong("total", 0);
long size = writePath.length();
if (knownTotal > 0 && size == knownTotal) {
// Fully received in a previous attempt (the process died
// between download end and unzip): nothing left to transfer.
downloadPhaseCompleted = true;
postProgress(knownTotal, knownTotal);
return;
}
if (knownTotal <= 0 || size < knownTotal) {
resumeOffset = size;
}
}
if (resumeOffset == 0) {
discardPartial(writePath);
}
if (!transferArchive(url, writePath, sidecar, resumeMeta, resumeOffset)) {
// The server rejected the range for a partial that no longer
// matches (416): drop it and retry once from zero.
discardPartial(writePath);
if (!transferArchive(url, writePath, sidecar, null, 0)) {
throw new IOException("Server rejected the download range for " + url);
}
}
downloadPhaseCompleted = true;
}
/** Drops a partial download and its sidecar; throws when the bytes stay. */
private static void discardPartial(File archive) throws IOException {
if (archive.exists() && !archive.delete()) {
throw new IOException("Failed to replace existing file: " + archive);
}
deleteResumeSidecar(archive);
}
/**
* One HTTP transfer, appending from resumeOffset when the server honours
* the range. Returns false only for the retryable stale-partial case
* (416 with a size mismatch); throws on every other failure.
*/
private boolean transferArchive(
String url, File writePath, File sidecar, JSONObject resumeMeta, long resumeOffset
) throws IOException {
Request.Builder builder = new Request.Builder().url(url);
if (resumeOffset > 0) {
// Only resume requests pin the encoding: Range offsets must
// address the same bytes that are on disk. Fresh downloads keep
// OkHttp's transparent gzip (it decompresses and strips the
// headers itself), matching the pre-resume behaviour for servers
// that compress regardless.
builder.header("Accept-Encoding", "identity");
builder.header("Range", "bytes=" + resumeOffset + "-");
String validator = null;
if (resumeMeta != null) {
validator = resumeMeta.optString("etag", null);
if (validator == null) {
validator = resumeMeta.optString("lastModified", null);
}
}
if (validator != null) {
// With a validator the server falls back to a full 200 when
// the file changed instead of appending mismatched bytes.
builder.header("If-Range", validator);
}
}
Call call = HttpClients.withDeadline(HTTP_CLIENT, params.deadlineNanos)
.newCall(builder.build());
// Registered so an orchestrated phase timeout can cancel it
// (CODE_AUDIT 2.12); cleared once the transfer is over.
params.attachCall(call);
try (Response response = call.execute()) {
HttpClients.rejectProtocolDowngrade(url, response);
if (response.code() == 416) {
long total = resumeMeta == null ? 0 : resumeMeta.optLong("total", 0);
if (total > 0 && writePath.length() == total) {
// The partial is actually the complete file.
postProgress(total, total);
return true;
}
return false;
}
if (!response.isSuccessful()) {
throw new IOException("Server error: " + response.code() + " " + response.message());
}
ResponseBody body = response.body();
if (body == null) {
throw new IOException("Empty response body for " + url);
}
String contentEncoding = response.header("Content-Encoding");
// Visible only when the server encoded the body itself (OkHttp
// strips the header when it transparently decompresses its own
// gzip). Byte offsets in an encoded representation do not match
// the decoded bytes on disk, so resume is off the table.
boolean encodedBody = contentEncoding != null
&& !contentEncoding.equalsIgnoreCase("identity");
boolean append = response.code() == 206 && resumeOffset > 0;
if (append && encodedBody) {
// The server ignored Accept-Encoding: identity on a range
// request; the appended bytes could not be trusted.
return false;
}
long baseOffset = append ? resumeOffset : 0;
long contentLength = body.contentLength();
long totalAll;
if (append) {
totalAll = HttpUtils.parseContentRange(
response.header("Content-Range"), resumeOffset);
if (totalAll < 0) {
// Malformed or mismatched Content-Range: treat like a
// stale partial (one clean retry from zero) instead of
// failing β a throw would keep the partial and hit the
// same wall on every future attempt.
return false;
}
} else {
totalAll = contentLength > 0 ? contentLength : 0;
}
if (totalAll > ArchiveLimits.MAX_ARCHIVE_BYTES) {
throw new IOException("archive too large: " + totalAll + " bytes");
}
ArchiveLimits.ensureFreeSpace(
writePath, totalAll > 0 ? totalAll - baseOffset : 0);
if (!append) {
// Destroy the old bytes before the sidecar can vouch for
// them with the new validators (a crash between the two
// writes must never leave a sidecar describing stale bytes).
discardPartial(writePath);
}
if (encodedBody) {
// No resume across an encoded transfer.
deleteResumeSidecar(writePath);
} else {
// Persist before streaming so a mid-stream crash can resume.
writeResumeMeta(sidecar, url, response, resumeMeta, totalAll);
}
long bytesRead;
long received = 0;
int currentPercentage = 0;
long lastPostedBytes = baseOffset;
// Unknown length: the response-time check could only reserve the
// margin, so the disk is probed before any write that would run
// past the bytes reserved so far (the shared probe plan,
// ArchiveLimits.planFreeSpaceProbe) β no write can ever eat into
// the margin. A throw keeps the partial for a later attempt.
long freeSpaceReservedUntil = 0;
// The archive digest is computed as the bytes reach the file, so
// the install does not re-read the whole archive afterwards.
MessageDigest digest = UpdateFileUtils.newSha256();
if (append) {
UpdateFileUtils.updateDigest(digest, writePath);
}
try (
BufferedSource source = body.source();
BufferedSink sink = Okio.buffer(Okio.sink(new DigestOutputStream(
new FileOutputStream(writePath, append), digest)))
) {
while ((bytesRead = source.read(sink.buffer(), UpdateFileUtils.BUFFER_SIZE)) != -1) {
// A known length was reserved up front: no per-chunk plan
// (and no JNI round trip on this hot loop).
long[] probe = totalAll > 0 ? null : ArchiveLimits.planFreeSpaceProbe(
totalAll, received, bytesRead, freeSpaceReservedUntil);
received += bytesRead;
if (probe != null) {
freeSpaceReservedUntil = probe[1];
}
if (probe != null && probe[0] > 0) {
try {
ArchiveLimits.ensureFreeSpace(writePath, probe[0]);
} catch (IOException e) {
// The chunk is still only buffered; closing the
// sink would flush it onto the disk that just
// failed the probe.
sink.buffer().clear();
throw e;
}
}
// Write whole segments only: a 64KB read no longer costs
// a write() syscall per partially filled segment.
sink.emitCompleteSegments();
long overall = baseOffset + received;
if (overall > ArchiveLimits.MAX_ARCHIVE_BYTES) {
// Unknown/chunked length backstop.
throw new IOException(
"archive too large: exceeded " + ArchiveLimits.MAX_ARCHIVE_BYTES);
}
if (totalAll > 0) {
int percentage = (int) (overall * 100.0 / totalAll + 0.5);
if (percentage > currentPercentage) {
currentPercentage = percentage;
lastPostedBytes = overall;
postProgress(overall, totalAll);
}
} else if (overall - lastPostedBytes >= PROGRESS_BYTES_THRESHOLD) {
lastPostedBytes = overall;
postProgress(overall, totalAll);
}
}
sink.flush();
}
if (contentLength >= 0 && received != contentLength) {
throw new IOException("Unexpected eof while reading downloaded package");
}
if (totalAll > 0 && writePath.length() != totalAll) {
throw new IOException("Download incomplete: expected " + totalAll
+ " bytes, got " + writePath.length());
}
streamedArchiveSha256 = UpdateFileUtils.toHex(digest.digest());
// Final progress event, skipped when the loop already posted this
// exact value (known length reaching 100% posts it in-loop).
if (baseOffset + received != lastPostedBytes) {
postProgress(baseOffset + received, totalAll);
}
} finally {
params.attachCall(null);
}
return true;
}
private void copyBundledAssetToFile(String assetName, File destination) throws IOException {
try (InputStream in = context.getAssets().open(assetName)) {
UpdateFileUtils.copyInputStreamToFile(in, destination);
}
}
private PatchArchiveContents extractPatchArchive(File archiveFile, File unzipDirectory)
throws IOException {
UpdateFileUtils.removeDirectory(unzipDirectory);
UpdateFileUtils.ensureDirectory(unzipDirectory);
ArrayList<String> entryNames = new ArrayList<String>();
byte[] manifestJson = new byte[0];
try (SafeZipFile zipFile = new SafeZipFile(archiveFile)) {
ensureArchiveWithinLimits(archiveFile, zipFile, unzipDirectory);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
entryNames.add(name);
if (name.equals("__diff.json")) {
if (entry.getSize() > ArchiveLimits.MAX_MANIFEST_BYTES) {
throw new IOException("delta manifest too large: " + entry.getSize());
}
manifestJson = UpdateFileUtils.readBytes(
zipFile.getInputStream(entry), ArchiveLimits.MAX_MANIFEST_BYTES);
continue;
}
zipFile.unzipToPath(entry, unzipDirectory);
}
}
return new PatchArchiveContents(entryNames, manifestJson);
}
/**
* Shared first half of the two patch tasks: download the archive and
* unpack it into the staging directory. The native applyArchiveDelta
* validates what it declared.
*/
private PatchArchiveContents stagePatchArchive() throws IOException {
downloadFile();
artifactSha256 = archiveSha256();
return extractPatchArchive(params.targetFile, stagingDirectory());
}
private void doFullPatch() throws IOException {
downloadFile();
File work = stagingDirectory();
UpdateFileUtils.removeDirectory(work);
UpdateFileUtils.ensureDirectory(work);
artifactSha256 = archiveSha256();
// The bundle's digest (for the install record) is taken from the
// bytes as they are extracted, instead of re-reading the bundle right
// after. Any entry resolving to the bundle path counts; the last write
// wins on disk and in the digest alike.
File bundleTarget = InstallRecord.bundleFile(work).getCanonicalFile();
stagedBundleSha256 = null;
try (SafeZipFile zipFile = new SafeZipFile(params.targetFile)) {
ensureArchiveWithinLimits(params.targetFile, zipFile, work);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()
&& new File(work, entry.getName()).getCanonicalFile().equals(bundleTarget)) {
MessageDigest digest = UpdateFileUtils.newSha256();
zipFile.unzipToPath(entry, work, digest);
stagedBundleSha256 = UpdateFileUtils.toHex(digest.digest());
} else {
zipFile.unzipToPath(entry, work);
}
}
}
deleteConsumedArchive();
}
private String archiveSha256() throws IOException {
return streamedArchiveSha256 != null
? streamedArchiveSha256 : UpdateFileUtils.sha256Hex(params.targetFile);
}
/**
* Last step of a successful patch task: the completion record (with the
* final bundle's digest) goes into the staging directory, which is then
* renamed over the version directory in one atomic step.
*/
private void promoteStaging() throws IOException {
File work = stagingDirectory();
if (targetsRunningVersion()) {
// The process switched to this very version while the task ran
// (a restartApp racing the download): never rename over the
// live directory. Its verified install stands; staging goes.
ensureNotReinstallingRunningVersion();
UpdateFileUtils.removeDirectory(work);
return;
}
InstallRecord.seal(work, params.hash, artifactSha256, stagedBundleSha256);
if (params.unzipDirectory.exists()) {
UpdateFileUtils.removeDirectory(params.unzipDirectory);
}
InstallRecord.promote(work, params.unzipDirectory);
}
/**
* Resource caps before extraction (cpp/patch_core/archive_limits.h): the
* archive itself, the central directory's declared contents, and the
* free space the expansion needs. Failing here is a PATCH_FAILED (the
* bytes arrived; they cannot be applied).
*/
private static void ensureArchiveWithinLimits(
File archiveFile, SafeZipFile zipFile, File unzipDirectory
) throws IOException {
long archiveBytes = archiveFile.length();
if (archiveBytes > ArchiveLimits.MAX_ARCHIVE_BYTES) {
throw new IOException("archive too large: " + archiveBytes + " bytes");
}
ArchiveLimits.ensureFreeSpace(unzipDirectory, zipFile.inspect(archiveBytes));
}
// The archive and its resume sidecar live and die together: once the
// archive is consumed (or classified as poisoned) the sidecar must not
// survive to vouch for a file that no longer exists or cannot be trusted.
private void deleteConsumedArchive() {
if (params.targetFile.exists()) {
params.targetFile.delete();
}
deleteResumeSidecar(params.targetFile);
}
private void doPatchFromApk() throws IOException {
PatchArchiveContents contents = stagePatchArchive();
File work = stagingDirectory();
File originBundleFile = new File(work, ".origin.bundle");
copyBundledAssetToFile("index.android.bundle", originBundleFile);
CopyGroupResult[] copies;
try {
// The APK's resources are zip entries, not files: the core
// rebuilds the bundle and hands the manifest copies back.
copies = applyArchiveDelta(
DownloadTaskParams.TASK_TYPE_PATCH_FROM_APK,
contents.entryNames,
contents.manifestJson,
work.getAbsolutePath(),
work.getAbsolutePath(),
originBundleFile.getAbsolutePath(),
new File(work, BUNDLE_DELTA_ENTRY).getAbsolutePath(),
InstallRecord.bundleFile(work).getAbsolutePath(),
true
);
} finally {
originBundleFile.delete();
}
bundledResourceCopier.copyFromResource(work, copies);
deleteConsumedArchive();
}
private void doPatchFromPpk() throws IOException {
PatchArchiveContents contents = stagePatchArchive();
File work = stagingDirectory();
applyArchiveDelta(
DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK,
contents.entryNames,
contents.manifestJson,
params.originDirectory.getAbsolutePath(),
work.getAbsolutePath(),
InstallRecord.bundleFile(params.originDirectory).getAbsolutePath(),
new File(work, BUNDLE_DELTA_ENTRY).getAbsolutePath(),
InstallRecord.bundleFile(work).getAbsolutePath(),
false
);
deleteConsumedArchive();
}
// Dot-named, so the selection under the versions root never picks it.
static final String TRASH_DIR_NAME = ".trash";
private void doCleanUp() {
final File trash = new File(params.unzipDirectory, TRASH_DIR_NAME);
// Phase 1, under the version-files lock: only renames doomed entries
// into the trash, so activation is never blocked behind a recursive
// delete of several version directories.
UpdateContext.getInstance(context).runCleanupWithLatestState(keepNames ->
cleanupOldEntries(
params.unzipDirectory.getAbsolutePath(),
keepNames,
params.maxAgeDays,
trash.getAbsolutePath()
));
// Phase 2, lock released: nothing in the trash is reachable as a
// version any more. Also purges leftovers of an interrupted run.
// Best effort: phase 1 already succeeded, and a leftover the native
// delete cannot remove must not fail every later cleanup task.
if (trash.isDirectory()) {
try {
cleanupOldEntries(trash.getAbsolutePath(), new String[0], 0, null);
} catch (RuntimeException e) {
Log.w(Texts.LOG_TAG, "Failed to purge cleanup trash", e);
}
}
}
private void cleanUpAfterFailure(int taskType) {
switch (taskType) {
case DownloadTaskParams.TASK_TYPE_PATCH_FULL:
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_APK:
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK:
// Only the staging directory is ours to drop: the final
// version directory is never touched by a failed install.
try {
UpdateFileUtils.removeDirectory(stagingDirectory());
} catch (IOException ioException) {
Log.e(Texts.LOG_TAG, "Failed to clean staging directory", ioException);
}
if (downloadPhaseCompleted) {
// Fully received but failed to unzip/patch: the archive is
// poisoned, and resuming it would fail the same way on
// every future attempt. A download-phase failure keeps the
// partial + sidecar instead β that is the resume state.
deleteConsumedArchive();
}
break;
case DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD:
deleteConsumedArchive();
break;
default:
break;
}
}
private boolean isPatchTask(int taskType) {
return taskType == DownloadTaskParams.TASK_TYPE_PATCH_FULL
|| taskType == DownloadTaskParams.TASK_TYPE_PATCH_FROM_APK
|| taskType == DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK;
}
private boolean hasCompletedDeltaDirectory() {
return params.unzipDirectory != null
&& params.hash != null
&& InstallRecord.isInstalled(params.unzipDirectory, params.hash);
}
// True when this task targets the version the process is running from.
private boolean targetsRunningVersion() {
String running = UpdateContext.runningVersion();
return running != null && params.hash != null && running.equals(params.hash);
}
/**
* The running version's directory is never replaced in place
* (CODE_AUDIT 2.10): images and fonts are read from it on demand, and an
* install from before completion records existed has no marker, so a
* re-download of the same hash would wipe the live directory. A running
* version whose record verifies against the bundle on disk needs no
* install and passes; anything else is refused as a file-operation
* failure rather than overwritten.
*/
private void ensureNotReinstallingRunningVersion() throws IOException {
try {
InstallRecord.verifyInstalled(params.unzipDirectory, params.hash, false);
} catch (IOException e) {
throw new FileOperationException("Running version " + params.hash
+ " cannot be reinstalled in place: " + e.getMessage());
}
}
@Override
public void run() {
int taskType = params.type;
final boolean runningVersion = isPatchTask(taskType) && targetsRunningVersion();
final boolean alreadyCompleted = isPatchTask(taskType)
&& hasCompletedDeltaDirectory();
try {
if (params.isCancelled()) {
throw new IOException("download task cancelled before it started");
}
if (runningVersion) {
ensureNotReinstallingRunningVersion();
Log.i(Texts.LOG_TAG, "download task: version " + params.hash
+ " is running in this process and already installed");
} else if (alreadyCompleted) {
Log.i(Texts.LOG_TAG,
"download task: version " + params.hash + " already completed");
} else {
switch (taskType) {
case DownloadTaskParams.TASK_TYPE_PATCH_FULL:
doFullPatch();
promoteStaging();
break;
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_APK:
doPatchFromApk();
promoteStaging();
break;
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK:
doPatchFromPpk();
promoteStaging();
break;
case DownloadTaskParams.TASK_TYPE_CLEANUP:
doCleanUp();
break;
case DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD:
downloadFile();
break;
default:
break;
}
}
} catch (Throwable error) {
Log.e(Texts.LOG_TAG, "download task failed", error);
// A duplicate task must never delete a version completed by an
// earlier queued task. The marker + bundle pair is the ownership
// handoff: once present, this failure did not create that install.
if (!hasCompletedDeltaDirectory()) {
cleanUpAfterFailure(taskType);
}
if (params.listener != null) {
// A patch task that failed after its artifact was fully
// downloaded (unzip / hdiff / resource copy, incl. copiesCrc
// verification) is a patch failure, not a download failure β
// the module maps the exception type to PATCH_FAILED.
Throwable classified = error;
if (downloadPhaseCompleted
&& isPatchTask(taskType)
&& !(error instanceof PatchFailedException)
&& !(error instanceof FileOperationException)) {
classified = new PatchFailedException(
String.valueOf(error.getMessage()), error);
}
params.listener.onDownloadFailed(classified);
}
return;
}
if (taskType == DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD) {
// A plain download's file is final at completion β a surviving
// sidecar would make a later download of the same URL return
// these bytes without ever asking the server again.
deleteResumeSidecar(params.targetFile);
}
// The task itself succeeded. Run the completion callback outside the
// try/catch above so an exception thrown by the callback (e.g. a
// PackageInstaller failure during APK staging) is not mistaken for
// a download failure that deletes the successfully downloaded file and
// settles the promise a second time.
if (params.listener != null) {
try {
params.listener.onDownloadCompleted(params);
} catch (Throwable error) {
Log.e(Texts.LOG_TAG, "download completion callback failed", error);
params.listener.onDownloadFailed(error);
}
}
}
// The native half of a patch install (cpp/patch_core/archive_patch_core.h
// ApplyArchivePatch): checks the archive's entries, parses and validates
// manifestJson (__diff.json), rebuilds the bundle and, unless
// hostCopiesResources, performs the copies, deletes and merge. Returns
// the copies the caller still owes (empty unless hostCopiesResources).
private static native CopyGroupResult[] applyArchiveDelta(
int patchType,
String[] entryNames,
byte[] manifestJson,
String sourceRoot,
String targetRoot,
String originBundlePath,
String bundlePatchPath,
String bundleOutputPath,
boolean hostCopiesResources
);
// trashDir non-empty: move the selected entries there instead of
// deleting them (see doCleanUp).
private static native void cleanupOldEntries(
String rootDir,
String[] keepNames,
int maxAgeDays,
String trashDir
);
}