Viewing File: /opt/alt/python35/lib/python3.5/site-packages/__pycache__/socks.cpython-35.pyc



"@Wu@sdZdZddlZddlZddlmZmZmZddlm	Z	ddl
mZddlm
Z
ddlmZd	ZZd
ZZdZZded
edeiZeeejejZejZZGdddeZGdddeZ GdddeZ!GdddeZ"GdddeZ#GdddeZ$GdddeZ%dddd d!d"iZ&d	d#d
d$dd%d&d'd(d)d*d+d,d-d.d/iZ'ed0ed0ed1iZ(dddd2ddd3d4Z)e)Z*d5d6Z+e+Z,d7d8Z-e-Z.dddd2dddddd9d:	Z/Gd;d<d<ejZ0d=d>Z1xUdED]MZ2e3e0e2dZ4e5e4e
se0j6j7e2e8e0e2e1e2qWGdCdDdDe0Z9dS)Fa

SocksiPy - Python SOCKS module.
Version 1.5.7

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 DAMANGE.


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
z1.5.7N)
EOPNOTSUPPEINVALEAGAIN)BytesIO)SEEK_CUR)Callable)	b64encodeSOCKS4SOCKS5HTTPc@s1eZdZdZdddZddZdS)
ProxyErrorz>
    socket_err contains original socket.error exception.
    NcCs4||_||_|r0|jdj|7_dS)Nz: {0})msg
socket_errformat)selfrrr	/socks.py__init__Ns		zProxyError.__init__cCs|jS)N)r)rrrr__str__UszProxyError.__str__)__name__
__module____qualname____doc__rrrrrrrJsrc@seZdZdS)GeneralProxyErrorN)rrrrrrrrXsrc@seZdZdS)ProxyConnectionErrorN)rrrrrrrrYsrc@seZdZdS)SOCKS5AuthErrorN)rrrrrrrrZsrc@seZdZdS)SOCKS5ErrorN)rrrrrrrr[src@seZdZdS)SOCKS4ErrorN)rrrrrrrr \sr c@seZdZdS)	HTTPErrorN)rrrrrrrr!]sr![zRequest rejected or failed\zLRequest rejected because SOCKS server cannot connect to identd on the client]zPRequest rejected because the client program and identd report different user-idszGeneral SOCKS server failurez!Connection not allowed by rulesetzNetwork unreachablezHost unreachablezConnection refusedzTTL expiredz(Command not supported, or protocol errorzAddress type not supportedi8iTcCsC|||||r|jnd|r3|jndft_dS)z
    set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]])

    Sets a default proxy which all further socksocket objects will use,
    unless explicitly changed. All parameters are as for socket.set_proxy().
    N)encode
socksocket
default_proxy)
proxy_typeaddrportrdnsusernamepasswordrrrset_default_proxyssr3cCstjS)z>
    Returns the default proxy, set by set_default_proxy.
    )r+r,rrrrget_default_proxysr4cCs(tjrt|j_ntddS)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.
    zNo default proxy specifiedN)r+r,socketr)modulerrrwrap_modules	r7c
Cs|\}
}|
jdr*|
jd}
|rN|jdrN|jd}d}xEtj||dtjD](}
|
\}}}}}d}yt|||}|	dk	rx|	D]}|j|qWt|tt	fr|j
||dk	r|j|||||||dk	r3|j||j
|
|f|SWqptjk
r}z'|}|dk	r|jd}WYdd}~XqpXqpW|dk	r|tjddS)acreate_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[]Nrzgai returned empty list.)
startswithstripr5getaddrinfoSOCK_STREAMr+
setsockopt
isinstanceintfloat
settimeout	set_proxybindconnecterrorclose)	dest_pairr-
proxy_addr
proxy_portZ
proxy_rdnsZproxy_usernameZproxy_passwordtimeoutsource_addressZsocket_optionsZremote_hostZremote_porterrrfamilyZsocket_typeproto	canonnamesasockopterrrcreate_connections>"




rUc@s+eZdZdZddZeZdS)_BaseSocketzJAllows Python 2's "delegated" methods such as send() to be overridden
    cOsZtj|||t|_x4|jD])}t|||j|<t||q)WdS)N)_orig_socketrdict
_savedmethods
_savenamesgetattrdelattr)rposkwnamerrrrs
z_BaseSocket.__init__N)rrrrrlistrZrrrrrVsrVcsfddS)Ncs|j||S)N)rY)rr]r^)r_rr<lambda>sz_makemethod.<locals>.<lambda>r)r_r)r_r_makemethodsrbsendtosendrecvfromrecvc@sceZdZdZdZejejdddZddZ	ddddddd	d
Z
e
ZddZd
dZ
dddZdddZddZddZddZeZddZeZddZeZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zeeeee eiZ!d)d*Z"d+d,Z#dS)-r+a2socksocket([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.
    NrcOs|tjtjfkr3d}t|j|tj||||||d|_|jrp|j|_	n	d|_	d|_
