
    e              	          d Z ddlmZ ddlZej                  rddlZn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j0                  d	k  r	 ddlZ ej6                  e      ZdxZZdxZ Z!dxZ"Z#ee!e#dZ$ e% e&e$jO                         e$jQ                                     Z)ej&                  xZ*Z+d Z, G d de-      Z. G d de.      Z/ G d de.      Z0 G d de.      Z1 G d de.      Z2 G d de.      Z3 G d de.      Z4ddd d!Z5d"d#d$d%d&d'd(d)d*Z6ed+e!d+e#d,iZ7	 	 d8d-Z8d. Z9d/ Z:e:Z;d0 Z<e<Z=	 	 	 	 	 d9d1Z> G d2 d3ej&                        Z?d4 Z@d5D ]K  Z eAe?ed      ZB eCeBej                        r!e?j                  j                  e        eGe?e e@e             M  G d6 d7e?      ZHy# e$ r	  ed
      w xY w):a
  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
    )	b64encodeN)
EOPNOTSUPPEINVALEAGAIN)BytesIO)SEEK_CURz1.6.7nt)   r   z8To run PySocks on Windows you must install win_inet_pton      r
   )SOCKS4SOCKS5HTTPc                 B     t        j                          fd       }|S )Nc                      | d   }	 |j                         }|dk(  r|j                  d        | i ||dk(  r|j                  d       S S # t        $ r} d }~ww xY w# dk(  r|j                  d       w w xY w)Nr   TF)
gettimeoutsetblocking	Exception)argskwargsself_is_blockingefunctions        )platform/bq/third_party/socks/__init__.pywrapperz"set_self_blocking.<locals>.wrapperf   s    Aw
	(??,Lq   &T,V,
 q   ' !	  		 q   ' !s#   -A 	AAAA A8)	functoolswraps)r   r   s   ` r   set_self_blockingr   d   s%    __X( ( N    c                       e Zd ZdZddZd Zy)
ProxyErrorz4Socket_err contains original socket.error exception.Nc                 n    || _         || _        |r%| xj                   dj                  |      z  c_         y y )Nz: {0})msg
socket_errformat)r   r$   r%   s      r   __init__zProxyError.__init__y   s/    $HHz22H r    c                     | j                   S N)r$   r   s    r   __str__zProxyError.__str__   s    xxr    r)   )__name__
__module____qualname____doc__r'   r+    r    r   r"   r"   w   s    >3r    r"   c                       e Zd Zy)GeneralProxyErrorNr,   r-   r.   r0   r    r   r2   r2          r    r2   c                       e Zd Zy)ProxyConnectionErrorNr3   r0   r    r   r6   r6      r4   r    r6   c                       e Zd Zy)SOCKS5AuthErrorNr3   r0   r    r   r8   r8      r4   r    r8   c                       e Zd Zy)SOCKS5ErrorNr3   r0   r    r   r:   r:      r4   r    r:   c                       e Zd Zy)SOCKS4ErrorNr3   r0   r    r   r<   r<      r4   r    r<   c                       e Zd Zy)	HTTPErrorNr3   r0   r    r   r>   r>      r4   r    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  c                     t        |d      r|j                         }t        |d      r|j                         }| ||||r|nd|r|ft        _        ydft        _        y)zSets a default proxy.

    All further socksocket objects will use the default unless explicitly
    changed. All parameters are as for socket.set_proxy().encodeN)hasattrrH   
