| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.util; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.net.BindException; |
| 10 |
import java.net.Inet6Address; |
| 11 |
import java.net.InetAddress; |
| 12 |
import java.net.InetSocketAddress; |
| 13 |
import java.net.ServerSocket; |
| 14 |
import java.net.Socket; |
| 15 |
import java.net.UnknownHostException; |
| 16 |
|
| 17 |
import org.h2.api.ErrorCode; |
| 18 |
import org.h2.engine.SysProperties; |
| 19 |
import org.h2.message.DbException; |
| 20 |
import org.h2.security.CipherFactory; |
| 21 |
|
| 22 |
/** |
| 23 |
* This utility class contains socket helper functions. |
| 24 |
*/ |
| 25 |
public class NetUtils { |
| 26 |
|
| 27 |
private static final int CACHE_MILLIS = 1000; |
| 28 |
private static InetAddress cachedBindAddress; |
| 29 |
private static String cachedLocalAddress; |
| 30 |
private static long cachedLocalAddressTime; |
| 31 |
|
| 32 |
private NetUtils() { |
| 33 |
// utility class |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Create a loopback socket (a socket that is connected to localhost) on |
| 38 |
* this port. |
| 39 |
* |
| 40 |
* @param port the port |
| 41 |
* @param ssl if SSL should be used |
| 42 |
* @return the socket |
| 43 |
* @throws IOException on failure |
| 44 |
*/ |
| 45 |
public static Socket createLoopbackSocket(int port, boolean ssl) |
| 46 |
throws IOException { |
| 47 |
String local = getLocalAddress(); |
| 48 |
try { |
| 49 |
return createSocket(local, port, ssl); |
| 50 |
} catch (IOException e) { |
| 51 |
try { |
| 52 |
return createSocket("localhost", port, ssl); |
| 53 |
} catch (IOException e2) { |
| 54 |
// throw the original exception |
| 55 |
throw e; |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Create a client socket that is connected to the given address and port. |
| 62 |
* |
| 63 |
* @param server to connect to (including an optional port) |
| 64 |
* @param defaultPort the default port (if not specified in the server |
| 65 |
* address) |
| 66 |
* @param ssl if SSL should be used |
| 67 |
* @return the socket |
| 68 |
* @throws IOException on failure |
| 69 |
*/ |
| 70 |
public static Socket createSocket(String server, int defaultPort, boolean ssl) throws IOException { |
| 71 |
return createSocket(server, defaultPort, ssl, 0); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Create a client socket that is connected to the given address and port. |
| 76 |
* |
| 77 |
* @param server to connect to (including an optional port) |
| 78 |
* @param defaultPort the default port (if not specified in the server |
| 79 |
* address) |
| 80 |
* @param ssl if SSL should be used |
| 81 |
* @param networkTimeout socket so timeout |
| 82 |
* @return the socket |
| 83 |
* @throws IOException on failure |
| 84 |
*/ |
| 85 |
public static Socket createSocket(String server, int defaultPort, |
| 86 |
boolean ssl, int networkTimeout) throws IOException { |
| 87 |
int port = defaultPort; |
| 88 |
// IPv6: RFC 2732 format is '[a:b:c:d:e:f:g:h]' or |
| 89 |
// '[a:b:c:d:e:f:g:h]:port' |
| 90 |
// RFC 2396 format is 'a.b.c.d' or 'a.b.c.d:port' or 'hostname' or |
| 91 |
// 'hostname:port' |
| 92 |
int startIndex = server.startsWith("[") ? server.indexOf(']') : 0; |
| 93 |
int idx = server.indexOf(':', startIndex); |
| 94 |
if (idx >= 0) { |
| 95 |
port = Integer.decode(server.substring(idx + 1)); |
| 96 |
server = server.substring(0, idx); |
| 97 |
} |
| 98 |
InetAddress address = InetAddress.getByName(server); |
| 99 |
return createSocket(address, port, ssl, networkTimeout); |
| 100 |
} |
| 101 |
|
| 102 |
/** |
| 103 |
* Create a client socket that is connected to the given address and port. |
| 104 |
* |
| 105 |
* @param address the address to connect to |
| 106 |
* @param port the port |
| 107 |
* @param ssl if SSL should be used |
| 108 |
* @return the socket |
| 109 |
* @throws IOException on failure |
| 110 |
*/ |
| 111 |
public static Socket createSocket(InetAddress address, int port, boolean ssl) |
| 112 |
throws IOException { |
| 113 |
return createSocket(address, port, ssl, 0); |
| 114 |
} |
| 115 |
/** |
| 116 |
* Create a client socket that is connected to the given address and port. |
| 117 |
* |
| 118 |
* @param address the address to connect to |
| 119 |
* @param port the port |
| 120 |
* @param ssl if SSL should be used |
| 121 |
* @param networkTimeout socket so timeout |
| 122 |
* @return the socket |
| 123 |
* @throws IOException on failure |
| 124 |
*/ |
| 125 |
public static Socket createSocket(InetAddress address, int port, boolean ssl, int networkTimeout) |
| 126 |
throws IOException { |
| 127 |
long start = System.nanoTime(); |
| 128 |
for (int i = 0;; i++) { |
| 129 |
try { |
| 130 |
if (ssl) { |
| 131 |
return CipherFactory.createSocket(address, port); |
| 132 |
} |
| 133 |
Socket socket = new Socket(); |
| 134 |
socket.setSoTimeout(networkTimeout); |
| 135 |
socket.connect(new InetSocketAddress(address, port), |
| 136 |
SysProperties.SOCKET_CONNECT_TIMEOUT); |
| 137 |
return socket; |
| 138 |
} catch (IOException e) { |
| 139 |
if (System.nanoTime() - start >= SysProperties.SOCKET_CONNECT_TIMEOUT * 1_000_000L) { |
| 140 |
// either it was a connect timeout, |
| 141 |
// or list of different exceptions |
| 142 |
throw e; |
| 143 |
} |
| 144 |
if (i >= SysProperties.SOCKET_CONNECT_RETRY) { |
| 145 |
throw e; |
| 146 |
} |
| 147 |
// wait a bit and retry |
| 148 |
try { |
| 149 |
// sleep at most 256 ms |
| 150 |
long sleep = Math.min(256, i * i); |
| 151 |
Thread.sleep(sleep); |
| 152 |
} catch (InterruptedException e2) { |
| 153 |
// ignore |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
/** |
| 160 |
* Create a server socket. The system property h2.bindAddress is used if |
| 161 |
* set. If SSL is used and h2.enableAnonymousTLS is true, an attempt is |
| 162 |
* made to modify the security property jdk.tls.legacyAlgorithms |
| 163 |
* (in newer JVMs) to allow anonymous TLS. |
| 164 |
* <p> |
| 165 |
* This system change is effectively permanent for the lifetime of the JVM. |
| 166 |
* @see CipherFactory#removeAnonFromLegacyAlgorithms() |
| 167 |
* |
| 168 |
* @param port the port to listen on |
| 169 |
* @param ssl if SSL should be used |
| 170 |
* @return the server socket |
| 171 |
*/ |
| 172 |
public static ServerSocket createServerSocket(int port, boolean ssl) { |
| 173 |
try { |
| 174 |
return createServerSocketTry(port, ssl); |
| 175 |
} catch (Exception e) { |
| 176 |
// try again |
| 177 |
return createServerSocketTry(port, ssl); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
/** |
| 182 |
* Get the bind address if the system property h2.bindAddress is set, or |
| 183 |
* null if not. |
| 184 |
* |
| 185 |
* @return the bind address |
| 186 |
*/ |
| 187 |
private static InetAddress getBindAddress() throws UnknownHostException { |
| 188 |
String host = SysProperties.BIND_ADDRESS; |
| 189 |
if (host == null || host.isEmpty()) { |
| 190 |
return null; |
| 191 |
} |
| 192 |
synchronized (NetUtils.class) { |
| 193 |
if (cachedBindAddress == null) { |
| 194 |
cachedBindAddress = InetAddress.getByName(host); |
| 195 |
} |
| 196 |
} |
| 197 |
return cachedBindAddress; |
| 198 |
} |
| 199 |
|
| 200 |
private static ServerSocket createServerSocketTry(int port, boolean ssl) { |
| 201 |
try { |
| 202 |
InetAddress bindAddress = getBindAddress(); |
| 203 |
if (ssl) { |
| 204 |
return CipherFactory.createServerSocket(port, bindAddress); |
| 205 |
} |
| 206 |
if (bindAddress == null) { |
| 207 |
return new ServerSocket(port); |
| 208 |
} |
| 209 |
return new ServerSocket(port, 0, bindAddress); |
| 210 |
} catch (BindException be) { |
| 211 |
throw DbException.get(ErrorCode.EXCEPTION_OPENING_PORT_2, |
| 212 |
be, Integer.toString(port), be.toString()); |
| 213 |
} catch (IOException e) { |
| 214 |
throw DbException.convertIOException(e, "port: " + port + " ssl: " + ssl); |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
/** |
| 219 |
* Check if a socket is connected to a local address. |
| 220 |
* |
| 221 |
* @param socket the socket |
| 222 |
* @return true if it is |
| 223 |
* @throws UnknownHostException on failure |
| 224 |
*/ |
| 225 |
public static boolean isLocalAddress(Socket socket) |
| 226 |
throws UnknownHostException { |
| 227 |
InetAddress test = socket.getInetAddress(); |
| 228 |
if (test.isLoopbackAddress()) { |
| 229 |
return true; |
| 230 |
} |
| 231 |
InetAddress localhost = InetAddress.getLocalHost(); |
| 232 |
// localhost.getCanonicalHostName() is very slow |
| 233 |
String host = localhost.getHostAddress(); |
| 234 |
for (InetAddress addr : InetAddress.getAllByName(host)) { |
| 235 |
if (test.equals(addr)) { |
| 236 |
return true; |
| 237 |
} |
| 238 |
} |
| 239 |
return false; |
| 240 |
} |
| 241 |
|
| 242 |
/** |
| 243 |
* Close a server socket and ignore any exceptions. |
| 244 |
* |
| 245 |
* @param socket the socket |
| 246 |
* @return null |
| 247 |
*/ |
| 248 |
public static ServerSocket closeSilently(ServerSocket socket) { |
| 249 |
if (socket != null) { |
| 250 |
try { |
| 251 |
socket.close(); |
| 252 |
} catch (IOException e) { |
| 253 |
// ignore |
| 254 |
} |
| 255 |
} |
| 256 |
return null; |
| 257 |
} |
| 258 |
|
| 259 |
/** |
| 260 |
* Get the local host address as a string. |
| 261 |
* For performance, the result is cached for one second. |
| 262 |
* |
| 263 |
* @return the local host address |
| 264 |
*/ |
| 265 |
public static synchronized String getLocalAddress() { |
| 266 |
long now = System.nanoTime(); |
| 267 |
if (cachedLocalAddress != null && now - cachedLocalAddressTime < CACHE_MILLIS * 1_000_000L) { |
| 268 |
return cachedLocalAddress; |
| 269 |
} |
| 270 |
InetAddress bind = null; |
| 271 |
boolean useLocalhost = false; |
| 272 |
try { |
| 273 |
bind = getBindAddress(); |
| 274 |
if (bind == null) { |
| 275 |
useLocalhost = true; |
| 276 |
} |
| 277 |
} catch (UnknownHostException e) { |
| 278 |
// ignore |
| 279 |
} |
| 280 |
if (useLocalhost) { |
| 281 |
try { |
| 282 |
bind = InetAddress.getLocalHost(); |
| 283 |
} catch (UnknownHostException e) { |
| 284 |
throw DbException.convert(e); |
| 285 |
} |
| 286 |
} |
| 287 |
String address; |
| 288 |
if (bind == null) { |
| 289 |
address = "localhost"; |
| 290 |
} else { |
| 291 |
address = bind.getHostAddress(); |
| 292 |
if (bind instanceof Inet6Address) { |
| 293 |
if (address.indexOf('%') >= 0) { |
| 294 |
address = "localhost"; |
| 295 |
} else if (address.indexOf(':') >= 0 && !address.startsWith("[")) { |
| 296 |
// adds'[' and ']' if required for |
| 297 |
// Inet6Address that contain a ':'. |
| 298 |
address = "[" + address + "]"; |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
if (address.equals("127.0.0.1")) { |
| 303 |
address = "localhost"; |
| 304 |
} |
| 305 |
cachedLocalAddress = address; |
| 306 |
cachedLocalAddressTime = now; |
| 307 |
return address; |
| 308 |
} |
| 309 |
|
| 310 |
/** |
| 311 |
* Get the host name of a local address, if available. |
| 312 |
* |
| 313 |
* @param localAddress the local address |
| 314 |
* @return the host name, or another text if not available |
| 315 |
*/ |
| 316 |
public static String getHostName(String localAddress) { |
| 317 |
try { |
| 318 |
InetAddress addr = InetAddress.getByName(localAddress); |
| 319 |
return addr.getHostName(); |
| 320 |
} catch (Exception e) { |
| 321 |
return "unknown"; |
| 322 |
} |
| 323 |
} |
| 324 |
|
| 325 |
/** |
| 326 |
* Appends short representation of the specified IP address to the string |
| 327 |
* builder. |
| 328 |
* |
| 329 |
* @param builder |
| 330 |
* string builder to append to, or {@code null} |
| 331 |
* @param address |
| 332 |
* IP address |
| 333 |
* @param addBrackets |
| 334 |
* if ({@code true}, add brackets around IPv6 addresses |
| 335 |
* @return the specified or the new string builder with short representation |
| 336 |
* of specified address |
| 337 |
*/ |
| 338 |
public static StringBuilder ipToShortForm(StringBuilder builder, byte[] address, boolean addBrackets) { |
| 339 |
switch (address.length) { |
| 340 |
case 4: |
| 341 |
if (builder == null) { |
| 342 |
builder = new StringBuilder(15); |
| 343 |
} |
| 344 |
builder // |
| 345 |
.append(address[0] & 0xff).append('.') // |
| 346 |
.append(address[1] & 0xff).append('.') // |
| 347 |
.append(address[2] & 0xff).append('.') // |
| 348 |
.append(address[3] & 0xff); |
| 349 |
break; |
| 350 |
case 16: |
| 351 |
short[] a = new short[8]; |
| 352 |
int maxStart = 0, maxLen = 0, currentLen = 0; |
| 353 |
for (int i = 0, offset = 0; i < 8; i++) { |
| 354 |
if ((a[i] = (short) ((address[offset++] & 0xff) << 8 | address[offset++] & 0xff)) == 0) { |
| 355 |
currentLen++; |
| 356 |
if (currentLen > maxLen) { |
| 357 |
maxLen = currentLen; |
| 358 |
maxStart = i - currentLen + 1; |
| 359 |
} |
| 360 |
} else { |
| 361 |
currentLen = 0; |
| 362 |
} |
| 363 |
} |
| 364 |
if (builder == null) { |
| 365 |
builder = new StringBuilder(addBrackets ? 41 : 39); |
| 366 |
} |
| 367 |
if (addBrackets) { |
| 368 |
builder.append('['); |
| 369 |
} |
| 370 |
int start; |
| 371 |
if (maxLen > 1) { |
| 372 |
for (int i = 0; i < maxStart; i++) { |
| 373 |
builder.append(Integer.toHexString(a[i] & 0xffff)).append(':'); |
| 374 |
} |
| 375 |
if (maxStart == 0) { |
| 376 |
builder.append(':'); |
| 377 |
} |
| 378 |
builder.append(':'); |
| 379 |
start = maxStart + maxLen; |
| 380 |
} else { |
| 381 |
start = 0; |
| 382 |
} |
| 383 |
for (int i = start; i < 8; i++) { |
| 384 |
builder.append(Integer.toHexString(a[i] & 0xffff)); |
| 385 |
if (i < 7) { |
| 386 |
builder.append(':'); |
| 387 |
} |
| 388 |
} |
| 389 |
if (addBrackets) { |
| 390 |
builder.append(']'); |
| 391 |
} |
| 392 |
break; |
| 393 |
default: |
| 394 |
StringUtils.convertBytesToHex(builder, address); |
| 395 |
} |
| 396 |
return builder; |
| 397 |
} |
| 398 |
|
| 399 |
} |