1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.net;
18
19import static com.google.common.base.Preconditions.checkArgument;
20import static com.google.common.base.Preconditions.checkNotNull;
21import static com.google.common.base.Preconditions.checkState;
22
23import com.google.common.annotations.Beta;
24import com.google.common.base.Objects;
25
26import java.util.regex.Matcher;
27import java.util.regex.Pattern;
28
29import javax.annotation.concurrent.Immutable;
30
31/**
32 * An immutable representation of a host and port.
33 *
34 * <p>Example usage:
35 * <pre>
36 * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
37 *     .withDefaultPort(80)
38 *     .requireBracketsForIPv6();
39 * hp.getHostText();  // returns "2001:db8::1"
40 * hp.getPort();      // returns 80
41 * hp.toString();     // returns "[2001:db8::1]:80"
42 * </pre>
43 *
44 * <p>Here are some examples of recognized formats:
45 * <ul>
46 *   <li>example.com
47 *   <li>example.com:80
48 *   <li>192.0.2.1
49 *   <li>192.0.2.1:80
50 *   <li>[2001:db8::1]     - {@link #getHostText()} omits brackets
51 *   <li>[2001:db8::1]:80  - {@link #getHostText()} omits brackets
52 *   <li>2001:db8::1       - Use {@link #requireBracketsForIPv6()} to prohibit this
53 * </ul>
54 *
55 * <p>Note that this is not an exhaustive list, because these methods are only
56 * concerned with brackets, colons, and port numbers.  Full validation of the
57 * host field (if desired) is the caller's responsibility.
58 *
59 * @author Paul Marks
60 * @since 10.0
61 */
62@Beta @Immutable
63public final class HostAndPort {
64  /** Magic value indicating the absence of a port number. */
65  private static final int NO_PORT = -1;
66
67  /** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */
68  private final String host;
69
70  /** Validated port number in the range [0..65535], or NO_PORT */
71  private final int port;
72
73  /** True if the parsed host has colons, but no surrounding brackets. */
74  private final boolean hasBracketlessColons;
75
76  private HostAndPort(String host, int port, boolean hasBracketlessColons) {
77    this.host = host;
78    this.port = port;
79    this.hasBracketlessColons = hasBracketlessColons;
80  }
81
82  /**
83   * Returns the portion of this {@code HostAndPort} instance that should
84   * represent the hostname or IPv4/IPv6 literal.
85   *
86   * A successful parse does not imply any degree of sanity in this field.
87   * For additional validation, see the {@link HostSpecifier} class.
88   */
89  public String getHostText() {
90    return host;
91  }
92
93  /** Return true if this instance has a defined port. */
94  public boolean hasPort() {
95    return port >= 0;
96  }
97
98  /**
99   * 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}
266