1. /*
  2. * @(#)Win32FileSystem.java 1.15 02/10/01
  3. *
  4. * Copyright 2004 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. int pn = parent.length();
  178. if (pn == 0) return child;
  179. int cn = child.length();
  180. if (cn == 0) return parent;
  181. String c = child;
  182. int childStart = 0;
  183. int parentEnd = pn;
  184. if ((cn > 1) && (c.charAt(0) == slash)) {
  185. if (c.charAt(1) == slash) {
  186. /* Drop prefix when child is a UNC pathname */
  187. childStart = 2;
  188. } else {
  189. /* Drop prefix when child is drive-relative */
  190. childStart = 1;
  191. }
  192. if (cn == childStart) { // Child is double slash
  193. if (parent.charAt(pn - 1) == slash)
  194. return parent.substring(0, pn - 1);
  195. return parent;
  196. }
  197. }
  198. if (parent.charAt(pn - 1) == slash)
  199. parentEnd--;
  200. int strlen = parentEnd + cn - childStart;
  201. char[] theChars = null;
  202. if (child.charAt(childStart) == slash) {
  203. theChars = new char[strlen];
  204. parent.getChars(0, parentEnd, theChars, 0);
  205. child.getChars(childStart, cn, theChars, parentEnd);
  206. } else {
  207. theChars = new char[strlen + 1];
  208. parent.getChars(0, parentEnd, theChars, 0);
  209. theChars[parentEnd] = slash;
  210. child.getChars(childStart, cn, theChars, parentEnd + 1);
  211. }
  212. return new String(theChars);
  213. }
  214. public String getDefaultParent() {
  215. return ("" + slash);
  216. }
  217. public String fromURIPath(String path) {
  218. String p = path;
  219. if ((p.length() > 2) && (p.charAt(2) == ':')) {
  220. // "/c:/foo" --> "c:/foo"
  221. p = p.substring(1);
  222. // "c:/foo/" --> "c:/foo", but "c:/" --> "c:/"
  223. if ((p.length() > 3) && p.endsWith("/"))
  224. p = p.substring(0, p.length() - 1);
  225. } else if ((p.length() > 1) && p.endsWith("/")) {
  226. // "/foo/" --> "/foo"
  227. p = p.substring(0, p.length() - 1);
  228. }
  229. return p;
  230. }
  231. /* -- Path operations -- */
  232. public boolean isAbsolute(File f) {
  233. int pl = f.getPrefixLength();
  234. return (((pl == 2) && (f.getPath().charAt(0) == slash))
  235. || (pl == 3));
  236. }
  237. protected native String getDriveDirectory(int drive);
  238. private static String[] driveDirCache = new String[26];
  239. private static int driveIndex(char d) {
  240. if ((d >= 'a') && (d <= 'z')) return d - 'a';
  241. if ((d >= 'A') && (d <= 'Z')) return d - 'A';
  242. return -1;
  243. }
  244. private String getDriveDirectory(char drive) {
  245. int i = driveIndex(drive);
  246. if (i < 0) return null;
  247. String s = driveDirCache[i];
  248. if (s != null) return s;
  249. s = getDriveDirectory(i + 1);
  250. driveDirCache[i] = s;
  251. return s;
  252. }
  253. private String getUserPath() {
  254. /* For both compatibility and security,
  255. we must look this up every time */
  256. return normalize(System.getProperty("user.dir"));
  257. }
  258. private String getDrive(String path) {
  259. int pl = prefixLength(path);
  260. return (pl == 3) ? path.substring(0, 2) : null;
  261. }
  262. public String resolve(File f) {
  263. String path = f.getPath();
  264. int pl = f.getPrefixLength();
  265. if ((pl == 2) && (path.charAt(0) == slash))
  266. return path; /* UNC */
  267. if (pl == 3)
  268. return path; /* Absolute local */
  269. if (pl == 0)
  270. return getUserPath() + slashify(path); /* Completely relative */
  271. if (pl == 1) { /* Drive-relative */
  272. String up = getUserPath();
  273. String ud = getDrive(up);
  274. if (ud != null) return ud + path;
  275. return up + path; /* User dir is a UNC path */
  276. }
  277. if (pl == 2) { /* Directory-relative */
  278. String up = getUserPath();
  279. String ud = getDrive(up);
  280. if ((ud != null) && path.startsWith(ud))
  281. return up + slashify(path.substring(2));
  282. char drive = path.charAt(0);
  283. String dir = getDriveDirectory(drive);
  284. String np;
  285. if (dir != null) {
  286. /* When resolving a directory-relative path that refers to a
  287. drive other than the current drive, insist that the caller
  288. have read permission on the result */
  289. String p = drive + (':' + dir + slashify(path.substring(2)));
  290. SecurityManager security = System.getSecurityManager();
  291. try {
  292. if (security != null) security.checkRead(p);
  293. } catch (SecurityException x) {
  294. /* Don't disclose the drive's directory in the exception */
  295. throw new SecurityException("Cannot resolve path " + path);
  296. }
  297. return p;
  298. }
  299. return drive + ":" + slashify(path.substring(2)); /* fake it */
  300. }
  301. throw new InternalError("Unresolvable path: " + path);
  302. }
  303. // Caches for canonicalization results to improve startup performance.
  304. // The first cache handles repeated canonicalizations of the same path
  305. // name. The prefix cache handles repeated canonicalizations within the
  306. // same directory, and must not create results differing from the true
  307. // canonicalization algorithm in canonicalize_md.c. For this reason the
  308. // prefix cache is conservative and is not used for complex path names.
  309. private ExpiringCache cache = new ExpiringCache();
  310. private ExpiringCache prefixCache = new ExpiringCache();
  311. public String canonicalize(String path) throws IOException {
  312. // If path is a drive letter only then skip canonicalization
  313. int len = path.length();
  314. if ((len == 2) &&
  315. (isLetter(path.charAt(0))) &&
  316. (path.charAt(1) == ':')) {
  317. char c = path.charAt(0);
  318. if ((c >= 'A') && (c <= 'Z'))
  319. return path;
  320. return "" + ((char) (c-32)) + ':';
  321. } else if ((len == 3) &&
  322. (isLetter(path.charAt(0))) &&
  323. (path.charAt(1) == ':') &&
  324. (path.charAt(2) == '\\')) {
  325. char c = path.charAt(0);
  326. if ((c >= 'A') && (c <= 'Z'))
  327. return path;
  328. return "" + ((char) (c-32)) + ':' + '\\';
  329. }
  330. if (!useCanonCaches) {
  331. return canonicalize0(path);
  332. } else {
  333. String res = cache.get(path);
  334. if (res == null) {
  335. String dir = null;
  336. String resDir = null;
  337. if (useCanonPrefixCache) {
  338. dir = parentOrNull(path);
  339. if (dir != null) {
  340. resDir = prefixCache.get(dir);
  341. if (resDir != null) {
  342. // Hit only in prefix cache; full path is canonical,
  343. // but we need to get the canonical name of the file
  344. // in this directory to get the appropriate capitalization
  345. String filename = path.substring(1 + dir.length());
  346. res = canonicalizeWithPrefix(resDir, filename);
  347. cache.put(dir + File.separatorChar + filename, res);
  348. }
  349. }
  350. }
  351. if (res == null) {
  352. res = canonicalize0(path);
  353. cache.put(path, res);
  354. if (useCanonPrefixCache && dir != null) {
  355. resDir = parentOrNull(res);
  356. if (resDir != null) {
  357. File f = new File(res);
  358. if (f.exists() && !f.isDirectory()) {
  359. prefixCache.put(dir, resDir);
  360. }
  361. }
  362. }
  363. }
  364. }
  365. assert canonicalize0(path).equalsIgnoreCase(res);
  366. return res;
  367. }
  368. }
  369. protected native String canonicalize0(String path)
  370. throws IOException;
  371. protected String canonicalizeWithPrefix(String canonicalPrefix,
  372. String filename) throws IOException
  373. {
  374. return canonicalizeWithPrefix0(canonicalPrefix,
  375. canonicalPrefix + File.separatorChar + filename);
  376. }
  377. // Run the canonicalization operation assuming that the prefix
  378. // (everything up to the last filename) is canonical; just gets
  379. // the canonical name of the last element of the path
  380. protected native String canonicalizeWithPrefix0(String canonicalPrefix,
  381. String pathWithCanonicalPrefix)
  382. throws IOException;
  383. // Best-effort attempt to get parent of this path; used for
  384. // optimization of filename canonicalization. This must return null for
  385. // any cases where the code in canonicalize_md.c would throw an
  386. // exception or otherwise deal with non-simple pathnames like handling
  387. // of "." and "..". It may conservatively return null in other
  388. // situations as well. Returning null will cause the underlying
  389. // (expensive) canonicalization routine to be called.
  390. static String parentOrNull(String path) {
  391. if (path == null) return null;
  392. char sep = File.separatorChar;
  393. char altSep = '/';
  394. int last = path.length() - 1;
  395. int idx = last;
  396. int adjacentDots = 0;
  397. int nonDotCount = 0;
  398. while (idx > 0) {
  399. char c = path.charAt(idx);
  400. if (c == '.') {
  401. if (++adjacentDots >= 2) {
  402. // Punt on pathnames containing . and ..
  403. return null;
  404. }
  405. if (nonDotCount == 0) {
  406. // Punt on pathnames ending in a .
  407. return null;
  408. }
  409. } else if (c == sep) {
  410. if (adjacentDots == 1 && nonDotCount == 0) {
  411. // Punt on pathnames containing . and ..
  412. return null;
  413. }
  414. if (idx == 0 ||
  415. idx >= last - 1 ||
  416. path.charAt(idx - 1) == sep ||
  417. path.charAt(idx - 1) == altSep) {
  418. // Punt on pathnames containing adjacent slashes
  419. // toward the end
  420. return null;
  421. }
  422. return path.substring(0, idx);
  423. } else if (c == altSep) {
  424. // Punt on pathnames containing both backward and
  425. // forward slashes
  426. return null;
  427. } else if (c == '*' || c == '?') {
  428. // Punt on pathnames containing wildcards
  429. return null;
  430. } else {
  431. ++nonDotCount;
  432. adjacentDots = 0;
  433. }
  434. --idx;
  435. }
  436. return null;
  437. }
  438. /* -- Attribute accessors -- */
  439. public native int getBooleanAttributes(File f);
  440. public native boolean checkAccess(File f, boolean write);
  441. public native long getLastModifiedTime(File f);
  442. public native long getLength(File f);
  443. /* -- File operations -- */
  444. public native boolean createFileExclusively(String path)
  445. throws IOException;
  446. public boolean delete(File f) {
  447. // Keep canonicalization caches in sync after file deletion
  448. // and renaming operations. Could be more clever than this
  449. // (i.e., only remove/update affected entries) but probably
  450. // not worth it since these entries expire after 30 seconds
  451. // anyway.
  452. cache.clear();
  453. prefixCache.clear();
  454. return delete0(f);
  455. }
  456. protected native boolean delete0(File f);
  457. public synchronized native boolean deleteOnExit(File f);
  458. public native String[] list(File f);
  459. public native boolean createDirectory(File f);
  460. public boolean rename(File f1, File f2) {
  461. // Keep canonicalization caches in sync after file deletion
  462. // and renaming operations. Could be more clever than this
  463. // (i.e., only remove/update affected entries) but probably
  464. // not worth it since these entries expire after 30 seconds
  465. // anyway.
  466. cache.clear();
  467. prefixCache.clear();
  468. return rename0(f1, f2);
  469. }
  470. protected native boolean rename0(File f1, File f2);
  471. public native boolean setLastModifiedTime(File f, long time);
  472. public native boolean setReadOnly(File f);
  473. /* -- Filesystem interface -- */
  474. private boolean access(String path) {
  475. try {
  476. SecurityManager security = System.getSecurityManager();
  477. if (security != null) security.checkRead(path);
  478. return true;
  479. } catch (SecurityException x) {
  480. return false;
  481. }
  482. }
  483. private static native int listRoots0();
  484. public File[] listRoots() {
  485. int ds = listRoots0();
  486. int n = 0;
  487. for (int i = 0; i < 26; i++) {
  488. if (((ds >> i) & 1) != 0) {
  489. if (!access((char)('A' + i) + ":" + slash))
  490. ds &= ~(1 << i);
  491. else
  492. n++;
  493. }
  494. }
  495. File[] fs = new File[n];
  496. int j = 0;
  497. char slash = this.slash;
  498. for (int i = 0; i < 26; i++) {
  499. if (((ds >> i) & 1) != 0)
  500. fs[j++] = new File((char)('A' + i) + ":" + slash);
  501. }
  502. return fs;
  503. }
  504. /* -- Basic infrastructure -- */
  505. public int compare(File f1, File f2) {
  506. return f1.getPath().compareToIgnoreCase(f2.getPath());
  507. }
  508. public int hashCode(File f) {
  509. /* Could make this more efficient: String.hashCodeIgnoreCase */
  510. return f.getPath().toLowerCase().hashCode() ^ 1234321;
  511. }
  512. private static native void initIDs();
  513. static {
  514. initIDs();
  515. }
  516. }