1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.v4.Socks4ClientDecoder.State;
24 import io.netty.util.NetUtil;
25 import io.netty.util.internal.UnstableApi;
26
27 import java.util.List;
28
29
30
31
32
33
34
35 public class Socks4ClientDecoder extends ReplayingDecoder<State> {
36
37 @UnstableApi
38 public enum State {
39 START,
40 SUCCESS,
41 FAILURE
42 }
43
44 public Socks4ClientDecoder() {
45 super(State.START);
46 setSingleDecode(true);
47 }
48
49 @Override
50 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
51 try {
52 switch (state()) {
53 case START: {
54 final int version = in.readUnsignedByte();
55 if (version != 0) {
56 throw new DecoderException("unsupported reply version: " + version + " (expected: 0)");
57 }
58
59 final Socks4CommandStatus status = Socks4CommandStatus.valueOf(in.readByte());
60 final int dstPort = in.readUnsignedShort();
61 final String dstAddr = NetUtil.intToIpAddress(in.readInt());
62
63 out.add(new DefaultSocks4CommandResponse(status, dstAddr, dstPort));
64 checkpoint(State.SUCCESS);
65 }
66 case SUCCESS: {
67 int readableBytes = actualReadableBytes();
68 if (readableBytes > 0) {
69 out.add(in.readRetainedSlice(readableBytes));
70 }
71 break;
72 }
73 case FAILURE: {
74 in.skipBytes(actualReadableBytes());
75 break;
76 }
77 }
78 } catch (Exception e) {
79 fail(out, e);
80 }
81 }
82
83 private void fail(List<Object> out, Exception cause) {
84 if (!(cause instanceof DecoderException)) {
85 cause = new DecoderException(cause);
86 }
87
88 Socks4CommandResponse m = new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED);
89 m.setDecoderResult(DecoderResult.failure(cause));
90 out.add(m);
91
92 checkpoint(State.FAILURE);
93 }
94 }