PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/BitTornado/socks.py

http://lh-abc.googlecode.com/
Python | 402 lines | 386 code | 0 blank | 16 comment | 3 complexity | dce5b4de7a3ef6b2d8ae625f6bdfc722 MD5 | raw file
  1. """SocksiPy - Python SOCKS module.
  2. Version 1.00
  3. Copyright 2006 Dan-Haim. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without modification,
  5. are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice, this
  7. list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. 3. Neither the name of Dan Haim nor the names of his contributors may be used
  12. to endorse or promote products derived from this software without specific
  13. prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
  15. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  16. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  17. EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  18. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  19. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
  20. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  21. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  22. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
  23. This module provides a standard socket-like interface for Python
  24. for tunneling connections through SOCKS proxies.
  25. """
  26. import socket
  27. import struct
  28. PROXY_TYPE_SOCKS4 = 1
  29. PROXY_TYPE_SOCKS5 = 2
  30. PROXY_TYPE_HTTP = 3
  31. PROXY_TYPE_HTTPS = 4
  32. _defaultproxy = None
  33. _orgsocket = socket.socket
  34. def getType(value):
  35. names = {PROXY_TYPE_SOCKS4: 'socks4',
  36. PROXY_TYPE_SOCKS5: 'socks5',
  37. PROXY_TYPE_HTTP: 'http',
  38. PROXY_TYPE_HTTPS: 'https'}
  39. return names[value]
  40. class ProxyError(Exception):
  41. def __init__(self, value):
  42. self.value = value
  43. def __str__(self):
  44. return repr(self.value)
  45. class GeneralProxyError(ProxyError):
  46. def __init__(self, value):
  47. self.value = value
  48. def __str__(self):
  49. return repr(self.value)
  50. class Socks5AuthError(ProxyError):
  51. def __init__(self, value):
  52. self.value = value
  53. def __str__(self):
  54. return repr(self.value)
  55. class Socks5Error(ProxyError):
  56. def __init__(self, value):
  57. self.value = value
  58. def __str__(self):
  59. return repr(self.value)
  60. class Socks4Error(ProxyError):
  61. def __init__(self, value):
  62. self.value = value
  63. def __str__(self):
  64. return repr(self.value)
  65. class HTTPError(ProxyError):
  66. def __init__(self, value):
  67. self.value = value
  68. def __str__(self):
  69. return repr(self.value)
  70. _generalerrors = ("success",
  71. "invalid data",
  72. "not connected",
  73. "not available",
  74. "bad proxy type",
  75. "bad input")
  76. _socks5errors = ("succeeded",
  77. "general SOCKS server failure",
  78. "connection not allowed by ruleset",
  79. "Network unreachable",
  80. "Host unreachable",
  81. "Connection refused",
  82. "TTL expired",
  83. "Command not supported",
  84. "Address type not supported",
  85. "Unknown error")
  86. _socks5autherrors = ("succeeded",
  87. "authentication is required",
  88. "all offered authentication methods were rejected",
  89. "unknown username or invalid password",
  90. "unknown error")
  91. _socks4errors = ("request granted",
  92. "request rejected or failed",
  93. "request rejected because SOCKS server cannot connect to identd on the client",
  94. "request rejected because the client program and identd report different user-ids",
  95. "unknown error")
  96. def setdefaultproxy(proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
  97. """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  98. Sets a default proxy which all further socksocket objects will use,
  99. unless explicitly changed.
  100. """
  101. global _defaultproxy
  102. _defaultproxy = (proxytype,addr,port,rdns,username,password)
  103. class socksocket(socket.socket):
  104. """socksocket([family[, type[, proto]]]) -> socket object
  105. Open a SOCKS enabled socket. The parameters are the same as
  106. those of the standard socket init. In order for SOCKS to work,
  107. you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
  108. """
  109. def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
  110. _orgsocket.__init__(self,family,type,proto,_sock)
  111. if _defaultproxy != None:
  112. self.__proxy = _defaultproxy
  113. else:
  114. self.__proxy = (None, None, None, None, None, None)
  115. self.__proxysockname = None
  116. self.__proxypeername = None
  117. def __recvall(self, bytes):
  118. """__recvall(bytes) -> data
  119. Receive EXACTLY the number of bytes requested from the socket.
  120. Blocks until the required number of bytes have been received.
  121. """
  122. data = ""
  123. while len(data) < bytes:
  124. data = data + self.recv(bytes-len(data))
  125. return data
  126. def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
  127. """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  128. Sets the proxy to be used.
  129. proxytype - The type of the proxy to be used. Three types
  130. are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  131. PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  132. addr - The address of the server (IP or DNS).
  133. port - The port of the server. Defaults to 1080 for SOCKS
  134. servers and 8080 for HTTP proxy servers.
  135. rdns - Should DNS queries be preformed on the remote side
  136. (rather than the local side). The default is True.
  137. Note: This has no effect with SOCKS4 servers.
  138. username - Username to authenticate with to the server.
  139. The default is no authentication.
  140. password - Password to authenticate with to the server.
  141. Only relevant when username is also provided.
  142. """
  143. self.__proxy = (proxytype,addr,port,rdns,username,password)
  144. def __negotiatesocks5(self,destaddr,destport):
  145. """__negotiatesocks5(self,destaddr,destport)
  146. Negotiates a connection through a SOCKS5 server.
  147. """
  148. # First we'll send the authentication packages we support.
  149. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
  150. # The username/password details were supplied to the
  151. # setproxy method so we support the USERNAME/PASSWORD
  152. # authentication (in addition to the standard none).
  153. self.sendall("\x05\x02\x00\x02")
  154. else:
  155. # No username/password were entered, therefore we
  156. # only support connections with no authentication.
  157. self.sendall("\x05\x01\x00")
  158. # We'll receive the server's response to determine which
  159. # method was selected
  160. chosenauth = self.__recvall(2)
  161. if chosenauth[0] != "\x05":
  162. self.close()
  163. raise GeneralProxyError((1,_generalerrors[1]))
  164. # Check the chosen authentication method
  165. if chosenauth[1] == "\x00":
  166. # No authentication is required
  167. pass
  168. elif chosenauth[1] == "\x02":
  169. # Okay, we need to perform a basic username/password
  170. # authentication.
  171. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5])
  172. authstat = self.__recvall(2)
  173. if authstat[0] != "\x01":
  174. # Bad response
  175. self.close()
  176. raise GeneralProxyError((1,_generalerrors[1]))
  177. if authstat[1] != "\x00":
  178. # Authentication failed
  179. self.close()
  180. raise Socks5AuthError,((3,_socks5autherrors[3]))
  181. # Authentication succeeded
  182. else:
  183. # Reaching here is always bad
  184. self.close()
  185. if chosenauth[1] == "\xFF":
  186. raise Socks5AuthError((2,_socks5autherrors[2]))
  187. else:
  188. raise GeneralProxyError((1,_generalerrors[1]))
  189. # Now we can request the actual connection
  190. req = "\x05\x01\x00"
  191. # If the given destination address is an IP address, we'll
  192. # use the IPv4 address request even if remote resolving was specified.
  193. try:
  194. ipaddr = socket.inet_aton(destaddr)
  195. req = req + "\x01" + ipaddr
  196. except socket.error:
  197. # Well it's not an IP number, so it's probably a DNS name.
  198. if self.__proxy[3]==True:
  199. # Resolve remotely
  200. ipaddr = None
  201. req = req + "\x03" + chr(len(destaddr)) + destaddr
  202. else:
  203. # Resolve locally
  204. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  205. req = req + "\x01" + ipaddr
  206. req = req + struct.pack(">H",destport)
  207. self.sendall(req)
  208. # Get the response
  209. resp = self.__recvall(4)
  210. if resp[0] != "\x05":
  211. self.close()
  212. raise GeneralProxyError((1,_generalerrors[1]))
  213. elif resp[1] != "\x00":
  214. # Connection failed
  215. self.close()
  216. if ord(resp[1])<=8:
  217. raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])])
  218. else:
  219. raise Socks5Error(9,_generalerrors[9])
  220. # Get the bound address/port
  221. elif resp[3] == "\x01":
  222. boundaddr = self.__recvall(4)
  223. elif resp[3] == "\x03":
  224. resp = resp + self.recv(1)
  225. boundaddr = self.__recvall(resp[4])
  226. else:
  227. self.close()
  228. raise GeneralProxyError((1,_generalerrors[1]))
  229. boundport = struct.unpack(">H",self.__recvall(2))[0]
  230. self.__proxysockname = (boundaddr,boundport)
  231. if ipaddr != None:
  232. self.__proxypeername = (socket.inet_ntoa(ipaddr),destport)
  233. else:
  234. self.__proxypeername = (destaddr,destport)
  235. def getproxysockname(self):
  236. """getsockname() -> address info
  237. Returns the bound IP address and port number at the proxy.
  238. """
  239. return self.__proxysockname
  240. def getproxypeername(self):
  241. """getproxypeername() -> address info
  242. Returns the IP and port number of the proxy.
  243. """
  244. return _orgsocket.getpeername(self)
  245. def getpeername(self):
  246. """getpeername() -> address info
  247. Returns the IP address and port number of the destination
  248. machine (note: getproxypeername returns the proxy)
  249. """
  250. return self.__proxypeername
  251. def __negotiatesocks4(self,destaddr,destport):
  252. """__negotiatesocks4(self,destaddr,destport)
  253. Negotiates a connection through a SOCKS4 server.
  254. """
  255. # Check if the destination address provided is an IP address
  256. rmtrslv = False
  257. try:
  258. ipaddr = socket.inet_aton(destaddr)
  259. except socket.error:
  260. # It's a DNS name. Check where it should be resolved.
  261. if self.__proxy[3]==True:
  262. ipaddr = "\x00\x00\x00\x01"
  263. rmtrslv = True
  264. else:
  265. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  266. # Construct the request packet
  267. req = "\x04\x01" + struct.pack(">H",destport) + ipaddr
  268. # The username parameter is considered userid for SOCKS4
  269. if self.__proxy[4] != None:
  270. req = req + self.__proxy[4]
  271. req = req + "\x00"
  272. # DNS name if remote resolving is required
  273. # NOTE: This is actually an extension to the SOCKS4 protocol
  274. # called SOCKS4A and may not be supported in all cases.
  275. if rmtrslv==True:
  276. req = req + destaddr + "\x00"
  277. self.sendall(req)
  278. # Get the response from the server
  279. resp = self.__recvall(8)
  280. if resp[0] != "\x00":
  281. # Bad data
  282. self.close()
  283. raise GeneralProxyError((1,_generalerrors[1]))
  284. if resp[1] != "\x5A":
  285. # Server returned an error
  286. self.close()
  287. if ord(resp[1]) in (91,92,93):
  288. self.close()
  289. raise Socks4Error((ord(resp[1]),_socks4errors[ord(resp[1])-90]))
  290. else:
  291. raise Socks4Error((94,_socks4errors[4]))
  292. # Get the bound address/port
  293. self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0])
  294. if rmtrslv != None:
  295. self.__proxypeername = (socket.inet_ntoa(ipaddr),destport)
  296. else:
  297. self.__proxypeername = (destaddr,destport)
  298. def __negotiatehttp(self,destaddr,destport):
  299. """__negotiatehttp(self,destaddr,destport)
  300. Negotiates a connection through an HTTP server.
  301. """
  302. # If we need to resolve locally, we do this now
  303. if self.__proxy[3] == False:
  304. addr = socket.gethostbyname(destaddr)
  305. else:
  306. addr = destaddr
  307. self.sendall("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n")
  308. # We read the response until we get the string "\r\n\r\n"
  309. resp = self.recv(1)
  310. while resp.find("\r\n\r\n")==-1:
  311. resp = resp + self.recv(1)
  312. # We just need the first line to check if the connection
  313. # was successful
  314. statusline = resp.splitlines()[0].split(" ",2)
  315. if statusline[0] not in ("HTTP/1.0","HTTP/1.1"):
  316. self.close()
  317. raise GeneralProxyError((1,_generalerrors[1]))
  318. try:
  319. statuscode = int(statusline[1])
  320. except ValueError:
  321. self.close()
  322. raise GeneralProxyError((1,_generalerrors[1]))
  323. if statuscode != 200:
  324. self.close()
  325. raise HTTPError((statuscode,statusline[2]))
  326. self.__proxysockname = ("0.0.0.0",0)
  327. self.__proxypeername = (addr,destport)
  328. def connect(self,destpair):
  329. """connect(self,despair)
  330. Connects to the specified destination through a proxy.
  331. destpar - A tuple of the IP/DNS address and the port number.
  332. (identical to socket's connect).
  333. To select the proxy server use setproxy().
  334. """
  335. # Do a minimal input check first
  336. if (type(destpair) in (list,tuple)==False) or (len(destpair)<2) or (type(destpair[0])!=str) or (type(destpair[1])!=int):
  337. raise GeneralProxyError((5,_generalerrors[5]))
  338. if self.__proxy[0] == PROXY_TYPE_SOCKS5:
  339. if self.__proxy[2] != None:
  340. portnum = self.__proxy[2]
  341. else:
  342. portnum = 1080
  343. _orgsocket.connect(self,(self.__proxy[1],portnum))
  344. self.__negotiatesocks5(destpair[0],destpair[1])
  345. elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
  346. if self.__proxy[2] != None:
  347. portnum = self.__proxy[2]
  348. else:
  349. portnum = 1080
  350. _orgsocket.connect(self,(self.__proxy[1],portnum))
  351. self.__negotiatesocks4(destpair[0],destpair[1])
  352. elif self.__proxy[0] == PROXY_TYPE_HTTP:
  353. if self.__proxy[2] != None:
  354. portnum = self.__proxy[2]
  355. else:
  356. portnum = 8080
  357. _orgsocket.connect(self,(self.__proxy[1],portnum))
  358. self.__negotiatehttp(destpair[0],destpair[1])
  359. elif self.__proxy[0] == PROXY_TYPE_HTTPS: # TODO
  360. if self.__proxy[2] != None:
  361. portnum = self.__proxy[2]
  362. else:
  363. portnum = 8080
  364. _orgsocket.connect(self,(self.__proxy[1],portnum))
  365. self.__negotiatehttp(destpair[0],destpair[1])
  366. elif self.__proxy[0] == None:
  367. _orgsocket.connect(self,(destpair[0],destpair[1]))
  368. else:
  369. raise GeneralProxyError((4,_generalerrors[4]))