1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.codehaus.plexus.archiver;
18
19 import java.io.File;
20 import java.io.FileNotFoundException;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.concurrent.atomic.AtomicInteger;
30
31 import org.codehaus.plexus.archiver.util.ArchiveEntryUtils;
32 import org.codehaus.plexus.archiver.util.DeferredSymlinks;
33 import org.codehaus.plexus.components.io.attributes.SymlinkUtils;
34 import org.codehaus.plexus.components.io.filemappers.FileMapper;
35 import org.codehaus.plexus.components.io.fileselectors.FileSelector;
36 import org.codehaus.plexus.components.io.resources.PlexusIoResource;
37 import org.codehaus.plexus.util.FileUtils;
38 import org.codehaus.plexus.util.StringUtils;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
43
44
45
46
47
48
49 public abstract class AbstractUnArchiver implements UnArchiver, FinalizerEnabled {
50 private final Logger logger = LoggerFactory.getLogger(getClass());
51
52 protected Logger getLogger() {
53 return logger;
54 }
55
56 private File destDirectory;
57
58 private File destFile;
59
60 private File sourceFile;
61
62 private boolean overwrite = true;
63
64 private FileMapper[] fileMappers;
65
66 private List<ArchiveFinalizer> finalizers;
67
68 private FileSelector[] fileSelectors;
69
70
71
72
73
74
75 private boolean useJvmChmod = true;
76
77
78
79
80 private boolean ignorePermissions = false;
81
82
83
84
85 private SymlinkFailureMode symlinkFailureMode = SymlinkFailureMode.COPY_TARGET;
86
87
88
89
90 private DeferredSymlinks deferredSymlinks;
91
92 public AbstractUnArchiver() {
93
94 }
95
96 public AbstractUnArchiver(final File sourceFile) {
97 this.sourceFile = sourceFile;
98 }
99
100 @Override
101 public File getDestDirectory() {
102 return destDirectory;
103 }
104
105 @Override
106 public void setDestDirectory(final File destDirectory) {
107 this.destDirectory = destDirectory;
108 }
109
110 @Override
111 public File getDestFile() {
112 return destFile;
113 }
114
115 @Override
116 public void setDestFile(final File destFile) {
117 this.destFile = destFile;
118 }
119
120 @Override
121 public File getSourceFile() {
122 return sourceFile;
123 }
124
125 @Override
126 public void setSourceFile(final File sourceFile) {
127 this.sourceFile = sourceFile;
128 }
129
130 @Override
131 public boolean isOverwrite() {
132 return overwrite;
133 }
134
135 @Override
136 public void setOverwrite(final boolean b) {
137 overwrite = b;
138 }
139
140 @Override
141 public FileMapper[] getFileMappers() {
142 return fileMappers;
143 }
144
145 @Override
146 public void setFileMappers(final FileMapper[] fileMappers) {
147 this.fileMappers = fileMappers;
148 }
149
150 @Override
151 public final void extract() throws ArchiverException {
152 validate();
153 deferredSymlinks = new DeferredSymlinks(getLogger());
154 try {
155 execute();
156 deferredSymlinks.resolve();
157 } catch (IOException e) {
158 throw new ArchiverException("Error while copying symbolic link targets", e);
159 } finally {
160 deferredSymlinks = null;
161 }
162 runArchiveFinalizers();
163 }
164
165 @Override
166 public final void extract(final String path, final File outputDirectory) throws ArchiverException {
167 validate(path, outputDirectory);
168 deferredSymlinks = new DeferredSymlinks(getLogger());
169 try {
170 execute(path, outputDirectory);
171 deferredSymlinks.resolve();
172 } catch (IOException e) {
173 throw new ArchiverException("Error while copying symbolic link targets", e);
174 } finally {
175 deferredSymlinks = null;
176 }
177 runArchiveFinalizers();
178 }
179
180 @Override
181 public void addArchiveFinalizer(final ArchiveFinalizer finalizer) {
182 if (finalizers == null) {
183 finalizers = new ArrayList<>();
184 }
185
186 finalizers.add(finalizer);
187 }
188
189 @Override
190 public void setArchiveFinalizers(final List<ArchiveFinalizer> archiveFinalizers) {
191 finalizers = archiveFinalizers;
192 }
193
194 private void runArchiveFinalizers() throws ArchiverException {
195 if (finalizers != null) {
196 for (ArchiveFinalizer finalizer : finalizers) {
197 finalizer.finalizeArchiveExtraction(this);
198 }
199 }
200 }
201
202 protected void validate(final String path, final File outputDirectory) {}
203
204 protected void validate() throws ArchiverException {
205 if (sourceFile == null) {
206 throw new ArchiverException("The source file isn't defined.");
207 }
208
209 if (sourceFile.isDirectory()) {
210 throw new ArchiverException("The source must not be a directory.");
211 }
212
213 if (!sourceFile.exists()) {
214 throw new ArchiverException("The source file " + sourceFile + " doesn't exist.");
215 }
216
217 if (destDirectory == null && destFile == null) {
218 throw new ArchiverException("The destination isn't defined.");
219 }
220
221 if (destDirectory != null && destFile != null) {
222 throw new ArchiverException("You must choose between a destination directory and a destination file.");
223 }
224
225 if (destDirectory != null && !destDirectory.isDirectory()) {
226 destFile = destDirectory;
227 destDirectory = null;
228 }
229
230 if (destFile != null && destFile.isDirectory()) {
231 destDirectory = destFile;
232 destFile = null;
233 }
234 }
235
236 @Override
237 public void setFileSelectors(final FileSelector[] fileSelectors) {
238 this.fileSelectors = fileSelectors;
239 }
240
241 @Override
242 public FileSelector[] getFileSelectors() {
243 return fileSelectors;
244 }
245
246 protected boolean isSelected(final String fileName, final PlexusIoResource fileInfo) throws ArchiverException {
247 if (fileSelectors != null) {
248 for (FileSelector fileSelector : fileSelectors) {
249 try {
250
251 if (!fileSelector.isSelected(fileInfo)) {
252 return false;
253 }
254 } catch (final IOException e) {
255 throw new ArchiverException(
256 "Failed to check, whether " + fileInfo.getName() + " is selected: " + e.getMessage(), e);
257 }
258 }
259 }
260 return true;
261 }
262
263 protected abstract void execute() throws ArchiverException;
264
265 protected abstract void execute(String path, File outputDirectory) throws ArchiverException;
266
267
268
269
270 @Override
271 @Deprecated
272 public boolean isUseJvmChmod() {
273 return useJvmChmod;
274 }
275
276
277
278
279
280
281 @Override
282 @Deprecated
283 public void setUseJvmChmod(final boolean useJvmChmod) {
284 this.useJvmChmod = useJvmChmod;
285 }
286
287
288
289
290 @Override
291 public boolean isIgnorePermissions() {
292 return ignorePermissions;
293 }
294
295
296
297
298 @Override
299 public void setIgnorePermissions(final boolean ignorePermissions) {
300 this.ignorePermissions = ignorePermissions;
301 }
302
303
304
305
306 @Override
307 public SymlinkFailureMode getSymlinkFailureMode() {
308 return symlinkFailureMode;
309 }
310
311
312
313
314 @Override
315 public void setSymlinkFailureMode(final SymlinkFailureMode symlinkFailureMode) {
316 if (symlinkFailureMode == null) {
317 throw new IllegalArgumentException("symlinkFailureMode must not be null");
318 }
319 this.symlinkFailureMode = symlinkFailureMode;
320 }
321
322 protected void extractFile(
323 final File srcF,
324 final File dir,
325 final InputStream compressedInputStream,
326 String entryName,
327 final Date entryDate,
328 final boolean isDirectory,
329 final Integer mode,
330 String symlinkDestination,
331 final FileMapper[] fileMappers)
332 throws IOException, ArchiverException {
333 if (fileMappers != null) {
334 for (final FileMapper fileMapper : fileMappers) {
335 entryName = fileMapper.getMappedFileName(entryName);
336 }
337 }
338
339
340 final File targetFileName = FileUtils.resolveFile(dir, entryName);
341
342
343
344
345 Path canonicalDirPath = dir.getCanonicalFile().toPath();
346 Path canonicalDestPath = targetFileName.getCanonicalFile().toPath();
347
348 if (!canonicalDestPath.startsWith(canonicalDirPath)) {
349 throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")");
350 }
351
352
353 if (StringUtils.isEmpty(symlinkDestination) && Files.isSymbolicLink(canonicalDestPath)) {
354 throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")");
355 }
356
357 try {
358 if (!shouldExtractEntry(dir, targetFileName, entryName, entryDate)) {
359 return;
360 }
361
362
363 final File dirF = targetFileName.getParentFile();
364 if (dirF != null) {
365 dirF.mkdirs();
366 }
367
368 if (!StringUtils.isEmpty(symlinkDestination)) {
369 if (!createSymlinkEntry(canonicalDirPath, targetFileName, symlinkDestination, entryName)) {
370 return;
371 }
372 } else if (isDirectory) {
373 targetFileName.mkdirs();
374 } else {
375 Files.copy(compressedInputStream, targetFileName.toPath(), REPLACE_EXISTING);
376 }
377
378 targetFileName.setLastModified(entryDate.getTime());
379
380 if (!isIgnorePermissions() && mode != null && !isDirectory) {
381 ArchiveEntryUtils.chmod(targetFileName, mode);
382 }
383 } catch (final FileNotFoundException ex) {
384 getLogger().warn("Unable to expand to file " + targetFileName.getPath());
385 }
386 }
387
388
389
390
391
392
393
394
395
396 protected void createSymbolicLink(File link, File target) throws IOException {
397 SymlinkUtils.createSymbolicLink(link, target);
398 }
399
400
401
402
403 private boolean createSymlinkEntry(Path root, File link, String target, String entryName) throws IOException {
404 try {
405 createSymbolicLink(link, new File(target));
406 return true;
407 } catch (IOException | UnsupportedOperationException e) {
408 if (symlinkFailureMode == SymlinkFailureMode.FAIL) {
409 if (e instanceof IOException) {
410 throw (IOException) e;
411 }
412 throw new IOException("Cannot create symbolic link " + link, e);
413 }
414 boolean copy = symlinkFailureMode == SymlinkFailureMode.COPY_TARGET && deferredSymlinks != null;
415 getLogger()
416 .warn(
417 "Cannot create symbolic link {} -> {} ({}). On Windows this needs the 'Create symbolic"
418 + " links' right or Developer Mode; {}.",
419 entryName,
420 target,
421 e.getMessage(),
422 copy ? "the link target will be copied instead" : "the entry is skipped");
423 if (copy) {
424 deferredSymlinks.add(root, link, target, entryName);
425 }
426 return false;
427 }
428 }
429
430
431
432
433 final AtomicInteger casingMessageEmitted = new AtomicInteger(0);
434
435
436 protected boolean shouldExtractEntry(File targetDirectory, File targetFileName, String entryName, Date entryDate)
437 throws IOException {
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455 if (!targetFileName.exists()) {
456 return true;
457 }
458
459 boolean entryIsDirectory =
460 entryName.endsWith("/");
461 String canonicalDestPath = targetFileName.getCanonicalPath();
462 String suffix = (entryIsDirectory ? "/" : "");
463 String relativeCanonicalDestPath =
464 canonicalDestPath.replace(targetDirectory.getCanonicalPath() + File.separatorChar, "") + suffix;
465 boolean fileOnDiskIsOlderThanEntry = targetFileName.lastModified() < entryDate.getTime();
466 boolean differentCasing =
467 !normalizedFileSeparator(entryName).equals(normalizedFileSeparator(relativeCanonicalDestPath));
468
469
470 if (differentCasing) {
471 String casingMessage = String.format(
472 Locale.ENGLISH,
473 "Archive entry '%s' and existing file '%s' names differ only by case."
474 + " This may lead to an unexpected outcome on case-insensitive filesystems.",
475 entryName,
476 canonicalDestPath);
477 getLogger().warn(casingMessage);
478 casingMessageEmitted.incrementAndGet();
479 }
480
481
482
483 return isOverwrite() || fileOnDiskIsOlderThanEntry;
484 }
485
486 private String normalizedFileSeparator(String pathOrEntry) {
487 return pathOrEntry.replace("/", File.separator);
488 }
489 }