|
| 1 | +package quickfix.mina; |
| 2 | + |
| 3 | +import io.netty.bootstrap.ServerBootstrap; |
| 4 | +import io.netty.channel.Channel; |
| 5 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 6 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 7 | +import io.netty.example.socksproxy.SocksServerInitializer; |
| 8 | +import io.netty.handler.logging.LogLevel; |
| 9 | +import io.netty.handler.logging.LoggingHandler; |
| 10 | +import org.apache.mina.util.DaemonThreadFactory; |
| 11 | +import org.slf4j.Logger; |
| 12 | +import org.slf4j.LoggerFactory; |
| 13 | + |
| 14 | +import java.util.concurrent.ThreadFactory; |
| 15 | + |
| 16 | +/** |
| 17 | + * Simple SOCKS proxy server based on Netty examples. Only SOCKS protocols are currently supported. |
| 18 | + * The implementation performs the proxy handshake, but it doesn't perform any user authentication. |
| 19 | + */ |
| 20 | +public class SocksProxyServer { |
| 21 | + |
| 22 | + private static final Logger LOGGER = LoggerFactory.getLogger(SocksProxyServer.class); |
| 23 | + private static final ThreadFactory THREAD_FACTORY = new DaemonThreadFactory(); |
| 24 | + |
| 25 | + private final ServerBootstrap bootstrap; |
| 26 | + private final int port; |
| 27 | + private Channel channel; |
| 28 | + |
| 29 | + public SocksProxyServer(int port) { |
| 30 | + this.bootstrap = new ServerBootstrap(); |
| 31 | + this.bootstrap.group(new NioEventLoopGroup(THREAD_FACTORY), new NioEventLoopGroup(THREAD_FACTORY)) |
| 32 | + .channel(NioServerSocketChannel.class) |
| 33 | + .handler(new LoggingHandler(LogLevel.DEBUG)) |
| 34 | + .childHandler(new SocksServerInitializer()); |
| 35 | + this.port = port; |
| 36 | + } |
| 37 | + |
| 38 | + public synchronized void start() { |
| 39 | + if (channel != null) { |
| 40 | + throw new IllegalStateException("SOCKS proxy server is running already"); |
| 41 | + } |
| 42 | + |
| 43 | + try { |
| 44 | + channel = bootstrap.bind(port) |
| 45 | + .sync() |
| 46 | + .channel(); |
| 47 | + } catch (InterruptedException e) { |
| 48 | + Thread.currentThread().interrupt(); |
| 49 | + throw new RuntimeException(e); |
| 50 | + } |
| 51 | + |
| 52 | + LOGGER.info("SOCKS proxy server started at port: {}", port); |
| 53 | + } |
| 54 | + |
| 55 | + public synchronized void stop() { |
| 56 | + if (channel == null) { |
| 57 | + throw new IllegalStateException("SOCKS proxy server is not running"); |
| 58 | + } |
| 59 | + |
| 60 | + try { |
| 61 | + channel.close().sync(); |
| 62 | + channel = null; |
| 63 | + } catch (InterruptedException e) { |
| 64 | + Thread.currentThread().interrupt(); |
| 65 | + throw new RuntimeException("Failed to close SOCKS proxy server"); |
| 66 | + } |
| 67 | + |
| 68 | + LOGGER.info("SOCKS proxy server stopped at port {}", port); |
| 69 | + } |
| 70 | + |
| 71 | + public int getPort() { |
| 72 | + return port; |
| 73 | + } |
| 74 | +} |
0 commit comments