001    /*
002     * Copyright (C) 2011 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.net;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    import static com.google.common.base.Preconditions.checkState;
022    
023    import com.google.common.annotations.Beta;
024    import com.google.common.base.Objects;
025    
026    import java.util.regex.Matcher;
027    import java.util.regex.Pattern;
028    
029    import javax.annotation.concurrent.Immutable;
030    
031    /**
032     * An immutable representation of a host and port.
033     *
034     * <p>Example usage:
035     * <pre>
036     * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
037     *     .withDefaultPort(80)
038     *     .requireBracketsForIPv6();
039     * hp.getHostText();  // returns "2001:db8::1"
040     * hp.getPort();      // returns 80
041     * hp.toString();     // returns "[2001:db8::1]:80"
042     * </pre>
043     *
044     * <p>Here are some examples of recognized formats:
045     * <ul>
046     *   <li>example.com
047     *   <li>example.com:80
048     *   <li>192.0.2.1
049     *   <li>192.0.2.1:80
050     *   <li>[2001:db8::1]     - {@link #getHostText()} omits brackets
051     *   <li>[2001:db8::1]:80  - {@link #getHostText()} omits brackets
052     *   <li>2001:db8::1       - Use {@link #requireBracketsForIPv6()} to prohibit this
053     * </ul>
054     *
055     * <p>Note that this is not an exhaustive list, because these methods are only
056     * concerned with brackets, colons, and port numbers.  Full validation of the
057     * host field (if desired) is the caller's responsibility.
058     *
059     * @author Paul Marks
060     * @since 10.0
061     */
062    @Beta @Immutable
063    public final class HostAndPort {
064      /** Magic value indicating the absence of a port number. */
065      private static final int NO_PORT = -1;
066    
067      /** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */
068      private final String host;
069    
070      /** Validated port number in the range [0..65535], or NO_PORT */
071      private final int port;
072    
073      /** True if the parsed host has colons, but no surrounding brackets. */
074      private final boolean hasBracketlessColons;
075    
076      private HostAndPort(String host, int port, boolean hasBracketlessColons) {
077        this.host = host;
078        this.port = port;
079        this.hasBracketlessColons = hasBracketlessColons;
080      }
081    
082      /**
083       * Returns the portion of this {@code HostAndPort} instance that should
084       * represent the hostname or IPv4/IPv6 literal.
085       *
086       * A successful parse does not imply any degree of sanity in this field.
087       * For additional validation, see the {@link HostSpecifier} class.
088       */
089      public String getHostText() {
090        return host;
091      }
092    
093      /** Return true if this instance has a defined port. */
094      public boolean hasPort() {
095        return port >= 0;
096      }
097    
098      /**
099       * Get the current port number, failing if no port is defined.
100       *
101       * @return a validated port number, in the range [0..65535]
102       * @throws IllegalStateException if no port is defined.  You can use
103       *         {@link #withDefaultPort(int)} to prevent this from occurring.
104       */
105      public int getPort() {
106        checkState(hasPort());
107        return port;
108      }
109    
110      /**
111       * Returns the current port number, with a default if no port is defined.
112       */
113      public int getPortOrDefault(int defaultPort) {
114        return hasPort() ? port : defaultPort;
115      }
116    
117      /**
118       * Build a HostAndPort instance from separate host and port values.
119       *
120       * <p>Note: Non-bracketed IPv6 literals are allowed.
121       * Use {@link #requireBracketsForIPv6()} to prohibit these.
122       *
123       * @param host the host string to parse.  Must not contain a port number.
124       * @param port a port number from [0..65535]
125       * @return if parsing was successful, a populated HostAndPort object.
126       * @throws IllegalArgumentException if {@code host} contains a port number,
127       *     or {@code port} is out of range.
128       */
129      public static HostAndPort fromParts(String host, int port) {
130        checkArgument(isValidPort(port));
131        HostAndPort parsedHost = fromString(host);
132        checkArgument(!parsedHost.hasPort());
133        return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons);
134      }
135    
136      private static final Pattern BRACKET_PATTERN = Pattern.compile("^\\[(.*:.*)\\](?::(\\d*))?$");
137    
138      /**
139       * Split a freeform string into a host and port, without strict validation.
140       *
141       * Note that the host-only formats will leave the port field undefined.  You
142       * can use {@link #withDefaultPort(int)} to patch in a default value.
143       *
144       * @param hostPortString the input string to parse.
145       * @return if parsing was successful, a populated HostAndPort object.
146       * @throws IllegalArgumentException if nothing meaningful could be parsed.
147       */
148      public static HostAndPort fromString(String hostPortString) {
149        checkNotNull(hostPortString);
150        String host;
151        String portString = null;
152        boolean hasBracketlessColons = false;
153    
154        if (hostPortString.startsWith("[")) {
155          // Parse a bracketed host, typically an IPv6 literal.
156          Matcher matcher = BRACKET_PATTERN.matcher(hostPortString);
157          checkArgument(matcher.matches(), "Invalid bracketed host/port: %s", hostPortString);
158          host = matcher.group(1);
159          portString = matcher.group(2);  // could be null
160        } else {
161          int colonPos = hostPortString.indexOf(':');
162          if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
163            // Exactly 1 colon.  Split into host:port.
164            host = hostPortString.substring(0, colonPos);
165            portString = hostPortString.substring(colonPos + 1);
166          } else {
167            // 0 or 2+ colons.  Bare hostname or IPv6 literal.
168            host = hostPortString;
169            hasBracketlessColons = (colonPos >= 0);
170          }
171        }
172    
173        int port = NO_PORT;
174        if (portString != null) {
175          // Try to parse the whole port string as a number.
176          // JDK7 accepts leading plus signs. We don't want to.
177          checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString);
178          try {
179            port = Integer.parseInt(portString);
180          } catch (NumberFormatException e) {
181            throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
182          }
183          checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString);
184        }
185    
186        return new HostAndPort(host, port, hasBracketlessColons);
187      }
188    
189      /**
190       * Provide a default port if the parsed string contained only a host.
191       *
192       * You can chain this after {@link #fromString(String)} to include a port in
193       * case the port was omitted from the input string.  If a port was already
194       * provided, then this method is a no-op.
195       *
196       * @param defaultPort a port number, from [0..65535]
197       * @return a HostAndPort instance, guaranteed to have a defined port.
198       */
199      public HostAndPort withDefaultPort(int defaultPort) {
200        checkArgument(isValidPort(defaultPort));
201        if (hasPort() || port == defaultPort) {
202          return this;
203        }
204        return new HostAndPort(host, defaultPort, hasBracketlessColons);
205      }
206    
207      /**
208       * Generate an error if the host might be a non-bracketed IPv6 literal.
209       *
210       * <p>URI formatting requires that IPv6 literals be surrounded by brackets,
211       * like "[2001:db8::1]".  Chain this call after {@link #fromString(String)}
212       * to increase the strictness of the parser, and disallow IPv6 literals
213       * that don't contain these brackets.
214       *
215       * <p>Note that this parser identifies IPv6 literals solely based on the
216       * presence of a colon.  To perform actual validation of IP addresses, see
217       * the {@link InetAddresses#forString(String)} method.
218       *
219       * @return {@code this}, to enable chaining of calls.
220       * @throws IllegalArgumentException if bracketless IPv6 is detected.
221       */
222      public HostAndPort requireBracketsForIPv6() {
223        checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host);
224        return this;
225      }
226    
227      @Override
228      public boolean equals(Object other) {
229        if (this == other) {
230          return true;
231        }
232        if (other instanceof HostAndPort) {
233          HostAndPort that = (HostAndPort) other;
234          return Objects.equal(this.host, that.host)
235              && this.port == that.port
236              && this.hasBracketlessColons == that.hasBracketlessColons;
237        }
238        return false;
239      }
240    
241      @Override
242      public int hashCode() {
243        return Objects.hashCode(host, port, hasBracketlessColons);
244      }
245    
246      /** Rebuild the host:port string, including brackets if necessary. */
247      @Override
248      public String toString() {
249        StringBuilder builder = new StringBuilder(host.length() + 7);
250        if (host.indexOf(':') >= 0) {
251          builder.append('[').append(host).append(']');
252        } else {
253          builder.append(host);
254        }
255        if (hasPort()) {
256          builder.append(':').append(port);
257        }
258        return builder.toString();
259      }
260    
261      /** Return true for valid port numbers. */
262      private static boolean isValidPort(int port) {
263        return port >= 0 && port <= 65535;
264      }
265    }