socksocketdefault_proxy)
proxy_typeaddrportrdnsusernamepasswords         r   set_default_proxyrR      s^     x""hx""h *D$,4$,4 @J:> @Jr    c                  H    d|v r|j                  d      |d<   t        | i |S N	proxytyperL   )poprR   )r   r   s     r   setdefaultproxyrW      s-    f%zz+6|d-f--r    c                  "    t         j                  S )z4Returns the default proxy, set by set_default_proxy.)rJ   rK   r0   r    r   get_default_proxyrY      s    ###r    c                 d    t         j                  rt         | j                  _        yt        d      )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)rJ   rK   socketr2   )modules    r   wrap_moduler]      s%     ) <==r    c
           	         | \  }
}|
j                  d      r|
j                  d      }
|r"|j                  d      r|j                  d      }d}t        j                  ||dt        j                        D ]  }|\  }}}}}d}	 t        |||      }|	r|	D ]  } |j                  |   t        |t        t        f      r|j                  |       |r|j                  ||||||       |r|j                  |       |j                  |
|f       |c S  |r|t        j                  d      # t        j                  t        f$ r }|}|r|j!                          d}Y d}~d}~ww xY w)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stripr[   getaddrinfoSOCK_STREAMrJ   
setsockopt
isinstanceintfloat
settimeout	set_proxybindconnecterrorr6   close)	dest_pairtimeoutsource_addressrL   
proxy_addr
proxy_port
proxy_rdnsproxy_usernameproxy_passwordsocket_optionsremote_hostremote_porterrrfamilysocket_typeproto	canonnamesasockoptr   s                         r   create_connectionr      sb   $  )Kc"!''-j++C0%%d+

C 
J6;M;MN451UIr	fk59D)C#DOOS) * 'C<0(z:z:-~?		.)LL+{34K) O8 	
,,1
22 23 	C

		s   BD**E#EE#c                   $    e Zd ZdZd Z e       Zy)_BaseSocketzBAllows Python 2 delegated methods such as send() to be overridden.c                     t        j                  | g|i | t               | _        | j                  D ]'  }t        | |      | j                  |<   t        | |       ) y r)   )_orig_socketr'   dict_savedmethods
