1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.socksx.v5;
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.ByteToMessageDecoder;
23 import io.netty.util.internal.EmptyArrays;
24
25 import java.util.List;
26
27
28
29
30
31
32
33 public final class Socks5PrivateAuthRequestDecoder extends ByteToMessageDecoder {
34
35 private enum State {
36 INIT,
37 SUCCESS,
38 FAILURE
39 }
40
41 private State state = State.INIT;
42
43 @Override
44 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
45 try {
46 if (state == State.SUCCESS) {
47 int readableBytes = in.readableBytes();
48 if (readableBytes > 0) {
49 out.add(in.readRetainedSlice(readableBytes));
50 }
51 return;
52 }
53 if (state == State.FAILURE) {
54 in.skipBytes(in.readableBytes());
55 return;
56 }
57
58
59 if (in.readableBytes() < 2) {
60 return;
61 }
62
63 final int startOffset = in.readerIndex();
64 final byte version = in.getByte(startOffset);
65 if (version != 1) {
66 throw new DecoderException("unsupported subnegotiation version: " + version + " (expected: 1)");
67 }
68
69 final int tokenLength = in.getUnsignedByte(startOffset + 1);
70
71
72 if (in.readableBytes() < 2 + tokenLength) {
73 return;
74 }
75
76
77 in.skipBytes(2);
78
79
80 byte[] token = new byte[tokenLength];
81 in.readBytes(token);
82
83
84 out.add(new DefaultSocks5PrivateAuthRequest(token));
85
86
87 state = State.SUCCESS;
88 } catch (Exception e) {
89 fail(in, out, e);
90 }
91 }
92
93 private void fail(ByteBuf in, List<Object> out, Exception cause) {
94 if (!(cause instanceof DecoderException)) {
95 cause = new DecoderException(cause);
96 }
97
98 state = State.FAILURE;
99 in.skipBytes(in.readableBytes());
100
101 Socks5Message m = new
102 DefaultSocks5PrivateAuthRequest(EmptyArrays.EMPTY_BYTES);
103 m.setDecoderResult(DecoderResult.failure(cause));
104 out.add(m);
105 }
106 }