1. /*
  2. * @(#)Win32FileSystem.java 1.15 02/10/01
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.io;
  8. import java.security.AccessController;
  9. import sun.security.action.GetPropertyAction;
  10. class Win32FileSystem extends FileSystem {
  11. private final char slash;
  12. private final char altSlash;
  13. private final char semicolon;
  14. public Win32FileSystem() {
  15. slash = ((String) AccessController.doPrivileged(
  16. new GetPropertyAction("file.separator"))).charAt(0);
  17. semicolon = ((String) AccessController.doPrivileged(
  18. new GetPropertyAction("path.separator"))).charAt(0);
  19. altSlash = (this.slash == '\\') ? '/' : '\\';
  20. }
  21. private boolean isSlash(char c) {
  22. return (c == '\\') || (c == '/');
  23. }
  24. private boolean isLetter(char c) {
  25. return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
  26. }
  27. private String slashify(String p) {
  28. if ((p.length() > 0) && (p.charAt(0) != slash)) return slash + p;
  29. else return p;
  30. }
  31. /* -- Normalization and construction -- */
  32. public char getSeparator() {
  33. return slash;
  34. }
  35. public char getPathSeparator() {
  36. return semicolon;
  37. }
  38. /* A normal Win32 pathname contains no duplicate slashes, except possibly
  39. for a UNC prefix, and does not end with a slash. It may be the empty
  40. string. Normalized Win32 pathnames have the convenient property that
  41. the length of the prefix almost uniquely identifies the type of the path
  42. and whether it is absolute or relative:
  43. 0 relative to both drive and directory
  44. 1 drive-relative (begins with '\\')
  45. 2 absolute UNC (if first char is '\\'),
  46. else directory-relative (has form "z:foo")
  47. 3 absolute local pathname (begins with "z:\\")
  48. */
  49. private int normalizePrefix(String path, int len, StringBuffer sb) {
  50. int src = 0;
  51. while ((src < len) && isSlash(path.charAt(src))) src++;
  52. char c;
  53. if ((len - src >= 2)
  54. && isLetter(c = path.charAt(src))
  55. && path.charAt(src + 1) == ':') {
  56. /* Remove leading slashes if followed by drive specifier.
  57. This hack is necessary to support file URLs containing drive
  58. specifiers (e.g., "file://c:/path"). As a side effect,
  59. "/c:/path" can be used as an alternative to "c:/path". */
  60. sb.append(c);
  61. sb.append(':');
  62. src += 2;
  63. } else {
  64. src = 0;
  65. if ((len >= 2)
  66. && isSlash(path.charAt(0))
  67. && isSlash(path.charAt(1))) {
  68. /* UNC pathname: Retain first slash; leave src pointed at
  69. second slash so that further slashes will be collapsed
  70. into the second slash. The result will be a pathname
  71. beginning with "\\\\" followed (most likely) by a host
  72. name. */
  73. src = 1;
  74. sb.append(slash);
  75. }
  76. }
  77. return src;
  78. }
  79. /* Normalize the given pathname, whose length is len, starting at the given
  80. offset; everything before this offset is already normal. */
  81. private String normalize(String path, int len, int off) {
  82. if (len == 0) return path;
  83. if (off < 3) off = 0; /* Avoid fencepost cases with UNC pathnames */
  84. int src;
  85. char slash = this.slash;
  86. StringBuffer sb = new StringBuffer(len);
  87. if (off == 0) {
  88. /* Complete normalization, including prefix */
  89. src = normalizePrefix(path, len, sb);
  90. } else {
  91. /* Partial normalization */
  92. src = off;
  93. sb.append(path.substring(0, off));
  94. }
  95. /* Remove redundant slashes from the remainder of the path, forcing all
  96. slashes into the preferred slash */
  97. while (src < len) {
  98. char c = path.charAt(src++);
  99. if (isSlash(c)) {
  100. while ((src < len) && isSlash(path.charAt(src))) src++;
  101. if (src == len) {
  102. /* Check for trailing separator */
  103. int sn = sb.length();
  104. if ((sn == 2) && (sb.charAt(1) == ':')) {
  105. /* "z:\\" */
  106. sb.append(slash);
  107. break;
  108. }
  109. if (sn == 0) {
  110. /* "\\" */
  111. sb.append(slash);
  112. break;
  113. }
  114. if ((sn == 1) && (isSlash(sb.charAt(0)))) {
  115. /* "\\\\" is not collapsed to "\\" because "\\\\" marks
  116. the beginning of a UNC pathname. Even though it is
  117. not, by itself, a valid UNC pathname, we leave it as
  118. is in order to be consistent with the win32 APIs,
  119. which treat this case as an invalid UNC pathname
  120. rather than as an alias for the root directory of
  121. the current drive. */
  122. sb.append(slash);
  123. break;
  124. }
  125. /* Path does not denote a root directory, so do not append
  126. trailing slash */
  127. break;
  128. } else {
  129. sb.append(slash);
  130. }
  131. } else {
  132. sb.append(c);
  133. }
  134. }
  135. String rv = sb.toString();
  136. return rv;
  137. }
  138. /* Check that the given pathname is normal. If not, invoke the real
  139. normalizer on the part of the pathname that requires normalization.
  140. This way we iterate through the whole pathname string only once. */
  141. public String normalize(String path) {
  142. int n = path.length();
  143. char slash = this.slash;
  144. char altSlash = this.altSlash;
  145. char prev = 0;
  146. for (int i = 0; i < n; i++) {
  147. char c = path.charAt(i);
  148. if (c == altSlash)
  149. return normalize(path, n, (prev == slash) ? i - 1 : i);
  150. if ((c == slash) && (prev == slash) && (i > 1))
  151. return normalize(path, n, i - 1);
  152. if ((c == ':') && (i > 1))
  153. return normalize(path, n, 0);
  154. prev = c;
  155. }
  156. if (prev == slash) return normalize(path, n, n - 1);
  157. return path;
  158. }
  159. public int prefixLength(String path) {
  160. char slash = this.slash;
  161. int n = path.length();
  162. if (n == 0) return 0;
  163. char c0 = path.charAt(0);
  164. char c1 = (n > 1) ? path.charAt(1) : 0;
  165. if (c0 == slash) {
  166. if (c1 == slash) return 2; /* Absolute UNC pathname "\\\\foo" */
  167. return 1; /* Drive-relative "\\foo" */
  168. }
  169. if (isLetter(c0) && (c1 == ':')) {
  170. if ((n > 2) && (path.charAt(2) == slash))
  171. return 3; /* Absolute local pathname "z:\\foo" */
  172. return 2; /* Directory-relative "z:foo" */
  173. }
  174. return 0; /* Completely relative */
  175. }
  176. public String resolve(String parent, String child) {
  177. char slash = this.slash;
  178. int pn = parent.length();
  179. if (pn == 0) return child;
  180. int cn = child.length();
  181. if (cn == 0) return parent;
  182. String c = child;
  183. if ((cn > 1) && (c.charAt(0) == slash)) {
  184. if (c.charAt(1) == slash) {
  185. /* Drop prefix when child is a UNC pathname */
  186. c = c.substring(2);
  187. } else {
  188. /* Drop prefix when child is drive-relative */
  189. c = c.substring(1);
  190. }
  191. }
  192. String p = parent;
  193. if (p.charAt(pn - 1) == slash) p = p.substring(0, pn - 1);
  194. return p + slashify(c);
  195. }
  196. public String getDefaultParent() {
  197. return ("" + slash);
  198. }
  199. public String fromURIPath(String path) {
  200. String p = path;
  201. if ((p.length() > 2) && (p.charAt(2) == ':')) {
  202. // "/c:/foo" --> "c:/foo"
  203. p = p.substring(1);
  204. // "c:/foo/" --> "c:/foo", but "c:/" --> "c:/"
  205. if ((p.length() > 3) && p.endsWith("/"))
  206. p = p.substring(0, p.length() - 1);
  207. } else if ((p.length() > 1) && p.endsWith("/")) {
  208. // "/foo/" --> "/foo"
  209. p = p.substring(0, p.length() - 1);
  210. }
  211. return p;
  212. }
  213. /* -- Path operations -- */
  214. public boolean isAbsolute(File f) {
  215. int pl = f.getPrefixLength();
  216. return (((pl == 2) && (f.getPath().charAt(0) == slash))
  217. || (pl == 3));
  218. }
  219. native String getDriveDirectory(int drive);
  220. private static String[] driveDirCache = new String[26];
  221. private static int driveIndex(char d) {
  222. if ((d >= 'a') && (d <= 'z')) return d - 'a';
  223. if ((d >= 'A') && (d <= 'Z')) return d - 'A';
  224. return -1;
  225. }
  226. private String getDriveDirectory(char drive) {
  227. int i = driveIndex(drive);
  228. if (i < 0) return null;
  229. String s = driveDirCache[i];
  230. if (s != null) return s;
  231. s = getDriveDirectory(i + 1);
  232. driveDirCache[i] = s;
  233. return s;
  234. }
  235. private String getUserPath() {
  236. /* For both compatibility and security,
  237. we must look this up every time */
  238. return normalize(System.getProperty("user.dir"));
  239. }
  240. private String getDrive(String path) {
  241. int pl = prefixLength(path);
  242. return (pl == 3) ? path.substring(0, 2) : null;
  243. }
  244. public String resolve(File f) {
  245. String path = f.getPath();
  246. int pl = f.getPrefixLength();
  247. if ((pl == 2) && (path.charAt(0) == slash))
  248. return path; /* UNC */
  249. if (pl == 3)
  250. return path; /* Absolute local */
  251. if (pl == 0)
  252. return getUserPath() + slashify(path); /* Completely relative */
  253. if (pl == 1) { /* Drive-relative */
  254. String up = getUserPath();
  255. String ud = getDrive(up);
  256. if (ud != null) return ud + path;
  257. return up + path; /* User dir is a UNC path */
  258. }
  259. if (pl == 2) { /* Directory-relative */
  260. String up = getUserPath();
  261. String ud = getDrive(up);
  262. if ((ud != null) && path.startsWith(ud))
  263. return up + slashify(path.substring(2));
  264. char drive = path.charAt(0);
  265. String dir = getDriveDirectory(drive);
  266. String np;
  267. if (dir != null) {
  268. /* When resolving a directory-relative path that refers to a
  269. drive other than the current drive, insist that the caller
  270. have read permission on the result */
  271. String p = drive + (':' + dir + slashify(path.substring(2)));
  272. SecurityManager security = System.getSecurityManager();
  273. try {
  274. if (security != null) security.checkRead(p);
  275. } catch (SecurityException x) {
  276. /* Don't disclose the drive's directory in the exception */
  277. throw new SecurityException("Cannot resolve path " + path);
  278. }
  279. return p;
  280. }
  281. return drive + ":" + slashify(path.substring(2)); /* fake it */
  282. }
  283. throw new InternalError("Unresolvable path: " + path);
  284. }
  285. // Caches for canonicalization results to improve startup performance.
  286. // The first cache handles repeated canonicalizations of the same path
  287. // name. The prefix cache handles repeated canonicalizations within the
  288. // same directory, and must not create results differing from the true
  289. // canonicalization algorithm in canonicalize_md.c. For this reason the
  290. // prefix cache is conservative and is not used for complex path names.
  291. private ExpiringCache cache = new ExpiringCache();
  292. private ExpiringCache prefixCache = new ExpiringCache();
  293. public String canonicalize(String path) throws IOException {
  294. if (!useCanonCaches) {
  295. return canonicalize0(path);
  296. } else {
  297. String res = cache.get(path);
  298. if (res == null) {
  299. String dir = null;
  300. String resDir = null;
  301. if (useCanonPrefixCache) {
  302. dir = parentOrNull(path);
  303. if (dir != null) {
  304. resDir = prefixCache.get(dir);
  305. if (resDir != null) {
  306. // Hit only in prefix cache; full path is canonical
  307. // but we need to get the canonical name of the file
  308. // in this directory to get the appropriate capitalization
  309. String filename = path.substring(1 + dir.length());
  310. res = canonicalizeWithPrefix(resDir, filename);
  311. cache.put(dir + File.separatorChar + filename, res);
  312. }
  313. }
  314. }
  315. if (res == null) {
  316. res = canonicalize0(path);
  317. cache.put(path, res);
  318. if (useCanonPrefixCache && dir != null) {
  319. resDir = parentOrNull(res);
  320. if (resDir != null) {
  321. File f = new File(res);
  322. if (f.exists() && !f.isDirectory()) {
  323. prefixCache.put(dir, resDir);
  324. }
  325. }
  326. }
  327. }
  328. }
  329. assert canonicalize0(path).equalsIgnoreCase(res);
  330. return res;
  331. }
  332. }
  333. protected native String canonicalize0(String path)
  334. throws IOException;
  335. protected String canonicalizeWithPrefix(String canonicalPrefix,
  336. String filename) throws IOException
  337. {
  338. return canonicalizeWithPrefix0(canonicalPrefix,
  339. canonicalPrefix + File.separatorChar + filename);
  340. }
  341. // Run the canonicalization operation assuming that the prefix
  342. // (everything up to the last filename) is canonical; just gets
  343. // the canonical name of the last element of the path
  344. protected native String canonicalizeWithPrefix0(String canonicalPrefix,
  345. String pathWithCanonicalPrefix)
  346. throws IOException;
  347. // Best-effort attempt to get parent of this path; used for
  348. // optimization of filename canonicalization. This must return null for
  349. // any cases where the code in canonicalize_md.c would throw an
  350. // exception or otherwise deal with non-simple pathnames like handling
  351. // of "." and "..". It may conservatively return null in other
  352. // situations as well. Returning null will cause the underlying
  353. // (expensive) canonicalization routine to be called.
  354. static String parentOrNull(String path) {
  355. if (path == null) return null;
  356. char sep = File.separatorChar;
  357. char altSep = '/';
  358. int last = path.length() - 1;
  359. int idx = last;
  360. int adjacentDots = 0;
  361. int nonDotCount = 0;
  362. while (idx > 0) {
  363. char c = path.charAt(idx);
  364. if (c == '.') {
  365. if (++adjacentDots >= 2) {
  366. // Punt on pathnames containing . and ..
  367. return null;
  368. }
  369. if (nonDotCount == 0) {
  370. // Punt on pathnames ending in a .
  371. return null;
  372. }
  373. } else if (c == sep) {
  374. if (adjacentDots == 1 && nonDotCount == 0) {
  375. // Punt on pathnames containing . and ..
  376. return null;
  377. }
  378. if (idx == 0 ||
  379. idx >= last - 1 ||
  380. path.charAt(idx - 1) == sep ||
  381. path.charAt(idx - 1) == altSep) {
  382. // Punt on pathnames containing adjacent slashes
  383. // toward the end
  384. return null;
  385. }
  386. return path.substring(0, idx);
  387. } else if (c == altSep) {
  388. // Punt on pathnames containing both backward and
  389. // forward slashes
  390. return null;
  391. } else if (c == '*' || c == '?') {
  392. // Punt on pathnames containing wildcards
  393. return null;
  394. } else {
  395. ++nonDotCount;
  396. adjacentDots = 0;
  397. }
  398. --idx;
  399. }
  400. return null;
  401. }
  402. /* -- Attribute accessors -- */
  403. public native int getBooleanAttributes(File f);
  404. public native boolean checkAccess(File f, boolean write);
  405. public native long getLastModifiedTime(File f);
  406. public native long getLength(File f);
  407. /* -- File operations -- */
  408. public native boolean createFileExclusively(String path)
  409. throws IOException;
  410. public boolean delete(File f) {
  411. // Keep canonicalization caches in sync after file deletion
  412. // and renaming operations. Could be more clever than this
  413. // (i.e., only remove/update affected entries) but probably
  414. // not worth it since these entries expire after 30 seconds
  415. // anyway.
  416. cache.clear();
  417. prefixCache.clear();
  418. return delete0(f);
  419. }
  420. private native boolean delete0(File f);
  421. public synchronized native boolean deleteOnExit(File f);
  422. public native String[] list(File f);
  423. public native boolean createDirectory(File f);
  424. public boolean rename(File f1, File f2) {
  425. // Keep canonicalization caches in sync after file deletion
  426. // and renaming operations. Could be more clever than this
  427. // (i.e., only remove/update affected entries) but probably
  428. // not worth it since these entries expire after 30 seconds
  429. // anyway.
  430. cache.clear();
  431. prefixCache.clear();
  432. return rename0(f1, f2);
  433. }
  434. private native boolean rename0(File f1, File f2);
  435. public native boolean setLastModifiedTime(File f, long time);
  436. public native boolean setReadOnly(File f);
  437. /* -- Filesystem interface -- */
  438. private boolean access(String path) {
  439. try {
  440. SecurityManager security = System.getSecurityManager();
  441. if (security != null) security.checkRead(path);
  442. return true;
  443. } catch (SecurityException x) {
  444. return false;
  445. }
  446. }
  447. private static native int listRoots0();
  448. public File[] listRoots() {
  449. int ds = listRoots0();
  450. int n = 0;
  451. for (int i = 0; i < 26; i++) {
  452. if (((ds >> i) & 1) != 0) {
  453. if (!access((char)('A' + i) + ":" + slash))
  454. ds &= ~(1 << i);
  455. else
  456. n++;
  457. }
  458. }
  459. File[] fs = new File[n];
  460. int j = 0;
  461. char slash = this.slash;
  462. for (int i = 0; i < 26; i++) {
  463. if (((ds >> i) & 1) != 0)
  464. fs[j++] = new File((char)('A' + i) + ":" + slash);
  465. }
  466. return fs;
  467. }
  468. /* -- Basic infrastructure -- */
  469. public int compare(File f1, File f2) {
  470. return f1.getPath().compareToIgnoreCase(f2.getPath());
  471. }
  472. public int hashCode(File f) {
  473. /* Could make this more efficient: String.hashCodeIgnoreCase */
  474. return f.getPath().toLowerCase().hashCode() ^ 1234321;
  475. }
  476. private static native void initIDs();
  477. static {
  478. initIDs();
  479. }
  480. }