B
    ì2;Z~  ã            	   @   sX  d Z ddlmZ ddlmZ ddlmZmZmZ ddl	Z	ddl
mZ ddlZddlZddlmZ ddlZddlZddlZdZejd	krºejd
k rºyddlZW n ek
r¸   edƒ‚Y nX e e¡Zd ZZd ZZd ZZeeedœZ e!e"e  #¡ e  $¡ ƒƒZ%ej Z&Z'dd„ Z(G dd„ de)ƒZ*G dd„ de*ƒZ+G dd„ de*ƒZ,G dd„ de*ƒZ-G dd„ de*ƒZ.G dd„ de*ƒZ/G dd„ de*ƒZ0d d!d"d#œZ1d$d%d&d'd(d)d*d+d,œZ2ed-ed-ed.iZ3dAd0d1„Z4d2d3„ Z5d4d5„ Z6e6Z7d6d7„ Z8e8Z9dBd8d9„Z:G d:d;„ d;ejƒZ;d<d=„ Z<xBd>D ]:Ze=e;edƒZ>e?e>eƒse;j@ Ae¡ eBe;ee<eƒƒ qW G d?d@„ d@e;ƒZCdS )CaŠ
  SocksiPy - Python SOCKS module.

Copyright 2006 Dan-Haim. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of Dan Haim nor the names of his contributors may be used
   to endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.

===============================================================================

Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)

Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge

Modifications made by Anorov (https://github.com/Anorov)
-Forked and renamed to PySocks
-Fixed issue with HTTP proxy failure checking (same bug that was in the
 old ___recvall() method)
-Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler,
 courtesy of e000 (https://github.com/e000):
 https://gist.github.com/869791#file_socksipyhandler.py
-Re-styled code to make it readable
    -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
    -Improved exception handling and output
    -Removed irritating use of sequence indexes, replaced with tuple unpacked
     variables
    -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b""
    -Other general fixes
-Added clarification that the HTTP proxy connection method only supports
 CONNECT-style tunneling HTTP proxies
-Various small bug fixes
é    )Ú	b64encode)ÚCallable)Ú
EOPNOTSUPPÚEINVALÚEAGAINN)ÚBytesIO)ÚSEEK_CURz1.6.7Únt)é   r   z8To run PySocks on Windows you must install win_inet_ptoné   é   r
   )ÚSOCKS4ÚSOCKS5ÚHTTPc                s   t  ˆ ¡‡ fdd„ƒ}|S )Nc           
      sp   | d }zNy$|  ¡ }|dkr&| d¡ ˆ | |ŽS  tk
rR } z‚ W d d }~X Y nX W d |dkrj| d¡ X d S )Nr   TF)Ú
gettimeoutÚsetblockingÚ	Exception)ÚargsÚkwargsÚselfZ_is_blockingÚe)Úfunction© ú$lib/python3.7/site-packages/socks.pyÚwrapper]   s    

z"set_self_blocking.<locals>.wrapper)Ú	functoolsÚwraps)r   r   r   )r   r   Úset_self_blocking[   s    r   c               @   s"   e Zd ZdZddd„Zdd„ ZdS )Ú
ProxyErrorz4Socket_err contains original socket.error exception.Nc             C   s(   || _ || _|r$|  j d |¡7  _ d S )Nz: {0})ÚmsgÚ
socket_errÚformat)r   r   r    r   r   r   Ú__init__p   s    zProxyError.__init__c             C   s   | j S )N)r   )r   r   r   r   Ú__str__w   s    zProxyError.__str__)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   r#   r   r   r   r   r   n   s   
r   c               @   s   e Zd ZdS )ÚGeneralProxyErrorN)r$   r%   r&   r   r   r   r   r(   {   s   r(   c               @   s   e Zd ZdS )ÚProxyConnectionErrorN)r$   r%   r&   r   r   r   r   r)      s   r)   c               @   s   e Zd ZdS )ÚSOCKS5AuthErrorN)r$   r%   r&   r   r   r   r   r*   ƒ   s   r*   c               @   s   e Zd ZdS )ÚSOCKS5ErrorN)r$   r%   r&   r   r   r   r   r+   ‡   s   r+   c               @   s   e Zd ZdS )ÚSOCKS4ErrorN)r$   r%   r&   r   r   r   r   r,   ‹   s   r,   c               @   s   e Zd ZdS )Ú	HTTPErrorN)r$   r%   r&   r   r   r   r   r-      s   r-   zRequest rejected or failedzLRequest rejected because SOCKS server cannot connect to identd on the clientzPRequest rejected because the client program and identd report different user-ids)é[   é\   é]   zGeneral SOCKS server failurez!Connection not allowed by rulesetzNetwork unreachablezHost unreachablezConnection refusedzTTL expiredz(Command not supported, or protocol errorzAddress type not supported)r   r   r
   é   é   é   é   é   i8  i  Tc             C   s.   | ||||r|  ¡ nd|r"|  ¡ ndft_dS )z›Sets a default proxy.

    All further socksocket objects will use the default unless explicitly
    changed. All parameters are as for socket.set_proxy().N)ÚencodeÚ
