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.handler.codec.socksx.v4;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.handler.codec.DecoderException;
21  import io.netty.handler.codec.DecoderResult;
22  import io.netty.handler.codec.ReplayingDecoder;
23  import io.netty.handler.codec.socksx.SocksVersion;
24  import io.netty.handler.codec.socksx.v4.Socks4ServerDecoder.State;
25  import io.netty.util.CharsetUtil;
26  import io.netty.util.NetUtil;
27  
28  import java.util.List;
29  
30  /**
31   * Decodes a single {@link Socks4CommandRequest} from the inbound {@link ByteBuf}s.
32   * On successful decode, this decoder will forward the received data to the next handler, so that
33   * other handler can remove this decoder later.  On failed decode, this decoder will discard the
34   * received data, so that other handler closes the connection later.
35   */
36  public class Socks4ServerDecoder extends ReplayingDecoder<State> {
37  
38      private static final int MAX_FIELD_LENGTH = 255;
39  
40      enum State {
41          START,
42          READ_USERID,
43          READ_DOMAIN,
44          SUCCESS,
45          FAILURE
46      }
47  
48      private Socks4CommandType type;
49      private String dstAddr;
50      private int dstPort;
51      private String userId;
52  
53      public Socks4ServerDecoder() {
54          super(State.START);
55          setSingleDecode(true);
56      }
57  
58      @Override
59      protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
60          try {
61              switch (state()) {
62              case START: {
63                  final int version = in.readUnsignedByte();
64                  if (version != SocksVersion.SOCKS4a.byteValue()) {
65                      throw new DecoderException("unsupported protocol version: " + version);
66                  }
67  
68                  type = Socks4CommandType.valueOf(in.readByte());
69                  dstPort = in.readUnsignedShort();
70                  dstAddr = NetUtil.intToIpAddress(in.readInt());
71                  checkpoint(State.READ_USERID);
72              }
73              case READ_USERID: {
74                  userId = readString("userid", in);
75                  checkpoint(State.READ_DOMAIN);
76              }
77              case READ_DOMAIN: {
78                  // Check for Socks4a protocol marker 0.0.0.x
79                  if (!"0.0.0.0".equals(dstAddr) && dstAddr.startsWith("0.0.0.")) {
80                      dstAddr = readString("dstAddr", in);
81                  }
82                  out.add(new DefaultSocks4CommandRequest(type, dstAddr, dstPort, userId));
83                  checkpoint(State.SUCCESS);
84              }
85              case SUCCESS: {
86                  int readableBytes = actualReadableBytes();
87                  if (readableBytes > 0) {
88                      out.add(in.readSlice(readableBytes).retain());
89                  }
90                  break;
91              }
92              case FAILURE: {
93                  in.skipBytes(actualReadableBytes());
94                  break;
95              }
96              }
97          } catch (Exception e) {
98              fail(out, e);
99          }
100     }
101 
102     private void fail(List<Object> out, Throwable cause) {
103         if (!(cause instanceof DecoderException)) {
104             cause = new DecoderException(cause);
105         }
106 
107         Socks4CommandRequest m = new DefaultSocks4CommandRequest(
108                 type != null? type : Socks4CommandType.CONNECT,
109                 dstAddr != null? dstAddr : "",
110                 dstPort != 0? dstPort : 65535,
111                 userId != null? userId : "");
112 
113         m.setDecoderResult(DecoderResult.failure(cause));
114         out.add(m);
115 
116         checkpoint(State.FAILURE);
117     }
118 
119     /**
120      * Reads a variable-length NUL-terminated string as defined in SOCKS4.
121      */
122     private static String readString(String fieldName, ByteBuf in) {
123         int length = in.bytesBefore(MAX_FIELD_LENGTH + 1, (byte) 0);
124         if (length < 0) {
125             throw new DecoderException("field '" + fieldName + "' longer than " + MAX_FIELD_LENGTH + " chars");
126         }
127 
128         String value = in.readSlice(length).toString(CharsetUtil.US_ASCII);
129         in.skipBytes(1); // Skip the NUL.
130 
131         return value;
132     }
133 }