1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
|
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import jdk.test.lib.process.OutputAnalyzer;
/*
* Utilities for interop testing.
*/
public class Utilities {
public static final String JAVA_HOME = System.getProperty("java.home");
public static final String JAVA
= String.join(File.separator, JAVA_HOME, "bin", "java");
public static final String JAVAC
= String.join(File.separator, JAVA_HOME, "bin", "javac");
public static final String TEST_SRC = System.getProperty("test.src");
public static final String TEST_CLASSES = System.getProperty("test.classes");
public static final String TEST_CLASSPATH = System.getProperty("test.class.path");
public static final Charset CHARSET = StandardCharsets.UTF_8;
public static final boolean DEBUG = Boolean.getBoolean("test.debug");
public static final int TIMEOUT = Integer.getInteger("test.timeout", 20);
public static final String LOG_PATH = System.getProperty("test.log.path");
public static final String PARAM_DELIMITER = ";";
public static final String VALUE_DELIMITER = ",";
public static final CipherSuite[] ALL_CIPHER_SUITES = getAllCipherSuites();
/*
* Gets all supported cipher suites.
*/
private static CipherSuite[] getAllCipherSuites() {
String[] supportedCipherSuites;
try {
supportedCipherSuites = SSLContext.getDefault()
.createSSLEngine()
.getSupportedCipherSuites();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(
"Failed to get supported cipher suites", e);
}
CipherSuite[] cipherSuites = Arrays.stream(supportedCipherSuites)
.map(cipherSuite -> {
return CipherSuite.cipherSuite(cipherSuite);})
.filter(cipherSuite -> {
return cipherSuite != CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV; })
.toArray(CipherSuite[]::new);
return cipherSuites;
}
/*
* Creates SSL context with the specified certificates.
*/
public static SSLContext createSSLContext(CertTuple certTuple)
throws Exception {
KeyStore trustStore = createTrustStore(certTuple.trustedCerts);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trustStore);
KeyStore keyStore = createKeyStore(certTuple.endEntityCerts);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(keyStore, null);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return context;
}
/*
* Creates trust store with the specified certificates.
*/
public static KeyStore createTrustStore(Cert... certs)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException {
KeyStore trustStore = KeyStore.getInstance("PKCS12");
trustStore.load(null, null);
if (certs != null) {
for (int i = 0; i < certs.length; i++) {
if (certs[i] != null) {
trustStore.setCertificateEntry("trust-" + i,
createCert(certs[i]));
}
}
}
return trustStore;
}
/*
* Creates key store with the specified certificates.
*/
public static KeyStore createKeyStore(Cert... certs)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, InvalidKeySpecException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
if (certs != null) {
for (int i = 0; i < certs.length; i++) {
if (certs[i] != null) {
keyStore.setKeyEntry("cert-" + i, createKey(certs[i]), null,
new Certificate[] { createCert(certs[i]) });
}
}
}
return keyStore;
}
/*
* Creates Certificate instance with the specified certificate.
*/
public static Certificate createCert(Cert cert) {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
return certFactory.generateCertificate(
new ByteArrayInputStream(cert.certMaterials.getBytes()));
} catch (CertificateException e) {
throw new RuntimeException("Create cert failed: " + cert, e);
}
}
/*
* Creates PrivateKey instance with the specified certificate.
*/
public static PrivateKey createKey(Cert cert)
throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(cert.keyMaterials));
KeyFactory keyFactory = KeyFactory.getInstance(
cert.keyAlgo.name);
PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
return privKey;
}
/*
* Reads an input stream, in which the content length isn't more than 1024.
*/
public static String readIn(InputStream input) throws IOException {
byte[] buf = new byte[1024];
int length = input.read(buf);
if (length > 0) {
return new String(buf, 0, length);
} else {
return "";
}
}
/*
* Writes the specified content to an output stream.
*/
public static void writeOut(OutputStream output, String content)
throws IOException {
output.write(content.getBytes(Utilities.CHARSET));
output.flush();
}
/*
* Sleeps until the condition is true or getting timeout.
*/
public static <T> boolean waitFor(Predicate<T> predicate, T t) {
long deadline = System.currentTimeMillis() + Utilities.TIMEOUT * 1000;
boolean predicateResult = predicate.test(t);
while (!predicateResult && System.currentTimeMillis() < deadline) {
try {
TimeUnit.SECONDS.sleep(1);
predicateResult = predicate.test(t);
} catch (InterruptedException e) {
throw new RuntimeException("Sleep is interrupted.", e);
}
}
return predicateResult;
}
/*
* Converts Enum array to string array.
* The string elements are the Enum names.
*/
public static String[] enumsToStrs(Enum<?>... elements) {
return enumsToStrs(element -> {
return element.name();
}, elements);
}
/*
* Converts NamedGroup array to string array.
* The string elements are the NameGroups' names.
*/
public static String[] namedGroupsToStrs(NamedGroup... namedGroups) {
return enumsToStrs(namedGroup -> {
return ((NamedGroup) namedGroup).name;
}, namedGroups);
}
/*
* Converts Enum array to string array.
* The string elements are determined by the specified Function.
*/
public static String[] enumsToStrs(Function<Enum<?>, String> function,
Enum<?>... elements) {
return elements == null
? null
: Arrays.stream(elements).map(function).toArray(String[]::new);
}
/*
* Converts string array to Enum array.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<T>> T[] strToEnums(Class<T> enumType,
String namesStr) {
if (namesStr == null) {
return null;
}
return Arrays.stream(namesStr.split(VALUE_DELIMITER)).map(name -> {
return Enum.valueOf(enumType, name);
}).collect(Collectors.toList()).toArray(
(T[]) Array.newInstance(enumType, 0));
}
/*
* Determines if the specified process is alive.
*/
public static boolean isAliveProcess(Process process) {
return process != null && process.isAlive();
}
/*
* Destroys the specified process and the associated child processes.
*/
public static void destroyProcess(Process process) {
process.children().forEach(ProcessHandle::destroy);
process.destroy();
}
/*
* Reads the content for the specified file.
*/
public static Optional<String> readFile(Path path) throws IOException {
if (!Files.exists(path)) {
return Optional.empty();
} else {
return Optional.of(new String(Files.readAllBytes(path)));
}
}
/*
* Tries to delete the specified file before getting timeout,
* in case that the file is not released by some process in time.
*/
public static void deleteFile(Path filePath) throws IOException {
if (filePath == null) {
return;
}
waitFor(path -> delete(path), filePath);
if (Files.exists(filePath)) {
throw new IOException(
"File is not deleted in time: " + filePath.toAbsolutePath());
}
}
private static boolean delete(Path filePath) {
boolean deleted = false;
try {
deleted = Files.deleteIfExists(filePath);
} catch (IOException e) {
e.printStackTrace(System.out);
}
return deleted;
}
/*
* Determines if the TLS session is resumed.
*/
public static boolean isSessionResumed(ResumptionMode mode,
byte[] firstSessionId, byte[] secondSessionId,
long firstSessionCreationTime, long secondSessionCreationTime) {
System.out.println("ResumptionMode: " + mode);
System.out.println("firstSessionId: " + Arrays.toString(firstSessionId));
System.out.println("secondSessionId: " + Arrays.toString(secondSessionId));
System.out.println("firstSessionCreationTime: " + firstSessionCreationTime);
System.out.println("secondSessionCreationTime: " + secondSessionCreationTime);
boolean resumed = firstSessionCreationTime == secondSessionCreationTime;
if (mode == ResumptionMode.ID) {
resumed = resumed && firstSessionId.length > 0
&& Arrays.equals(firstSessionId, secondSessionId);
}
return resumed;
}
@SuppressWarnings("unchecked")
public static <T> String join(String delimiter, Function<T, String> toStr,
T... elements) {
if (elements == null) {
return "";
}
StringJoiner joiner = new StringJoiner(delimiter);
for (T element : elements) {
if (element != null) {
String str = toStr.apply(element);
if (str != null && !str.isEmpty()) {
joiner.add(str);
}
}
}
return joiner.toString();
}
@SuppressWarnings("unchecked")
public static <T> String join(String delimiter, T... elements) {
return join(delimiter, elem -> {
return elem.toString();
}, elements);
}
@SuppressWarnings("unchecked")
public static <T> String join(T... elements) {
return join(VALUE_DELIMITER, elements);
}
@SuppressWarnings("unchecked")
public static <T> String join(Function<T, String> toStr, T... elements) {
return join(VALUE_DELIMITER, toStr, elements);
}
public static String joinOptValue(String delimiter, String option,
Object value) {
return value == null || value.toString().isEmpty()
? ""
: option + delimiter + value;
}
public static String joinOptValue(String option, Object value) {
return joinOptValue(" ", option, value);
}
public static String joinNameValue(String option, Object value) {
return joinOptValue("=", option, value);
}
public static String[] split(String str, String delimiter) {
if (str == null) {
return null;
}
return str.split(delimiter);
}
public static String[] split(String str) {
return split(str, VALUE_DELIMITER);
}
public static String trimStr(String str) {
return str == null ? "" : str.trim();
}
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
/*
* Determines the expected negotiated application protocol from the server
* and client application protocols.
*/
public static String expectedNegoAppProtocol(String[] serverAppProtocols,
String[] clientAppProtocols) {
if (serverAppProtocols != null && clientAppProtocols != null) {
for(String clientAppProtocol : clientAppProtocols) {
for(String serverAppProtocol : serverAppProtocols) {
if (clientAppProtocol.equals(serverAppProtocol)) {
return clientAppProtocol;
}
}
}
}
return null;
}
/*
* Finds the minimum protocol in the specified protocols.
*/
public static Protocol minProtocol(Protocol[] protocols) {
return findProtocol(protocols, true);
}
/*
* Finds the maximum protocol in the specified protocols.
*/
public static Protocol maxProtocol(Protocol[] protocols) {
return findProtocol(protocols, false);
}
private static Protocol findProtocol(Protocol[] protocols, boolean findMin) {
if (protocols == null) {
return null;
}
Arrays.sort(protocols, (p1, p2) -> {
return (p1.id - p2.id) * (findMin ? 1 : -1);
});
return protocols[0];
}
}
|