1 /*
2  * Copyright (c) 2008, 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.  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 
26 package sun.nio.fs;
27 
28 import java.nio.file.Path;
29 import java.io.File;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.util.Arrays;
33 
34 /**
35  * Unix specific Path <--> URI conversion
36  */
37 
38 class UnixUriUtils {
UnixUriUtils()39     private UnixUriUtils() { }
40 
41     /**
42      * Converts URI to Path
43      */
fromUri(UnixFileSystem fs, URI uri)44     static Path fromUri(UnixFileSystem fs, URI uri) {
45         if (!uri.isAbsolute())
46             throw new IllegalArgumentException("URI is not absolute");
47         if (uri.isOpaque())
48             throw new IllegalArgumentException("URI is not hierarchical");
49         String scheme = uri.getScheme();
50         if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
51             throw new IllegalArgumentException("URI scheme is not \"file\"");
52         if (uri.getRawAuthority() != null)
53             throw new IllegalArgumentException("URI has an authority component");
54         if (uri.getRawFragment() != null)
55             throw new IllegalArgumentException("URI has a fragment component");
56         if (uri.getRawQuery() != null)
57             throw new IllegalArgumentException("URI has a query component");
58 
59         // compatibility with java.io.File
60         if (!uri.toString().startsWith("file:///"))
61             return new File(uri).toPath();
62 
63         // transformation use raw path
64         String p = uri.getRawPath();
65         int len = p.length();
66         if (len == 0)
67             throw new IllegalArgumentException("URI path component is empty");
68 
69         // transform escaped octets and unescaped characters to bytes
70         if (p.endsWith("/") && len > 1)
71             len--;
72         byte[] result = new byte[len];
73         int rlen = 0;
74         int pos = 0;
75         while (pos < len) {
76             char c = p.charAt(pos++);
77             byte b;
78             if (c == '%') {
79                 assert (pos+2) <= len;
80                 char c1 = p.charAt(pos++);
81                 char c2 = p.charAt(pos++);
82                 b = (byte)((decode(c1) << 4) | decode(c2));
83                 if (b == 0)
84                     throw new IllegalArgumentException("Nul character not allowed");
85             } else {
86                 assert c < 0x80;
87                 b = (byte)c;
88             }
89             result[rlen++] = b;
90         }
91         if (rlen != result.length)
92             result = Arrays.copyOf(result, rlen);
93 
94         return new UnixPath(fs, result);
95     }
96 
97     /**
98      * Converts Path to URI
99      */
100     static URI toUri(UnixPath up) {
101         byte[] path = up.toAbsolutePath().asByteArray();
102         StringBuilder sb = new StringBuilder("file:///");
103         assert path[0] == '/';
104         for (int i=1; i<path.length; i++) {
105             char c = (char)(path[i] & 0xff);
106             if (match(c, L_PATH, H_PATH)) {
107                 sb.append(c);
108             } else {
109                sb.append('%');
110                sb.append(hexDigits[(c >> 4) & 0x0f]);
111                sb.append(hexDigits[(c) & 0x0f]);
112             }
113         }
114 
115         // trailing slash if directory
116         if (sb.charAt(sb.length()-1) != '/') {
117             int mode = UnixNativeDispatcher.stat(up);
118             if ((mode & UnixConstants.S_IFMT) == UnixConstants.S_IFDIR)
119                 sb.append('/');
120         }
121 
122         try {
123             return new URI(sb.toString());
124         } catch (URISyntaxException x) {
125             throw new AssertionError(x);  // should not happen
126         }
127     }
128 
129     // The following is copied from java.net.URI
130 
131     // Compute the low-order mask for the characters in the given string
lowMask(String chars)132     private static long lowMask(String chars) {
133         int n = chars.length();
134         long m = 0;
135         for (int i = 0; i < n; i++) {
136             char c = chars.charAt(i);
137             if (c < 64)
138                 m |= (1L << c);
139         }
140         return m;
141     }
142 
143     // Compute the high-order mask for the characters in the given string
highMask(String chars)144     private static long highMask(String chars) {
145         int n = chars.length();
146         long m = 0;
147         for (int i = 0; i < n; i++) {
148             char c = chars.charAt(i);
149             if ((c >= 64) && (c < 128))
150                 m |= (1L << (c - 64));
151         }
152         return m;
153     }
154 
155     // Compute a low-order mask for the characters
156     // between first and last, inclusive
lowMask(char first, char last)157     private static long lowMask(char first, char last) {
158         long m = 0;
159         int f = Math.max(Math.min(first, 63), 0);
160         int l = Math.max(Math.min(last, 63), 0);
161         for (int i = f; i <= l; i++)
162             m |= 1L << i;
163         return m;
164     }
165 
166     // Compute a high-order mask for the characters
167     // between first and last, inclusive
highMask(char first, char last)168     private static long highMask(char first, char last) {
169         long m = 0;
170         int f = Math.max(Math.min(first, 127), 64) - 64;
171         int l = Math.max(Math.min(last, 127), 64) - 64;
172         for (int i = f; i <= l; i++)
173             m |= 1L << i;
174         return m;
175     }
176 
177     // Tell whether the given character is permitted by the given mask pair
match(char c, long lowMask, long highMask)178     private static boolean match(char c, long lowMask, long highMask) {
179         if (c < 64)
180             return ((1L << c) & lowMask) != 0;
181         if (c < 128)
182             return ((1L << (c - 64)) & highMask) != 0;
183         return false;
184     }
185 
186     // decode
decode(char c)187     private static int decode(char c) {
188         if ((c >= '0') && (c <= '9'))
189             return c - '0';
190         if ((c >= 'a') && (c <= 'f'))
191             return c - 'a' + 10;
192         if ((c >= 'A') && (c <= 'F'))
193             return c - 'A' + 10;
194         throw new AssertionError();
195     }
196 
197     // digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
198     //            "8" | "9"
199     private static final long L_DIGIT = lowMask('0', '9');
200     private static final long H_DIGIT = 0L;
201 
202     // upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
203     //            "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
204     //            "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
205     private static final long L_UPALPHA = 0L;
206     private static final long H_UPALPHA = highMask('A', 'Z');
207 
208     // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
209     //            "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
210     //            "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
211     private static final long L_LOWALPHA = 0L;
212     private static final long H_LOWALPHA = highMask('a', 'z');
213 
214     // alpha         = lowalpha | upalpha
215     private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
216     private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
217 
218     // alphanum      = alpha | digit
219     private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
220     private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
221 
222     // mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
223     //                 "(" | ")"
224     private static final long L_MARK = lowMask("-_.!~*'()");
225     private static final long H_MARK = highMask("-_.!~*'()");
226 
227     // unreserved    = alphanum | mark
228     private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
229     private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
230 
231     // pchar         = unreserved | escaped |
232     //                 ":" | "@" | "&" | "=" | "+" | "$" | ","
233     private static final long L_PCHAR
234         = L_UNRESERVED | lowMask(":@&=+$,");
235     private static final long H_PCHAR
236         = H_UNRESERVED | highMask(":@&=+$,");
237 
238    // All valid path characters
239    private static final long L_PATH = L_PCHAR | lowMask(";/");
240    private static final long H_PATH = H_PCHAR | highMask(";/");
241 
242    private static final char[] hexDigits = {
243         '0', '1', '2', '3', '4', '5', '6', '7',
244         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
245     };
246 }
247