1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.handler.codec.socksx.v5;
18
19 import io.netty.buffer.ByteBuf;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.handler.codec.DecoderException;
22 import io.netty.handler.codec.DecoderResult;
23 import io.netty.handler.codec.ReplayingDecoder;
24 import io.netty.handler.codec.socksx.SocksVersion;
25 import io.netty.handler.codec.socksx.v5.Socks5CommandResponseDecoder.State;
26 import io.netty.util.internal.ObjectUtil;
27 import io.netty.util.internal.UnstableApi;
28
29 import java.util.List;
30
31
32
33
34
35
36
37 public class Socks5CommandResponseDecoder extends ReplayingDecoder<State> {
38
39 @UnstableApi
40 public enum State {
41 INIT,
42 SUCCESS,
43 FAILURE
44 }
45
46 private final Socks5AddressDecoder addressDecoder;
47
48 public Socks5CommandResponseDecoder() {
49 this(Socks5AddressDecoder.DEFAULT);
50 }
51
52 public Socks5CommandResponseDecoder(Socks5AddressDecoder addressDecoder) {
53 super(State.INIT);
54 this.addressDecoder = ObjectUtil.checkNotNull(addressDecoder, "addressDecoder");
55 }
56
57 @Override
58 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
59 try {
60 switch (state()) {
61 case INIT: {
62 final byte version = in.readByte();
63 if (version != SocksVersion.SOCKS5.byteValue()) {
64 throw new DecoderException(
65 "unsupported version: " + version + " (expected: " + SocksVersion.SOCKS5.byteValue() + ')');
66 }
67 final Socks5CommandStatus status = Socks5CommandStatus.valueOf(in.readByte());
68 in.skipBytes(1);
69 final Socks5AddressType addrType = Socks5AddressType.valueOf(in.readByte());
70 final String addr = addressDecoder.decodeAddress(addrType, in);
71 final int port = in.readUnsignedShort();
72
73 out.add(new DefaultSocks5CommandResponse(status, addrType, addr, port));
74 checkpoint(State.SUCCESS);
75 }
76 case SUCCESS: {
77 int readableBytes = actualReadableBytes();
78 if (readableBytes > 0) {
79 out.add(in.readRetainedSlice(readableBytes));
80 }
81 break;
82 }
83 case FAILURE: {
84 in.skipBytes(actualReadableBytes());
85 break;
86 }
87 }
88 } catch (Exception e) {
89 fail(out, e);
90 }
91 }
92
93 private void fail(List<Object> out, Exception cause) {
94 if (!(cause instanceof DecoderException)) {
95 cause = new DecoderException(cause);
96 }
97
98 checkpoint(State.FAILURE);
99
100 Socks5Message m = new DefaultSocks5CommandResponse(
101 Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4, null, 0);
102 m.setDecoderResult(DecoderResult.failure(cause));
103 out.add(m);
104 }
105 }