001package org.hl7.fhir.utilities;
002
003import java.io.File;
004import java.io.IOException;
005import java.nio.file.Path;
006import java.nio.file.Paths;
007
008import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
009import org.hl7.fhir.utilities.settings.FhirSettings;
010
011import lombok.AccessLevel;
012import lombok.AllArgsConstructor;
013import lombok.With;
014
015@AllArgsConstructor(access = AccessLevel.PRIVATE)
016public class PathBuilder {
017
018  /**
019   * By default, the normalized built path must be a child of the first entry of the buildPath arguments. If a
020   * different parent is desired, this can be set via <code>withRequiredTarget</code>
021   */
022  @With
023  private final String requiredTarget;
024
025  /**
026   * By default, the first entry of the buildPath argument cannot be null or an empty string. Setting this to false will
027   * disable this check.
028   */
029  @With
030  private final boolean requireNonNullNonEmptyFirstEntry;
031
032  /**
033   * By default, the first entry of the buildPath argument cannot be a root directory (<code>"/", "C:\", etc. </code>. Setting this to false will disable this check.
034   */
035  @With
036  private final boolean requireNonRootFirstEntry;
037
038  /**
039   * By default, the normalized built path must be a child of the first entry of the buildPath arguments. Setting this
040   * to false will disable this check.
041   */
042  @With
043  private final boolean requirePathIsChildOfTarget;
044
045  /**
046   * Returns an instance of PathBuilder with all checks enabled (recommended).
047   *
048   * @return
049   */
050  public static PathBuilder getPathBuilder() {
051    return new PathBuilder(null, true, true, true);
052  }
053
054  /**
055   * <p>Builds a path from the passed argument strings. This path will be compatible with the local filesystem.
056   * </p>
057   *
058   * <p>
059   * If the args contain variables enclosed in square brackets (<code>[ ]</code>), they will be replaced with values in
060   * the built path. There are several built-in variables available, listed below. Any text between square brackets that
061   * does not match these will be replaced by a matching System environment variable if one is available.
062   * </p>
063   *
064   * <p>
065   * Built-in variables include:
066   * <ul>
067   *  <li><i>[tmp]</i> An available temp directory (Java Temp directory, <code>c:\\temp, $TMPDIR, %TEMP%</code>, etc.) </li>
068   *  <li><i>[user]</i> The OS user directory (~, user.home, etc) </li>
069   * </ul>
070   * </p>
071   *
072   * <p>
073   * This method will run several checks by default to ensure that the built path does not point to unintended areas of
074   * the filesystem. If these checks are violated, a RuntimeException will be thrown. If needed in special cases, the
075   * behavior of these checks can be modified via the linked fluent constructor methods below.
076   * </p>
077   *
078   * @param args entries with which to construct the filesystem path
079   * @throws RuntimeException
080   * @return a local filesystem path
081   * @throws IOException 
082   *
083   * @see this#withRequiredTarget(String)
084   * @see this#withRequireNonNullNonEmptyFirstEntry(boolean)
085   * @see this#withRequireNonRootFirstEntry(boolean)
086   * @see this#withRequirePathIsChildOfTarget(boolean)
087   */
088  public String buildPath(String... args) throws IOException {
089
090    checkNonNullNonEmptyFirstEntry(args);
091    checkNonRootFirstEntry(args);
092
093    StringBuilder stringBuilder = new StringBuilder();
094    boolean argIsNotEmptyOrNull = false;
095
096    boolean first = true;
097    for (String arg : args) {
098      if (first && arg == null)
099        continue;
100      first = false;
101      if (!argIsNotEmptyOrNull)
102        argIsNotEmptyOrNull = !Utilities.noString(arg);
103      else if (!stringBuilder.toString().endsWith(File.separator))
104        stringBuilder.append(File.separator);
105      String a = arg;
106      if (stringBuilder.length() == 0) {
107        a = replaceVariables(a);
108      }
109      a = a.replace("\\", File.separator);
110      a = a.replace("/", File.separator);
111      if (stringBuilder.length() > 0 && a.startsWith(File.separator))
112        a = a.substring(File.separator.length());
113
114      while (a.startsWith(".." + File.separator)) {
115        if (stringBuilder.length() == 0) {
116          stringBuilder = new StringBuilder(Paths.get(".").toAbsolutePath().normalize().toString());
117        } else {
118          String p = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
119          if (!p.contains(File.separator)) {
120            stringBuilder = new StringBuilder();
121          } else {
122            stringBuilder = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator)) + File.separator);
123          }
124        }
125        a = a.substring(3);
126      }
127      if ("..".equals(a)) {
128        int i = stringBuilder.substring(0, stringBuilder.length() - 1).lastIndexOf(File.separator);
129        stringBuilder = new StringBuilder(stringBuilder.substring(0, i + 1));
130      } else
131        stringBuilder.append(a);
132    }
133    checkPathIsChildOfTarget(stringBuilder.toString(), args);
134    return stringBuilder.toString();
135  }
136
137  private void checkPathIsChildOfTarget(String path, String[] args) throws IOException {
138    if (!requirePathIsChildOfTarget) {
139      return;
140    }
141
142    final String target = requiredTarget != null
143      ? requiredTarget
144      : args[0];
145
146    if (!Path.of(path).normalize().startsWith(Path.of(replaceVariables(target)).normalize())) {
147      throw new RuntimeException("Computed path does not start with first element: " + String.join(", ", args));
148    }
149  }
150
151  private void checkNonRootFirstEntry(String[] args) {
152    if (!requireNonRootFirstEntry) {
153      return;
154    }
155    if (isPathRoot(args[0])) {
156      throw new RuntimeException("First entry in file path cannot be root: " + args[0]+", full path = "+String.join(", ", args));
157    }
158  }
159
160  private void checkNonNullNonEmptyFirstEntry(String[] args) {
161    if (!requireNonNullNonEmptyFirstEntry) {
162      return;
163    }
164    if (args[0] == null || Utilities.noString(args[0].trim())) {
165      throw new RuntimeException("First entry in file path cannot be null or empty, full path = "+String.join(", ", args));
166    }
167  }
168
169
170  private String replaceVariables(String a) throws IOException {
171    if ("[tmp]".equals(a)) {
172      return getTempDir();
173    } else if (a.startsWith("[tmp]")) {
174      return getTempDir()+a.substring(5);
175    } else if ("[user]".equals(a)) {
176      return System.getProperty("user.home");
177    }
178    return a;
179  }
180
181  private String getTempDir() throws IOException {
182    if (hasCTempDir()) {
183      return Utilities.C_TEMP_DIR;
184    } else if (FhirSettings.hasTempPath()) {
185      return FhirSettings.getTempPath();
186    } else {
187      return System.getProperty("java.io.tmpdir");
188    }
189  }
190
191  protected static boolean hasCTempDir() throws IOException {
192    if (!System.getProperty("os.name").toLowerCase().contains("win")) {
193      return false;
194    }
195    File tmp = ManagedFileAccess.file(Utilities.C_TEMP_DIR);
196    return tmp.exists() && tmp.isDirectory() && tmp.canWrite();
197  }
198
199  protected static boolean isPathRoot(String pathString) {
200    boolean actual;
201    Path path = Path.of(pathString);
202    Path normalizedPath = path.normalize();
203    actual = normalizedPath.equals(path.getRoot());
204    return actual;
205  }
206}