1 /*
2  * Copyright (c) 2008, 2020, 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                 if (c == 0 || c >= 0x80)
87                     throw new IllegalArgumentException("Bad escape");
88                 b = (byte)c;
89             }
90             result[rlen++] = b;
91         }
92         if (rlen != result.length)
93             result = Arrays.copyOf(result, rlen);
94 
95         return new UnixPath(fs, result);
96     }
97 
98     /**
99      * Converts Path to URI
100      */
toUri(UnixPath up)101     static URI toUri(UnixPath up) {
102         byte[] path = up.toAbsolutePath().asByteArray();
103         StringBuilder sb = new StringBuilder("file:///");
104         assert path[0] == '/';
105         for (int i=1; i<path.length; i++) {
106             char c = (char)(path[i] & 0xff);
107             if (match(c, L_PATH, H_PATH)) {
108                 sb.append(c);
109             } else {
110                sb.append('%');
111                sb.append(hexDigits[(c >> 4) & 0x0f]);
112                sb.append(hexDigits[(c) & 0x0f]);
113             }
114         }
115 
116         // trailing slash if directory
117         if (sb.charAt(sb.length()-1) != '/') {
118             try {
119                 up.checkRead();
120                 int mode = UnixNativeDispatcher.stat(up);
121                 if ((mode & UnixConstants.S_IFMT) == UnixConstants.S_IFDIR)
122                     sb.append('/');
123             } catch (SecurityException ignore) { }
124         }
125 
126         try {
127             return new URI(sb.toString());
128         } catch (URISyntaxException x) {
129             throw new AssertionError(x);  // should not happen
130         }
131     }
132 
133     // The following is copied from java.net.URI
134 
135     // Compute the low-order mask for the characters in the given string
lowMask(String chars)136     private static long lowMask(String chars) {
137         int n = chars.length();
138         long m = 0;
139         for (int i = 0; i < n; i++) {
140             char c = chars.charAt(i);
141             if (c < 64)
142                 m |= (1L << c);
143         }
144         return m;
145     }
146 
147     // Compute the high-order mask for the characters in the given string
highMask(String chars)148     private static long highMask(String chars) {
149         int n = chars.length();
150         long m = 0;
151         for (int i = 0; i < n; i++) {
152             char c = chars.charAt(i);
153             if ((c >= 64) && (c < 128))
154                 m |= (1L << (c - 64));
155         }
156         return m;
157     }
158 
159     // Compute a low-order mask for the characters
160     // between first and last, inclusive
lowMask(char first, char last)161     private static long lowMask(char first, char last) {
162         long m = 0;
163         int f = Math.max(Math.min(first, 63), 0);
164         int l = Math.max(Math.min(last, 63), 0);
165         for (int i = f; i <= l; i++)
166             m |= 1L << i;
167         return m;
168     }
169 
170     // Compute a high-order mask for the characters
171     // between first and last, inclusive
highMask(char first, char last)172     private static long highMask(char first, char last) {
173         long m = 0;
174         int f = Math.max(Math.min(first, 127), 64) - 64;
175         int l = Math.max(Math.min(last, 127), 64) - 64;
176         for (int i = f; i <= l; i++)
177             m |= 1L << i;
178         return m;
179     }
180 
181     // Tell whether the given character is permitted by the given mask pair
match(char c, long lowMask, long highMask)182     private static boolean match(char c, long lowMask, long highMask) {
183         if (c < 64)
184             return ((1L << c) & lowMask) != 0;
185         if (c < 128)
186             return ((1L << (c - 64)) & highMask) != 0;
187         return false;
188     }
189 
190     // decode
decode(char c)191     private static int decode(char c) {
192         if ((c >= '0') && (c <= '9'))
193             return c - '0';
194         if ((c >= 'a') && (c <= 'f'))
195             return c - 'a' + 10;
196         if ((c >= 'A') && (c <= 'F'))
197             return c - 'A' + 10;
198         throw new AssertionError();
199     }
200 
201     // digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
202     //            "8" | "9"
203     private static final long L_DIGIT = lowMask('0', '9');
204     private static final long H_DIGIT = 0L;
205 
206     // upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
207     //            "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
208     //            "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
209     private static final long L_UPALPHA = 0L;
210     private static final long H_UPALPHA = highMask('A', 'Z');
211 
212     // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
213     //            "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
214     //            "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
215     private static final long L_LOWALPHA = 0L;
216     private static final long H_LOWALPHA = highMask('a', 'z');
217 
218     // alpha         = lowalpha | upalpha
219     private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
220     private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
221 
222     // alphanum      = alpha | digit
223     private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
224     private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
225 
226     // mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
227     //                 "(" | ")"
228     private static final long L_MARK = lowMask("-_.!~*'()");
229     private static final long H_MARK = highMask("-_.!~*'()");
230 
231     // unreserved    = alphanum | mark
232     private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
233     private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
234 
235     // pchar         = unreserved | escaped |
236     //                 ":" | "@" | "&" | "=" | "+" | "$" | ","
237     private static final long L_PCHAR
238         = L_UNRESERVED | lowMask(":@&=+$,");
239     private static final long H_PCHAR
240         = H_UNRESERVED | highMask(":@&=+$,");
241 
242    // All valid path characters
243    private static final long L_PATH = L_PCHAR | lowMask(";/");
244    private static final long H_PATH = H_PCHAR | highMask(";/");
245 
246    private static final char[] hexDigits = {
247         '0', '1', '2', '3', '4', '5', '6', '7',
248         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
249     };
250 }
251