View Javadoc
1   /*
2    * Copyright 2015 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  
17  package io.netty.handler.codec.socksx.v5;
18  
19  import io.netty.buffer.ByteBuf;
20  import io.netty.handler.codec.DecoderException;
21  import io.netty.util.CharsetUtil;
22  import io.netty.util.NetUtil;
23  
24  /**
25   * Decodes a SOCKS5 address field into its string representation.
26   *
27   * @see Socks5CommandRequestDecoder
28   * @see Socks5CommandResponseDecoder
29   */
30  public interface Socks5AddressDecoder {
31  
32      Socks5AddressDecoder DEFAULT = new Socks5AddressDecoder() {
33  
34          private static final int IPv6_LEN = 16;
35  
36          @Override
37          public String decodeAddress(Socks5AddressType addrType, ByteBuf in) throws Exception {
38              if (addrType == Socks5AddressType.IPv4) {
39                  return NetUtil.intToIpAddress(in.readInt());
40              }
41              if (addrType == Socks5AddressType.DOMAIN) {
42                  final int length = in.readUnsignedByte();
43                  final String domain = in.toString(in.readerIndex(), length, CharsetUtil.US_ASCII);
44                  in.skipBytes(length);
45                  return domain;
46              }
47              if (addrType == Socks5AddressType.IPv6) {
48                  if (in.hasArray()) {
49                      final int readerIdx = in.readerIndex();
50                      in.readerIndex(readerIdx + IPv6_LEN);
51                      return NetUtil.bytesToIpAddress(in.array(), in.arrayOffset() + readerIdx, IPv6_LEN);
52                  } else {
53                      byte[] tmp = new byte[IPv6_LEN];
54                      in.readBytes(tmp);
55                      return NetUtil.bytesToIpAddress(tmp);
56                  }
57              } else {
58                  throw new DecoderException("unsupported address type: " + (addrType.byteValue() & 0xFF));
59              }
60          }
61      };
62  
63      /**
64       * Decodes a SOCKS5 address field into its string representation.
65       *
66       * @param addrType the type of the address
67       * @param in the input buffer which contains the SOCKS5 address field at its reader index
68       */
69      String decodeAddress(Socks5AddressType addrType, ByteBuf in) throws Exception;
70  }