1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.proxy.handlers.socks;
21
22 import org.apache.mina.core.buffer.IoBuffer;
23 import org.apache.mina.core.filterchain.IoFilter.NextFilter;
24 import org.apache.mina.proxy.session.ProxyIoSession;
25 import org.apache.mina.proxy.utils.ByteUtilities;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29
30
31
32
33
34
35
36 public class Socks4LogicHandler extends AbstractSocksLogicHandler {
37
38 private final static Logger logger = LoggerFactory
39 .getLogger(Socks4LogicHandler.class);
40
41
42
43
44 public Socks4LogicHandler(final ProxyIoSession proxyIoSession) {
45 super(proxyIoSession);
46 }
47
48
49
50
51
52
53 public void doHandshake(final NextFilter nextFilter) {
54 logger.debug(" doHandshake()");
55
56
57 writeRequest(nextFilter, request);
58 }
59
60
61
62
63
64
65
66
67 protected void writeRequest(final NextFilter nextFilter,
68 final SocksProxyRequest request) {
69 try {
70 boolean isV4ARequest = request.getHost() != null;
71 byte[] userID = request.getUserName().getBytes("ASCII");
72 byte[] host = isV4ARequest ? request.getHost().getBytes("ASCII")
73 : null;
74
75 int len = 9 + userID.length;
76
77 if (isV4ARequest) {
78 len += host.length + 1;
79 }
80
81 IoBuffer buf = IoBuffer.allocate(len);
82
83 buf.put(request.getProtocolVersion());
84 buf.put(request.getCommandCode());
85 buf.put(request.getPort());
86 buf.put(request.getIpAddress());
87 buf.put(userID);
88 buf.put(SocksProxyConstants.TERMINATOR);
89
90 if (isV4ARequest) {
91 buf.put(host);
92 buf.put(SocksProxyConstants.TERMINATOR);
93 }
94
95 if (isV4ARequest) {
96 logger.debug(" sending SOCKS4a request");
97 } else {
98 logger.debug(" sending SOCKS4 request");
99 }
100
101 buf.flip();
102 writeData(nextFilter, buf);
103 } catch (Exception ex) {
104 closeSession("Unable to send Socks request: ", ex);
105 }
106 }
107
108
109
110
111
112
113
114
115 public void messageReceived(final NextFilter nextFilter,
116 final IoBuffer buf) {
117 try {
118 if (buf.remaining() >= SocksProxyConstants.SOCKS_4_RESPONSE_SIZE) {
119 handleResponse(buf);
120 }
121 } catch (Exception ex) {
122 closeSession("Proxy handshake failed: ", ex);
123 }
124 }
125
126
127
128
129
130
131
132
133
134
135 protected void handleResponse(final IoBuffer buf) throws Exception {
136 byte first = buf.get(0);
137
138 if (first != 0) {
139 throw new Exception("Socks response seems to be malformed");
140 }
141
142 byte status = buf.get(1);
143
144
145 buf.position(buf.position() + SocksProxyConstants.SOCKS_4_RESPONSE_SIZE);
146
147 if (status == SocksProxyConstants.V4_REPLY_REQUEST_GRANTED) {
148 setHandshakeComplete();
149 } else {
150 throw new Exception("Proxy handshake failed - Code: 0x"
151 + ByteUtilities.asHex(new byte[] { status }) + " ("
152 + SocksProxyConstants.getReplyCodeAsString(status) + ")");
153 }
154 }
155 }