1/*
2 * Copyright (c) 1998, 2010, 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.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.io;
27
28import java.security.AccessController;
29
30import dalvik.system.BlockGuard;
31import sun.security.action.GetPropertyAction;
32
33
34class UnixFileSystem extends FileSystem {
35
36    private final char slash;
37    private final char colon;
38    private final String javaHome;
39
40    public UnixFileSystem() {
41        slash = AccessController.doPrivileged(
42            new GetPropertyAction("file.separator")).charAt(0);
43        colon = AccessController.doPrivileged(
44            new GetPropertyAction("path.separator")).charAt(0);
45        javaHome = AccessController.doPrivileged(
46            new GetPropertyAction("java.home"));
47    }
48
49
50    /* -- Normalization and construction -- */
51
52    public char getSeparator() {
53        return slash;
54    }
55
56    public char getPathSeparator() {
57        return colon;
58    }
59
60    /*
61     * A normal Unix pathname does not contain consecutive slashes and does not end
62     * with a slash. The empty string and "/" are special cases that are also
63     * considered normal.
64     */
65    public String normalize(String pathname) {
66        int n = pathname.length();
67        char[] normalized = pathname.toCharArray();
68        int index = 0;
69        char prevChar = 0;
70        for (int i = 0; i < n; i++) {
71            char current = normalized[i];
72            // Remove duplicate slashes.
73            if (!(current == '/' && prevChar == '/')) {
74                normalized[index++] = current;
75            }
76
77            prevChar = current;
78        }
79
80        // Omit the trailing slash, except when pathname == "/".
81        if (prevChar == '/' && n > 1) {
82            index--;
83        }
84
85        return (index != n) ? new String(normalized, 0, index) : pathname;
86    }
87
88    public int prefixLength(String pathname) {
89        if (pathname.length() == 0) return 0;
90        return (pathname.charAt(0) == '/') ? 1 : 0;
91    }
92
93    // Invariant: Both |parent| and |child| are normalized paths.
94    public String resolve(String parent, String child) {
95        if (child.isEmpty() || child.equals("/")) {
96            return parent;
97        }
98
99        if (child.charAt(0) == '/') {
100            if (parent.equals("/")) return child;
101            return parent + child;
102        }
103
104        if (parent.equals("/")) return parent + child;
105        return parent + '/' + child;
106    }
107
108    public String getDefaultParent() {
109        return "/";
110    }
111
112    public String fromURIPath(String path) {
113        String p = path;
114        if (p.endsWith("/") && (p.length() > 1)) {
115            // "/foo/" --> "/foo", but "/" --> "/"
116            p = p.substring(0, p.length() - 1);
117        }
118        return p;
119    }
120
121
122    /* -- Path operations -- */
123
124    public boolean isAbsolute(File f) {
125        return (f.getPrefixLength() != 0);
126    }
127
128    public String resolve(File f) {
129        if (isAbsolute(f)) return f.getPath();
130        return resolve(System.getProperty("user.dir"), f.getPath());
131    }
132
133    // Caches for canonicalization results to improve startup performance.
134    // The first cache handles repeated canonicalizations of the same path
135    // name. The prefix cache handles repeated canonicalizations within the
136    // same directory, and must not create results differing from the true
137    // canonicalization algorithm in canonicalize_md.c. For this reason the
138    // prefix cache is conservative and is not used for complex path names.
139    private ExpiringCache cache = new ExpiringCache();
140    // On Unix symlinks can jump anywhere in the file system, so we only
141    // treat prefixes in java.home as trusted and cacheable in the
142    // canonicalization algorithm
143    private ExpiringCache javaHomePrefixCache = new ExpiringCache();
144
145    public String canonicalize(String path) throws IOException {
146        if (!useCanonCaches) {
147            return canonicalize0(path);
148        } else {
149            String res = cache.get(path);
150            if (res == null) {
151                String dir = null;
152                String resDir = null;
153                if (useCanonPrefixCache) {
154                    // Note that this can cause symlinks that should
155                    // be resolved to a destination directory to be
156                    // resolved to the directory they're contained in
157                    dir = parentOrNull(path);
158                    if (dir != null) {
159                        resDir = javaHomePrefixCache.get(dir);
160                        if (resDir != null) {
161                            // Hit only in prefix cache; full path is canonical
162                            String filename = path.substring(1 + dir.length());
163                            res = resDir + slash + filename;
164                            cache.put(dir + slash + filename, res);
165                        }
166                    }
167                }
168                if (res == null) {
169                    BlockGuard.getThreadPolicy().onReadFromDisk();
170                    res = canonicalize0(path);
171                    cache.put(path, res);
172                    if (useCanonPrefixCache &&
173                        dir != null && dir.startsWith(javaHome)) {
174                        resDir = parentOrNull(res);
175                        // Note that we don't allow a resolved symlink
176                        // to elsewhere in java.home to pollute the
177                        // prefix cache (java.home prefix cache could
178                        // just as easily be a set at this point)
179                        if (resDir != null && resDir.equals(dir)) {
180                            File f = new File(res);
181                            if (f.exists() && !f.isDirectory()) {
182                                javaHomePrefixCache.put(dir, resDir);
183                            }
184                        }
185                    }
186                }
187            }
188            return res;
189        }
190    }
191    private native String canonicalize0(String path) throws IOException;
192    // Best-effort attempt to get parent of this path; used for
193    // optimization of filename canonicalization. This must return null for
194    // any cases where the code in canonicalize_md.c would throw an
195    // exception or otherwise deal with non-simple pathnames like handling
196    // of "." and "..". It may conservatively return null in other
197    // situations as well. Returning null will cause the underlying
198    // (expensive) canonicalization routine to be called.
199    static String parentOrNull(String path) {
200        if (path == null) return null;
201        char sep = File.separatorChar;
202        int last = path.length() - 1;
203        int idx = last;
204        int adjacentDots = 0;
205        int nonDotCount = 0;
206        while (idx > 0) {
207            char c = path.charAt(idx);
208            if (c == '.') {
209                if (++adjacentDots >= 2) {
210                    // Punt on pathnames containing . and ..
211                    return null;
212                }
213            } else if (c == sep) {
214                if (adjacentDots == 1 && nonDotCount == 0) {
215                    // Punt on pathnames containing . and ..
216                    return null;
217                }
218                if (idx == 0 ||
219                    idx >= last - 1 ||
220                    path.charAt(idx - 1) == sep) {
221                    // Punt on pathnames containing adjacent slashes
222                    // toward the end
223                    return null;
224                }
225                return path.substring(0, idx);
226            } else {
227                ++nonDotCount;
228                adjacentDots = 0;
229            }
230            --idx;
231        }
232        return null;
233    }
234
235    /* -- Attribute accessors -- */
236
237    private native int getBooleanAttributes0(String abspath);
238
239    public int getBooleanAttributes(File f) {
240        BlockGuard.getThreadPolicy().onReadFromDisk();
241
242        int rv = getBooleanAttributes0(f.getPath());
243        String name = f.getName();
244        boolean hidden = (name.length() > 0) && (name.charAt(0) == '.');
245        return rv | (hidden ? BA_HIDDEN : 0);
246    }
247
248    public boolean checkAccess(File f, int access) {
249        BlockGuard.getThreadPolicy().onReadFromDisk();
250        return checkAccess0(f, access);
251    }
252
253    private native boolean checkAccess0(File f, int access);
254
255    public long getLastModifiedTime(File f) {
256        BlockGuard.getThreadPolicy().onReadFromDisk();
257        return getLastModifiedTime0(f);
258    }
259
260    private native long getLastModifiedTime0(File f);
261
262    public long getLength(File f) {
263        BlockGuard.getThreadPolicy().onReadFromDisk();
264        return getLength0(f);
265    }
266
267    private native long getLength0(File f);
268
269    public boolean setPermission(File f, int access, boolean enable, boolean owneronly) {
270        BlockGuard.getThreadPolicy().onWriteToDisk();
271        return setPermission0(f, access, enable, owneronly);
272    }
273
274    private native boolean setPermission0(File f, int access, boolean enable, boolean owneronly);
275
276    /* -- File operations -- */
277
278    public boolean createFileExclusively(String path) throws IOException {
279        BlockGuard.getThreadPolicy().onWriteToDisk();
280        return createFileExclusively0(path);
281    }
282
283    private native boolean createFileExclusively0(String path) throws IOException;
284
285    public boolean delete(File f) {
286        // Keep canonicalization caches in sync after file deletion
287        // and renaming operations. Could be more clever than this
288        // (i.e., only remove/update affected entries) but probably
289        // not worth it since these entries expire after 30 seconds
290        // anyway.
291        cache.clear();
292        javaHomePrefixCache.clear();
293        BlockGuard.getThreadPolicy().onWriteToDisk();
294        return delete0(f);
295    }
296
297    private native boolean delete0(File f);
298
299    public String[] list(File f) {
300        BlockGuard.getThreadPolicy().onReadFromDisk();
301        return list0(f);
302    }
303
304    private native String[] list0(File f);
305
306    public boolean createDirectory(File f) {
307        BlockGuard.getThreadPolicy().onWriteToDisk();
308        return createDirectory0(f);
309    }
310
311    private native boolean createDirectory0(File f);
312
313    public boolean rename(File f1, File f2) {
314        // Keep canonicalization caches in sync after file deletion
315        // and renaming operations. Could be more clever than this
316        // (i.e., only remove/update affected entries) but probably
317        // not worth it since these entries expire after 30 seconds
318        // anyway.
319        cache.clear();
320        javaHomePrefixCache.clear();
321        BlockGuard.getThreadPolicy().onWriteToDisk();
322        return rename0(f1, f2);
323    }
324
325    private native boolean rename0(File f1, File f2);
326
327    public boolean setLastModifiedTime(File f, long time) {
328        BlockGuard.getThreadPolicy().onWriteToDisk();
329        return setLastModifiedTime0(f, time);
330    }
331
332    private native boolean setLastModifiedTime0(File f, long time);
333
334    public boolean setReadOnly(File f) {
335        BlockGuard.getThreadPolicy().onWriteToDisk();
336        return setReadOnly0(f);
337    }
338
339    private native boolean setReadOnly0(File f);
340
341
342    /* -- Filesystem interface -- */
343
344    public File[] listRoots() {
345        try {
346            SecurityManager security = System.getSecurityManager();
347            if (security != null) {
348                security.checkRead("/");
349            }
350            return new File[] { new File("/") };
351        } catch (SecurityException x) {
352            return new File[0];
353        }
354    }
355
356    /* -- Disk usage -- */
357    public long getSpace(File f, int t) {
358        BlockGuard.getThreadPolicy().onReadFromDisk();
359
360        return getSpace0(f, t);
361    }
362
363    private native long getSpace0(File f, int t);
364
365    /* -- Basic infrastructure -- */
366
367    public int compare(File f1, File f2) {
368        return f1.getPath().compareTo(f2.getPath());
369    }
370
371    public int hashCode(File f) {
372        return f.getPath().hashCode() ^ 1234321;
373    }
374
375
376    private static native void initIDs();
377
378    static {
379        initIDs();
380    }
381
382}
383