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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
|
/*
* Copyright (c) 2012, 2018, 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.
*/
/* Test utility classes
*
*/
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import jdk.test.lib.Utils;
public class TestServers {
private TestServers() { }
/**
* An abstract server identifies a server which listens on a port on on a
* given machine.
*/
static abstract class AbstractServer {
private AbstractServer() {
}
public abstract int getPort();
public abstract InetAddress getAddress();
}
/**
* A downgraded type of AbstractServer which will refuse connections. Note:
* use it once and throw it away - this implementation opens an anonymous
* socket and closes it, returning the address of the closed socket. If
* other servers are started afterwards, the address/port might get reused
* and become connectable again - so it's not a good idea to assume that
* connections using this address/port will always be refused. Connections
* will be refused as long as the address/port of the refusing server has
* not been reused.
*/
static class RefusingServer extends AbstractServer {
final InetAddress address;
final int port;
private RefusingServer(InetAddress address, int port) {
this.address = address;
this.port = port;
}
@Override
public int getPort() {
return port;
}
@Override
public InetAddress getAddress() {
return address;
}
public static RefusingServer newRefusingServer() throws IOException {
return new RefusingServer(InetAddress.getLocalHost(),
Utils.refusingEndpoint().getPort());
}
}
/**
* An abstract class for implementing small TCP servers for the nio tests
* purposes. Disclaimer: This is a naive implementation that uses the old
* networking APIs (not those from {@code java.nio.*}) and shamelessly
* extends/creates Threads instead of using an executor service.
*/
static abstract class AbstractTcpServer extends AbstractServer
implements Runnable, Closeable {
protected final long linger; // #of ms to wait before responding
private Thread acceptThread; // thread waiting for accept
// list of opened connections that should be closed on close.
private List<TcpConnectionThread> connections = new ArrayList<>();
private ServerSocket serverSocket; // the server socket
private boolean started = false; // whether the server is started
Throwable error = null;
/**
* Creates a new abstract TCP server.
*
* @param linger the amount of time the server should wait before
* responding to requests.
*/
protected AbstractTcpServer(long linger) {
this.linger = linger;
}
/**
* The local port to which the server is bound.
*
* @return The local port to which the server is bound.
* @exception IllegalStateException is thrown if the server is not
* started.
*/
@Override
public final synchronized int getPort() {
if (!started) {
throw new IllegalStateException("Not started");
}
return serverSocket.getLocalPort();
}
/**
* The local address to which the server is bound.
*
* @return The local address to which the server is bound.
* @exception IllegalStateException is thrown if the server is not
* started.
*/
@Override
public final synchronized InetAddress getAddress() {
if (!started) {
throw new IllegalStateException("Not started");
}
return serverSocket.getInetAddress();
}
/**
* Tells whether the server is started.
*
* @return true if the server is started.
*/
public final synchronized boolean isStarted() {
return started;
}
/**
* Creates a new server socket.
*
* @param port local port to bind to.
* @param backlog requested maximum length of the queue of incoming
* connections.
* @param address local address to bind to.
* @return a new bound server socket ready to accept connections.
* @throws IOException if the socket cannot be created or bound.
*/
protected ServerSocket newServerSocket(int port, int backlog,
InetAddress address)
throws IOException {
return new ServerSocket(port, backlog, address);
}
/**
* Starts listening for connections.
*
* @throws IOException if the server socket cannot be created or bound.
*/
public final synchronized void start() throws IOException {
if (started) {
return;
}
final ServerSocket socket =
newServerSocket(0, 100, InetAddress.getLocalHost());
serverSocket = socket;
acceptThread = new Thread(this);
acceptThread.setDaemon(true);
acceptThread.start();
started = true;
}
/**
* Calls {@code Thread.sleep(linger);}
*/
protected final void lingerIfRequired() {
if (linger > 0) {
try {
Thread.sleep(linger);
} catch (InterruptedException x) {
Thread.interrupted();
final ServerSocket socket = serverSocket();
if (socket != null && !socket.isClosed()) {
System.err.println("Thread interrupted...");
}
}
}
}
final synchronized ServerSocket serverSocket() {
return this.serverSocket;
}
/**
* The main accept loop.
*/
@Override
public final void run() {
final ServerSocket sSocket = serverSocket();
try {
Socket s;
while (isStarted() && !Thread.interrupted()
&& (s = sSocket.accept()) != null) {
lingerIfRequired();
listen(s);
}
} catch (Exception x) {
error = x;
} finally {
synchronized (this) {
if (!sSocket.isClosed()) {
try {
sSocket.close();
} catch (IOException x) {
System.err.println("Failed to close server socket");
}
}
if (started && this.serverSocket == sSocket) {
started = false;
this.serverSocket = null;
this.acceptThread = null;
}
}
}
}
/**
* Represents a connection accepted by the server.
*/
protected abstract class TcpConnectionThread extends Thread {
protected final Socket socket;
protected TcpConnectionThread(Socket socket) {
this.socket = socket;
this.setDaemon(true);
}
public void close() throws IOException {
socket.close();
interrupt();
}
}
/**
* Creates a new TcpConnnectionThread to handle the connection through
* an accepted socket.
*
* @param s the socket returned by {@code serverSocket.accept()}.
* @return a new TcpConnnectionThread to handle the connection through
* an accepted socket.
*/
protected abstract TcpConnectionThread createConnection(Socket s);
/**
* Creates and starts a new TcpConnectionThread to handle the accepted
* socket.
*
* @param s the socket returned by {@code serverSocket.accept()}.
*/
private synchronized void listen(Socket s) {
TcpConnectionThread c = createConnection(s);
c.start();
addConnection(c);
}
/**
* Add the connection to the list of accepted connections.
*
* @param connection an accepted connection.
*/
protected synchronized void addConnection(
TcpConnectionThread connection) {
connections.add(connection);
}
/**
* Remove the connection from the list of accepted connections.
*
* @param connection an accepted connection.
*/
protected synchronized void removeConnection(
TcpConnectionThread connection) {
connections.remove(connection);
}
/**
* Close the server socket and all the connections present in the list
* of accepted connections.
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
if (acceptThread != null) {
acceptThread.interrupt();
}
int failed = 0;
for (TcpConnectionThread c : connections) {
try {
c.close();
} catch (IOException x) {
// no matter - we're closing.
failed++;
}
}
connections.clear();
if (failed > 0) {
throw new IOException("Failed to close some connections");
}
}
}
/**
* A small TCP Server that emulates the echo service for tests purposes. See
* http://en.wikipedia.org/wiki/Echo_Protocol This server uses an anonymous
* port - NOT the standard port 7. We don't guarantee that its behavior
* exactly matches the RFC - the only purpose of this server is to have
* something that responds to nio tests...
*/
static class EchoServer extends AbstractTcpServer {
public EchoServer() {
this(0L);
}
public EchoServer(long linger) {
super(linger);
}
@Override
protected TcpConnectionThread createConnection(Socket s) {
return new EchoConnection(s);
}
private final class EchoConnection extends TcpConnectionThread {
public EchoConnection(Socket socket) {
super(socket);
}
@Override
public void run() {
try {
final InputStream is = socket.getInputStream();
final OutputStream out = socket.getOutputStream();
byte[] b = new byte[255];
int n;
while ((n = is.read(b)) > 0) {
lingerIfRequired();
out.write(b, 0, n);
}
} catch (IOException io) {
// fall through to finally
} finally {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException x) {
System.err.println(
"Failed to close echo connection socket");
}
}
removeConnection(this);
}
}
}
public static EchoServer startNewServer() throws IOException {
return startNewServer(0);
}
public static EchoServer startNewServer(long linger) throws IOException {
final EchoServer echoServer = new EchoServer(linger);
echoServer.start();
return echoServer;
}
}
/**
* A small TCP Server that accept connections but does not response to any input.
*/
static final class NoResponseServer extends EchoServer {
public NoResponseServer() {
super(Long.MAX_VALUE);
}
public static NoResponseServer startNewServer() throws IOException {
final NoResponseServer noResponseServer = new NoResponseServer();
noResponseServer.start();
return noResponseServer;
}
}
/**
* A small TCP server that emulates the Day & Time service for tests
* purposes. See http://en.wikipedia.org/wiki/Daytime_Protocol This server
* uses an anonymous port - NOT the standard port 13. We don't guarantee
* that its behavior exactly matches the RFC - the only purpose of this
* server is to have something that responds to nio tests...
*/
static final class DayTimeServer extends AbstractTcpServer {
public DayTimeServer() {
this(0L);
}
public DayTimeServer(long linger) {
super(linger);
}
@Override
protected TcpConnectionThread createConnection(Socket s) {
return new DayTimeServerConnection(s);
}
@Override
protected void addConnection(TcpConnectionThread connection) {
// do nothing - the connection just write the date and terminates.
}
@Override
protected void removeConnection(TcpConnectionThread connection) {
// do nothing - we're not adding connections to the list...
}
private final class DayTimeServerConnection extends TcpConnectionThread {
public DayTimeServerConnection(Socket socket) {
super(socket);
}
@Override
public void run() {
try {
final OutputStream out = socket.getOutputStream();
lingerIfRequired();
out.write(new Date(System.currentTimeMillis())
.toString().getBytes("US-ASCII"));
out.flush();
} catch (IOException io) {
// fall through to finally
} finally {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException x) {
System.err.println(
"Failed to close echo connection socket");
}
}
}
}
}
public static DayTimeServer startNewServer()
throws IOException {
return startNewServer(0);
}
public static DayTimeServer startNewServer(long linger)
throws IOException {
final DayTimeServer daytimeServer = new DayTimeServer(linger);
daytimeServer.start();
return daytimeServer;
}
}
/**
* An abstract class for implementing small UDP Servers for the nio tests
* purposes. Disclaimer: This is a naive implementation that uses the old
* networking APIs (not those from {@code java.nio.*}) and shamelessly
* extends/creates Threads instead of using an executor service.
*/
static abstract class AbstractUdpServer extends AbstractServer
implements Runnable, Closeable {
protected final long linger; // #of ms to wait before responding
private Thread acceptThread; // thread waiting for packets
private DatagramSocket serverSocket; // the server socket
private boolean started = false; // whether the server is started
Throwable error = null;
/**
* Creates a new abstract UDP server.
*
* @param linger the amount of time the server should wait before
* responding to requests.
*/
protected AbstractUdpServer(long linger) {
this.linger = linger;
}
/**
* The local port to which the server is bound.
*
* @return The local port to which the server is bound.
* @exception IllegalStateException is thrown if the server is not
* started.
*/
@Override
public final synchronized int getPort() {
if (!started) {
throw new IllegalStateException("Not started");
}
return serverSocket.getLocalPort();
}
/**
* The local address to which the server is bound.
*
* @return The local address to which the server is bound.
* @exception IllegalStateException is thrown if the server is not
* started.
*/
@Override
public final synchronized InetAddress getAddress() {
if (!started) {
throw new IllegalStateException("Not started");
}
return serverSocket.getLocalAddress();
}
/**
* Tells whether the server is started.
*
* @return true if the server is started.
*/
public final synchronized boolean isStarted() {
return started;
}
/**
* Creates a new datagram socket.
*
* @param port local port to bind to.
* @param address local address to bind to.
* @return a new bound server socket ready to listen for packets.
* @throws IOException if the socket cannot be created or bound.
*/
protected DatagramSocket newDatagramSocket(int port,
InetAddress address)
throws IOException {
return new DatagramSocket(port, address);
}
/**
* Starts listening for connections.
*
* @throws IOException if the server socket cannot be created or bound.
*/
public final synchronized void start() throws IOException {
if (started) {
return;
}
final DatagramSocket socket =
newDatagramSocket(0, InetAddress.getLocalHost());
serverSocket = socket;
acceptThread = new Thread(this);
acceptThread.setDaemon(true);
acceptThread.start();
started = true;
}
/**
* Calls {@code Thread.sleep(linger);}
*/
protected final void lingerIfRequired() {
if (linger > 0) {
try {
Thread.sleep(linger);
} catch (InterruptedException x) {
Thread.interrupted();
final DatagramSocket socket = serverSocket();
if (socket != null && !socket.isClosed()) {
System.err.println("Thread interrupted...");
}
}
}
}
final synchronized DatagramSocket serverSocket() {
return this.serverSocket;
}
final synchronized boolean send(DatagramSocket socket,
DatagramPacket response) throws IOException {
if (!socket.isClosed()) {
socket.send(response);
return true;
} else {
return false;
}
}
/**
* The main receive loop.
*/
@Override
public final void run() {
final DatagramSocket sSocket = serverSocket();
try {
final int size = Math.max(1024, sSocket.getReceiveBufferSize());
if (size > sSocket.getReceiveBufferSize()) {
sSocket.setReceiveBufferSize(size);
}
while (isStarted() && !Thread.interrupted() && !sSocket.isClosed()) {
final byte[] buf = new byte[size];
final DatagramPacket packet =
new DatagramPacket(buf, buf.length);
lingerIfRequired();
sSocket.receive(packet);
//System.out.println("Received packet from: "
// + packet.getAddress()+":"+packet.getPort());
handle(sSocket, packet);
}
} catch (Exception x) {
error = x;
} finally {
synchronized (this) {
if (!sSocket.isClosed()) {
sSocket.close();
}
if (started && this.serverSocket == sSocket) {
started = false;
this.serverSocket = null;
this.acceptThread = null;
}
}
}
}
/**
* Represents an UDP request received by the server.
*/
protected abstract class UdpRequestThread extends Thread {
protected final DatagramPacket request;
protected final DatagramSocket socket;
protected UdpRequestThread(DatagramSocket socket, DatagramPacket request) {
this.socket = socket;
this.request = request;
this.setDaemon(true);
}
}
/**
* Creates a new UdpRequestThread to handle a DatagramPacket received
* through a DatagramSocket.
*
* @param socket the socket through which the request was received.
* @param request the datagram packet received through the socket.
* @return a new UdpRequestThread to handle the request received through
* a DatagramSocket.
*/
protected abstract UdpRequestThread createConnection(DatagramSocket socket,
DatagramPacket request);
/**
* Creates and starts a new UdpRequestThread to handle the received
* datagram packet.
*
* @param socket the socket through which the request was received.
* @param request the datagram packet received through the socket.
*/
private synchronized void handle(DatagramSocket socket,
DatagramPacket request) {
UdpRequestThread c = createConnection(socket, request);
// c can be null if the request requires no response.
if (c != null) {
c.start();
}
}
/**
* Close the server socket.
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
if (acceptThread != null) {
acceptThread.interrupt();
}
}
}
/**
* A small UDP Server that emulates the discard service for tests purposes.
* See http://en.wikipedia.org/wiki/Discard_Protocol This server uses an
* anonymous port - NOT the standard port 9. We don't guarantee that its
* behavior exactly matches the RFC - the only purpose of this server is to
* have something that responds to nio tests...
*/
static final class UdpDiscardServer extends AbstractUdpServer {
public UdpDiscardServer() {
this(0L);
}
public UdpDiscardServer(long linger) {
super(linger);
}
@Override
protected UdpRequestThread createConnection(DatagramSocket socket,
DatagramPacket request) {
// no response required
return null;
}
public static UdpDiscardServer startNewServer() throws IOException {
return startNewServer(0);
}
public static UdpDiscardServer startNewServer(long linger) throws IOException {
final UdpDiscardServer discardServer = new UdpDiscardServer(linger);
discardServer.start();
return discardServer;
}
}
/**
* A small UDP Server that emulates the echo service for tests purposes. See
* http://en.wikipedia.org/wiki/Echo_Protocol This server uses an anonymous
* port - NOT the standard port 7. We don't guarantee that its behavior
* exactly matches the RFC - the only purpose of this server is to have
* something that responds to nio tests...
*/
static final class UdpEchoServer extends AbstractUdpServer {
public UdpEchoServer() {
this(0L);
}
public UdpEchoServer(long linger) {
super(linger);
}
@Override
protected UdpEchoRequest createConnection(DatagramSocket socket,
DatagramPacket request) {
return new UdpEchoRequest(socket, request);
}
private final class UdpEchoRequest extends UdpRequestThread {
public UdpEchoRequest(DatagramSocket socket, DatagramPacket request) {
super(socket, request);
}
@Override
public void run() {
try {
lingerIfRequired();
final DatagramPacket response =
new DatagramPacket(request.getData(),
request.getOffset(), request.getLength(),
request.getAddress(), request.getPort());
send(socket, response);
} catch (IOException io) {
System.err.println("Failed to send response: " + io);
io.printStackTrace(System.err);
}
}
}
public static UdpEchoServer startNewServer() throws IOException {
return startNewServer(0);
}
public static UdpEchoServer startNewServer(long linger) throws IOException {
final UdpEchoServer echoServer = new UdpEchoServer(linger);
echoServer.start();
return echoServer;
}
}
/**
* A small UDP server that emulates the Day & Time service for tests
* purposes. See http://en.wikipedia.org/wiki/Daytime_Protocol This server
* uses an anonymous port - NOT the standard port 13. We don't guarantee
* that its behavior exactly matches the RFC - the only purpose of this
* server is to have something that responds to nio tests...
*/
static final class UdpDayTimeServer extends AbstractUdpServer {
public UdpDayTimeServer() {
this(0L);
}
public UdpDayTimeServer(long linger) {
super(linger);
}
@Override
protected UdpDayTimeRequestThread createConnection(DatagramSocket socket,
DatagramPacket request) {
return new UdpDayTimeRequestThread(socket, request);
}
private final class UdpDayTimeRequestThread extends UdpRequestThread {
public UdpDayTimeRequestThread(DatagramSocket socket,
DatagramPacket request) {
super(socket, request);
}
@Override
public void run() {
try {
lingerIfRequired();
final byte[] data = new Date(System.currentTimeMillis())
.toString().getBytes("US-ASCII");
final DatagramPacket response =
new DatagramPacket(data, 0, data.length,
request.getAddress(), request.getPort());
send(socket, response);
} catch (IOException io) {
System.err.println("Failed to send response: " + io);
io.printStackTrace(System.err);
}
}
}
public static UdpDayTimeServer startNewServer() throws IOException {
return startNewServer(0);
}
public static UdpDayTimeServer startNewServer(long linger)
throws IOException {
final UdpDayTimeServer echoServer = new UdpDayTimeServer(linger);
echoServer.start();
return echoServer;
}
}
}
|