1 /*
   2  * Copyright (c) 1998, 2016, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25    @summary Common definitions for general exhaustive pathname tests
  26    @author  Mark Reinhold
  27  */
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.nio.file.*;
  32 
  33 
  34 public class General {
  35 
  36     public static boolean debug = false;
  37 
  38     private static boolean win32 = (File.separatorChar == '\\');
  39 
  40     private static int gensymCounter = 0;
  41 
  42     protected static final String userDir = System.getProperty("user.dir");
  43     private static final Path userDirPath = Paths.get(userDir).toAbsolutePath();
  44 
  45     protected static String baseDir = null;
  46     protected static String relative = null;
  47 
  48     /* Generate a filename unique to this run */
  49     private static String gensym() {
  50         return "x." + ++gensymCounter;
  51     }
  52 
  53     /**
  54      * Create files and folders in the test working directory.
  55      * The purpose is to make sure the test will not go out of
  56      * its user dir when walking the file tree.
  57      *
  58      * @param  depth    The number of directory levels to be created under
  59      *                  the user directory. It should be the maximum value
  60      *                  of the depths passed to checkNames method (including
  61      *                  direct or indirect calling) in a whole test.
  62      */
  63     protected static void initTestData(int depth) throws IOException {
  64         File parent = new File(userDir);
  65         for (int i = 0; i < depth; i++) {
  66             File tmp = new File(parent, gensym());
  67             tmp.createNewFile();
  68             tmp = new File(parent, gensym());
  69             if (tmp.mkdir())
  70                 parent = tmp;
  71             else
  72                 throw new IOException("Fail to create directory, " + tmp);
  73         }
  74         baseDir = parent.getAbsolutePath();
  75         relative = baseDir.substring(userDir.length() + 1);
  76     }
  77 
  78     /**
  79      * Find a file in the given subdirectory, or descend into further
  80      * subdirectories, if any, if no file is found here.  Return null if no
  81      * file can be found anywhere beneath the given subdirectory.
  82      * @param  dir     Directory at which we started
  83      * @param  subdir  Subdirectory that we're exploring
  84      * @param  dl      Listing of subdirectory
  85      */
  86     private static String findSomeFile(String dir, String subdir, String[] dl) {
  87         for (int i = 0; i < dl.length; i++) {
  88             File f = new File(subdir, dl[i]);
  89             File df = new File(dir, f.getPath());
  90             if (Files.isRegularFile(df.toPath(), LinkOption.NOFOLLOW_LINKS)) {
  91                 return f.getPath();
  92             }
  93         }
  94         for (int i = 0; i < dl.length; i++) {
  95             File f = (subdir.length() == 0) ? new File(dl[i])
  96                                             : new File(subdir, dl[i]);
  97             File df = new File(dir, f.getPath());
  98             if (Files.isDirectory(df.toPath(), LinkOption.NOFOLLOW_LINKS)) {
  99                 String[] dl2 = df.list();
 100                 if (dl2 != null) {
 101                     String ff = findSomeFile(dir, f.getPath(), dl2);
 102                     if (ff != null) return ff;
 103                 }
 104             }
 105         }
 106         return null;
 107     }
 108 
 109 
 110     /**
 111      * Construct a string that names a file in the given directory.  If create
 112      * is true, then create a file if none is found, and throw an exception if
 113      * that is not possible; otherwise, return null if no file can be found.
 114      */
 115     private static String findSomeFile(String dir, boolean create) {
 116         File d = new File(dir);
 117         String[] dl = d.list();
 118         if (dl == null) {
 119             throw new RuntimeException("Can't list " + dir);
 120         }
 121         for (int i = 0; i < dl.length; i++) {
 122             File f = new File(dir, dl[i]);
 123             if (Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS)) {
 124                 return dl[i];
 125             }
 126         }
 127         String f = findSomeFile(dir, "", dl);
 128         if (f != null) {
 129             return f;
 130         }
 131         if (create) {
 132             File nf = new File(d, gensym());
 133             OutputStream os;
 134             try {
 135                 os = new FileOutputStream(nf);
 136                 os.close();
 137             } catch (IOException x) {
 138                 throw new RuntimeException("Can't create a file in " + dir);
 139             }
 140             return nf.getName();
 141         }
 142         return null;
 143     }
 144 
 145 
 146     /**
 147      * Construct a string that names a subdirectory of the given directory.
 148      * If create is true, then create a subdirectory if none is found, and
 149      * throw an exception if that is not possible; otherwise, return null if
 150      * no subdirectory can be found.
 151      */
 152     private static String findSomeDir(String dir, boolean create) {
 153         File d = new File(dir);
 154         String[] dl = d.list();
 155         if (dl == null) {
 156             throw new RuntimeException("Can't list " + dir);
 157         }
 158         for (int i = 0; i < dl.length; i++) {
 159             File f = new File(d, dl[i]);
 160             if (Files.isDirectory(f.toPath(), LinkOption.NOFOLLOW_LINKS)) {
 161                 String[] dl2 = f.list();
 162                 if (dl2 == null || dl2.length >= 250) {
 163                     /* Heuristic to avoid scanning huge directories */
 164                     continue;
 165                 }
 166                 return dl[i];
 167             }
 168         }
 169         if (create) {
 170             File sd = new File(d, gensym());
 171             if (sd.mkdir()) return sd.getName();
 172         }
 173         return null;
 174     }
 175 
 176 
 177     /** Construct a string that does not name a file in the given directory */
 178     private static String findNon(String dir) {
 179         File d = new File(dir);
 180         String[] x = new String[] { "foo", "bar", "baz" };
 181         for (int i = 0; i < x.length; i++) {
 182             File f = new File(d, x[i]);
 183             if (!f.exists()) {
 184                 return x[i];
 185             }
 186         }
 187         for (int i = 0; i < 1024; i++) {
 188             String n = "xx" + Integer.toString(i);
 189             File f = new File(d, n);
 190             if (!f.exists()) {
 191                 return n;
 192             }
 193         }
 194         throw new RuntimeException("Can't find a non-existent file in " + dir);
 195     }
 196 
 197 
 198     /** Ensure that the named file does not exist */
 199     public static void ensureNon(String fn) {
 200         if ((new File(fn)).exists()) {
 201             throw new RuntimeException("Test path " + fn + " exists");
 202         }
 203     }
 204 
 205 
 206     /** Tell whether the given character is a "slash" on this platform */
 207     private static boolean isSlash(char x) {
 208         if (x == File.separatorChar) return true;
 209         if (win32 && (x == '/')) return true;
 210         return false;
 211     }
 212 
 213 
 214     /**
 215      * Trim trailing slashes from the given string, but leave singleton slashes
 216      * alone (they denote root directories)
 217      */
 218     private static String trimTrailingSlashes(String s) {
 219         int n = s.length();
 220         if (n == 0) return s;
 221         n--;
 222         while ((n > 0) && isSlash(s.charAt(n))) {
 223             if ((n >= 1) && s.charAt(n - 1) == ':') break;
 224             n--;
 225         }
 226         return s.substring(0, n + 1);
 227     }
 228 
 229 
 230     /** Concatenate two paths, trimming slashes as needed */
 231     private static String pathConcat(String a, String b) {
 232         if (a.length() == 0) return b;
 233         if (b.length() == 0) return a;
 234         if (isSlash(a.charAt(a.length() - 1))
 235             || isSlash(b.charAt(0))
 236             || (win32 && (a.charAt(a.length() - 1) == ':'))) {
 237             return a + b;
 238         } else {
 239             return a + File.separatorChar + b;
 240         }
 241     }
 242 
 243 
 244 
 245     /** Hash table of input pathnames, used to detect duplicates */
 246     private static Hashtable<String, String> checked = new Hashtable<>();
 247 
 248     /**
 249      * Check the given pathname.  Its canonical pathname should be the given
 250      * answer.  If the path names a file that exists and is readable, then
 251      * FileInputStream and RandomAccessFile should both be able to open it.
 252      */
 253     public static void check(String answer, String path) throws IOException {
 254         String ans = trimTrailingSlashes(answer);
 255         if (path.length() == 0) return;
 256         if (checked.get(path) != null) {
 257             System.err.println("DUP " + path);
 258             return;
 259         }
 260         checked.put(path, path);
 261 
 262         String cpath;
 263         try {
 264             File f = new File(path);
 265             cpath = f.getCanonicalPath();
 266             if (f.exists() && f.isFile() && f.canRead()) {
 267                 InputStream in = new FileInputStream(path);
 268                 in.close();
 269                 RandomAccessFile raf = new RandomAccessFile(path, "r");
 270                 raf.close();
 271             }
 272         } catch (IOException x) {
 273             System.err.println(ans + " <-- " + path + " ==> " + x);
 274             if (debug) return;
 275             else throw x;
 276         }
 277         if (cpath.equals(ans)) {
 278             System.err.println(ans + " <== " + path);
 279         } else {
 280             System.err.println(ans + " <-- " + path + " ==> " + cpath + " MISMATCH");
 281             if (!debug) {
 282                 throw new RuntimeException("Mismatch: " + path + " ==> " + cpath +
 283                                            ", should be " + ans);
 284             }
 285         }
 286     }
 287 
 288 
 289 
 290     /*
 291      * The following three mutually-recursive methods generate and check a tree
 292      * of filenames of arbitrary depth.  Each method has (at least) these
 293      * arguments:
 294      *
 295      *     int depth         Remaining tree depth
 296      *     boolean create    Controls whether test files and directories
 297      *                       will be created as needed
 298      *     String ans        Expected answer for the check method (above)
 299      *     String ask        Input pathname to be passed to the check method
 300      */
 301 
 302 
 303     /** Check a single slash case, plus its children */
 304     private static void checkSlash(int depth, boolean create,
 305                                   String ans, String ask, String slash)
 306         throws Exception
 307     {
 308         check(ans, ask + slash);
 309         checkNames(depth, create,
 310                    ans.endsWith(File.separator) ? ans : ans + File.separator,
 311                    ask + slash);
 312     }
 313 
 314 
 315     /** Check slash cases for the given ask string */
 316     public static void checkSlashes(int depth, boolean create,
 317                                     String ans, String ask)
 318         throws Exception
 319     {
 320         check(ans, ask);
 321         if (depth == 0) return;
 322 
 323         checkSlash(depth, create, ans, ask, "/");
 324         checkSlash(depth, create, ans, ask, "//");
 325         checkSlash(depth, create, ans, ask, "///");
 326         if (win32) {
 327             checkSlash(depth, create, ans, ask, "\\");
 328             checkSlash(depth, create, ans, ask, "\\\\");
 329             checkSlash(depth, create, ans, ask, "\\/");
 330             checkSlash(depth, create, ans, ask, "/\\");
 331             checkSlash(depth, create, ans, ask, "\\\\\\");
 332         }
 333     }
 334 
 335 
 336     /** Check name cases for the given ask string */
 337     public static void checkNames(int depth, boolean create,
 338                                   String ans, String ask)
 339         throws Exception
 340     {
 341         if (!Paths.get(ans).toAbsolutePath().startsWith(userDirPath)) {
 342             return;
 343         }
 344 
 345         int d = depth - 1;
 346         File f = new File(ans);
 347         String n;
 348 
 349         /* Normal name */
 350         if (f.exists()) {
 351             if (Files.isDirectory(f.toPath(), LinkOption.NOFOLLOW_LINKS) && f.list() != null) {
 352                 if ((n = findSomeFile(ans, create)) != null)
 353                     checkSlashes(d, create, ans + n, ask + n);
 354                 if ((n = findSomeDir(ans, create)) != null)
 355                     checkSlashes(d, create, ans + n, ask + n);
 356             }
 357             n = findNon(ans);
 358             checkSlashes(d, create, ans + n, ask + n);
 359         } else {
 360             n = "foo" + depth;
 361             checkSlashes(d, create, ans + n, ask + n);
 362         }
 363 
 364         /* "." */
 365         checkSlashes(d, create, trimTrailingSlashes(ans), ask + ".");
 366 
 367         /* ".." */
 368         if ((n = f.getParent()) != null) {
 369             String n2;
 370             if (win32
 371                 && ((n2 = f.getParentFile().getParent()) != null)
 372                 && n2.equals("\\\\")) {
 373                 /* Win32 resolves \\foo\bar\.. to \\foo\bar */
 374                 checkSlashes(d, create, ans, ask + "..");
 375             } else {
 376                 checkSlashes(d, create, n, ask + "..");
 377             }
 378         }
 379         else {
 380             if (win32)
 381                 checkSlashes(d, create, ans, ask + "..");
 382             else {
 383                 // Fix for 4237875. We must ensure that we are sufficiently
 384                 // deep in the path hierarchy to test parents this high up
 385                 File thisPath = new File(ask);
 386                 File nextPath = new File(ask + "..");
 387                 if (!thisPath.getCanonicalPath().equals(nextPath.getCanonicalPath()))
 388                     checkSlashes(d, create, ans + "..", ask + "..");
 389             }
 390         }
 391     }
 392 }