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