socksocketÚdefault_proxy)Ú
proxy_typeÚaddrÚportÚrdnsÚusernameÚpasswordr   r   r   Úset_default_proxy¨   s    r?   c              O   s    d|kr|  d¡|d< t| |ŽS )NÚ	proxytyper9   )Úpopr?   )r   r   r   r   r   Úsetdefaultproxy³   s    rB   c               C   s   t jS )z4Returns the default proxy, set by set_default_proxy.)r7   r8   r   r   r   r   Úget_default_proxy¹   s    rC   c             C   s   t jrt | j_ntdƒ‚dS )a  Attempts to replace a module's socket library with a SOCKS socket.

    Must set a default proxy using set_default_proxy(...) first. This will
    only work on modules that import socket directly into the namespace;
    most of the Python Standard Library falls into this category.zNo default proxy specifiedN)r7   r8   Úsocketr(   )Úmoduler   r   r   Úwrap_moduleÀ   s    
rF   c
             C   s8  | \}
}|
  d¡r|
 d¡}
|r4|  d¡r4| d¡}d}xæt ||dtj¡D ]Ð}|\}}}}}d}yxt|||ƒ}|	rŒx|	D ]}|j|Ž  qzW t|tt	fƒr¤| 
|¡ |r¼| ||||||¡ |rÊ| |¡ | |
|f¡ |S  tjtfk
r } z|}|r
| ¡  d}W dd}~X Y qLX qLW |r*|‚t d¡‚dS )aí  create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object

    Like socket.create_connection(), but connects to proxy
    before returning the socket object.

    dest_pair - 2-tuple of (IP/hostname, port).
    **proxy_args - Same args passed to socksocket.set_proxy() if present.
    timeout - Optional socket timeout value, in seconds.
    source_address - tuple (host, port) for the socket to bind to as its source
    address before connecting (only for compatibility)
    ú[z[]Nr   zgai returned empty list.)Ú
startswithÚstriprD   ÚgetaddrinfoÚSOCK_STREAMr7   Z
setsockoptÚ
isinstanceÚintÚfloatÚ
settimeoutÚ	set_proxyÚbindÚconnectÚerrorr)   Úclose)Ú	dest_pairÚtimeoutZsource_addressr9   Ú
proxy_addrÚ
proxy_portZ
proxy_rdnsZproxy_usernameZproxy_passwordZsocket_optionsZremote_hostZremote_portÚerrÚrÚfamilyZsocket_typeÚprotoZ	canonnameZsaZsockZoptr   r   r   r   Úcreate_connectionÎ   s>    





r]   c               @   s   e Zd ZdZdd„ Zeƒ ZdS )Ú_BaseSocketzBAllows Python 2 delegated methods such as send() to be overridden.c             O   sH   t j| f|ž|Ž tƒ | _x(| jD ]}t| |ƒ| j|< t| |ƒ q"W d S )N)Ú_orig_socketr"   ÚdictÚ_savedmethodsÚ
_savenamesÚgetattrÚdelattr)r   ÚposÚkwÚnamer   r   r   r"     s
    z_BaseSocket.__init__N)r$   r%   r&   r'   r"   Úlistrb   r   r   r   r   r^     s   r^   c                s   ‡ fdd„S )Nc                s   | j ˆ  ||ŽS )N)ra   )r   re   rf   )rg   r   r   Ú<lambda>  s    z_makemethod.<locals>.<lambda>r   )rg   r   )rg   r   Ú_makemethod  s    rj   )ÚsendtoÚsendÚrecvfromÚrecvc                   s.  e Zd ZdZdZejejdf‡ fdd„	Zdd„ Z	‡ fdd	„Z
