View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.util;
18  
19  import java.io.File;
20  import java.io.IOException;
21  import java.io.UnsupportedEncodingException;
22  import java.net.MalformedURLException;
23  import java.net.URI;
24  import java.net.URL;
25  import java.net.URLDecoder;
26  import java.nio.charset.StandardCharsets;
27  import java.nio.file.FileSystems;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.attribute.GroupPrincipal;
31  import java.nio.file.attribute.PosixFileAttributeView;
32  import java.nio.file.attribute.PosixFilePermission;
33  import java.nio.file.attribute.UserPrincipal;
34  import java.nio.file.attribute.UserPrincipalLookupService;
35  import java.util.Objects;
36  import java.util.Set;
37  
38  import org.apache.logging.log4j.Logger;
39  import org.apache.logging.log4j.status.StatusLogger;
40  
41  /**
42   * File utilities.
43   */
44  public final class FileUtils {
45  
46      /** Constant for the file URL protocol. */
47      private static final String PROTOCOL_FILE = "file";
48  
49      private static final String JBOSS_FILE = "vfsfile";
50  
51      private static final Logger LOGGER = StatusLogger.getLogger();
52  
53      private FileUtils() {
54      }
55  
56      /**
57       * Tries to convert the specified URI to a file object. If this fails, <b>null</b> is returned.
58       *
59       * @param uri the URI
60       * @return the resulting file object
61       */
62      public static File fileFromUri(URI uri) {
63          // There MUST be a better way to do this. TODO Search other ASL projects...
64          if (uri == null || (uri.getScheme() != null
65                  && (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
66              return null;
67          }
68          if (uri.getScheme() == null) {
69              File file = new File(uri.toString());
70              if (file.exists()) {
71                  return file;
72              }
73              try {
74                  final String path = uri.getPath();
75                  file = new File(path);
76                  if (file.exists()) {
77                      return file;
78                  }
79                  uri = new File(path).toURI();
80              } catch (final Exception ex) {
81                  LOGGER.warn("Invalid URI {}", uri);
82                  return null;
83              }
84          }
85          final String charsetName = StandardCharsets.UTF_8.name();
86          try {
87              String fileName = uri.toURL().getFile();
88              if (new File(fileName).exists()) { // LOG4J2-466
89                  return new File(fileName); // allow files with '+' char in name
90              }
91              fileName = URLDecoder.decode(fileName, charsetName);
92              return new File(fileName);
93          } catch (final MalformedURLException ex) {
94              LOGGER.warn("Invalid URL {}", uri, ex);
95          } catch (final UnsupportedEncodingException uee) {
96              LOGGER.warn("Invalid encoding: {}", charsetName, uee);
97          }
98          return null;
99      }
100 
101     public static boolean isFile(final URL url) {
102         return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
103     }
104 
105     public static String getFileExtension(final File file) {
106         final String fileName = file.getName();
107         if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
108             return fileName.substring(fileName.lastIndexOf(".") + 1);
109         }
110         return null;
111     }
112 
113     /**
114      * Asserts that the given directory exists and creates it if necessary.
115      *
116      * @param dir the directory that shall exist
117      * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
118      * @throws java.io.IOException thrown if the directory could not be created.
119      */
120     public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting) throws IOException {
121         // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
122         if (!dir.exists()) {
123             if (!createDirectoryIfNotExisting) {
124                 throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
125             }
126             if (!dir.mkdirs()) {
127                 throw new IOException("Could not create directory " + dir.getAbsolutePath());
128             }
129         }
130         if (!dir.isDirectory()) {
131             throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
132         }
133     }
134 
135     /**
136      * Creates the parent directories for the given File.
137      *
138      * @param file
139      * @throws IOException
140      */
141     public static void makeParentDirs(final File file) throws IOException {
142         final File parent = Objects.requireNonNull(file, "file").getCanonicalFile().getParentFile();
143         if (parent != null) {
144             mkdir(parent, true);
145         }
146     }
147 
148     /**
149      * Define file posix attribute view on a path/file.
150      *
151      * @param path Target path
152      * @param filePermissions Permissions to apply
153      * @param fileOwner File owner
154      * @param fileGroup File group
155      * @throws IOException If IO error during definition of file attribute view
156      */
157     public static void defineFilePosixAttributeView(final Path path,
158             final Set<PosixFilePermission> filePermissions,
159             final String fileOwner,
160             final String fileGroup) throws IOException {
161         final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
162         if (view != null) {
163             final UserPrincipalLookupService lookupService = FileSystems.getDefault()
164                     .getUserPrincipalLookupService();
165             if (fileOwner != null) {
166                 final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner);
167                 if (userPrincipal != null) {
168                     // If not sudoers member, it will throw Operation not permitted
169                     // Only processes with an effective user ID equal to the user ID
170                     // of the file or with appropriate privileges may change the ownership of a file.
171                     // If _POSIX_CHOWN_RESTRICTED is in effect for path
172                     view.setOwner(userPrincipal);
173                 }
174             }
175             if (fileGroup != null) {
176                 final GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(fileGroup);
177                 if (groupPrincipal != null) {
178                     // The current user id should be members of this group,
179                     // if not will raise Operation not permitted
180                     view.setGroup(groupPrincipal);
181                 }
182             }
183             if (filePermissions != null) {
184                 view.setPermissions(filePermissions);
185             }
186         }
187     }
188 
189     /**
190      * Check if posix file attribute view is supported on the default FileSystem.
191      *
192      * @return true if posix file attribute view supported, false otherwise
193      */
194     public static boolean isFilePosixAttributeViewSupported() {
195         return FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
196     }
197 }