d|_dS)Nz0Socket type must be stream or datagram, not {!r})NNNNNN)r5r<
SOCK_DGRAM
ValueErrorrrVr
_proxyconnr,proxyproxy_socknameproxy_peername)rrNtyperOargskwargsrrrrrs				zsocksocket.__init__cCsXd}xKt||krS|j|t|}|sFtd||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.
        zConnection closed unexpectedly)lenreadr)rfilecountdatadrrr_readallszsocksocket._readallTcCsC|||||r|jnd|r3|jndf|_dS)aset_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
        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)r*rj)rr-r.r/r0r1r2rrrrBszsocksocket.set_proxycOs>|j\}}}}}}|s4|jtjkrGtj|||S|jrbtjtd|t	krd}	tjt
|	tj||||j\}
}d|f}t|_|j
}
|jj|
d}|j|j||\}
}|
\}}
|\}
}tj|||fd|_dS)	zm
        Implements proxy connection for UDP sockets,
        which happens during the bind() phase.
        z"Socket already bound to an addressz'UDP only supported by SOCKS5 proxy type0s0.0.0.0rN)ryr)rjrmr5rgrWrCrirErr
rrVgetsockname_proxy_addrrD_SOCKS5_requestrk)rr]r^r-rHrIr0r1r2r_r/dstrjZ
UDP_ASSOCIATEZrelayhostrrrrC*s(	zsocksocket.bindc
Os|jtjkr(tj||||S|js>|jd|d}|dd}t}d}|j|d}|j||j	||tj
||j|||}	|	|jS)	Nrr	ss)rrr)
rmr5rgrVrcrirCrwrite_write_SOCKS5_addressrdgetvaluetell)
rbytesrnroaddressflagsheaderZRSVZ
STANDALONEsentrrrrcNs	

	

"zsocksocket.sendtocKsE|jtjkr+|j|||j|Stj||||SdS)N)rmr5rgrcrlrVrd)rrrrorrrrdaszsocksocket.sendc	Cs|jtjkr%tj|||S|js;|jdttj|||}|j	dt
|jd}t|rt
d|j|\}}|jr|j\}}||ks|d|fkrtjtd|j||ffS)	Nrrr
r	zReceived UDP packet fragmentzPacket filtered)rrr
)rmr5rgrVrerirCrrfseekrrrordNotImplementedError_read_SOCKS5_addressrlrEr)	rbufsizerbufZfragZfromhostZfromportZpeerhostZpeerportrrrregs	
	zsocksocket.recvfromcOs|j||\}}|S)N)re)rr]r^rr}rrrrf{szsocksocket.recvcCs#|jr|jjtj|S)N)rirFrV)rrrrrFs	
zsocksocket.closecCs|jS)zL
        Returns the bound IP address and port number at the proxy.
        )rk)rrrrget_proxy_socknameszsocksocket.get_proxy_socknamecCs
tj|S)z>
        Returns the IP and port number of the proxy.
        )rVgetpeername)rrrrget_proxy_peernameszsocksocket.get_proxy_peernamecCs|jS)z
        Returns the IP address and port number of the destination
        machine (note: get_proxy_peername returns the proxy)
        )rl)rrrrget_peernameszsocksocket.get_peernamecGs+d}|j|||\|_|_dS)zI
        Negotiates a stream connection through a SOCKS5 server.
        sN)r|rlrk)r	dest_addrZCONNECTrrr_negotiate_SOCKS5s	zsocksocket._negotiate_SOCKS5cCs|j\}}}}}}	|jd}
|jdd}z6|r[|	r[|
jdn
|
jd|
j|j|d}|dddkrtd	|ddd
kr`|
jdtt|j|tt|	j|	|
j|j|d}
|
dddkr;td	|
dddkrt	d
nG|dddkr|dddkrt	dntd	|
jd|d|j
||
}|
j|j|d}|dddkrtd	t|dd}|dkrXtj
|d}tdj|||j|}||fSWd|j|
jXdS)z
        Send SOCKS5 request with given command (CMD field) and
        address (DST field). Returns resolved DST address that was used.
        wbrbrssr
r	sz%SOCKS5 proxy server sent invalid datassszSOCKS5 authentication failedsz7All offered SOCKS5 authentication methods were rejectedrz
Unknown errorz
{0:#04x}: {1}N)rjmakefilerflushrwrchrrqr*rrr
SOCKS5_ERRORSgetrrrrF)rconncmdr~r-r.r/r0r1r2writerreaderZchosen_authZauth_statusZresolvedrespstatusrEZbndrrrr|sL

;


zsocksocket._SOCKS5_requestcCs|\}}|j\}}}}}}	tjdtjdi}
xtjtjfD]}y`tj||}|j|
||tj||}|jtjd|||fSWqRtj	k
rwRYqRXqRW|r|j
d}
|jdtt|
j
|
ntj
||tjtjtjtj}|d}|d}|dd}tj||}|j|
||tj||}|jtjd|||fS)z~
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        ssz>Hidnasrr%)rjr5AF_INETAF_INET6	inet_ptonr	inet_ntopstructpackrEr*rrqr;	AF_UNSPECr<IPPROTO_TCP
AI_ADDRCONFIG)rr.rsrr/r-r}r0r1r2Zfamily_to_byterN
addr_bytesZ
host_bytesZ	addressesZtarget_addrrrrrs0**