d
d„ Zdd„ Zd5dd„Zdd„ Z‡ fdd„Z‡ fdd„Zd6‡ fdd„	Zd7‡ fdd„	Zdd„ Z‡ fdd„Zdd „ ZeZd!d"„ ZeZd#d$„ ZeZd%d&„ Z‡ fd'd(„Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Z e!ee"ee#e iZ$e%‡ fd1d2„ƒZ&d3d4„ Z'‡  Z(S )8r7   a2  socksocket([family[, type[, proto]]]) -> socket object

    Open a SOCKS enabled socket. The parameters are the same as
    those of the standard socket init. In order for SOCKS to work,
    you must specify family=AF_INET and proto=0.
    The "type" argument must be either SOCK_STREAM or SOCK_DGRAM.
    Nr   c                sp   |t jt jfkr"d}t| |¡ƒ‚tt| ƒj|||f|ž|Ž d | _| j	rT| j	| _
nd| _
d | _d | _d | _d S )Nz0Socket type must be stream or datagram, not {!r})NNNNNN)rD   rK   Ú
SOCK_DGRAMÚ
ValueErrorr!   Úsuperr7   r"   Ú
_proxyconnr8   ÚproxyÚproxy_socknameÚproxy_peernameÚ_timeout)r   r[   Útyper\   r   r   r   )Ú	__class__r   r   r"   1  s    
zsocksocket.__init__c             C   s@   d}x6t |ƒ|k r:| |t |ƒ ¡}|s0tdƒ‚||7 }qW |S )zŠReceive EXACTLY the number of bytes requested from the file object.

        Blocks until the required number of bytes have been received.ó    zConnection closed unexpectedly)ÚlenÚreadr(   )r   ÚfileÚcountÚdataÚdr   r   r   Ú_readallC  s    zsocksocket._readallc                s@   || _ y|  ¡ }tt| ƒ | j ¡ W n tjk
r:   Y nX d S )N)rv   Úget_proxy_peernamerq   r7   rO   rD   rS   )r   rV   Zpeer)rx   r   r   rO   O  s    zsocksocket.settimeoutc             C   s   | j S )N)rv   )r   r   r   r   r   X  s    zsocksocket.gettimeoutc             C   s   |r|   d ¡ n
|   d¡ d S )Ng        )rO   )r   Úvr   r   r   r   [  s    zsocksocket.setblockingTc             C   s.   |||||r|  ¡ nd|r"|  ¡ ndf| _dS )a   Sets the proxy to be used.

        proxy_type -  The type of the proxy to be used. Three types
                        are supported: PROXY_TYPE_SOCKS4 (including socks4a),
                        PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
        addr -        The address of the server (IP or DNS).
        port -        The port of the server. Defaults to 1080 for SOCKS
                        servers and 8080 for HTTP proxy servers.
        rdns -        Should DNS queries be performed on the remote side
                       (rather than the local side). The default is True.
                       Note: This has no effect with SOCKS4 servers.
        username -    Username to authenticate with to the server.
                       The default is no authentication.
        password -    Password to authenticate with to the server.
                       Only relevant when username is also provided.N)r6   rs   )r   r9   r:   r;   r<   r=   r>   r   r   r   rP   a  s    zsocksocket.set_proxyc             O   s"   d|kr|  d¡|d< | j||ŽS )Nr@   r9   )rA   rP   )r   r   r   r   r   r   Úsetproxyv  s    zsocksocket.setproxyc                sø   | j \}}}}}}|r"| jtjkr4tj| f|ž|ŽS | jrFt td¡‚|t	kr^d}	t t
|	¡‚tt| ƒj||Ž |  ¡ \}
}d|f}tƒ | _|  ¡ }| j |¡ d}|  | j||¡\}
}|\}}
|\}
}tt| ƒ ||f¡ tt| ƒ | j¡ d| _dS )zVImplements proxy connection for UDP sockets.

        Happens during the bind() phase.z"Socket already bound to an addressz'UDP only supported by SOCKS5 proxy typeÚ0ó   )z0.0.0.0r   N)rs   rw   rD   ro   r_   rQ   rr   rS   r   r   r   rq   r7   ZgetsocknameÚ_proxy_addrrR   Ú_SOCKS5_requestrO   rv   rt   )r   re   rf   r9   rW   rX   r<   r=   r>   r   Ú_r;   Údstrs   ZUDP_ASSOCIATEZrelayÚhost)rx   r   r   rQ   {  s*    zsocksocket.bindc       
         s¢   | j tjkr$tt| ƒj|f|ž|ŽS | js4|  d¡ |d }|d d… }tƒ }d}| 	|¡ d}| 	|¡ |  
