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