View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
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   * Socks4LogicHandler.java - SOCKS4/SOCKS4a authentication mechanisms logic handler.
31   * 
32   * @author The Apache MINA Project (dev@mina.apache.org)
33   * @version $Rev: 714192 $, $Date: 2008-11-15 00:45:52 +0100 (Sat, 15 Nov 2008) $
34   * @since MINA 2.0.0-M3
35   */
36  public class Socks4LogicHandler extends AbstractSocksLogicHandler {
37  
38      private final static Logger logger = LoggerFactory
39              .getLogger(Socks4LogicHandler.class);
40  
41      /**
42       * {@inheritDoc}
43       */
44      public Socks4LogicHandler(final ProxyIoSession proxyIoSession) {
45          super(proxyIoSession);
46      }
47  
48      /**
49       * Perform the handshake.
50       * 
51       * @param nextFilter the next filter
52       */
53      public void doHandshake(final NextFilter nextFilter) {
54          logger.debug(" doHandshake()");
55  
56          // Send request
57          writeRequest(nextFilter, request);
58      }
59  
60      /**
61       * Encode a SOCKS4/SOCKS4a request and writes it to the next filter
62       * so it can be sent to the proxy server.
63       * 
64       * @param nextFilter the next filter
65       * @param request the request to send.
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      * Handle incoming data during the handshake process. Should consume only the
110      * handshake data from the buffer, leaving any extra data in place.
111      * 
112      * @param nextFilter the next filter
113      * @param buf the server response data buffer
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      * Handle a SOCKS4/SOCKS4a response from the proxy server. Test
128      * the response buffer reply code and call {@link #setHandshakeComplete()}
129      * if access is granted.
130      * 
131      * @param buf the buffer holding the server response data.
132      * @throws exception if server response is malformed or if request is rejected
133      * by the proxy server.
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         // Consumes all the response data from the buffer
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 }