||¡ tt| ƒj| ¡ | f|ž|Ž}	|	| ¡  S )N)Ú r   éÿÿÿÿs     ó    )rw   rD   ro   rq   r7   rk   rr   rQ   r   ÚwriteÚ_write_SOCKS5_addressrl   ÚgetvalueÚtell)
r   Úbytesr   r   ZaddressÚflagsÚheaderZRSVZ
STANDALONEZsent)rx   r   r   rk      s    


zsocksocket.sendtoc                s:   | j tjkr | j||| jf|ŽS tt| ƒj||f|ŽS d S )N)rw   rD   ro   rk   ru   rq   r7   rl   )r   r’   r“   r   )rx   r   r   rl   ´  s    zsocksocket.sendc       	         s¾   | j tjkrtt| ƒ ||¡S | js.|  d¡ ttt| ƒ 	|d |¡ƒ}| 
dt¡ | d¡}t|ƒrntdƒ‚|  |¡\}}| jr¬| j\}}||ks |d|fkr¬t td¡‚| |¡||ffS )N)r‹   r   i   r   r   zReceived UDP packet fragmentr   zPacket filtered)rw   rD   ro   rq   r7   rm   rr   rQ   r   rn   Úseekr   r{   ÚordÚNotImplementedErrorÚ_read_SOCKS5_addressru   rS   r   )	r   Úbufsizer“   ZbufZfragZfromhostZfromportZpeerhostZpeerport)rx   r   r   rm   º  s    


zsocksocket.recvfromc             O   s   | j ||Ž\}}|S )N)rm   )r   re   rf   r’   rˆ   r   r   r   rn   Î  s    zsocksocket.recvc                s   | j r| j  ¡  tt| ƒ ¡ S )N)rr   rT   rq   r7   )r   )rx   r   r   rT   Ò  s    
zsocksocket.closec             C   s   | j S )z:Returns the bound IP address and port number at the proxy.)rt   )r   r   r   r   Úget_proxy_sockname×  s    zsocksocket.get_proxy_socknamec             C   s   |   ¡ S )z>
        Returns the IP and port number of the proxy.
        )Úgetpeername)r   r   r   r   r   Ý  s    zsocksocket.get_proxy_peernamec             C   s   | j S )zwReturns the IP address and port number of the destination machine.

        Note: get_proxy_peername returns the proxy.)ru   )r   r   r   r   Úget_peernameå  s    zsocksocket.get_peernamec             G   s   d}|   | ||¡\| _| _dS )z7Negotiates a stream connection through a SOCKS5 server.ó   N)r‡   ru   rt   )r   Ú	dest_addrZCONNECTr   r   r   Ú_negotiate_SOCKS5í  s    zsocksocket._negotiate_SOCKS5c                sð  | j \}}}}}}	| d¡}
| dd¡}z®|r@|	r@|
 d¡ n
|
 d¡ |
 ¡  |  |d¡}|dd… dkrvtd	ƒ‚|dd… d
krþ|
 dtt|ƒƒ ¡  | tt|	ƒƒ ¡  |	 ¡ |
 ¡  |  |d¡}|dd… dkrätd	ƒ‚|dd… dkrüt	dƒ‚n6|dd… dkr4|dd… dkr,t	dƒ‚ntd	ƒ‚|
 d| d ¡ |  