z socksocket._write_SOCKS5_addresscCs|j|d}|dkr<tj|j|d}nu|dkru|j|d}|j|t|}n<|dkrtjtj|j|d}ntdtjd|j|d	d
}||fS)Nr	sr%ssz%SOCKS5 proxy server sent invalid dataz>Hr
r)	rwr5	inet_ntoarrrrrunpack)rrsZatypr.lengthr/rrrr!s$"zsocksocket._read_SOCKS5_addresscCs|j\}}}}}}|jd}	|jdd}
zd}ytj|}WnBtjk
r|rd}d}ntjtj|}YnX|	jtjddd	||	j||r|	j||	jd
|r	|	j|j	dd
|	j
|j|
d}
|
dd	d
krGtd
t
|
d	d}|dkrtj|d}tdj||tj|
ddtjd|
dddf|_|rtj||f|_n||f|_Wd|
j|	jXdS)zB
        Negotiates a connection through a SOCKS4 server.
        rrrFsTz>BBHr%r	srr)z%SOCKS4 proxy server sent invalid datar
Zz
Unknown errorz
{0:#04x}: {1}Nz>H)rjrr5	inet_atonrE
gethostbynamerrrr*rrwrr
SOCKS4_ERRORSrr rrrrkrlrF)rr	dest_portr-r.r/r0r1r2rrZremote_resolverrrrErrr_negotiate_SOCKS40sB	



<
zsocksocket._negotiate_SOCKS4cCs|j\}}}}}}|r'|ntj|}d|jddt|jdd|jdg}	|r|r|	jdt|d||	jd|jdj|	|j	}
|
j
}|
j|stdy|j
d	d
\}}
}Wntk
r5tdYnX|jdsQtd
yt|
}
Wntk
rtdYnX|
dkrdj|
|}|
dkr|d7}t|d|_||f|_dS)z
        Negotiates a connection through an HTTP server.
        NOTE: This currently only supports HTTP CONNECT-style proxies.
        sCONNECT r:s	 HTTP/1.1sHost: sProxy-Authorization: basic s
zConnection closed unexpectedly r
z'HTTP proxy server sent invalid responsezHTTP/z0Proxy server does not appear to be an HTTP proxyz4HTTP proxy server did not return a valid HTTP statusz{0}: {1}za
[*] Note: The HTTP proxy server may not be supported by PySocks (must be a CONNECT tunnel proxy)0.0.0.0rN)rrr)rr)rjr5rr*strappendrsendalljoinrreadlinerFrsplitrhr9r?r!rrkrl)rrrr-r.r/r0r1r2Zhttp_headersZfobjZstatus_linerOZstatus_codeZ
status_msgrErrr_negotiate_HTTPks<(




	zsocksocket._negotiate_HTTPcCsct|dks%|djdr4tjd|\}}|jtjkr|jsh|jdtj|}|dkr|rd|_	n||f|_	dS|j
\}}}}}}	t|tt
fst|dks|st|trtd|dkr>||_	tj|||fdS|j}ytj||Wn{tjk
r}
zX|j|\}}d	j||}t|}d
j||}
t|
|
WYdd}
~
XnXy!|j|}||||Wn_tjk
r@}
z|jtd|
WYdd}
~
Xntk
r^|jYnXdS)
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
rr8zPySocks doesn't support IPv6rz0.0.0.0Nz0Invalid destination-connection (host, port) pairz{0}:{1}z!Error connecting to {0} proxy {1}zSocket error)rr)rqr9r5rErmrgrirCrrlrjr>r`tupler?rrVrDr{rFrPRINTABLE_PROXY_TYPESr_proxy_negotiatorsr)rrGrrr-rHrIr0r1r2rEZproxy_serverZprintable_typerZ	negotiaterrrrDsR%	
	

		"

!

zsocksocket.connectcCsL|j\}}}}}}|p-tj|}|sBtd||fS)zD
        Return proxy address to connect to as tuple object
        zInvalid proxy type)rj
DEFAULT_PORTSrr)rr-rHrIr0r1r2rrrr{s
zsocksocket._proxy_addr)$rrrrr,r5rr<rrwrBZsetproxyrCrcrdrerfrFrZgetproxysocknamerZgetproxypeernamerrrr|rrrrrr
rrrDr{rrrrr+s:
$R*;7Mr+)zsendtozsendzrecvfromzrecv):r__version__r5rerrnorrriorosrcollectionsrbase64rZPROXY_TYPE_SOCKS4rZPROXY_TYPE_SOCKS5r
ZPROXY_TYPE_HTTPrZPROXY_TYPESrXzipvalueskeysrZ
_orgsocketrWIOErrorrrrrrr r!rrrr3Zsetdefaultproxyr4Zgetdefaultproxyr7Z
wrapmodulerUrVrbr_r[methodr>rZrsetattrr+rrrr<module>5sl


!
7


Back to Directory File Manager