_savenamesgetattrdelattrr   poskwnames       r   r'   z_BaseSocket.__init__  sS    d/S/B/!VOOD'.tT':Dt$D$ $r    N)r,   r-   r.   r/   r'   listr   r0   r    r   r   r     s    L  Jr    r   c                       fdS )Nc                 .     | j                      |i |S r)   )r   r   s      r   <lambda>z_makemethod.<locals>.<lambda>&  s    $<D$6$6t$<c$HR$Hr    r0   )r   s   `r   _makemethodr   %  s	    HHr    )sendtosendrecvfromrecvc                   0    e Zd ZdZdZej                  ej                  df fd	Zd Z	 fdZ
d Zd Z	 	 dd	Zd
 Z fdZ fdZd fd	Zd fd	Zd Z fdZd ZeZd ZeZd ZeZd Z fdZd Zd Zd Zd Z e!ee"ee#e iZ$e% fd       Z&d Z' xZ(S )rJ   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                 6   |t         j                  t         j                  fvrd}t        |j	                  |            t        t        |   |||g|i | d | _        | j                  r| j                  | _
        nd| _
        d | _        d | _        d | _        y )Nz0Socket type must be stream or datagram, not {!r})NNNNNN)r[   rc   
SOCK_DGRAM
ValueErrorr&   superrJ   r'   
_proxyconnrK   proxyproxy_socknameproxy_peername_timeout)r   r{   typer}   r   r   r$   	__class__s          r   r'   zsocksocket.__init__>  s    **F,=,=>>DCSZZ-..j$(uNtNvN++DJ=DJ""r    c                     d}t        |      |k  r>|j                  |t        |      z
        }|st        d      ||z  }t        |      |k  r>|S )zReceive EXACTLY the number of bytes requested from the file object.

        Blocks until the required number of bytes have been received.r    Connection closed unexpectedly)lenreadr2   )r   filecountdatads        r   _readallzsocksocket._readallP  sY     $i%		%#d)+,A'(HIIAID	 $i%
 r    c                     || _         	 | j                         }t        t        |   | j                          y # t
        j                  $ r Y y w xY wr)   )r   get_proxy_peernamer   rJ   rh   r[   rl   )r   ro   peerr   s      r   rh   zsocksocket.settimeout\  sF    	**,D*d.t}}=|| 		s   -8 AAc                     | j                   S r)   )r   r*   s    r   r   zsocksocket.gettimeoute  s    }}r    c                 N    |r| j                  d        y | j                  d       y )Ng        )rh   )r   vs     r   r   zsocksocket.setblockingh  s    OOD!OOC r    c                     t        |d      r|j                         }t        |d      r|j                         }|||||r|nd|r	|f| _        ydf| _        y)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.rH   N)rI   rH   r   )r   rL   rM   rN   rO   rP   rQ   s          r   ri   zsocksocket.set_proxyn  sZ    " 8X&__&(8X&__&( $d"*h"*h6
046
r    c                 V    d|v r|j                  d      |d<    | j                  |i |S rT   )rV   ri   )r   r   r   s      r   setproxyzsocksocket.setproxy  s3    & #)::k#:F< t~~t.v..r    c                    | j                   \  }}}}}}|r| j                  t        j                  k7  rt	        j
                  | g|i |S | j                  rt        j                  t        d      |t        k7  rd}	t        j                  t        |	      t        t        |   |i | | j                         \  }
}d|f}t	               | _        | j                         }| j                  j                  |       d}| j!                  | j                  ||      \  }
}|\  }}
|\  }
}t        t        | ?  ||f       t        t        | G  | j$                         d| _        y)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   )0.0.0.0r   N)r   r   r[   r   r   rj   r   rl   r   r   r   r   rJ   getsockname_proxy_addrrk   _SOCKS5_requestrh   r   r   )r   r   r   rL   rq   rr   rO   rP   rQ   r$   _rN   dstr   UDP_ASSOCIATErelayhostr   s                    r   rj   zsocksocket.bind  sA   
 ZZ	ZT8	TYY&*;*;;$$T6C6266??,,v'KLL;C,,z3//j$$c0R0
 ""$4Dk&.  "&''L5 a4j$'t5j$*4==9,r    c                    | j                   t        j                  k7  rt        t        |   |g|i |S | j                  s| j                  d       |d   }|d d }t               }d}|j                  |       d}|j                  |       | j                  ||       t        t        | .  |j                         |z   g|i |}	|	|j                         z
  S )N r   s         )r   r[   r   r   rJ   r   r   rj   r   write_write_SOCKS5_addressr   getvaluetell)r   bytesr   r   addressflagsheaderRSV
STANDALONEsentr   s             r   r   zsocksocket.sendto  s    99)))T1%I$I&IIIIgr(Sb	S
Z ""7F3Z+FOO,=,E 6 6.46fkkm##r    c                     | j                   t        j                  k(  r | j                  ||| j                  fi |S t        t        |   ||fi |S r)   )r   r[   r   r   r   r   rJ   r   )r   r   r   r   r   s       r   r   zsocksocket.send  sN    99)))4;;ueT-@-@KFKKT/uGGGr    c                 ,   | j                   t        j                  k7  rt        t        |   ||      S | j                  s| j                  d       t        t        t        | '  |dz   |            }|j                  dt               |j                  d      }t        |      rt        d      | j                  |      \  }}| j                   r4| j                   \  }}||k7  s|d|fvrt        j"                  t$        d      |j                  |      ||ffS )Nr   i   r   r   zReceived UDP packet fragmentr   zPacket filtered)r   r[   r   r   rJ   r   r   rj   r   r   seekr   r   ordNotImplementedError_read_SOCKS5_addressr   rl   r   )
r   bufsizer   buffragfromhostfromportpeerhostpeerportr   s
            r   r   zsocksocket.recvfrom  s    99)))T3GUCCIIgeJ27T>5IJHxx{t9%&DEE!66s;(!%!4!4Hh8#x8}'Dll6+<==!Hh#788r    c                 0     | j                   |i |\  }}|S r)   )r   )r   r   r   r   r   s        r   r   zsocksocket.recv  s      4==#,,qr    c                 t    | j                   r| j                   j                          t        t        |          S r)   )r   rm   r   rJ   )r   r   s    r   rm   zsocksocket.close  s*    ??OO!!#Z,..r    c                     | j                   S )z:Returns the bound IP address and port number at the proxy.)r   r*   s    r   get_proxy_socknamezsocksocket.get_proxy_sockname  s    """r    c                 "    | j                         S )z>
        Returns the IP and port number of the proxy.
        )getpeernamer*   s    r   r   zsocksocket.get_proxy_peername  s     !!r    c                     | j                   S )zwReturns the IP address and port number of the destination machine.

        Note: get_proxy_peername returns the proxy.)r   r*   s    r   get_peernamezsocksocket.get_peername  s     """r    c                 H    d}| j                  | ||      \  | _        | _        y)z7Negotiates a stream connection through a SOCKS5 server.   N)r   r   r   )r   	dest_addrCONNECTs      r   _negotiate_SOCKS5zsocksocket._negotiate_SOCKS5  s)    373G3G'94&0T0r    c                    | j                   \  }}}}}}	|j                  d      }
|j                  dd      }	 |r|	r|
j                  d       n|
j                  d       |
j                          | j	                  |d      }|dd dk7  rt        d	      |dd d
k(  r|
j                  dt        t        |            j                         z   |z   t        t        |	            j                         z   |	z          |
j                          | j	                  |d      }|dd dk7  rt        d	      |dd dk7  r1t        d      |dd dk7  r|dd dk(  rt        d      t        d	      |
j                  d|z   dz          | j                  ||
      }|
j                          | j	                  |d      }|dd dk7  rt        d	      t        |dd       }|dk7  r1t        j                  |d      }t        dj                  ||            | j!                  |      }t"        t$        | O  | j(                         ||f|j+                          |
j+                          S # |j+                          |
j+                          w xY w)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      %SOCKS5 proxy server sent invalid data   r   r   zSOCKS5 authentication failed   z7All offered SOCKS5 authentication methods were rejectedr
   Unknown error{0:#04x}: {1})r   makefiler   flushr   r2   chrr   rH   r8   r   r   SOCKS5_ERRORSgetr:   r&   r   r   rJ   rh   r   rm   )r   conncmdr   rL   rM   rN   rO   rP   rQ   writerreaderchosen_authauth_statusresolvedrespstatusrl   bndr   s                      r   r   zsocksocket._SOCKS5_request  s   
 <@::8
D$ht$tQ'O	H 01 _- LLN--2K1Q7* (;= =
 1Q7* Ws3x='9'@'@'BB'("3x=188:;  (( ) "mmFA6q#w.+?A Aq#w.)*HII
 Qq!W,q#w.)$% % ,?A A LL30111#v>HLLN ==+DAayG#';= = a^F~%))&/B!/"8"8"GHH ++F3C*d.t}}=c?LLNLLN LLNLLNs   HI "I>c                    |\  }}| j                   \  }}}}}}	t        j                  dt        j                  di}
t        j                  t        j                  fD ]p  }	 t        j                  ||      }|j                  |
|   |z          t        j                  ||      }|j                  t        j                  d|             ||fc S  |rI|j                  d      }|j                  dt        t        |            j                         z   |z          nt        j                  ||t        j                  t        j                  t        j                   t        j"                        }|d   }|d   }|d   d   }t        j                  ||      }|j                  |
|   |z          t        j                  ||      }|j                  t        j                  d|             ||fS # t        j                  $ r Y w xY w)z~
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        r      >Hidnar   r   rB   )r   r[   AF_INETAF_INET6	inet_ptonr   	inet_ntopstructpackrl   rH   r   r   rb   	AF_UNSPECrc   IPPROTO_TCPAI_ADDRCONFIG)r   rM   r   r   rN   rL   r   rO   rP   rQ   family_to_byter{   
addr_bytes
host_bytes	addressestarget_addrs                   r   r   z socksocket._write_SOCKS5_address^  s   
 
d59ZZ2
Aq$( ..'6??GL
 ~~v7F#--fd;


>&1J>?''
;

6;;tT23Tz! 8 V,JJJwS_!5!<!<!>>KL **4v7G7G+1+=+=+1+=+=+1+?+?AI $A,K ^Fq>!$D))&$7JJJ~f-
:;##FJ7D

6;;tT*+Tz1 << s   A+G))H ?H c                    | j                  |d      }|dk(  r&t        j                  | j                  |d            }nx|dk(  r.| j                  |d      }| j                  |t        |            }nE|dk(  r5t        j                  t        j
                  | j                  |d            }nt        d      t        j                  d| j                  |d	            d
   }||fS )Nr   r   rB   r   r     r   r  r   r   )	r   r[   	inet_ntoar   r  r
  r2   r  unpack)r   r   atyprM   lengthrN   s         r   r   zsocksocket._read_SOCKS5_address  s    }}T1%7?##DMM$$:;DW_]]4+F==s6{3DW_##FOOT]]45LMD#$KLL}}T4==q#9:1=Tzr    c                 t   | j                   \  }}}}}}| j                  d      }	| j                  dd      }
	 d}	 t        j                  |      }|	j                  t        j                  ddd	|             |	j                  |       |r|	j                  |       |	j                  d
       |r#|	j                  |j                  d      d
z          |	j                          | j                  |
d      }|dd	 d
k7  rt        d      t        |d	d       }|dk7  r1t        j                  |d      }t!        dj#                  ||            t        j$                  |dd       t        j&                  d|dd       d   f| _        |rt        j$                  |      |f| _        n	||f| _        |
j-                          |	j-                          y# t        j                  $ r3 |rd}d}n(t        j                  t        j
                  |            }Y w xY w# |
j-                          |	j-                          w xY w)z0Negotiates a connection through a SOCKS4 server.r   r   r   Fs      Tz>BBHrB   r   r   r  rF   z%SOCKS4 proxy server sent invalid datar   Z   r   r   Nr  )r   r   r[   	inet_atonrl   gethostbynamer   r  r  rH   r   r   r2   r   SOCKS4_ERRORSr   r<   r&   r  r  r   r   rm   )r   r   	dest_portrL   rM   rN   rO   rP   rQ   r   r   remote_resolver  r  r  rl   s                   r   _negotiate_SOCKS4zsocksocket._negotiate_SOCKS4  s   ;?::8
D$ht$tQ'4	"N	9#--i8
 LLVT4CDLL$ X&LL!
 Y--f5?@LLN ==+DAayG#';= = a^F~%))&/B!/"8"8"GHH $*#3#3DH#=#)==tAay#A!#D#FD&,&6&6z&BI&M#&/&:#LLNLLN_ << 9!4J%)N!'!1!1,,Y7"9J9\ LLNLLNs0   H G EH AHH HH "H7c                 j   | j                   \  }}}}}}|r|nt        j                  |      }d|j                  d      z   dz   t	        |      j                         z   dz   d|j                  d      z   g}	|r%|r#|	j                  dt        |dz   |z         z          |	j                  d       | j                  dj                  |	             | j                         }
|
j                         }|
j                          |st        d      	 |j                  d	d
      \  }}}|j                  d      st        d      	 t!        |      }|dk7  r&dj%                  ||      }|dv r|dz  }t#        |      d| _        ||f| _        y# t        $ r t        d      w xY w# t        $ r t#        d      w xY w)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   
r    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)r   r[   r   rH   strappendr   sendalljoinr   readlinerm   r2   splitr   r`   rf   r>   r&   r   r   )r   r   r"  rL   rM   rN   rO   rP   rQ   http_headersfobjstatus_liner}   status_code
status_msgrl   s                   r   _negotiate_HTTPzsocksocket._negotiate_HTTP  s    <@::8
D$h !yf&:&:9&E 4;;v..59~$$&')56	((00
  >"+HtOh,F"G!H I 	G$W\\,/0 }}mmo