||
¡}|
 ¡  |  |d¡}|dd… dkr€td	ƒ‚t|dd… ƒ}|dkr¶t |d¡}td ||¡ƒ‚|  |¡}tt| ƒ | j¡ ||fS | ¡  |
 ¡  X dS )z‘
        Send SOCKS5 request with given command (CMD field) and
        address (DST field). Returns resolved DST address that was used.
        ÚwbÚrbr   s    s    r   r   ó   z%SOCKS5 proxy server sent invalid dataó   r   r   zSOCKS5 authentication failedó   ÿz7All offered SOCKS5 authentication methods were rejectedr
   zUnknown errorz{0:#04x}: {1}N)rs   ÚmakefilerŽ   Úflushr€   r(   Úchrrz   r6   r*   r   r–   ÚSOCKS5_ERRORSÚgetr+   r!   r˜   rq   r7   rO   rv   rT   )r   ZconnÚcmdr‰   r9   r:   r;   r<   r=   r>   ÚwriterÚreaderZchosen_authZauth_statusZresolvedÚrespÚstatusrS   Zbnd)rx   r   r   r‡   ó  sX    

.


zsocksocket._SOCKS5_requestc          	   C   sH  |\}}| j \}}}}}}	tjdtjdi}
xrtjtjfD ]b}yDt ||¡}| |
| | ¡ t ||¡}| t d|¡¡ ||fS  tj	k
r˜   w8Y q8X q8W |rÌ| 
d¡}| dtt|ƒƒ 
¡  | ¡ nbt ||tjtjtjtj¡}|d }|d }|d d }t ||¡}| |
| | ¡ t ||¡}| t d|¡¡ ||fS )z~
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        r   ó   z>HÚidnar…   r   r1   )rs   rD   ÚAF_INETÚAF_INET6Z	inet_ptonrŽ   Ú	inet_ntopÚstructÚpackrS   r6   r§   rz   rJ   Z	AF_UNSPECrK   ZIPPROTO_TCPZAI_ADDRCONFIG)r   r:   r|   rŠ   r;   r9   rˆ   r<   r=   r>   Zfamily_to_byter[   Ú
addr_bytesZ
host_bytesZ	addressesZtarget_addrr   r   r   r   M  s6    
 z socksocket._write_SOCKS5_addressc             C   s–   |   |d¡}|dkr(t |   |d¡¡}nN|dkrN|   |d¡}|   |t|ƒ¡}n(|dkrnt tj|   |d¡¡}ntdƒ‚t d|   |d	¡¡d
 }||fS )Nr   r   r1   r…   r¯   é   z%SOCKS5 proxy server sent invalid dataz>Hr   r   )	r€   rD   Ú	inet_ntoar–   r³   r²   r(   r´   Úunpack)r   r|   Zatypr:   Úlengthr;   r   r   r   r˜   z  s    zsocksocket._read_SOCKS5_addressc             C   sŽ  | j \}}}}}}|  d¡}	|  dd¡}
zLd}yt |¡}W n4 tjk
rr   |r^d}d}nt t |¡¡}Y nX |	 t ddd	|¡¡ |	 |¡ |r¢|	 |¡ |	 d
¡ |rÄ|	 | 	d¡d
 ¡ |	 
¡  |  |
d¡}|dd	… d
krðtdƒ‚t|d	d… ƒ}|dkr&t |d¡}td ||¡ƒ‚t |dd… ¡t d|dd… ¡d f| _|rjt |¡|f| _n
||f| _W d|
 ¡  |	 ¡  X dS )z0Negotiates a connection through a SOCKS4 server.r    r¡   r   Fs      Tz>BBHr1   r   r   r°   r5   z%SOCKS4 proxy server sent invalid datar   éZ   zUnknown errorz{0:#04x}: {1}Nz>H)rs   r¥   rD   Z	inet_atonrS   ÚgethostbynamerŽ   r´   rµ   r6   r¦   r€   r(   r–   ÚSOCKS4_ERRORSr©   r,   r!   r¸   r¹   rt   ru   rT   )r   rž   Ú	dest_portr9   r:   r;   r<   r=   r>   r«   r¬   Zremote_resolver¶   r­   r®   rS   r   r   r   Ú_negotiate_SOCKS4‰  sH    




zsocksocket._negotiate_SOCKS4c             C   sj  | j \}}}}}}|r|nt |¡}d| d¡ d t|ƒ ¡  d d| d¡ g}	|rv|rv|	 dt|d | ƒ ¡ |	 d¡ |  d |	¡¡ |  	¡ }
|
 
¡ }|
 ¡  |s´tdƒ‚y| d	d
¡\}}}W n tk
ræ   tdƒ‚Y nX | d¡sútdƒ‚yt|ƒ}W n tk
r$   tdƒ‚Y nX |dkrVd ||¡}|dkrN|d7 }t|ƒ‚d| _||f| _dS )zwNegotiates a connection through an HTTP server.

        NOTE: This currently only supports HTTP CONNECT-style proxies.s   CONNECT r°   ó   :s	    HTTP/1.1s   Host: s   Proxy-Authorization: basic s   
