1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.socksproxy;
17
18 import io.netty.channel.ChannelHandler;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.SimpleChannelInboundHandler;
21 import io.netty.handler.codec.socks.SocksAuthResponse;
22 import io.netty.handler.codec.socks.SocksAuthScheme;
23 import io.netty.handler.codec.socks.SocksAuthStatus;
24 import io.netty.handler.codec.socks.SocksCmdRequest;
25 import io.netty.handler.codec.socks.SocksCmdRequestDecoder;
26 import io.netty.handler.codec.socks.SocksCmdType;
27 import io.netty.handler.codec.socks.SocksInitResponse;
28 import io.netty.handler.codec.socks.SocksRequest;
29
30
31 @ChannelHandler.Sharable
32 public final class SocksServerHandler extends SimpleChannelInboundHandler<SocksRequest> {
33
34 @Override
35 public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
36 switch (socksRequest.requestType()) {
37 case INIT: {
38
39
40
41 ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
42 ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
43 break;
44 }
45 case AUTH:
46 ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
47 ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
48 break;
49 case CMD:
50 SocksCmdRequest req = (SocksCmdRequest) socksRequest;
51 if (req.cmdType() == SocksCmdType.CONNECT) {
52 ctx.pipeline().addLast(new SocksServerConnectHandler());
53 ctx.pipeline().remove(this);
54 ctx.fireChannelRead(socksRequest);
55 } else {
56 ctx.close();
57 }
58 break;
59 case UNKNOWN:
60 ctx.close();
61 break;
62 }
63 }
64
65 @Override
66 public void channelReadComplete(ChannelHandlerContext ctx) {
67 ctx.flush();
68 }
69
70 @Override
71 public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
72 throwable.printStackTrace();
73 SocksServerUtils.closeOnFlush(ctx.channel());
74 }
75 }