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