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    *   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  
17  package io.netty.handler.codec.socksx.v5;
18  
19  import io.netty.buffer.ByteBuf;
20  import io.netty.handler.codec.EncoderException;
21  import io.netty.util.CharsetUtil;
22  import io.netty.util.NetUtil;
23  
24  /**
25   * Encodes a SOCKS5 address into binary representation.
26   *
27   * @see Socks5ClientEncoder
28   * @see Socks5ServerEncoder
29   */
30  public interface Socks5AddressEncoder {
31  
32      Socks5AddressEncoder DEFAULT = new Socks5AddressEncoder() {
33          @Override
34          public void encodeAddress(Socks5AddressType addrType, String addrValue, ByteBuf out) throws Exception {
35              final byte typeVal = addrType.byteValue();
36              if (typeVal == Socks5AddressType.IPv4.byteValue()) {
37                  if (addrValue != null) {
38                      out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
39                  } else {
40                      out.writeInt(0);
41                  }
42              } else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) {
43                  if (addrValue != null) {
44                      out.writeByte(addrValue.length());
45                      out.writeCharSequence(addrValue, CharsetUtil.US_ASCII);
46                  } else {
47                      out.writeByte(0);
48                  }
49              } else if (typeVal == Socks5AddressType.IPv6.byteValue()) {
50                  if (addrValue != null) {
51                      out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
52                  } else {
53                      out.writeLong(0);
54                      out.writeLong(0);
55                  }
56              } else {
57                  throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF));
58              }
59          }
60      };
61  
62      /**
63       * Encodes a SOCKS5 address.
64       *
65       * @param addrType the type of the address
66       * @param addrValue the string representation of the address
67       * @param out the output buffer where the encoded SOCKS5 address field will be written to
68       */
69      void encodeAddress(Socks5AddressType addrType, String addrValue, ByteBuf out) throws Exception;
70  }