#$DEE	O-8->->sA-F*E;
 (#BD D	Hk*K
 #%%k:>Eo-  $ % E""-"Io1  	O#$MNN	O  	HFH H	Hs   F >F FF2c                    t        |      dk7  s|d   j                  d      r!t        j                  dt	        |      z        |\  }}| j
                  t        j                  k(  rK| j                  s| j                  d       t        j                  |      }|dk(  r
|sd| _
        y||f| _
        y| j                  \  }}}}}}	t        |t        t        f      r t        |      dk7  s|rt        |t              st!        d      t"        t$        | O  | j(                         |:|| _
        t"        t$        | O  | j(                         t"        t$        | W  ||f       y| j-                         }	 t"        t$        | W  |       	 | j.                  |   }
 |
| ||       y# t        j                  $ r!}| j1                          t!        d	|      d}~wt2        $ r | j1                           w xY w# t        j                  $ rj}| j1                          |\  }}d
j5                  ||      }t6        |   }dj5                  ||      }t8        j;                  d||       t=        ||      d}~ww xY w)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   r_   z PySocks doesn't support IPv6: %sr   r   Nz0Invalid destination-connection (host, port) pairzSocket errorz{0}:{1}z!Error connecting to {0} proxy {1}z%s due to: %s)r   r`   r[   rl   r)  r   r   r   rj   r   r   r   re   r   tuplerf   r2   r   rJ   rh   r   rk   r   _proxy_negotiatorsrm   r"   r&   PRINTABLE_PROXY_TYPESlogdebugr6   )r   rn   r   r"  rL   rq   rr   rO   rP   rQ   	negotiaterl   proxy_serverprintable_typer$   r   s                  r   rk   zsocksocket.connect  sK    y>Q)A,"9"9#"> ,,A!$Y 0 1 1  )	999)))??		'",,Y7I I%i&*#  (1)&<# ZZ	ZT8	 9tUm4y>Q& !)S1#BD D
 	j$*4==9"+D*d.t}}=*d+Y	,BC%%'
	*d+J7  33J?	$	95<< ?

