o _L@sdZddlZddlZddlZddlZeedddureddZdZdZ dZ da ejZ Gd d d e ZGd d d eZGd ddeZGdddeZGdddeZGdddeZdZdZdZdZ d ddZddZGdddejZdS)!aSocksiPy - Python SOCKS module. Version 1.00 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. Nsocketz-socket.socket missing, proxy support unusablec@ eZdZdS) ProxyErrorN__name__ __module__ __qualname__r r 0/usr/lib/python3/dist-packages/httplib2/socks.pyr7rc@r)GeneralProxyErrorNr r r r rr;rrc@r)Socks5AuthErrorNr r r r rr?rrc@r) Socks5ErrorNr r r r rrCrrc@r) Socks4ErrorNr r r r rrGrrc@r) HTTPErrorNr r r r rrKrr)successz invalid dataz not connectedz not availablezbad proxy typez bad input) succeededzgeneral SOCKS server failurez!connection not allowed by rulesetzNetwork unreachablezHost unreachablezConnection refusedz TTL expiredzCommand not supportedzAddress type not supportedz Unknown error)rzauthentication is requiredz0all offered authentication methods were rejectedz$unknown username or invalid password unknown error)zrequest grantedzrequest rejected or failedzLrequest rejected because SOCKS server cannot connect to identd on the clientzPrequest rejected because the client program and identd report different user-idsrTcCs||||||fadS)zsetdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. N) _defaultproxy) proxytypeaddrportrdnsusernamepasswordr r rsetdefaultproxywsrcCstdkr t|j_dStd)a7wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. N)rzno proxy specified)r socksocketrr)moduler r r wrapmodules r"cseZdZdZejejddfddZddZfdd Z d d Z d d Z       dddZ ddZ ddZddZddZddZddZddZZS) r asocksocket([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, type=SOCK_STREAM and proto=0. rNcCs>t|||||tdkrt|_nd|_d|_d|_d|_dS)N)NNNNNNT) _orgsocket__init__r_socksocket__proxy_socksocket__proxysockname_socksocket__proxypeername_socksocket__httptunnel)selffamilytypeproto_sockr r rr$s zsocksocket.__init__cCsL||}t||kr$||t|}|std||}t||ks |S)z__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. )rzconnection closed unexpectedly)recvlenr)r)countdatadr r r __recvalls   zsocksocket.__recvallcs(|js||}tt|j|g|RS)zq override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed )r(_socksocket__rewriteproxysuperr sendall)r)contentargs __class__r rr6s zsocksocket.sendallc Csd\}}|d}|D]}|dr|}q |ds%|dr'|}q |rr|rr|||||dd}|d}|jdd krX|jd d krX|d ||d d ||d d |d ||d|dfd|S)z rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. )NN zhost:getpost rrNrzHost: %sz%s http://%s%s %sr)splitlower startswithremover%insert_socksocket__getauthheaderjoin)r)headerhostendpthdrshdrr r r__rewriteproxys$    $ zsocksocket.__rewriteproxycCs*|jdd|jd}dt|S)Nr:r?zProxy-Authorization: Basic )r%base64 b64encodedecode)r)authr r r__getauthheaderszsocksocket.__getauthheaderTcCs0|||||r |nd|r|nd|f|_dS)a setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - 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 preformed 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. headers - Additional or modified headers for the proxy connect request. N)encoder%)r)rrrrrrheadersr r rsetproxys zsocksocket.setproxyc Cs|jddkr|jddkr|tdddddn |tdddd|d}|ddtdkrC|tdt df|ddtdkrPn|ddtdkrt }| d| t |jd| |jd| t |jd| |jd|||d}|ddtdkr|tdt df|ddtdkr|td td fn||dtd krtdtdftdt dftdddd}zt|}|td|}Wn:tjy4|jd r d}|td tt ||}ntt|}|td|}Ynw|td |}|||d}|ddtdkr`|tdt df|ddtdkr|t|ddd krtt|ddtt|ddftd td f|d dtdkr|d} n,|d dtd kr||d}|t|dd} n |tdt dftd |dd} | | f|_|dkrt||f|_dS||f|_dS)zk__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. rNr?BBBBrrBBBrr>H )r%r6structpack_socksocket__recvallchrrScloser_generalerrors bytearrayappendr/extendr_socks5autherrorsr inet_atonerror gethostbynameordr _socks5errorsr.unpackr& inet_ntoar') r)destaddrdestport chosenauthpacketauthstatreqipaddrresp boundaddr boundportr r r__negotiatesocks5s         (   zsocksocket.__negotiatesocks5cC|jS)zigetsockname() -> address info Returns the bound IP address and port number at the proxy. )r&r)r r rgetproxysocknamebszsocksocket.getproxysocknamecCs t|S)z`getproxypeername() -> address info Returns the IP and port number of the proxy. )r# getpeernameryr r rgetproxypeernamehs zsocksocket.getproxypeernamecCrx)zgetpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) )r'ryr r rr{nszsocksocket.getpeernamec Csd}zt|}Wn#tjy,|jdr"tddddd}d}ntt|}Ynwtddd||}|jdd krE||jd}|td}|rY||td}| || d }|ddtdkr{| t dt df|dd td kr| t|dd d vr| tt|dd tt|dd d ftdtdft|dd td|d ddf|_|d krt||f|_d S||f|_d S)zk__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. FrrVrrTz>BBHrNrZrZ)[\]^rY)rrfrgr%r\r]rhr_rSr6r^r`rrarir _socks4errorsrlrkr&r')r)rmrnrmtrslvrsrrrtr r r__negotiatesocks4usB   ,zsocksocket.__negotiatesocks4c Cs|jds t|}n|}d|dt|dg}d}d}|jddkrA|jdD]\}}||d|d g7}|d k}|d k}q(|sJ|d |d g7}|sb|jd dkrb|jddkrb||d g7}|d |d | | d} | d dkr| | d} | d dks| dd d} | dd d fvr|tdtdfzt| d} Wnty|tdtdfw| dkr|t| | dfd|_||f|_dS)zh__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. rzCONNECT :z HTTP/1.1 FNz: r;rHzproxy-authorizationzHost: rr?rz rr>rzHTTP/1.0zHTTP/1.1)z0.0.0.0r)r%rrhstr iteritemsrArErcr6rFrSr.find splitlinesr@r`rraint ValueErrorrr&r') r)rmrnrrTwrote_host_headerwrote_auth_headerkeyvalrt statusline statuscoder r r__negotiatehttpsJ      zsocksocket.__negotiatehttpcCst|ttfvst|dkst|dttfrt|dtkr'tdt df|j dt krT|j ddkr;|j d}nd}t ||j d|f||d|ddS|j dtkr|j ddkrh|j d}nd}t ||j d|f||d|ddS|j dtkr|j ddkr|j d}nd}t ||j d|f||d|ddS|j dtkr|j ddkr|j d}nd}t ||j d|f|ddkr||d|ddSd |_dS|j ddkrt ||d|dfdStd t d f) zconnect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). rrrr?Ni8iiFr)r+listtupler/ isinstancerbytesrrrar%PROXY_TYPE_SOCKS5r#connect_socksocket__negotiatesocks5PROXY_TYPE_SOCKS4_socksocket__negotiatesocks4PROXY_TYPE_HTTP_socksocket__negotiatehttpPROXY_TYPE_HTTP_NO_TUNNELr()r)destpairportnumr r rrsF       zsocksocket.connect)NNNTNNN)r r r __doc__rAF_INET SOCK_STREAMr$r^r6r4rErUrrzr|r{rrr __classcell__r r r9rr s.    'g3-r )NNNTNN)rrNrr\sysgetattr ImportErrorrrrrrr# Exceptionrrrrrrrarjrerrr"r r r r rs6%