Socks5ProxySocketFactory.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 Socks5 proxy
  27.  *
  28.  * @author Atul Aggarwal
  29.  */
  30. public class Socks5ProxySocketFactory
  31.     extends SocketFactory
  32. {
  33.     private ProxyInfo proxy;
  34.    
  35.     public Socks5ProxySocketFactory(ProxyInfo proxy)
  36.     {
  37.         this.proxy = proxy;
  38.     }

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

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

  52.     public Socket createSocket(InetAddress host, int port)
  53.         throws IOException
  54.     {
  55.        
  56.         return socks5ProxifiedSocket(host.getHostAddress(),port);
  57.        
  58.     }

  59.     public Socket createSocket( InetAddress address, int port,
  60.                                 InetAddress localAddress, int localPort)
  61.         throws IOException
  62.     {
  63.        
  64.         return socks5ProxifiedSocket(address.getHostAddress(),port);
  65.        
  66.     }
  67.    
  68.     private Socket socks5ProxifiedSocket(String host, int port)
  69.         throws IOException
  70.     {
  71.         Socket socket = null;
  72.         InputStream in = null;
  73.         OutputStream out = null;
  74.         String proxy_host = proxy.getProxyAddress();
  75.         int proxy_port = proxy.getProxyPort();
  76.         String user = proxy.getProxyUsername();
  77.         String passwd = proxy.getProxyPassword();
  78.        
  79.         try
  80.         {
  81.             socket=new Socket(proxy_host, proxy_port);    
  82.             in=socket.getInputStream();
  83.             out=socket.getOutputStream();

  84.             socket.setTcpNoDelay(true);

  85.             byte[] buf=new byte[1024];
  86.             int index=0;

  87. /*
  88.                    +----+----------+----------+
  89.                    |VER | NMETHODS | METHODS  |
  90.                    +----+----------+----------+
  91.                    | 1  |    1     | 1 to 255 |
  92.                    +----+----------+----------+

  93.    The VER field is set to X'05' for this version of the protocol.  The
  94.    NMETHODS field contains the number of method identifier octets that
  95.    appear in the METHODS field.

  96.    The values currently defined for METHOD are:

  97.           o  X'00' NO AUTHENTICATION REQUIRED
  98.           o  X'01' GSSAPI
  99.           o  X'02' USERNAME/PASSWORD
  100.           o  X'03' to X'7F' IANA ASSIGNED
  101.           o  X'80' to X'FE' RESERVED FOR PRIVATE METHODS
  102.           o  X'FF' NO ACCEPTABLE METHODS
  103. */

  104.             buf[index++]=5;

  105.             buf[index++]=2;
  106.             buf[index++]=0;           // NO AUTHENTICATION REQUIRED
  107.             buf[index++]=2;           // USERNAME/PASSWORD

  108.             out.write(buf, 0, index);

  109. /*
  110.     The server selects from one of the methods given in METHODS, and
  111.     sends a METHOD selection message:

  112.                          +----+--------+
  113.                          |VER | METHOD |
  114.                          +----+--------+
  115.                          | 1  |   1    |
  116.                          +----+--------+
  117. */
  118.       //in.read(buf, 0, 2);
  119.             fill(in, buf, 2);

  120.             boolean check=false;
  121.             switch((buf[1])&0xff)
  122.             {
  123.                 case 0:                // NO AUTHENTICATION REQUIRED
  124.                     check=true;
  125.                     break;
  126.                 case 2:                // USERNAME/PASSWORD
  127.                     if(user==null || passwd==null)
  128.                     {
  129.                         break;
  130.                     }

  131. /*
  132.    Once the SOCKS V5 server has started, and the client has selected the
  133.    Username/Password Authentication protocol, the Username/Password
  134.    subnegotiation begins.  This begins with the client producing a
  135.    Username/Password request:

  136.            +----+------+----------+------+----------+
  137.            |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
  138.            +----+------+----------+------+----------+
  139.            | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
  140.            +----+------+----------+------+----------+

  141.    The VER field contains the current version of the subnegotiation,
  142.    which is X'01'. The ULEN field contains the length of the UNAME field
  143.    that follows. The UNAME field contains the username as known to the
  144.    source operating system. The PLEN field contains the length of the
  145.    PASSWD field that follows. The PASSWD field contains the password
  146.    association with the given UNAME.
  147. */
  148.                     index=0;
  149.                     buf[index++]=1;
  150.                     buf[index++]=(byte)(user.length());
  151.                     System.arraycopy(user.getBytes(), 0, buf, index,
  152.                         user.length());
  153.                     index+=user.length();
  154.                     buf[index++]=(byte)(passwd.length());
  155.                     System.arraycopy(passwd.getBytes(), 0, buf, index,
  156.                         passwd.length());
  157.                     index+=passwd.length();

  158.                     out.write(buf, 0, index);

  159. /*
  160.    The server verifies the supplied UNAME and PASSWD, and sends the
  161.    following response:

  162.                         +----+--------+
  163.                         |VER | STATUS |
  164.                         +----+--------+
  165.                         | 1  |   1    |
  166.                         +----+--------+

  167.    A STATUS field of X'00' indicates success. If the server returns a
  168.    `failure' (STATUS value other than X'00') status, it MUST close the
  169.    connection.
  170. */
  171.                     //in.read(buf, 0, 2);
  172.                     fill(in, buf, 2);
  173.                     if(buf[1]==0)
  174.                     {
  175.                         check=true;
  176.                     }
  177.                     break;
  178.                 default:
  179.             }

  180.             if(!check)
  181.             {
  182.                 try
  183.                 {
  184.                     socket.close();
  185.                 }
  186.                 catch(Exception eee)
  187.                 {
  188.                 }
  189.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS5,
  190.                     "fail in SOCKS5 proxy");
  191.             }

  192. /*
  193.       The SOCKS request is formed as follows:

  194.         +----+-----+-------+------+----------+----------+
  195.         |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
  196.         +----+-----+-------+------+----------+----------+
  197.         | 1  |  1  | X'00' |  1   | Variable |    2     |
  198.         +----+-----+-------+------+----------+----------+

  199.       Where:

  200.       o  VER    protocol version: X'05'
  201.       o  CMD
  202.          o  CONNECT X'01'
  203.          o  BIND X'02'
  204.          o  UDP ASSOCIATE X'03'
  205.       o  RSV    RESERVED
  206.          o  ATYP   address type of following address
  207.          o  IP V4 address: X'01'
  208.          o  DOMAINNAME: X'03'
  209.          o  IP V6 address: X'04'
  210.       o  DST.ADDR       desired destination address
  211.       o  DST.PORT desired destination port in network octet
  212.          order
  213. */
  214.      
  215.             index=0;
  216.             buf[index++]=5;
  217.             buf[index++]=1;       // CONNECT
  218.             buf[index++]=0;

  219.             byte[] hostb=host.getBytes();
  220.             int len=hostb.length;
  221.             buf[index++]=3;      // DOMAINNAME
  222.             buf[index++]=(byte)(len);
  223.             System.arraycopy(hostb, 0, buf, index, len);
  224.             index+=len;
  225.             buf[index++]=(byte)(port>>>8);
  226.             buf[index++]=(byte)(port&0xff);

  227.             out.write(buf, 0, index);

  228. /*
  229.    The SOCKS request information is sent by the client as soon as it has
  230.    established a connection to the SOCKS server, and completed the
  231.    authentication negotiations.  The server evaluates the request, and
  232.    returns a reply formed as follows:

  233.         +----+-----+-------+------+----------+----------+
  234.         |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
  235.         +----+-----+-------+------+----------+----------+
  236.         | 1  |  1  | X'00' |  1   | Variable |    2     |
  237.         +----+-----+-------+------+----------+----------+

  238.    Where:

  239.    o  VER    protocol version: X'05'
  240.    o  REP    Reply field:
  241.       o  X'00' succeeded
  242.       o  X'01' general SOCKS server failure
  243.       o  X'02' connection not allowed by ruleset
  244.       o  X'03' Network unreachable
  245.       o  X'04' Host unreachable
  246.       o  X'05' XMPPConnection refused
  247.       o  X'06' TTL expired
  248.       o  X'07' Command not supported
  249.       o  X'08' Address type not supported
  250.       o  X'09' to X'FF' unassigned
  251.     o  RSV    RESERVED
  252.     o  ATYP   address type of following address
  253.       o  IP V4 address: X'01'
  254.       o  DOMAINNAME: X'03'
  255.       o  IP V6 address: X'04'
  256.     o  BND.ADDR       server bound address
  257.     o  BND.PORT       server bound port in network octet order
  258. */

  259.       //in.read(buf, 0, 4);
  260.             fill(in, buf, 4);

  261.             if(buf[1]!=0)
  262.             {
  263.                 try
  264.                 {
  265.                     socket.close();
  266.                 }
  267.                 catch(Exception eee)
  268.                 {
  269.                 }
  270.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS5,
  271.                     "server returns "+buf[1]);
  272.             }

  273.             switch(buf[3]&0xff)
  274.             {
  275.                 case 1:
  276.                     //in.read(buf, 0, 6);
  277.                     fill(in, buf, 6);
  278.                     break;
  279.                 case 3:
  280.                     //in.read(buf, 0, 1);
  281.                     fill(in, buf, 1);
  282.                     //in.read(buf, 0, buf[0]+2);
  283.                     fill(in, buf, (buf[0]&0xff)+2);
  284.                     break;
  285.                 case 4:
  286.                     //in.read(buf, 0, 18);
  287.                     fill(in, buf, 18);
  288.                     break;
  289.                 default:
  290.             }
  291.             return socket;
  292.            
  293.         }
  294.         catch(RuntimeException e)
  295.         {
  296.             throw e;
  297.         }
  298.         catch(Exception e)
  299.         {
  300.             try
  301.             {
  302.                 if(socket!=null)
  303.                 {
  304.                     socket.close();
  305.                 }
  306.             }
  307.             catch(Exception eee)
  308.             {
  309.             }
  310.             String message="ProxySOCKS5: "+e.toString();
  311.             if(e instanceof Throwable)
  312.             {
  313.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS5,message,
  314.                     (Throwable)e);
  315.             }
  316.             throw new IOException(message);
  317.         }
  318.     }
  319.    
  320.     private void fill(InputStream in, byte[] buf, int len)
  321.       throws IOException
  322.     {
  323.         int s=0;
  324.         while(s<len)
  325.         {
  326.             int i=in.read(buf, s, len-s);
  327.             if(i<=0)
  328.             {
  329.                 throw new ProxyException(ProxyInfo.ProxyType.SOCKS5, "stream " +
  330.                     "is closed");
  331.             }
  332.             s+=i;
  333.         }
  334.     }
  335. }