Socks4ProxySocketFactory.java

  1. /**
  2.  *
  3.  * Copyright the original author or authors
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.proxy;

  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.net.InetAddress;
  22. import java.net.Socket;
  23. import java.net.UnknownHostException;

  24. import javax.net.SocketFactory;

  25. /**
  26.  * Socket factory for socks4 proxy
  27.  *  
  28.  * @author Atul Aggarwal
  29.  */
  30. public class Socks4ProxySocketFactory
  31.     extends SocketFactory
  32. {
  33.     private ProxyInfo proxy;
  34.    
  35.     public Socks4ProxySocketFactory(ProxyInfo proxy)
  36.     {
  37.         this.proxy = proxy;
  38.     }

  39.     public Socket createSocket(String host, int port)
  40.         throws IOException, UnknownHostException
  41.     {
  42.         return socks4ProxifiedSocket(host,port);
  43.        
  44.     }

  45.     public Socket createSocket(String host ,int port, InetAddress localHost,
  46.                                 int localPort)
  47.         throws IOException, UnknownHostException
  48.     {
  49.         return socks4ProxifiedSocket(host,port);
  50.     }

  51.     public Socket createSocket(InetAddress host, int port)
  52.         throws IOException
  53.     {
  54.         return socks4ProxifiedSocket(host.getHostAddress(),port);
  55.     }

  56.     public Socket createSocket( InetAddress address, int port,
  57.                                 InetAddress localAddress, int localPort)
  58.         throws IOException
  59.     {
  60.         return socks4ProxifiedSocket(address.getHostAddress(),port);
  61.        
  62.     }
  63.    
  64.     @SuppressWarnings("resource")
  65.     private Socket socks4ProxifiedSocket(String host, int port)
  66.         throws IOException
  67.     {
  68.         Socket socket = null;
  69.         InputStream in = null;
  70.         OutputStream out = null;
  71.         String proxy_host = proxy.getProxyAddress();
  72.         int proxy_port = proxy.getProxyPort();
  73.         String user = proxy.getProxyUsername();

  74.         try
  75.         {
  76.             socket=new Socket(proxy_host, proxy_port);    
  77.             in=socket.getInputStream();
  78.             out=socket.getOutputStream();
  79.             socket.setTcpNoDelay(true);
  80.            
  81.             byte[] buf=new byte[1024];
  82.             int index=0;

  83.     /*
  84.     1) CONNECT

  85.     The client connects to the SOCKS server and sends a CONNECT request when
  86.     it wants to establish a connection to an application server. The client
  87.     includes in the request packet the IP address and the port number of the
  88.     destination host, and userid, in the following format.

  89.            +----+----+----+----+----+----+----+----+----+----+....+----+
  90.            | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
  91.            +----+----+----+----+----+----+----+----+----+----+....+----+
  92.     # of bytes:   1    1      2              4           variable       1

  93.     VN is the SOCKS protocol version number and should be 4. CD is the
  94.     SOCKS command code and should be 1 for CONNECT request. NULL is a byte
  95.     of all zero bits.
  96.     */

  97.             index=0;
  98.             buf[index++]=4;
  99.             buf[index++]=1;

  100.             buf[index++]=(byte)(port>>>8);
  101.             buf[index++]=(byte)(port&0xff);

  102.             try
  103.             {
  104.                 InetAddress addr=InetAddress.getByName(host);
  105.                 byte[] byteAddress = addr.getAddress();
  106.                 for (int i = 0; i < byteAddress.length; i++)
  107.                 {
  108.                     buf[index++]=byteAddress[i];
  109.                 }
  110.             }
  111.             catch(UnknownHostException uhe)
  112.             {
  113.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS4,
  114.                     uhe.toString(), uhe);
  115.             }

  116.             if(user!=null)
  117.             {
  118.                 System.arraycopy(user.getBytes(), 0, buf, index, user.length());
  119.                 index+=user.length();
  120.             }
  121.             buf[index++]=0;
  122.             out.write(buf, 0, index);

  123.     /*
  124.     The SOCKS server checks to see whether such a request should be granted
  125.     based on any combination of source IP address, destination IP address,
  126.     destination port number, the userid, and information it may obtain by
  127.     consulting IDENT, cf. RFC 1413.  If the request is granted, the SOCKS
  128.     server makes a connection to the specified port of the destination host.
  129.     A reply packet is sent to the client when this connection is established,
  130.     or when the request is rejected or the operation fails.

  131.            +----+----+----+----+----+----+----+----+
  132.            | VN | CD | DSTPORT |      DSTIP        |
  133.            +----+----+----+----+----+----+----+----+
  134.     # of bytes:   1    1      2              4

  135.     VN is the version of the reply code and should be 0. CD is the result
  136.     code with one of the following values:

  137.     90: request granted
  138.     91: request rejected or failed
  139.     92: request rejected becasue SOCKS server cannot connect to
  140.     identd on the client
  141.     93: request rejected because the client program and identd
  142.     report different user-ids

  143.     The remaining fields are ignored.
  144.     */

  145.             int len=6;
  146.             int s=0;
  147.             while(s<len)
  148.             {
  149.                 int i=in.read(buf, s, len-s);
  150.                 if(i<=0)
  151.                 {
  152.                     throw new ProxyException(ProxyInfo.ProxyType.SOCKS4,
  153.                         "stream is closed");
  154.                 }
  155.                 s+=i;
  156.             }
  157.             if(buf[0]!=0)
  158.             {
  159.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS4,
  160.                     "server returns VN "+buf[0]);
  161.             }
  162.             if(buf[1]!=90)
  163.             {
  164.                 try
  165.                 {
  166.                     socket.close();
  167.                 }
  168.                 catch(Exception eee)
  169.                 {
  170.                 }
  171.                 String message="ProxySOCKS4: server returns CD "+buf[1];
  172.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS4,message);
  173.             }
  174.             byte[] temp = new byte[2];
  175.             in.read(temp, 0, 2);
  176.             return socket;
  177.         }
  178.         catch(RuntimeException e)
  179.         {
  180.             throw e;
  181.         }
  182.         catch(Exception e)
  183.         {
  184.             try
  185.             {
  186.                 if(socket!=null)socket.close();
  187.             }
  188.             catch(Exception eee)
  189.             {
  190.             }
  191.             throw new ProxyException(ProxyInfo.ProxyType.SOCKS4, e.toString());
  192.         }
  193.     }
  194. }