Path: blob/master/test/jdk/sun/security/x509/URICertStore/SocksProxy.java
41153 views
/*1* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.IOException;24import java.net.InetAddress;25import java.net.ServerSocket;26import java.net.Socket;27import java.util.Objects;28import java.util.function.Consumer;2930import javax.net.ServerSocketFactory;3132/*33* A simple socks proxy for traveling socket.34*/35class SocksProxy implements Runnable, AutoCloseable {3637private ServerSocket server;38private Consumer<Socket> socketConsumer;3940private SocksProxy(ServerSocket server, Consumer<Socket> socketConsumer) {41this.server = server;42this.socketConsumer = socketConsumer;43}4445static SocksProxy startProxy(Consumer<Socket> socketConsumer)46throws IOException {47Objects.requireNonNull(socketConsumer, "socketConsumer cannot be null");4849ServerSocket server50= ServerSocketFactory.getDefault().createServerSocket(0);5152System.setProperty("socksProxyHost",53InetAddress.getLoopbackAddress().getHostAddress());54System.setProperty("socksProxyPort",55String.valueOf(server.getLocalPort()));56System.setProperty("socksProxyVersion", "5");5758SocksProxy proxy = new SocksProxy(server, socketConsumer);59Thread proxyThread = new Thread(proxy, "Proxy");60proxyThread.setDaemon(true);61proxyThread.start();6263return proxy;64}6566@Override67public void run() {68while (!server.isClosed()) {69try(Socket socket = server.accept()) {70System.out.println("Server: accepted connection");71if (socketConsumer != null) {72socketConsumer.accept(socket);73}74} catch (IOException e) {75if (!server.isClosed()) {76throw new RuntimeException(77"Server: accept connection failed", e);78} else {79System.out.println("Server is closed.");80}81}82}83}8485@Override86public void close() throws Exception {87if (!server.isClosed()) {88server.close();89}90}9192int getPort() {93return server.getLocalPort();94}95}969798