/
BootZipCopyAction.java
605 lines (520 loc) · 20.3 KB
/
BootZipCopyAction.java
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
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false,
(entry) -> prepareStoredEntry(library.openStream(), entry));
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
if (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0) {
try {
Method getPermissionsMethod = details.getClass().getMethod("getPermissions");
getPermissionsMethod.setAccessible(true);
Object permissions = getPermissionsMethod.invoke(details);
return (int) permissions.getClass().getMethod("toUnixNumeric").invoke(permissions);
}
catch (Exception ex) {
throw new GradleException("Failed to get permissions", ex);
}
}
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}