1 /*
   2  * Copyright (c) 1998, 2013, 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 
  43     /* Generate a filename unique to this run */
  44     protected static String gensym() {
  45         return "x." + ++gensymCounter;
  46     }
  47 
  48 
  49     /**
  50      * Find a file in the given subdirectory, or descend into further
  51      * subdirectories, if any, if no file is found here.  Return null if no
  52      * file can be found anywhere beneath the given subdirectory.
  53      * @param  dir     Directory at which we started
  54      * @param  subdir  Subdirectory that we're exploring
  55      * @param  dl      Listing of subdirectory
  56      */
  57     private static String findSomeFile(String dir, String subdir, String[] dl) {
  58         for (int i = 0; i < dl.length; i++) {
  59             File f = new File(subdir, dl[i]);
  60             File df = new File(dir, f.getPath());
  61             if (Files.isRegularFile(df.toPath(), LinkOption.NOFOLLOW_LINKS)) {
  62                 return f.getPath();
  63             }
  64         }
  65         for (int i = 0; i < dl.length; i++) {
  66             File f = (subdir.length() == 0) ? new File(dl[i])
  67                                             : new File(subdir, dl[i]);
  68             File df = new File(dir, f.getPath());
  69             if (Files.isDirectory(df.toPath(), LinkOption.NOFOLLOW_LINKS)) {
  70                 String[] dl2 = df.list();
  71                 if (dl2 != null) {
  72                     String ff = findSomeFile(dir, f.getPath(), dl2);
  73                     if (ff != null) return ff;
  74                 }
  75             }
  76         }
  77         return null;
  78     }
  79 
  80 
  81     /**
  82      * Construct a string that names a file in the given directory.  If create
  83      * is true, then create a file if none is found, and throw an exception if
  84      * that is not possible; otherwise, return null if no file can be found.
  85      */
  86     private static String findSomeFile(String dir, boolean create) {
  87         File d = new File(dir);
  88         String[] dl = d.list();
  89         if (dl == null) {
  90             throw new RuntimeException("Can't list " + dir);
  91         }
  92         for (int i = 0; i < dl.length; i++) {
  93             File f = new File(dir, dl[i]);
  94             if (Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS)) {
  95                 return dl[i];
  96             }
  97         }
  98         String f = findSomeFile(dir, "", dl);
  99         if (f != null) {
 100             return f;
 101         }
 102         if (create) {
 103             File nf = new File(d, gensym());
 104             OutputStream os;
 105             try {
 106                 os = new FileOutputStream(nf);
 107                 os.close();
 108             } catch (IOException x) {
 109                 throw new RuntimeException("Can't create a file in " + dir);
 110             }
 111             return nf.getName();
 112         }
 113         return null;
 114     }
 115 
 116 
 117     /**
 118      * Construct a string that names a subdirectory of the given directory.
 119      * If create is true, then create a subdirectory if none is found, and
 120      * throw an exception if that is not possible; otherwise, return null if
 121      * no subdirectory can be found.
 122      */
 123     private static String findSomeDir(String dir, boolean create) {
 124         File d = new File(dir);
 125         String[] dl = d.list();
 126         if (dl == null) {
 127             throw new RuntimeException("Can't list " + dir);
 128         }
 129         for (int i = 0; i < dl.length; i++) {
 130             File f = new File(d, dl[i]);
 131             if (Files.isDirectory(f.toPath(), LinkOption.NOFOLLOW_LINKS)) {
 132                 String[] dl2 = f.list();
 133                 if (dl2 == null || dl2.length >= 250) {
 134                     /* Heuristic to avoid scanning huge directories */
 135                     continue;
 136                 }
 137                 return dl[i];
 138             }
 139         }
 140         if (create) {
 141             File sd = new File(d, gensym());
 142             if (sd.mkdir()) return sd.getName();
 143         }
 144         return null;
 145     }
 146 
 147 
 148     /** Construct a string that does not name a file in the given directory */
 149     private static String findNon(String dir) {
 150         File d = new File(dir);
 151         String[] x = new String[] { "foo", "bar", "baz" };
 152         for (int i = 0; i < x.length; i++) {
 153             File f = new File(d, x[i]);
 154             if (!f.exists()) {
 155                 return x[i];
 156             }
 157         }
 158         for (int i = 0; i < 1024; i++) {
 159             String n = "xx" + Integer.toString(i);
 160             File f = new File(d, n);
 161             if (!f.exists()) {
 162                 return n;
 163             }
 164         }
 165         throw new RuntimeException("Can't find a non-existent file in " + dir);
 166     }
 167 
 168 
 169     /** Ensure that the named file does not exist */
 170     public static void ensureNon(String fn) {
 171         if ((new File(fn)).exists()) {
 172             throw new RuntimeException("Test path " + fn + " exists");
 173         }
 174     }
 175 
 176 
 177     /** Tell whether the given character is a "slash" on this platform */
 178     private static boolean isSlash(char x) {
 179         if (x == File.separatorChar) return true;
 180         if (win32 && (x == '/')) return true;
 181         return false;
 182     }
 183 
 184 
 185     /**
 186      * Trim trailing slashes from the given string, but leave singleton slashes
 187      * alone (they denote root directories)
 188      */
 189     private static String trimTrailingSlashes(String s) {
 190         int n = s.length();
 191         if (n == 0) return s;
 192         n--;
 193         while ((n > 0) && isSlash(s.charAt(n))) {
 194             if ((n >= 1) && s.charAt(n - 1) == ':') break;
 195             n--;
 196         }
 197         return s.substring(0, n + 1);
 198     }
 199 
 200 
 201     /** Concatenate two paths, trimming slashes as needed */
 202     private static String pathConcat(String a, String b) {
 203         if (a.length() == 0) return b;
 204         if (b.length() == 0) return a;
 205         if (isSlash(a.charAt(a.length() - 1))
 206             || isSlash(b.charAt(0))
 207             || (win32 && (a.charAt(a.length() - 1) == ':'))) {
 208             return a + b;
 209         } else {
 210             return a + File.separatorChar + b;
 211         }
 212     }
 213 
 214 
 215 
 216     /** Hash table of input pathnames, used to detect duplicates */
 217     private static Hashtable checked = new Hashtable();
 218 
 219     /**
 220      * Check the given pathname.  Its canonical pathname should be the given
 221      * answer.  If the path names a file that exists and is readable, then
 222      * FileInputStream and RandomAccessFile should both be able to open it.
 223      */
 224     public static void check(String answer, String path) throws IOException {
 225         String ans = trimTrailingSlashes(answer);
 226         if (path.length() == 0) return;
 227         if (checked.get(path) != null) {
 228             System.err.println("DUP " + path);
 229             return;
 230         }
 231         checked.put(path, path);
 232 
 233         String cpath;
 234         try {
 235             File f = new File(path);
 236             cpath = f.getCanonicalPath();
 237             if (f.exists() && f.isFile() && f.canRead()) {
 238                 InputStream in = new FileInputStream(path);
 239                 in.close();
 240                 RandomAccessFile raf = new RandomAccessFile(path, "r");
 241                 raf.close();
 242             }
 243         } catch (IOException x) {
 244             System.err.println(ans + " <-- " + path + " ==> " + x);
 245             if (debug) return;
 246             else throw x;
 247         }
 248         if (cpath.equals(ans)) {
 249             System.err.println(ans + " <== " + path);
 250         } else {
 251             System.err.println(ans + " <-- " + path + " ==> " + cpath + " MISMATCH");
 252             if (!debug) {
 253                 throw new RuntimeException("Mismatch: " + path + " ==> " + cpath +
 254                                            ", should be " + ans);
 255             }
 256         }
 257     }
 258 
 259 
 260 
 261     /*
 262      * The following three mutually-recursive methods generate and check a tree
 263      * of filenames of arbitrary depth.  Each method has (at least) these
 264      * arguments:
 265      *
 266      *     int depth         Remaining tree depth
 267      *     boolean create    Controls whether test files and directories
 268      *                       will be created as needed
 269      *     String ans        Expected answer for the check method (above)
 270      *     String ask        Input pathname to be passed to the check method
 271      */
 272 
 273 
 274     /** Check a single slash case, plus its children */
 275     public static void checkSlash(int depth, boolean create,
 276                                   String ans, String ask, String slash)
 277         throws Exception
 278     {
 279         check(ans, ask + slash);
 280         checkNames(depth, create,
 281                    ans.endsWith(File.separator) ? ans : ans + File.separator,
 282                    ask + slash);
 283     }
 284 
 285 
 286     /** Check slash cases for the given ask string */
 287     public static void checkSlashes(int depth, boolean create,
 288                                     String ans, String ask)
 289         throws Exception
 290     {
 291         check(ans, ask);
 292         if (depth == 0) return;
 293 
 294         checkSlash(depth, create, ans, ask, "/");
 295         checkSlash(depth, create, ans, ask, "//");
 296         checkSlash(depth, create, ans, ask, "///");
 297         if (win32) {
 298             checkSlash(depth, create, ans, ask, "\\");
 299             checkSlash(depth, create, ans, ask, "\\\\");
 300             checkSlash(depth, create, ans, ask, "\\/");
 301             checkSlash(depth, create, ans, ask, "/\\");
 302             checkSlash(depth, create, ans, ask, "\\\\\\");
 303         }
 304     }
 305 
 306 
 307     /** Check name cases for the given ask string */
 308     public static void checkNames(int depth, boolean create,
 309                                   String ans, String ask)
 310         throws Exception
 311     {
 312         int d = depth - 1;
 313         File f = new File(ans);
 314         String n;
 315 
 316         /* Normal name */
 317         if (f.exists()) {
 318             if (Files.isDirectory(f.toPath(), LinkOption.NOFOLLOW_LINKS) && f.list() != null) {
 319                 if ((n = findSomeFile(ans, create)) != null)
 320                     checkSlashes(d, create, ans + n, ask + n);
 321                 if ((n = findSomeDir(ans, create)) != null)
 322                     checkSlashes(d, create, ans + n, ask + n);
 323             }
 324             n = findNon(ans);
 325             checkSlashes(d, create, ans + n, ask + n);
 326         } else {
 327             n = "foo" + depth;
 328             checkSlashes(d, create, ans + n, ask + n);
 329         }
 330 
 331         /* "." */
 332         checkSlashes(d, create, trimTrailingSlashes(ans), ask + ".");
 333 
 334         /* ".." */
 335         if ((n = f.getParent()) != null) {
 336             String n2;
 337             if (win32
 338                 && ((n2 = f.getParentFile().getParent()) != null)
 339                 && n2.equals("\\\\")) {
 340                 /* Win32 resolves \\foo\bar\.. to \\foo\bar */
 341                 checkSlashes(d, create, ans, ask + "..");
 342             } else {
 343                 checkSlashes(d, create, n, ask + "..");
 344             }
 345         }
 346         else {
 347             if (win32)
 348                 checkSlashes(d, create, ans, ask + "..");
 349             else {
 350                 // Fix for 4237875. We must ensure that we are sufficiently
 351                 // deep in the path hierarchy to test parents this high up
 352                 File thisPath = new File(ask);
 353                 File nextPath = new File(ask + "..");
 354                 if (!thisPath.getCanonicalPath().equals(nextPath.getCanonicalPath()))
 355                     checkSlashes(d, create, ans + "..", ask + "..");
 356             }
 357         }
 358     }
 359 }