zConnection closed unexpectedlyú r   z'HTTP proxy server sent invalid responsezHTTP/z0Proxy server does not appear to be an HTTP proxyz4HTTP proxy server did not return a valid HTTP statuséÈ   z{0}: {1})i  i“  i•  za
[*] Note: The HTTP proxy server may not be supported by PySocks (must be a CONNECT tunnel proxy))s   0.0.0.0r   N)rs   rD   r¼   r6   ÚstrÚappendr   ZsendallÚjoinr¥   ÚreadlinerT   r(   Úsplitrp   rH   rM   r-   r!   rt   ru   )r   rž   r¾   r9   r:   r;   r<   r=   r>   Zhttp_headersZfobjZstatus_liner\   Zstatus_codeZ
status_msgrS   r   r   r   Ú_negotiate_HTTPÅ  sB     



zsocksocket._negotiate_HTTPc          
      s  t |ƒdks|d  d¡r,t dt|ƒ ¡‚|\}}| jtjkr|| jsP|  d¡ t 	|¡}|dkrn|snd| _
n
||f| _
dS | j\}}}}}}	t|ttfƒr¶t |ƒdks¶|r¶t|tƒs¾tdƒ‚tt| ƒ | j¡ |dkr
|| _
tt| ƒ | j¡ tt| ƒ ||f¡ dS |  ¡ }ytt| ƒ |¡ W nn tjk
r” }
 zL|  ¡  |\}}d	 ||¡}t| }d
 ||¡}t d||
¡ t||
ƒ‚W dd}
~
X Y ntX y| j| }|| ||ƒ W nV tjk
rè }
 z|  ¡  td|
ƒ‚W dd}
~
X Y n  tk
r   |  ¡  ‚ Y nX dS )zã
        Connects to the specified destination through a proxy.
        Uses the same API as socket's connect().
        To select the proxy server, use set_proxy().

        dest_pair - 2-tuple of (IP/hostname, port).
        r   r   rG   z PySocks doesn't support IPv6: %s)r‹   r   z0.0.0.0Nz0Invalid destination-connection (host, port) pairz{0}:{1}z!Error connecting to {0} proxy {1}z%s due to: %szSocket error)rz   rH   rD   rS   rÃ   rw   ro   rr   rQ   r¼   ru   rs   rL   rh   ÚtuplerM   r(   rq   r7   rO   rv   rR   r†   rT   r!   ÚPRINTABLE_PROXY_TYPESÚlogÚdebugr)   Ú_proxy_negotiatorsr   )r   rU   rž   r¾   r9   rW   rX   r<   r=   r>   rS   Zproxy_serverZprintable_typer   Z	negotiate)rx   r   r   rR     s\    	





zsocksocket.connectc             C   s4   | j \}}}}}}|pt |¡}|s,tdƒ‚||fS )zD
        Return proxy address to connect to as tuple object
        zInvalid proxy type)rs   ÚDEFAULT_PORTSr©   r(   )r   r9   rW   rX   r<   r=   r>   r   r   r   r†   ]  s
    zsocksocket._proxy_addr)NNNTNN)r   )r   ))r$   r%   r&   r'   r8   rD   r±   rK   r"   r€   rO   r   r   rP   rƒ   rQ   rk   rl   rm   rn   rT   rš   Zgetproxysocknamer   Zgetproxypeernamerœ   r›   rŸ   r‡   r   r˜   r¿   rÈ   r   r   r   rÍ   r   rR   r†   Ú__classcell__r   r   )rx   r   r7   &  sD   	 
%Z-<<Wr7   )NNNTNN)	NNNNNTNNN)Dr'   Úbase64r   Úcollectionsr   Úerrnor   r   r   r   Úior   ZloggingÚosr   rD   r´   ÚsysÚ__version__rg   Úversion_infoZwin_inet_ptonÚImportErrorZ	getLoggerr$   rË   ZPROXY_TYPE_SOCKS4r   ZPROXY_TYPE_SOCKS5r   ZPROXY_TYPE_HTTPr   ZPROXY_TYPESr`   ÚzipÚvaluesÚkeysrÊ   Z
_orgsocketr_   r   ÚIOErrorr   r(   r)   r*   r+   r,   r-   r½   r¨   rÎ   r?   rB   rC   ZgetdefaultproxyrF   Z
wrapmoduler]   r^   rj   rc   ÚmethodrL   rb   rÄ   Úsetattrr7   r   r   r   r   Ú<module>7   s‚   

 

    
8
