1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * See LICENSE.txt included in this distribution for the specific 9 * language governing permissions and limitations under the License. 10 * 11 * When distributing Covered Code, include this CDDL HEADER in each 12 * file and include the License file at LICENSE.txt. 13 * If applicable, add the following below this CDDL HEADER, with the 14 * fields enclosed by brackets "[]" replaced with your own identifying 15 * information: Portions Copyright [yyyy] [name of copyright owner] 16 * 17 * CDDL HEADER END 18 */ 19 20 /* 21 * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. 22 */ 23 package org.opengrok.web.util; 24 25 import org.opengrok.indexer.configuration.RuntimeEnvironment; 26 27 import java.io.File; 28 import java.io.FileNotFoundException; 29 import java.io.IOException; 30 import java.nio.file.InvalidPathException; 31 32 public class FileUtil { 33 34 private static final RuntimeEnvironment env = RuntimeEnvironment.getInstance(); 35 36 // private to enforce static FileUtil()37 private FileUtil() { 38 } 39 40 /** 41 * @param path path relative to source root 42 * @return file object corresponding to the file under source root 43 * @throws FileNotFoundException if the file constructed from the {@code path} parameter and source root 44 * does not exist 45 * @throws InvalidPathException if the file constructed from the {@code path} parameter and source root 46 * leads outside source root 47 * @throws NoPathParameterException if the {@code path} parameter is null 48 */ 49 @SuppressWarnings("lgtm[java/path-injection]") toFile(String path)50 public static File toFile(String path) throws NoPathParameterException, IOException { 51 if (path == null) { 52 throw new NoPathParameterException("Missing path parameter"); 53 } 54 55 File file = new File(env.getSourceRootFile(), path); 56 57 if (!file.getCanonicalPath().startsWith(env.getSourceRootPath() + File.separator)) { 58 throw new InvalidPathException(path, "File points to outside of source root"); 59 } 60 61 if (!file.exists()) { 62 throw new FileNotFoundException("File " + file + " not found"); 63 } 64 65 return file; 66 } 67 } 68