1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27package java.net; 28 29import java.io.IOException; 30import java.util.Objects; 31 32import sun.net.util.IPAddressUtil; 33 34/** 35 * The abstract class <code>URLStreamHandler</code> is the common 36 * superclass for all stream protocol handlers. A stream protocol 37 * handler knows how to make a connection for a particular protocol 38 * type, such as <code>http</code>, <code>ftp</code>, or 39 * <code>gopher</code>. 40 * <p> 41 * In most cases, an instance of a <code>URLStreamHandler</code> 42 * subclass is not created directly by an application. Rather, the 43 * first time a protocol name is encountered when constructing a 44 * <code>URL</code>, the appropriate stream protocol handler is 45 * automatically loaded. 46 * 47 * @author James Gosling 48 * @see java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) 49 * @since JDK1.0 50 */ 51public abstract class URLStreamHandler { 52 /** 53 * Opens a connection to the object referenced by the 54 * <code>URL</code> argument. 55 * This method should be overridden by a subclass. 56 * 57 * <p>If for the handler's protocol (such as HTTP or JAR), there 58 * exists a public, specialized URLConnection subclass belonging 59 * to one of the following packages or one of their subpackages: 60 * java.lang, java.io, java.util, java.net, the connection 61 * returned will be of that subclass. For example, for HTTP an 62 * HttpURLConnection will be returned, and for JAR a 63 * JarURLConnection will be returned. 64 * 65 * @param u the URL that this connects to. 66 * @return a <code>URLConnection</code> object for the <code>URL</code>. 67 * @exception IOException if an I/O error occurs while opening the 68 * connection. 69 */ 70 abstract protected URLConnection openConnection(URL u) throws IOException; 71 72 /** 73 * Same as openConnection(URL), except that the connection will be 74 * made through the specified proxy; Protocol handlers that do not 75 * support proxying will ignore the proxy parameter and make a 76 * normal connection. 77 * 78 * Calling this method preempts the system's default ProxySelector 79 * settings. 80 * 81 * @param u the URL that this connects to. 82 * @param p the proxy through which the connection will be made. 83 * If direct connection is desired, Proxy.NO_PROXY 84 * should be specified. 85 * @return a <code>URLConnection</code> object for the <code>URL</code>. 86 * @exception IOException if an I/O error occurs while opening the 87 * connection. 88 * @exception IllegalArgumentException if either u or p is null, 89 * or p has the wrong type. 90 * @exception UnsupportedOperationException if the subclass that 91 * implements the protocol doesn't support this method. 92 * @since 1.5 93 */ 94 protected URLConnection openConnection(URL u, Proxy p) throws IOException { 95 throw new UnsupportedOperationException("Method not implemented."); 96 } 97 98 /** 99 * Parses the string representation of a <code>URL</code> into a 100 * <code>URL</code> object. 101 * <p> 102 * If there is any inherited context, then it has already been 103 * copied into the <code>URL</code> argument. 104 * <p> 105 * The <code>parseURL</code> method of <code>URLStreamHandler</code> 106 * parses the string representation as if it were an 107 * <code>http</code> specification. Most URL protocol families have a 108 * similar parsing. A stream protocol handler for a protocol that has 109 * a different syntax must override this routine. 110 * 111 * @param u the <code>URL</code> to receive the result of parsing 112 * the spec. 113 * @param spec the <code>String</code> representing the URL that 114 * must be parsed. 115 * @param start the character index at which to begin parsing. This is 116 * just past the '<code>:</code>' (if there is one) that 117 * specifies the determination of the protocol name. 118 * @param limit the character position to stop parsing at. This is the 119 * end of the string or the position of the 120 * "<code>#</code>" character, if present. All information 121 * after the sharp sign indicates an anchor. 122 */ 123 protected void parseURL(URL u, String spec, int start, int limit) { 124 // These fields may receive context content if this was relative URL 125 String protocol = u.getProtocol(); 126 String authority = u.getAuthority(); 127 String userInfo = u.getUserInfo(); 128 String host = u.getHost(); 129 int port = u.getPort(); 130 String path = u.getPath(); 131 String query = u.getQuery(); 132 133 // This field has already been parsed 134 String ref = u.getRef(); 135 136 boolean isRelPath = false; 137 boolean queryOnly = false; 138 // ----- BEGIN android ----- 139 boolean querySet = false; 140 // ----- END android ----- 141 142 // FIX: should not assume query if opaque 143 // Strip off the query part 144 if (start < limit) { 145 int queryStart = spec.indexOf('?'); 146 queryOnly = queryStart == start; 147 if ((queryStart != -1) && (queryStart < limit)) { 148 query = spec.substring(queryStart+1, limit); 149 if (limit > queryStart) 150 limit = queryStart; 151 spec = spec.substring(0, queryStart); 152 // ----- BEGIN android ----- 153 querySet = true; 154 // ----- END android ----- 155 } 156 } 157 158 int i = 0; 159 // Parse the authority part if any 160 // ----- BEGIN android ----- 161 // boolean isUNCName = (start <= limit - 4) && 162 // (spec.charAt(start) == '/') && 163 // (spec.charAt(start + 1) == '/') && 164 // (spec.charAt(start + 2) == '/') && 165 // (spec.charAt(start + 3) == '/'); 166 boolean isUNCName = false; 167 // ----- END android ----- 168 if (!isUNCName && (start <= limit - 2) && (spec.charAt(start) == '/') && 169 (spec.charAt(start + 1) == '/')) { 170 start += 2; 171 i = spec.indexOf('/', start); 172 if (i < 0) { 173 i = spec.indexOf('?', start); 174 if (i < 0) 175 i = limit; 176 } 177 178 host = authority = spec.substring(start, i); 179 180 int ind = authority.indexOf('@'); 181 if (ind != -1) { 182 userInfo = authority.substring(0, ind); 183 host = authority.substring(ind+1); 184 } else { 185 userInfo = null; 186 } 187 if (host != null) { 188 // If the host is surrounded by [ and ] then its an IPv6 189 // literal address as specified in RFC2732 190 if (host.length()>0 && (host.charAt(0) == '[')) { 191 if ((ind = host.indexOf(']')) > 2) { 192 193 String nhost = host ; 194 host = nhost.substring(0,ind+1); 195 if (!IPAddressUtil. 196 isIPv6LiteralAddress(host.substring(1, ind))) { 197 throw new IllegalArgumentException( 198 "Invalid host: "+ host); 199 } 200 201 port = -1 ; 202 if (nhost.length() > ind+1) { 203 if (nhost.charAt(ind+1) == ':') { 204 ++ind ; 205 // port can be null according to RFC2396 206 if (nhost.length() > (ind + 1)) { 207 port = Integer.parseInt(nhost.substring(ind+1)); 208 } 209 } else { 210 throw new IllegalArgumentException( 211 "Invalid authority field: " + authority); 212 } 213 } 214 } else { 215 throw new IllegalArgumentException( 216 "Invalid authority field: " + authority); 217 } 218 } else { 219 ind = host.indexOf(':'); 220 port = -1; 221 if (ind >= 0) { 222 // port can be null according to RFC2396 223 if (host.length() > (ind + 1)) { 224 // ----- BEGIN android ----- 225 // port = Integer.parseInt(host.substring(ind + 1)); 226 char firstPortChar = host.charAt(ind+1); 227 if (firstPortChar >= '0' && firstPortChar <= '9') { 228 port = Integer.parseInt(host.substring(ind + 1)); 229 } else { 230 throw new IllegalArgumentException("invalid port: " + 231 host.substring(ind + 1)); 232 } 233 // ----- END android ----- 234 } 235 host = host.substring(0, ind); 236 } 237 } 238 } else { 239 host = ""; 240 } 241 if (port < -1) 242 throw new IllegalArgumentException("Invalid port number :" + 243 port); 244 start = i; 245 246 // ----- BEGIN android ----- 247 // If the authority is defined then the path is defined by the 248 // spec only; See RFC 2396 Section 5.2.4. 249 // if (authority != null && authority.length() > 0) 250 // path = ""; 251 path = null; 252 if (!querySet) { 253 query = null; 254 } 255 // ----- END android ----- 256 } 257 258 if (host == null) { 259 host = ""; 260 } 261 262 // Parse the file path if any 263 if (start < limit) { 264 if (spec.charAt(start) == '/') { 265 path = spec.substring(start, limit); 266 } else if (path != null && path.length() > 0) { 267 isRelPath = true; 268 int ind = path.lastIndexOf('/'); 269 String seperator = ""; 270 if (ind == -1 && authority != null) 271 seperator = "/"; 272 path = path.substring(0, ind + 1) + seperator + 273 spec.substring(start, limit); 274 275 } else { 276 String seperator = (authority != null) ? "/" : ""; 277 path = seperator + spec.substring(start, limit); 278 } 279 } 280 // ----- BEGIN android ----- 281 //else if (queryOnly && path != null) { 282 // int ind = path.lastIndexOf('/'); 283 // if (ind < 0) 284 // ind = 0; 285 // path = path.substring(0, ind) + "/"; 286 //} 287 // ----- END android ----- 288 if (path == null) 289 path = ""; 290 291 // ----- BEGIN android ----- 292 //if (isRelPath) { 293 if (true) { 294 // ----- END android ----- 295 // Remove embedded /./ 296 while ((i = path.indexOf("/./")) >= 0) { 297 path = path.substring(0, i) + path.substring(i + 2); 298 } 299 // Remove embedded /../ if possible 300 i = 0; 301 while ((i = path.indexOf("/../", i)) >= 0) { 302 // ----- BEGIN android ----- 303 /* 304 * Trailing /../ 305 */ 306 if (i == 0) { 307 path = path.substring(i + 3); 308 i = 0; 309 // ----- END android ----- 310 /* 311 * A "/../" will cancel the previous segment and itself, 312 * unless that segment is a "/../" itself 313 * i.e. "/a/b/../c" becomes "/a/c" 314 * but "/../../a" should stay unchanged 315 */ 316 } else if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 && 317 (path.indexOf("/../", limit) != 0)) { 318 path = path.substring(0, limit) + path.substring(i + 3); 319 i = 0; 320 } else { 321 i = i + 3; 322 } 323 } 324 // Remove trailing .. if possible 325 while (path.endsWith("/..")) { 326 i = path.indexOf("/.."); 327 if ((limit = path.lastIndexOf('/', i - 1)) >= 0) { 328 path = path.substring(0, limit+1); 329 } else { 330 break; 331 } 332 } 333 // Remove starting . 334 if (path.startsWith("./") && path.length() > 2) 335 path = path.substring(2); 336 337 // Remove trailing . 338 if (path.endsWith("/.")) 339 path = path.substring(0, path.length() -1); 340 341 // Remove trailing ? 342 if (path.endsWith("?")) 343 path = path.substring(0, path.length() -1); 344 } 345 346 setURL(u, protocol, host, port, authority, userInfo, path, query, ref); 347 } 348 349 /** 350 * Returns the default port for a URL parsed by this handler. This method 351 * is meant to be overidden by handlers with default port numbers. 352 * @return the default port for a <code>URL</code> parsed by this handler. 353 * @since 1.3 354 */ 355 protected int getDefaultPort() { 356 return -1; 357 } 358 359 /** 360 * Provides the default equals calculation. May be overidden by handlers 361 * for other protocols that have different requirements for equals(). 362 * This method requires that none of its arguments is null. This is 363 * guaranteed by the fact that it is only called by java.net.URL class. 364 * @param u1 a URL object 365 * @param u2 a URL object 366 * @return <tt>true</tt> if the two urls are 367 * considered equal, ie. they refer to the same 368 * fragment in the same file. 369 * @since 1.3 370 */ 371 protected boolean equals(URL u1, URL u2) { 372 return Objects.equals(u1.getRef(), u2.getRef()) && 373 Objects.equals(u1.getQuery(), u2.getQuery()) && 374 // sameFile compares the protocol, file, port & host components of 375 // the URLs. 376 sameFile(u1, u2); 377 } 378 379 /** 380 * Provides the default hash calculation. May be overidden by handlers for 381 * other protocols that have different requirements for hashCode 382 * calculation. 383 * @param u a URL object 384 * @return an <tt>int</tt> suitable for hash table indexing 385 * @since 1.3 386 */ 387 protected int hashCode(URL u) { 388 // Hash on the same set of fields that we compare in equals(). 389 return Objects.hash( 390 u.getRef(), 391 u.getQuery(), 392 u.getProtocol(), 393 u.getFile(), 394 u.getHost(), 395 u.getPort()); 396 } 397 398 /** 399 * Compare two urls to see whether they refer to the same file, 400 * i.e., having the same protocol, host, port, and path. 401 * This method requires that none of its arguments is null. This is 402 * guaranteed by the fact that it is only called indirectly 403 * by java.net.URL class. 404 * @param u1 a URL object 405 * @param u2 a URL object 406 * @return true if u1 and u2 refer to the same file 407 * @since 1.3 408 */ 409 protected boolean sameFile(URL u1, URL u2) { 410 // Compare the protocols. 411 if (!((u1.getProtocol() == u2.getProtocol()) || 412 (u1.getProtocol() != null && 413 u1.getProtocol().equalsIgnoreCase(u2.getProtocol())))) 414 return false; 415 416 // Compare the files. 417 if (!(u1.getFile() == u2.getFile() || 418 (u1.getFile() != null && u1.getFile().equals(u2.getFile())))) 419 return false; 420 421 // Compare the ports. 422 int port1, port2; 423 port1 = (u1.getPort() != -1) ? u1.getPort() : u1.handler.getDefaultPort(); 424 port2 = (u2.getPort() != -1) ? u2.getPort() : u2.handler.getDefaultPort(); 425 if (port1 != port2) 426 return false; 427 428 // Compare the hosts. 429 if (!hostsEqual(u1, u2)) 430 return false; 431 432 return true; 433 } 434 435 /** 436 * Get the IP address of our host. An empty host field or a DNS failure 437 * will result in a null return. 438 * 439 * @param u a URL object 440 * @return an <code>InetAddress</code> representing the host 441 * IP address. 442 * @since 1.3 443 */ 444 protected synchronized InetAddress getHostAddress(URL u) { 445 if (u.hostAddress != null) 446 return u.hostAddress; 447 448 String host = u.getHost(); 449 if (host == null || host.equals("")) { 450 return null; 451 } else { 452 try { 453 u.hostAddress = InetAddress.getByName(host); 454 } catch (UnknownHostException ex) { 455 return null; 456 } catch (SecurityException se) { 457 return null; 458 } 459 } 460 return u.hostAddress; 461 } 462 463 /** 464 * Compares the host components of two URLs. 465 * @param u1 the URL of the first host to compare 466 * @param u2 the URL of the second host to compare 467 * @return <tt>true</tt> if and only if they 468 * are equal, <tt>false</tt> otherwise. 469 * @since 1.3 470 */ 471 protected boolean hostsEqual(URL u1, URL u2) { 472 // Android changed: Don't compare the InetAddresses of the hosts. 473 if (u1.getHost() != null && u2.getHost() != null) 474 return u1.getHost().equalsIgnoreCase(u2.getHost()); 475 else 476 return u1.getHost() == null && u2.getHost() == null; 477 } 478 479 /** 480 * Converts a <code>URL</code> of a specific protocol to a 481 * <code>String</code>. 482 * 483 * @param u the URL. 484 * @return a string representation of the <code>URL</code> argument. 485 */ 486 protected String toExternalForm(URL u) { 487 // pre-compute length of StringBuffer 488 int len = u.getProtocol().length() + 1; 489 if (u.getAuthority() != null && u.getAuthority().length() > 0) 490 len += 2 + u.getAuthority().length(); 491 if (u.getPath() != null) { 492 len += u.getPath().length(); 493 } 494 if (u.getQuery() != null) { 495 len += 1 + u.getQuery().length(); 496 } 497 if (u.getRef() != null) 498 len += 1 + u.getRef().length(); 499 500 StringBuilder result = new StringBuilder(len); 501 result.append(u.getProtocol()); 502 result.append(":"); 503 if (u.getAuthority() != null) {// ANDROID: && u.getAuthority().length() > 0) { 504 result.append("//"); 505 result.append(u.getAuthority()); 506 } 507 String fileAndQuery = u.getFile(); 508 if (fileAndQuery != null) { 509 result.append(fileAndQuery); 510 } 511 if (u.getRef() != null) { 512 result.append("#"); 513 result.append(u.getRef()); 514 } 515 return result.toString(); 516 } 517 518 /** 519 * Sets the fields of the <code>URL</code> argument to the indicated values. 520 * Only classes derived from URLStreamHandler are supposed to be able 521 * to call the set method on a URL. 522 * 523 * @param u the URL to modify. 524 * @param protocol the protocol name. 525 * @param host the remote host value for the URL. 526 * @param port the port on the remote machine. 527 * @param authority the authority part for the URL. 528 * @param userInfo the userInfo part of the URL. 529 * @param path the path component of the URL. 530 * @param query the query part for the URL. 531 * @param ref the reference. 532 * @exception SecurityException if the protocol handler of the URL is 533 * different from this one 534 * @see java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String) 535 * @since 1.3 536 */ 537 protected void setURL(URL u, String protocol, String host, int port, 538 String authority, String userInfo, String path, 539 String query, String ref) { 540 if (this != u.handler) { 541 throw new SecurityException("handler for url different from " + 542 "this handler"); 543 } 544 // ensure that no one can reset the protocol on a given URL. 545 u.set(u.getProtocol(), host, port, authority, userInfo, path, query, ref); 546 } 547 548 /** 549 * Sets the fields of the <code>URL</code> argument to the indicated values. 550 * Only classes derived from URLStreamHandler are supposed to be able 551 * to call the set method on a URL. 552 * 553 * @param u the URL to modify. 554 * @param protocol the protocol name. This value is ignored since 1.2. 555 * @param host the remote host value for the URL. 556 * @param port the port on the remote machine. 557 * @param file the file. 558 * @param ref the reference. 559 * @exception SecurityException if the protocol handler of the URL is 560 * different from this one 561 * @deprecated Use setURL(URL, String, String, int, String, String, String, 562 * String); 563 */ 564 @Deprecated 565 protected void setURL(URL u, String protocol, String host, int port, 566 String file, String ref) { 567 /* 568 * Only old URL handlers call this, so assume that the host 569 * field might contain "user:passwd@host". Fix as necessary. 570 */ 571 String authority = null; 572 String userInfo = null; 573 if (host != null && host.length() != 0) { 574 authority = (port == -1) ? host : host + ":" + port; 575 int at = host.lastIndexOf('@'); 576 if (at != -1) { 577 userInfo = host.substring(0, at); 578 host = host.substring(at+1); 579 } 580 } 581 582 /* 583 * Assume file might contain query part. Fix as necessary. 584 */ 585 String path = null; 586 String query = null; 587 if (file != null) { 588 int q = file.lastIndexOf('?'); 589 if (q != -1) { 590 query = file.substring(q+1); 591 path = file.substring(0, q); 592 } else 593 path = file; 594 } 595 setURL(u, protocol, host, port, authority, userInfo, path, query, ref); 596 } 597} 598