'>> 

- || 
	3JJL%/"J
$++J
CL2:>N5<<^=IKCIIosE2&sE22
	3s1   0G. F G+1GG+.I+A%I&&I+c                 |    | j                   \  }}}}}}|xs t        j                  |      }|st        d      ||fS )zD
        Return proxy address to connect to as tuple object
        zInvalid proxy type)r   DEFAULT_PORTSr   r2   )r   rL   rq   rr   rO   rP   rQ   s          r   r   zsocksocket._proxy_addrn  sL    
 ZZ	ZT8	@=#4#4Z#@
#$899:%%r    NNNTNN)r   ))r,   r-   r.   r/   rK   r[   r	  rc   r'   r   rh   r   r   ri   r   rj   r   r   r   r   rm   r   getproxysocknamer   getproxypeernamer   r   r   r   r   r   r$  r4  r   r   r   r7  r   rk   r   __classcell__)r   s   @r   rJ   rJ   3  s     M$nn63E3E$
! EI*.62/
#-J$(H9(/
# *" *# K&Xt+Z:x9.x "#4!#4 T Tl	&r    rJ   r@  )	NNNNNTNNN)Ir/   base64r   sixPY2collectionscollections_abccollections.abcabcerrnor   r   r   r   ior   loggingosr   r[   r  sys__version__r   version_infowin_inet_ptonImportError	getLoggerr,   r9  PROXY_TYPE_SOCKS4r   PROXY_TYPE_SOCKS5r   PROXY_TYPE_HTTPr   PROXY_TYPESr   zipvalueskeysr8  
_orgsocketr   r   IOErrorr"   r2   r6   r8   r:   r<   r>   r!  r   r?  rR   rW   rY   getdefaultproxyr]   
wrapmoduler   r   r   r   methodre   Callabler   r*  setattrrJ   r0   r    r   <module>rc     s[  6p  
77' , , ,    	    
 77d?s''&0H
 g!  F  F $64@S!3!3!5{7G7G7IJK "MM )
\&
 
	
 		: 		j 		* 		* 		
 	 '!	 )
-




4
&	 vtT48 CG.2@.$ $	> 
 482626:>%):3z
&-- 
I2D[$-F fo667%%d+T;t#45 3D	& D	&  HFH 	HHs   3G G