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         if (f.endsWith(JFCParser.FILE_EXTENSION)) {
 131             return f.substring(0, f.length() - JFCParser.FILE_EXTENSION.length());
 132         } else  {
 133             return f;
 134         }
 135     }
 136 
 137     // Invoked by DCmdStart
 138     public static Configuration createKnown(String name) throws IOException, ParseException {
 139         // Known name, no need for permission
 140         for (KnownConfiguration known : getKnownConfigurations()) {
 141             if (known.isNamed(name)) {
 142                 return known.getConfigurationFile();
 143             }
 144         }
 145         // Check JFC directory
 146         SafePath path = SecuritySupport.JFC_DIRECTORY;
 147         if (path != null && SecuritySupport.exists(path)) {
 148             for (String extension : Arrays.asList("", JFCParser.FILE_EXTENSION)) {
 149                 SafePath file = new SafePath(path.toPath().resolveSibling(name + extension));
 150                 if (SecuritySupport.exists(file) && !SecuritySupport.isDirectory(file)) {
 151                     try (Reader r = SecuritySupport.newFileReader(file)) {
 152                         String jfcName = nameFromPath(file.toPath());
 153                         return JFCParser.createConfiguration(jfcName, r);
 154                     }
 155                 }
 156             }
 157         }
 158 
 159         // Assume path included in name
 160 
 161         Path localPath = Paths.get(name);
 162         String jfcName = nameFromPath(localPath);
 163         try (Reader r = Files.newBufferedReader(localPath)) {
 164             return JFCParser.createConfiguration(jfcName, r);
 165         }
 166     }
 167 
 168     private static String readContent(InputStream source) throws IOException {
 169         byte[] bytes = read(source, BUFFER_SIZE);
 170         return new String(bytes, StandardCharsets.UTF_8);
 171     }
 172 
 173     // copied from java.io.file.Files to avoid dependency on JDK 9 code
 174     private static byte[] read(InputStream source, int initialSize) throws IOException {
 175         int capacity = initialSize;
 176         byte[] buf = new byte[capacity];
 177         int nread = 0;
 178         int n;
 179         for (;;) {
 180             // read to EOF which may read more or less than initialSize (eg: file
 181             // is truncated while we are reading)
 182             while ((n = source.read(buf, nread, capacity - nread)) > 0)
 183                 nread += n;
 184 
 185             // if last call to source.read() returned -1, we are done
 186             // otherwise, try to read one more byte; if that failed we're done too
 187             if (n < 0 || (n = source.read()) < 0)
 188                 break;
 189 
 190             // one more byte was read; need to allocate a larger buffer
 191             if (capacity <= MAX_BUFFER_SIZE - capacity) {
 192                 capacity = Math.max(capacity << 1, BUFFER_SIZE);
 193             } else {
 194                 if (capacity == MAX_BUFFER_SIZE)
 195                     throw new OutOfMemoryError("Required array size too large");
 196                 capacity = MAX_BUFFER_SIZE;
 197             }
 198             buf = Arrays.copyOf(buf, capacity);
 199             buf[nread++] = (byte)n;
 200         }
 201         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
 202     }
 203 
 204 
 205     /**
 206      * Returns list of predefined configurations available.
 207      *
 208      * @return list of configurations, not null
 209      */
 210     public static List<Configuration> getConfigurations() {
 211         List<Configuration> configs = new ArrayList<>();
 212         for (KnownConfiguration knownConfig : getKnownConfigurations()) {
 213             try {
 214                 configs.add(knownConfig.getConfigurationFile());
 215             } catch (IOException e) {
 216                 Logger.log(LogTag.JFR, LogLevel.WARN, "Could not load configuration " + knownConfig.getName() + ". " + e.getMessage());
 217             } catch (ParseException e) {
 218                 Logger.log(LogTag.JFR, LogLevel.WARN, "Could not parse configuration " + knownConfig.getName() + ". " + e.getMessage());
 219             }
 220         }
 221         return configs;
 222     }
 223 
 224     private static List<KnownConfiguration> getKnownConfigurations() {
 225         if (knownConfigurations == null) {
 226             List<KnownConfiguration> configProxies = new ArrayList<>();
 227             for (SafePath p : SecuritySupport.getPredefinedJFCFiles()) {
 228                 try {
 229                     configProxies.add(new KnownConfiguration(p));
 230                 } catch (IOException ioe) {
 231                     // ignore
 232                 }
 233             }
 234             knownConfigurations = configProxies;
 235         }
 236         return knownConfigurations;
 237     }
 238 
 239     public static Configuration getPredefined(String name) throws IOException, ParseException {
 240         for (KnownConfiguration knownConfig : getKnownConfigurations()) {
 241             if (knownConfig.getName().equals(name)) {
 242                 return knownConfig.getConfigurationFile();
 243             }
 244         }
 245         throw new NoSuchFileException("Could not locate configuration with name " + name);
 246     }
 247 }