View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.example.socksproxy;
17  
18  import io.netty.bootstrap.Bootstrap;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelFuture;
21  import io.netty.channel.ChannelFutureListener;
22  import io.netty.channel.ChannelHandler;
23  import io.netty.channel.ChannelHandlerContext;
24  import io.netty.channel.ChannelOption;
25  import io.netty.channel.SimpleChannelInboundHandler;
26  import io.netty.channel.socket.nio.NioSocketChannel;
27  import io.netty.handler.codec.socksx.SocksMessage;
28  import io.netty.handler.codec.socksx.v4.DefaultSocks4CommandResponse;
29  import io.netty.handler.codec.socksx.v4.Socks4CommandRequest;
30  import io.netty.handler.codec.socksx.v4.Socks4CommandStatus;
31  import io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse;
32  import io.netty.handler.codec.socksx.v5.Socks5CommandRequest;
33  import io.netty.handler.codec.socksx.v5.Socks5CommandStatus;
34  import io.netty.util.concurrent.Future;
35  import io.netty.util.concurrent.FutureListener;
36  import io.netty.util.concurrent.Promise;
37  
38  @ChannelHandler.Sharable
39  public final class SocksServerConnectHandler extends SimpleChannelInboundHandler<SocksMessage> {
40  
41      private final Bootstrap b = new Bootstrap();
42  
43      @Override
44      public void messageReceived(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
45          if (message instanceof Socks4CommandRequest) {
46              final Socks4CommandRequest request = (Socks4CommandRequest) message;
47              Promise<Channel> promise = ctx.executor().newPromise();
48              promise.addListener(
49                      new FutureListener<Channel>() {
50                          @Override
51                          public void operationComplete(final Future<Channel> future) throws Exception {
52                              final Channel outboundChannel = future.getNow();
53                              if (future.isSuccess()) {
54                                  ChannelFuture responseFuture = ctx.channel().writeAndFlush(
55                                          new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));
56  
57                                  responseFuture.addListener(new ChannelFutureListener() {
58                                      @Override
59                                      public void operationComplete(ChannelFuture channelFuture) {
60                                          ctx.pipeline().remove(SocksServerConnectHandler.this);
61                                          outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
62                                          ctx.pipeline().addLast(new RelayHandler(outboundChannel));
63                                      }
64                                  });
65                              } else {
66                                  ctx.channel().writeAndFlush(
67                                          new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
68                                  SocksServerUtils.closeOnFlush(ctx.channel());
69                              }
70                          }
71                      });
72  
73              final Channel inboundChannel = ctx.channel();
74              b.group(inboundChannel.eventLoop())
75                      .channel(NioSocketChannel.class)
76                      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
77                      .option(ChannelOption.SO_KEEPALIVE, true)
78                      .handler(new DirectClientHandler(promise));
79  
80              b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
81                  @Override
82                  public void operationComplete(ChannelFuture future) throws Exception {
83                      if (future.isSuccess()) {
84                          // Connection established use handler provided results
85                      } else {
86                          // Close the connection if the connection attempt has failed.
87                          ctx.channel().writeAndFlush(
88                                  new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)
89                          );
90                          SocksServerUtils.closeOnFlush(ctx.channel());
91                      }
92                  }
93              });
94          } else if (message instanceof Socks5CommandRequest) {
95              final Socks5CommandRequest request = (Socks5CommandRequest) message;
96              Promise<Channel> promise = ctx.executor().newPromise();
97              promise.addListener(
98                      new FutureListener<Channel>() {
99                          @Override
100                         public void operationComplete(final Future<Channel> future) throws Exception {
101                             final Channel outboundChannel = future.getNow();
102                             if (future.isSuccess()) {
103                                 ChannelFuture responseFuture =
104                                         ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
105                                                 Socks5CommandStatus.SUCCESS, request.dstAddrType()));
106 
107                                 responseFuture.addListener(new ChannelFutureListener() {
108                                     @Override
109                                     public void operationComplete(ChannelFuture channelFuture) {
110                                         ctx.pipeline().remove(SocksServerConnectHandler.this);
111                                         outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
112                                         ctx.pipeline().addLast(new RelayHandler(outboundChannel));
113                                     }
114                                 });
115                             } else {
116                                 ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
117                                         Socks5CommandStatus.FAILURE, request.dstAddrType()));
118                                 SocksServerUtils.closeOnFlush(ctx.channel());
119                             }
120                         }
121                     });
122 
123             final Channel inboundChannel = ctx.channel();
124             b.group(inboundChannel.eventLoop())
125                     .channel(NioSocketChannel.class)
126                     .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
127                     .option(ChannelOption.SO_KEEPALIVE, true)
128                     .handler(new DirectClientHandler(promise));
129 
130             b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
131                 @Override
132                 public void operationComplete(ChannelFuture future) throws Exception {
133                     if (future.isSuccess()) {
134                         // Connection established use handler provided results
135                     } else {
136                         // Close the connection if the connection attempt has failed.
137                         ctx.channel().writeAndFlush(
138                                 new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType()));
139                         SocksServerUtils.closeOnFlush(ctx.channel());
140                     }
141                 }
142             });
143         } else {
144             ctx.close();
145         }
146     }
147 
148     @Override
149     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
150         SocksServerUtils.closeOnFlush(ctx.channel());
151     }
152 }