1 /*
   2  * Copyright (c) 2015, 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 sun.nio.fs;
  27 
  28 import java.io.IOException;
  29 import java.nio.charset.Charset;
  30 import java.nio.file.Files;
  31 import java.nio.file.Path;
  32 import java.security.AccessController;
  33 import java.security.PrivilegedAction;
  34 import java.util.Collections;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 import java.util.regex.Matcher;
  39 import java.util.regex.Pattern;
  40 
  41 /**
  42  * File type detector that uses a file extension to look up its MIME type
  43  * based on a mime.types file.
  44  */
  45 
  46 class MimeTypesFileTypeDetector extends AbstractFileTypeDetector {
  47 
  48     // path to mime.types file
  49     private final Path mimeTypesFile;
  50 
  51     // map of extension to MIME type
  52     private Map<String,String> mimeTypeMap;
  53 
  54     // set to true when file loaded
  55     private volatile boolean loaded = false;
  56 
  57     public MimeTypesFileTypeDetector(Path filePath) {
  58         mimeTypesFile = filePath;
  59     }
  60 
  61     @Override
  62     protected String implProbeContentType(Path path) {
  63         Path fn = path.getFileName();
  64         if (fn == null)
  65             return null;  // no file name
  66 
  67         String ext = getExtension(fn.toString());
  68         if (ext.isEmpty())
  69             return null;  // no extension
  70 
  71         loadMimeTypes();
  72         if (mimeTypeMap == null || mimeTypeMap.isEmpty())
  73             return null;
  74 
  75         // Case-sensitive search
  76         String mimeType;
  77         do {
  78             mimeType = mimeTypeMap.get(ext);
  79             if (mimeType == null)
  80                 ext = getExtension(ext);
  81         } while (mimeType == null && !ext.isEmpty());
  82 
  83         return mimeType;
  84     }
  85 
  86     /**
  87      * Parse the mime types file, and store the type-extension mappings into
  88      * mimeTypeMap. The mime types file is not loaded until the first probe
  89      * to achieve the lazy initialization. It adopts double-checked locking
  90      * optimization to reduce the locking overhead.
  91      */
  92     private void loadMimeTypes() {
  93         if (!loaded) {
  94             synchronized (this) {
  95                 if (!loaded) {
  96                     List<String> lines = AccessController.doPrivileged(
  97                         new PrivilegedAction<>() {
  98                             @Override
  99                             public List<String> run() {
 100                                 try {
 101                                     return Files.readAllLines(mimeTypesFile,
 102                                                               Charset.defaultCharset());
 103                                 } catch (IOException ignore) {
 104                                     return Collections.emptyList();
 105                                 }
 106                             }
 107                         });
 108 
 109                     mimeTypeMap = new HashMap<>(lines.size());
 110                     String entry = "";
 111                     for (String line : lines) {
 112                         entry += line;
 113                         if (entry.endsWith("\\")) {
 114                             entry = entry.substring(0, entry.length() - 1);
 115                             continue;
 116                         }
 117                         parseMimeEntry(entry);
 118                         entry = "";
 119                     }
 120                     if (!entry.isEmpty()) {
 121                         parseMimeEntry(entry);
 122                     }
 123                     loaded = true;
 124                 }
 125             }
 126         }
 127     }
 128 
 129     /**
 130      * Parse a mime-types entry, which can have the following formats.
 131      * 1) Simple space-delimited format
 132      * image/jpeg   jpeg jpg jpe JPG
 133      *
 134      * 2) Netscape key-value pair format
 135      * type=application/x-java-jnlp-file desc="Java Web Start" exts="jnlp"
 136      * or
 137      * type=text/html exts=htm,html
 138      */
 139     private void parseMimeEntry(String entry) {
 140         entry = entry.trim();
 141         if (entry.isEmpty() || entry.charAt(0) == '#')
 142             return;
 143 
 144         entry = entry.replaceAll("\\s*#.*", "");
 145         int equalIdx = entry.indexOf('=');
 146         if (equalIdx > 0) {
 147             // Parse a mime-types command having the key-value pair format
 148             final String TYPEEQUAL = "type=";
 149             String typeRegex = "\\b" + TYPEEQUAL +
 150                     "(\"\\p{Graph}+?/\\p{Graph}+?\"|\\p{Graph}+/\\p{Graph}+\\b)";
 151             Pattern typePattern = Pattern.compile(typeRegex);
 152             Matcher typeMatcher = typePattern.matcher(entry);
 153 
 154             if (typeMatcher.find()) {
 155                 String type = typeMatcher.group().substring(TYPEEQUAL.length());
 156                 if (type.charAt(0) == '"') {
 157                     type = type.substring(1, type.length() - 1);
 158                 }
 159 
 160                 final String EXTEQUAL = "exts=";
 161                 String extRegex = "\\b" + EXTEQUAL +
 162                         "(\"[\\p{Graph}|\\p{Blank}]+?\"|\\p{Graph}+\\b)";
 163                 Pattern extPattern = Pattern.compile(extRegex);
 164                 Matcher extMatcher = extPattern.matcher(entry);
 165 
 166                 if (extMatcher.find()) {
 167                     String exts =
 168                             extMatcher.group().substring(EXTEQUAL.length());
 169                     if (exts.charAt(0) == '"') {
 170                         exts = exts.substring(1, exts.length() - 1);
 171                     }
 172                     String[] extList = exts.split("[\\p{Blank}|\\p{Punct}]+");
 173                     for (String ext : extList) {
 174                         putIfAbsent(ext, type);
 175                     }
 176                 }
 177             }
 178         } else {
 179             // Parse a mime-types command having the space-delimited format
 180             String[] elements = entry.split("\\s+");
 181             int i = 1;
 182             while (i < elements.length) {
 183                 putIfAbsent(elements[i++], elements[0]);
 184             }
 185         }
 186     }
 187 
 188     private void putIfAbsent(String key, String value) {
 189         if (key != null && !key.isEmpty() &&
 190             value != null && !value.isEmpty() &&
 191             !mimeTypeMap.containsKey(key))
 192         {
 193             mimeTypeMap.put(key, value);
 194         }
 195     }
 196 }