Path: blob/master/src/java.base/unix/classes/sun/nio/fs/UnixUriUtils.java
41137 views
/*1* Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.nio.fs;2627import java.nio.file.Path;28import java.io.File;29import java.net.URI;30import java.net.URISyntaxException;31import java.util.Arrays;32import java.util.HexFormat;3334/**35* Unix specific Path <--> URI conversion36*/3738class UnixUriUtils {39private UnixUriUtils() { }4041/**42* Converts URI to Path43*/44static Path fromUri(UnixFileSystem fs, URI uri) {45if (!uri.isAbsolute())46throw new IllegalArgumentException("URI is not absolute");47if (uri.isOpaque())48throw new IllegalArgumentException("URI is not hierarchical");49String scheme = uri.getScheme();50if ((scheme == null) || !scheme.equalsIgnoreCase("file"))51throw new IllegalArgumentException("URI scheme is not \"file\"");52if (uri.getRawAuthority() != null)53throw new IllegalArgumentException("URI has an authority component");54if (uri.getRawFragment() != null)55throw new IllegalArgumentException("URI has a fragment component");56if (uri.getRawQuery() != null)57throw new IllegalArgumentException("URI has a query component");5859// compatibility with java.io.File60if (!uri.toString().startsWith("file:///"))61return new File(uri).toPath();6263// transformation use raw path64String p = uri.getRawPath();65int len = p.length();66if (len == 0)67throw new IllegalArgumentException("URI path component is empty");6869// transform escaped octets and unescaped characters to bytes70if (p.endsWith("/") && len > 1)71len--;72byte[] result = new byte[len];73int rlen = 0;74int pos = 0;75while (pos < len) {76char c = p.charAt(pos++);77byte b;78if (c == '%') {79assert (pos+2) <= len;80char c1 = p.charAt(pos++);81char c2 = p.charAt(pos++);82b = (byte)((decode(c1) << 4) | decode(c2));83if (b == 0)84throw new IllegalArgumentException("Nul character not allowed");85} else {86if (c == 0 || c >= 0x80)87throw new IllegalArgumentException("Bad escape");88b = (byte)c;89}90result[rlen++] = b;91}92if (rlen != result.length)93result = Arrays.copyOf(result, rlen);9495return new UnixPath(fs, result);96}9798/**99* Converts Path to URI100*/101static URI toUri(UnixPath up) {102byte[] path = up.toAbsolutePath().asByteArray();103StringBuilder sb = new StringBuilder("file:///");104assert path[0] == '/';105HexFormat hex = HexFormat.of().withUpperCase();106for (int i=1; i<path.length; i++) {107char c = (char)(path[i] & 0xff);108if (match(c, L_PATH, H_PATH)) {109sb.append(c);110} else {111sb.append('%');112hex.toHexDigits(sb, (byte)c);113}114}115116// trailing slash if directory117if (sb.charAt(sb.length()-1) != '/') {118try {119up.checkRead();120int mode = UnixNativeDispatcher.stat(up);121if ((mode & UnixConstants.S_IFMT) == UnixConstants.S_IFDIR)122sb.append('/');123} catch (SecurityException ignore) { }124}125126try {127return new URI(sb.toString());128} catch (URISyntaxException x) {129throw new AssertionError(x); // should not happen130}131}132133// The following is copied from java.net.URI134135// Compute the low-order mask for the characters in the given string136private static long lowMask(String chars) {137int n = chars.length();138long m = 0;139for (int i = 0; i < n; i++) {140char c = chars.charAt(i);141if (c < 64)142m |= (1L << c);143}144return m;145}146147// Compute the high-order mask for the characters in the given string148private static long highMask(String chars) {149int n = chars.length();150long m = 0;151for (int i = 0; i < n; i++) {152char c = chars.charAt(i);153if ((c >= 64) && (c < 128))154m |= (1L << (c - 64));155}156return m;157}158159// Compute a low-order mask for the characters160// between first and last, inclusive161private static long lowMask(char first, char last) {162long m = 0;163int f = Math.max(Math.min(first, 63), 0);164int l = Math.max(Math.min(last, 63), 0);165for (int i = f; i <= l; i++)166m |= 1L << i;167return m;168}169170// Compute a high-order mask for the characters171// between first and last, inclusive172private static long highMask(char first, char last) {173long m = 0;174int f = Math.max(Math.min(first, 127), 64) - 64;175int l = Math.max(Math.min(last, 127), 64) - 64;176for (int i = f; i <= l; i++)177m |= 1L << i;178return m;179}180181// Tell whether the given character is permitted by the given mask pair182private static boolean match(char c, long lowMask, long highMask) {183if (c < 64)184return ((1L << c) & lowMask) != 0;185if (c < 128)186return ((1L << (c - 64)) & highMask) != 0;187return false;188}189190// decode191private static int decode(char c) {192if ((c >= '0') && (c <= '9'))193return c - '0';194if ((c >= 'a') && (c <= 'f'))195return c - 'a' + 10;196if ((c >= 'A') && (c <= 'F'))197return c - 'A' + 10;198throw new AssertionError();199}200201// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |202// "8" | "9"203private static final long L_DIGIT = lowMask('0', '9');204private static final long H_DIGIT = 0L;205206// 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"209private static final long L_UPALPHA = 0L;210private static final long H_UPALPHA = highMask('A', 'Z');211212// 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"215private static final long L_LOWALPHA = 0L;216private static final long H_LOWALPHA = highMask('a', 'z');217218// alpha = lowalpha | upalpha219private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;220private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;221222// alphanum = alpha | digit223private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;224private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;225226// mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |227// "(" | ")"228private static final long L_MARK = lowMask("-_.!~*'()");229private static final long H_MARK = highMask("-_.!~*'()");230231// unreserved = alphanum | mark232private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;233private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;234235// pchar = unreserved | escaped |236// ":" | "@" | "&" | "=" | "+" | "$" | ","237private static final long L_PCHAR238= L_UNRESERVED | lowMask(":@&=+$,");239private static final long H_PCHAR240= H_UNRESERVED | highMask(":@&=+$,");241242// All valid path characters243private static final long L_PATH = L_PCHAR | lowMask(";/");244private static final long H_PATH = H_PCHAR | highMask(";/");245}246247248