1 /*
   2  * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jfr.internal.jfc;
  27 
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.io.Reader;
  31 import java.nio.charset.StandardCharsets;
  32 import java.nio.file.Files;
  33 import java.nio.file.NoSuchFileException;
  34 import java.nio.file.Path;
  35 import java.nio.file.Paths;
  36 import java.text.ParseException;
  37 import java.util.ArrayList;
  38 import java.util.Arrays;
  39 import java.util.List;
  40 
  41 import jdk.jfr.Configuration;
  42 import jdk.jfr.internal.LogLevel;
  43 import jdk.jfr.internal.LogTag;
  44 import jdk.jfr.internal.Logger;
  45 import jdk.jfr.internal.SecuritySupport;
  46 import jdk.jfr.internal.SecuritySupport.SafePath;
  47 
  48 /**
  49  * {@link Configuration} factory for JFC files. *
  50  */
  51 public final class JFC {
  52     private static final int BUFFER_SIZE = 8192;
  53     private static final int MAXIMUM_FILE_SIZE = 1024 * 1024;
  54     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
  55     private static volatile List<KnownConfiguration> knownConfigurations;
  56 
  57     /**
  58      * Reads a known configuration file (located into a string, but doesn't
  59      * parse it until it's being used.
  60      */
  61     private static final class KnownConfiguration {
  62         private final String content;
  63         private final String filename;
  64         private final String name;
  65         private Configuration configuration;
  66 
  67         public KnownConfiguration(SafePath knownPath) throws IOException {
  68             this.content = readContent(knownPath);
  69             this.name = nameFromPath(knownPath.toPath());
  70             this.filename = nullSafeFileName(knownPath.toPath());
  71         }
  72 
  73         public boolean isNamed(String name) {
  74             return filename.equals(name) || this.name.equals(name);
  75         }
  76 
  77         public Configuration getConfigurationFile() throws IOException, ParseException {
  78             if (configuration == null) {
  79                 configuration = JFCParser.createConfiguration(name, content);
  80             }
  81             return configuration;
  82         }
  83 
  84         public String getName() {
  85             return name;
  86         }
  87 
  88         private static String readContent(SafePath knownPath) throws IOException {
  89             if (SecuritySupport.getFileSize(knownPath) > MAXIMUM_FILE_SIZE) {
  90                 throw new IOException("Configuration with more than "
  91                         + MAXIMUM_FILE_SIZE + " characters can't be read.");
  92             }
  93             try (InputStream r = SecuritySupport.newFileInputStream(knownPath)) {
  94                 return JFC.readContent(r);
  95             }
  96         }
  97     }
  98 
  99     private JFC() {
 100         // private utility class
 101     }
 102 
 103     /**
 104      * Reads a configuration from a file.
 105      *
 106      * @param path the file containing the configuration, not {@code null}
 107      * @return {@link Configuration}, not {@code null}
 108      * @throws ParseException if the file can't be parsed
 109      * @throws IOException if the file can't be read
 110      *
 111      * @throws SecurityException if a security manager exists and its
 112      *         <code>checkRead</code> method denies read access to the file.
 113      * @see java.io.File#getPath()
 114      * @see java.lang.SecurityManager#checkRead(java.lang.String)
 115      */
 116     public static Configuration create(String name, Reader reader) throws IOException, ParseException {
 117         return JFCParser.createConfiguration(name, reader);
 118     }
 119 
 120     private static String nullSafeFileName(Path file) throws IOException {
 121         Path filename = file.getFileName();
 122         if (filename == null) {
 123             throw new IOException("Path has no file name");
 124         }
 125         return filename.toString();
 126     }
 127 
 128     public static String nameFromPath(Path file) throws IOException {
 129         String f = nullSafeFileName(file);
 130         return f.substring(0, f.length() - JFCParser.FILE_EXTENSION.length());
 131     }
 132 
 133     // Invoked by DCmdStart
 134     public static Configuration createKnown(String name) throws IOException, ParseException {
 135         // Known name, no need for permission
 136         for (KnownConfiguration known : getKnownConfigurations()) {
 137             if (known.isNamed(name)) {
 138                 return known.getConfigurationFile();
 139             }
 140         }
 141         // Check JFC directory
 142         SafePath path = SecuritySupport.JFC_DIRECTORY;
 143         if (path != null && SecuritySupport.exists(path)) {
 144             for (String extension : Arrays.asList("", JFCParser.FILE_EXTENSION)) {
 145                 SafePath file = new SafePath(path.toPath().resolveSibling(name + extension));
 146                 if (SecuritySupport.exists(file) && !SecuritySupport.isDirectory(file)) {
 147                     try (Reader r = SecuritySupport.newFileReader(file)) {
 148                         String jfcName = nameFromPath(file.toPath());
 149                         return JFCParser.createConfiguration(jfcName, r);
 150                     }
 151                 }
 152             }
 153         }
 154 
 155         // Assume path included in name
 156 
 157         Path localPath = Paths.get(name);
 158         String jfcName = nameFromPath(localPath);
 159         try (Reader r = Files.newBufferedReader(localPath)) {
 160             return JFCParser.createConfiguration(jfcName, r);
 161         }
 162     }
 163 
 164     private static String readContent(InputStream source) throws IOException {
 165         byte[] bytes = read(source, BUFFER_SIZE);
 166         return new String(bytes, StandardCharsets.UTF_8);
 167     }
 168 
 169     // copied from java.io.file.Files to avoid dependency on JDK 9 code
 170     private static byte[] read(InputStream source, int initialSize) throws IOException {
 171         int capacity = initialSize;
 172         byte[] buf = new byte[capacity];
 173         int nread = 0;
 174         int n;
 175         for (;;) {
 176             // read to EOF which may read more or less than initialSize (eg: file
 177             // is truncated while we are reading)
 178             while ((n = source.read(buf, nread, capacity - nread)) > 0)
 179                 nread += n;
 180 
 181             // if last call to source.read() returned -1, we are done
 182             // otherwise, try to read one more byte; if that failed we're done too
 183             if (n < 0 || (n = source.read()) < 0)
 184                 break;
 185 
 186             // one more byte was read; need to allocate a larger buffer
 187             if (capacity <= MAX_BUFFER_SIZE - capacity) {
 188                 capacity = Math.max(capacity << 1, BUFFER_SIZE);
 189             } else {
 190                 if (capacity == MAX_BUFFER_SIZE)
 191                     throw new OutOfMemoryError("Required array size too large");
 192                 capacity = MAX_BUFFER_SIZE;
 193             }
 194             buf = Arrays.copyOf(buf, capacity);
 195             buf[nread++] = (byte)n;
 196         }
 197         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
 198     }
 199 
 200 
 201     /**
 202      * Returns list of predefined configurations available.
 203      *
 204      * @return list of configurations, not null
 205      */
 206     public static List<Configuration> getConfigurations() {
 207         List<Configuration> configs = new ArrayList<>();
 208         for (KnownConfiguration knownConfig : getKnownConfigurations()) {
 209             try {
 210                 configs.add(knownConfig.getConfigurationFile());
 211             } catch (IOException e) {
 212                 Logger.log(LogTag.JFR, LogLevel.WARN, "Could not load configuration " + knownConfig.getName() + ". " + e.getMessage());
 213             } catch (ParseException e) {
 214                 Logger.log(LogTag.JFR, LogLevel.WARN, "Could not parse configuration " + knownConfig.getName() + ". " + e.getMessage());
 215             }
 216         }
 217         return configs;
 218     }
 219 
 220     private static List<KnownConfiguration> getKnownConfigurations() {
 221         if (knownConfigurations == null) {
 222             List<KnownConfiguration> configProxies = new ArrayList<>();
 223             for (SafePath p : SecuritySupport.getPredefinedJFCFiles()) {
 224                 try {
 225                     configProxies.add(new KnownConfiguration(p));
 226                 } catch (IOException ioe) {
 227                     // ignore
 228                 }
 229             }
 230             knownConfigurations = configProxies;
 231         }
 232         return knownConfigurations;
 233     }
 234 
 235     public static Configuration getPredefined(String name) throws IOException, ParseException {
 236         for (KnownConfiguration knownConfig : getKnownConfigurations()) {
 237             if (knownConfig.getName().equals(name)) {
 238                 return knownConfig.getConfigurationFile();
 239             }
 240         }
 241         throw new NoSuchFileException("Could not locate configuration with name " + name);
 242     }
 243 }