View Javadoc
1   /*
2    * Copyright The Plexus developers.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.codehaus.plexus.archiver.util;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.nio.file.FileVisitResult;
21  import java.nio.file.Files;
22  import java.nio.file.LinkOption;
23  import java.nio.file.NoSuchFileException;
24  import java.nio.file.Path;
25  import java.nio.file.SimpleFileVisitor;
26  import java.nio.file.attribute.BasicFileAttributes;
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  
31  import org.slf4j.Logger;
32  
33  import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
34  
35  /**
36   * Symbolic links the file system refused, to be replaced by a copy of their target once every entry is on disk.
37   *
38   * @see org.codehaus.plexus.archiver.SymlinkFailureMode#COPY_TARGET
39   * @since 4.15.0
40   */
41  public final class DeferredSymlinks {
42  
43      private final Logger logger;
44  
45      private final List<Entry> entries = new ArrayList<>();
46  
47      public DeferredSymlinks(Logger logger) {
48          this.logger = logger;
49      }
50  
51      /**
52       * Records a link that could not be created.
53       *
54       * @param root the canonical directory the copy must stay inside
55       * @param link where the link would have been created; its parent directory must exist
56       * @param target the link target as stored in the archive or resource
57       * @param entryName the entry name, for messages
58       * @throws IOException if the parent directory cannot be canonicalized
59       */
60      public void add(Path root, File link, String target, String entryName) throws IOException {
61          // canonicalize the parent, not the link path, which might be an existing link
62          Path linkPath = link.getParentFile().getCanonicalFile().toPath().resolve(link.getName());
63          entries.add(new Entry(root, linkPath, target, entryName));
64      }
65  
66      /**
67       * Copies the target of each recorded link in place of the link. Repeats until no more links resolve, so links
68       * that precede their target and chains of links work in any order. Targets outside the root, missing targets,
69       * cycles, occupied link paths and directories that contain the link are skipped with a warning.
70       *
71       * @throws IOException if copying fails
72       */
73      public void resolve() throws IOException {
74          List<Entry> pending = new ArrayList<>(entries);
75          entries.clear();
76          boolean progress = true;
77          while (progress && !pending.isEmpty()) {
78              progress = false;
79              for (Iterator<Entry> it = pending.iterator(); it.hasNext(); ) {
80                  Entry link = it.next();
81                  Path real;
82                  try {
83                      real = link.link
84                              .resolveSibling(link.target.replace('/', File.separatorChar))
85                              .normalize()
86                              .toRealPath();
87                  } catch (NoSuchFileException e) {
88                      // the target may be another refused link that a later round copies
89                      continue;
90                  }
91                  it.remove();
92                  if (!real.startsWith(link.root)) {
93                      logger.warn(
94                              "Skipping symbolic link {}: target {} is outside the target directory",
95                              link.entryName,
96                              link.target);
97                  } else if (Files.exists(link.link, LinkOption.NOFOLLOW_LINKS)) {
98                      logger.warn("Skipping symbolic link {}: {} already exists", link.entryName, link.link);
99                  } else if (Files.isDirectory(real) && link.link.startsWith(real)) {
100                     logger.warn("Skipping symbolic link {}: target {} contains the link", link.entryName, link.target);
101                 } else {
102                     copy(real, link.link);
103                     progress = true;
104                 }
105             }
106         }
107         for (Entry link : pending) {
108             logger.warn(
109                     "Skipping symbolic link {}: target {} is not in the archive, or the links form a cycle",
110                     link.entryName,
111                     link.target);
112         }
113     }
114 
115     private void copy(Path source, Path destination) throws IOException {
116         if (!Files.isDirectory(source)) {
117             Files.copy(source, destination, COPY_ATTRIBUTES);
118             return;
119         }
120         Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
121             @Override
122             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
123                 Files.createDirectories(destination.resolve(source.relativize(dir)));
124                 return FileVisitResult.CONTINUE;
125             }
126 
127             @Override
128             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
129                 if (attrs.isSymbolicLink()) {
130                     logger.warn("Skipping symbolic link {} while copying {}", file, source);
131                 } else {
132                     Files.copy(file, destination.resolve(source.relativize(file)), COPY_ATTRIBUTES);
133                 }
134                 return FileVisitResult.CONTINUE;
135             }
136         });
137     }
138 
139     private static final class Entry {
140         final Path root;
141 
142         final Path link;
143 
144         final String target;
145 
146         final String entryName;
147 
148         Entry(Path root, Path link, String target, String entryName) {
149             this.root = root;
150             this.link = link;
151             this.target = target;
152             this.entryName = entryName;
153         }
154     }
155 }