webull-openapi-python-sdk 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. samples/__init__.py +1 -0
  2. samples/data/__init__.py +1 -0
  3. samples/data/data_client.py +57 -0
  4. samples/data/data_streaming_client.py +86 -0
  5. samples/data/data_streaming_client_async.py +101 -0
  6. samples/trade/__init__.py +0 -0
  7. samples/trade/trade_client.py +163 -0
  8. samples/trade/trade_client_v2.py +181 -0
  9. samples/trade/trade_event_client.py +47 -0
  10. webull/__init__.py +1 -0
  11. webull/core/__init__.py +12 -0
  12. webull/core/auth/__init__.py +0 -0
  13. webull/core/auth/algorithm/__init__.py +0 -0
  14. webull/core/auth/algorithm/sha_hmac1.py +65 -0
  15. webull/core/auth/algorithm/sha_hmac256.py +75 -0
  16. webull/core/auth/composer/__init__.py +0 -0
  17. webull/core/auth/composer/default_signature_composer.py +125 -0
  18. webull/core/auth/credentials.py +46 -0
  19. webull/core/auth/signers/__init__.py +0 -0
  20. webull/core/auth/signers/app_key_signer.py +72 -0
  21. webull/core/auth/signers/signer.py +48 -0
  22. webull/core/auth/signers/signer_factory.py +58 -0
  23. webull/core/cache/__init__.py +225 -0
  24. webull/core/client.py +410 -0
  25. webull/core/common/__init__.py +0 -0
  26. webull/core/common/api_type.py +19 -0
  27. webull/core/common/easy_enum.py +35 -0
  28. webull/core/common/region.py +7 -0
  29. webull/core/compat.py +85 -0
  30. webull/core/context/__init__.py +0 -0
  31. webull/core/context/request_context_holder.py +33 -0
  32. webull/core/data/endpoints.json +22 -0
  33. webull/core/data/retry_config.json +15 -0
  34. webull/core/endpoint/__init__.py +8 -0
  35. webull/core/endpoint/chained_endpoint_resolver.py +57 -0
  36. webull/core/endpoint/default_endpoint_resolver.py +60 -0
  37. webull/core/endpoint/local_config_regional_endpoint_resolver.py +77 -0
  38. webull/core/endpoint/resolver_endpoint_request.py +46 -0
  39. webull/core/endpoint/user_customized_endpoint_resolver.py +55 -0
  40. webull/core/exception/__init__.py +0 -0
  41. webull/core/exception/error_code.py +23 -0
  42. webull/core/exception/error_msg.py +21 -0
  43. webull/core/exception/exceptions.py +53 -0
  44. webull/core/headers.py +57 -0
  45. webull/core/http/__init__.py +0 -0
  46. webull/core/http/initializer/__init__.py +0 -0
  47. webull/core/http/initializer/client_initializer.py +79 -0
  48. webull/core/http/initializer/token/__init__.py +0 -0
  49. webull/core/http/initializer/token/bean/__init__.py +0 -0
  50. webull/core/http/initializer/token/bean/access_token.py +40 -0
  51. webull/core/http/initializer/token/bean/check_token_request.py +44 -0
  52. webull/core/http/initializer/token/bean/create_token_request.py +45 -0
  53. webull/core/http/initializer/token/bean/refresh_token_request.py +44 -0
  54. webull/core/http/initializer/token/token_manager.py +208 -0
  55. webull/core/http/initializer/token/token_operation.py +72 -0
  56. webull/core/http/method_type.py +43 -0
  57. webull/core/http/protocol_type.py +43 -0
  58. webull/core/http/request.py +121 -0
  59. webull/core/http/response.py +166 -0
  60. webull/core/request.py +278 -0
  61. webull/core/retry/__init__.py +0 -0
  62. webull/core/retry/backoff_strategy.py +102 -0
  63. webull/core/retry/retry_condition.py +214 -0
  64. webull/core/retry/retry_policy.py +63 -0
  65. webull/core/retry/retry_policy_context.py +51 -0
  66. webull/core/utils/__init__.py +0 -0
  67. webull/core/utils/common.py +62 -0
  68. webull/core/utils/data.py +25 -0
  69. webull/core/utils/desensitize.py +33 -0
  70. webull/core/utils/validation.py +49 -0
  71. webull/core/vendored/__init__.py +0 -0
  72. webull/core/vendored/requests/__init__.py +94 -0
  73. webull/core/vendored/requests/__version__.py +28 -0
  74. webull/core/vendored/requests/_internal_utils.py +56 -0
  75. webull/core/vendored/requests/adapters.py +539 -0
  76. webull/core/vendored/requests/api.py +166 -0
  77. webull/core/vendored/requests/auth.py +307 -0
  78. webull/core/vendored/requests/certs.py +34 -0
  79. webull/core/vendored/requests/compat.py +85 -0
  80. webull/core/vendored/requests/cookies.py +555 -0
  81. webull/core/vendored/requests/exceptions.py +136 -0
  82. webull/core/vendored/requests/help.py +134 -0
  83. webull/core/vendored/requests/hooks.py +48 -0
  84. webull/core/vendored/requests/models.py +960 -0
  85. webull/core/vendored/requests/packages/__init__.py +17 -0
  86. webull/core/vendored/requests/packages/certifi/__init__.py +17 -0
  87. webull/core/vendored/requests/packages/certifi/__main__.py +16 -0
  88. webull/core/vendored/requests/packages/certifi/cacert.pem +4433 -0
  89. webull/core/vendored/requests/packages/certifi/core.py +51 -0
  90. webull/core/vendored/requests/packages/chardet/__init__.py +53 -0
  91. webull/core/vendored/requests/packages/chardet/big5freq.py +400 -0
  92. webull/core/vendored/requests/packages/chardet/big5prober.py +61 -0
  93. webull/core/vendored/requests/packages/chardet/chardistribution.py +247 -0
  94. webull/core/vendored/requests/packages/chardet/charsetgroupprober.py +120 -0
  95. webull/core/vendored/requests/packages/chardet/charsetprober.py +159 -0
  96. webull/core/vendored/requests/packages/chardet/cli/__init__.py +1 -0
  97. webull/core/vendored/requests/packages/chardet/cli/chardetect.py +99 -0
  98. webull/core/vendored/requests/packages/chardet/codingstatemachine.py +102 -0
  99. webull/core/vendored/requests/packages/chardet/compat.py +48 -0
  100. webull/core/vendored/requests/packages/chardet/cp949prober.py +63 -0
  101. webull/core/vendored/requests/packages/chardet/enums.py +90 -0
  102. webull/core/vendored/requests/packages/chardet/escprober.py +115 -0
  103. webull/core/vendored/requests/packages/chardet/escsm.py +260 -0
  104. webull/core/vendored/requests/packages/chardet/eucjpprober.py +106 -0
  105. webull/core/vendored/requests/packages/chardet/euckrfreq.py +209 -0
  106. webull/core/vendored/requests/packages/chardet/euckrprober.py +61 -0
  107. webull/core/vendored/requests/packages/chardet/euctwfreq.py +401 -0
  108. webull/core/vendored/requests/packages/chardet/euctwprober.py +60 -0
  109. webull/core/vendored/requests/packages/chardet/gb2312freq.py +297 -0
  110. webull/core/vendored/requests/packages/chardet/gb2312prober.py +60 -0
  111. webull/core/vendored/requests/packages/chardet/hebrewprober.py +306 -0
  112. webull/core/vendored/requests/packages/chardet/jisfreq.py +339 -0
  113. webull/core/vendored/requests/packages/chardet/jpcntx.py +247 -0
  114. webull/core/vendored/requests/packages/chardet/langbulgarianmodel.py +242 -0
  115. webull/core/vendored/requests/packages/chardet/langcyrillicmodel.py +347 -0
  116. webull/core/vendored/requests/packages/chardet/langgreekmodel.py +239 -0
  117. webull/core/vendored/requests/packages/chardet/langhebrewmodel.py +214 -0
  118. webull/core/vendored/requests/packages/chardet/langhungarianmodel.py +239 -0
  119. webull/core/vendored/requests/packages/chardet/langthaimodel.py +213 -0
  120. webull/core/vendored/requests/packages/chardet/langturkishmodel.py +207 -0
  121. webull/core/vendored/requests/packages/chardet/latin1prober.py +159 -0
  122. webull/core/vendored/requests/packages/chardet/mbcharsetprober.py +105 -0
  123. webull/core/vendored/requests/packages/chardet/mbcsgroupprober.py +68 -0
  124. webull/core/vendored/requests/packages/chardet/mbcssm.py +586 -0
  125. webull/core/vendored/requests/packages/chardet/sbcharsetprober.py +146 -0
  126. webull/core/vendored/requests/packages/chardet/sbcsgroupprober.py +87 -0
  127. webull/core/vendored/requests/packages/chardet/sjisprober.py +106 -0
  128. webull/core/vendored/requests/packages/chardet/universaldetector.py +300 -0
  129. webull/core/vendored/requests/packages/chardet/utf8prober.py +96 -0
  130. webull/core/vendored/requests/packages/chardet/version.py +23 -0
  131. webull/core/vendored/requests/packages/urllib3/__init__.py +114 -0
  132. webull/core/vendored/requests/packages/urllib3/_collections.py +346 -0
  133. webull/core/vendored/requests/packages/urllib3/connection.py +405 -0
  134. webull/core/vendored/requests/packages/urllib3/connectionpool.py +910 -0
  135. webull/core/vendored/requests/packages/urllib3/contrib/__init__.py +0 -0
  136. webull/core/vendored/requests/packages/urllib3/contrib/_appengine_environ.py +44 -0
  137. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/__init__.py +0 -0
  138. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/bindings.py +607 -0
  139. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/low_level.py +360 -0
  140. webull/core/vendored/requests/packages/urllib3/contrib/appengine.py +303 -0
  141. webull/core/vendored/requests/packages/urllib3/contrib/ntlmpool.py +125 -0
  142. webull/core/vendored/requests/packages/urllib3/contrib/pyopenssl.py +484 -0
  143. webull/core/vendored/requests/packages/urllib3/contrib/securetransport.py +818 -0
  144. webull/core/vendored/requests/packages/urllib3/contrib/socks.py +206 -0
  145. webull/core/vendored/requests/packages/urllib3/exceptions.py +260 -0
  146. webull/core/vendored/requests/packages/urllib3/fields.py +192 -0
  147. webull/core/vendored/requests/packages/urllib3/filepost.py +112 -0
  148. webull/core/vendored/requests/packages/urllib3/packages/__init__.py +19 -0
  149. webull/core/vendored/requests/packages/urllib3/packages/backports/__init__.py +0 -0
  150. webull/core/vendored/requests/packages/urllib3/packages/backports/makefile.py +67 -0
  151. webull/core/vendored/requests/packages/urllib3/packages/ordered_dict.py +273 -0
  152. webull/core/vendored/requests/packages/urllib3/packages/six.py +882 -0
  153. webull/core/vendored/requests/packages/urllib3/packages/socks.py +887 -0
  154. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py +19 -0
  155. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py +170 -0
  156. webull/core/vendored/requests/packages/urllib3/poolmanager.py +467 -0
  157. webull/core/vendored/requests/packages/urllib3/request.py +164 -0
  158. webull/core/vendored/requests/packages/urllib3/response.py +721 -0
  159. webull/core/vendored/requests/packages/urllib3/util/__init__.py +68 -0
  160. webull/core/vendored/requests/packages/urllib3/util/connection.py +148 -0
  161. webull/core/vendored/requests/packages/urllib3/util/queue.py +35 -0
  162. webull/core/vendored/requests/packages/urllib3/util/request.py +132 -0
  163. webull/core/vendored/requests/packages/urllib3/util/response.py +101 -0
  164. webull/core/vendored/requests/packages/urllib3/util/retry.py +426 -0
  165. webull/core/vendored/requests/packages/urllib3/util/selectors.py +601 -0
  166. webull/core/vendored/requests/packages/urllib3/util/ssl_.py +396 -0
  167. webull/core/vendored/requests/packages/urllib3/util/timeout.py +256 -0
  168. webull/core/vendored/requests/packages/urllib3/util/url.py +252 -0
  169. webull/core/vendored/requests/packages/urllib3/util/wait.py +164 -0
  170. webull/core/vendored/requests/packages.py +28 -0
  171. webull/core/vendored/requests/sessions.py +750 -0
  172. webull/core/vendored/requests/status_codes.py +105 -0
  173. webull/core/vendored/requests/structures.py +119 -0
  174. webull/core/vendored/requests/utils.py +916 -0
  175. webull/core/vendored/six.py +905 -0
  176. webull/data/__init__.py +3 -0
  177. webull/data/common/__init__.py +0 -0
  178. webull/data/common/category.py +26 -0
  179. webull/data/common/connect_ack.py +29 -0
  180. webull/data/common/direction.py +25 -0
  181. webull/data/common/exchange_code.py +33 -0
  182. webull/data/common/exercise_style.py +22 -0
  183. webull/data/common/expiration_cycle.py +26 -0
  184. webull/data/common/instrument_status.py +23 -0
  185. webull/data/common/option_type.py +20 -0
  186. webull/data/common/subscribe_type.py +22 -0
  187. webull/data/common/timespan.py +29 -0
  188. webull/data/data_client.py +35 -0
  189. webull/data/data_streaming_client.py +89 -0
  190. webull/data/internal/__init__.py +0 -0
  191. webull/data/internal/default_retry_policy.py +84 -0
  192. webull/data/internal/exceptions.py +60 -0
  193. webull/data/internal/quotes_client.py +314 -0
  194. webull/data/internal/quotes_decoder.py +40 -0
  195. webull/data/internal/quotes_payload_decoder.py +35 -0
  196. webull/data/internal/quotes_topic.py +36 -0
  197. webull/data/quotes/__init__.py +0 -0
  198. webull/data/quotes/instrument.py +33 -0
  199. webull/data/quotes/market_data.py +187 -0
  200. webull/data/quotes/market_streaming_data.py +66 -0
  201. webull/data/quotes/subscribe/__init__.py +0 -0
  202. webull/data/quotes/subscribe/ask_bid_result.py +49 -0
  203. webull/data/quotes/subscribe/basic_result.py +45 -0
  204. webull/data/quotes/subscribe/broker_result.py +33 -0
  205. webull/data/quotes/subscribe/message_pb2.py +37 -0
  206. webull/data/quotes/subscribe/order_result.py +30 -0
  207. webull/data/quotes/subscribe/payload_type.py +19 -0
  208. webull/data/quotes/subscribe/quote_decoder.py +28 -0
  209. webull/data/quotes/subscribe/quote_result.py +47 -0
  210. webull/data/quotes/subscribe/snapshot_decoder.py +30 -0
  211. webull/data/quotes/subscribe/snapshot_result.py +69 -0
  212. webull/data/quotes/subscribe/tick_decoder.py +29 -0
  213. webull/data/quotes/subscribe/tick_result.py +47 -0
  214. webull/data/request/__init__.py +0 -0
  215. webull/data/request/get_batch_historical_bars_request.py +43 -0
  216. webull/data/request/get_corp_action_request.py +47 -0
  217. webull/data/request/get_eod_bars_request.py +32 -0
  218. webull/data/request/get_historical_bars_request.py +43 -0
  219. webull/data/request/get_instruments_request.py +30 -0
  220. webull/data/request/get_quotes_request.py +35 -0
  221. webull/data/request/get_snapshot_request.py +38 -0
  222. webull/data/request/get_tick_request.py +37 -0
  223. webull/data/request/subscribe_request.py +43 -0
  224. webull/data/request/unsubscribe_request.py +42 -0
  225. webull/trade/__init__.py +2 -0
  226. webull/trade/common/__init__.py +0 -0
  227. webull/trade/common/account_type.py +22 -0
  228. webull/trade/common/category.py +29 -0
  229. webull/trade/common/combo_ticker_type.py +23 -0
  230. webull/trade/common/combo_type.py +31 -0
  231. webull/trade/common/currency.py +24 -0
  232. webull/trade/common/forbid_reason.py +27 -0
  233. webull/trade/common/instrument_type.py +27 -0
  234. webull/trade/common/markets.py +27 -0
  235. webull/trade/common/order_entrust_type.py +21 -0
  236. webull/trade/common/order_side.py +23 -0
  237. webull/trade/common/order_status.py +25 -0
  238. webull/trade/common/order_tif.py +24 -0
  239. webull/trade/common/order_type.py +30 -0
  240. webull/trade/common/trade_policy.py +22 -0
  241. webull/trade/common/trading_date_type.py +24 -0
  242. webull/trade/common/trailing_type.py +23 -0
  243. webull/trade/events/__init__.py +0 -0
  244. webull/trade/events/default_retry_policy.py +64 -0
  245. webull/trade/events/events_pb2.py +43 -0
  246. webull/trade/events/events_pb2_grpc.py +66 -0
  247. webull/trade/events/signature_composer.py +61 -0
  248. webull/trade/events/types.py +21 -0
  249. webull/trade/request/__init__.py +0 -0
  250. webull/trade/request/cancel_order_request.py +28 -0
  251. webull/trade/request/get_account_balance_request.py +28 -0
  252. webull/trade/request/get_account_positions_request.py +30 -0
  253. webull/trade/request/get_account_profile_request.py +26 -0
  254. webull/trade/request/get_app_subscriptions.py +28 -0
  255. webull/trade/request/get_open_orders_request.py +30 -0
  256. webull/trade/request/get_order_detail_request.py +27 -0
  257. webull/trade/request/get_today_orders_request.py +31 -0
  258. webull/trade/request/get_trade_calendar_request.py +30 -0
  259. webull/trade/request/get_trade_instrument_detail_request.py +24 -0
  260. webull/trade/request/get_trade_security_detail_request.py +42 -0
  261. webull/trade/request/get_tradeable_instruments_request.py +27 -0
  262. webull/trade/request/palce_order_request.py +91 -0
  263. webull/trade/request/place_order_request_v2.py +58 -0
  264. webull/trade/request/replace_order_request.py +73 -0
  265. webull/trade/request/replace_order_request_v2.py +38 -0
  266. webull/trade/request/v2/__init__.py +0 -0
  267. webull/trade/request/v2/cancel_option_request.py +28 -0
  268. webull/trade/request/v2/cancel_order_request.py +28 -0
  269. webull/trade/request/v2/get_account_balance_request.py +28 -0
  270. webull/trade/request/v2/get_account_list.py +23 -0
  271. webull/trade/request/v2/get_account_positions_request.py +24 -0
  272. webull/trade/request/v2/get_order_detail_request.py +26 -0
  273. webull/trade/request/v2/get_order_history_request.py +35 -0
  274. webull/trade/request/v2/palce_order_request.py +87 -0
  275. webull/trade/request/v2/place_option_request.py +64 -0
  276. webull/trade/request/v2/preview_option_request.py +28 -0
  277. webull/trade/request/v2/preview_order_request.py +59 -0
  278. webull/trade/request/v2/replace_option_request.py +28 -0
  279. webull/trade/request/v2/replace_order_request.py +57 -0
  280. webull/trade/trade/__init__.py +0 -0
  281. webull/trade/trade/account_info.py +83 -0
  282. webull/trade/trade/order_operation.py +246 -0
  283. webull/trade/trade/trade_calendar.py +37 -0
  284. webull/trade/trade/trade_instrument.py +72 -0
  285. webull/trade/trade/v2/__init__.py +0 -0
  286. webull/trade/trade/v2/account_info_v2.py +55 -0
  287. webull/trade/trade/v2/order_operation_v2.py +206 -0
  288. webull/trade/trade_client.py +43 -0
  289. webull/trade/trade_events_client.py +233 -0
  290. webull_openapi_python_sdk-1.0.0.dist-info/METADATA +28 -0
  291. webull_openapi_python_sdk-1.0.0.dist-info/RECORD +295 -0
  292. webull_openapi_python_sdk-1.0.0.dist-info/WHEEL +5 -0
  293. webull_openapi_python_sdk-1.0.0.dist-info/licenses/LICENSE +202 -0
  294. webull_openapi_python_sdk-1.0.0.dist-info/licenses/NOTICE +56 -0
  295. webull_openapi_python_sdk-1.0.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,887 @@
1
+ # Copyright 2022 Webull
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """SocksiPy - Python SOCKS module.
16
+
17
+ Copyright 2006 Dan-Haim. All rights reserved.
18
+
19
+ Redistribution and use in source and binary forms, with or without
20
+ modification, are permitted provided that the following conditions are met:
21
+ 1. Redistributions of source code must retain the above copyright notice, this
22
+ list of conditions and the following disclaimer.
23
+ 2. Redistributions in binary form must reproduce the above copyright notice,
24
+ this list of conditions and the following disclaimer in the documentation
25
+ and/or other materials provided with the distribution.
26
+ 3. Neither the name of Dan Haim nor the names of his contributors may be used
27
+ to endorse or promote products derived from this software without specific
28
+ prior written permission.
29
+
30
+ THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
31
+ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
32
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
33
+ EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
36
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
37
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
38
+ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
+
40
+
41
+ This module provides a standard socket-like interface for Python
42
+ for tunneling connections through SOCKS proxies.
43
+
44
+ ===============================================================================
45
+
46
+ Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
47
+ for use in PyLoris (http://pyloris.sourceforge.net/)
48
+
49
+ Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
50
+ mainly to merge bug fixes found in Sourceforge
51
+
52
+ Modifications made by Anorov (https://github.com/Anorov)
53
+ -Forked and renamed to PySocks
54
+ -Fixed issue with HTTP proxy failure checking (same bug that was in the
55
+ old ___recvall() method)
56
+ -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler,
57
+ courtesy of e000 (https://github.com/e000):
58
+ https://gist.github.com/869791#file_socksipyhandler.py
59
+ -Re-styled code to make it readable
60
+ -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
61
+ -Improved exception handling and output
62
+ -Removed irritating use of sequence indexes, replaced with tuple unpacked
63
+ variables
64
+ -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03"
65
+ -Other general fixes
66
+ -Added clarification that the HTTP proxy connection method only supports
67
+ CONNECT-style tunneling HTTP proxies
68
+ -Various small bug fixes
69
+ """
70
+
71
+ from base64 import b64encode
72
+ try:
73
+ from collections.abc import Callable
74
+ except ImportError:
75
+ from collections import Callable
76
+ from errno import EOPNOTSUPP, EINVAL, EAGAIN
77
+ import functools
78
+ from io import BytesIO
79
+ import logging
80
+ import os
81
+ from os import SEEK_CUR
82
+ import socket
83
+ import struct
84
+ import sys
85
+
86
+ __version__ = "1.6.7"
87
+
88
+
89
+ if os.name == "nt" and sys.version_info < (3, 0):
90
+ try:
91
+ import win_inet_pton
92
+ except ImportError:
93
+ raise ImportError(
94
+ "To run PySocks on Windows you must install win_inet_pton")
95
+
96
+ log = logging.getLogger(__name__)
97
+
98
+ PROXY_TYPE_SOCKS4 = SOCKS4 = 1
99
+ PROXY_TYPE_SOCKS5 = SOCKS5 = 2
100
+ PROXY_TYPE_HTTP = HTTP = 3
101
+
102
+ PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP}
103
+ PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys()))
104
+
105
+ _orgsocket = _orig_socket = socket.socket
106
+
107
+
108
+ def set_self_blocking(function):
109
+
110
+ @functools.wraps(function)
111
+ def wrapper(*args, **kwargs):
112
+ self = args[0]
113
+ try:
114
+ _is_blocking = self.gettimeout()
115
+ if _is_blocking == 0:
116
+ self.setblocking(True)
117
+ return function(*args, **kwargs)
118
+ except Exception as e:
119
+ raise
120
+ finally:
121
+ # set orgin blocking
122
+ if _is_blocking == 0:
123
+ self.setblocking(False)
124
+ return wrapper
125
+
126
+
127
+ class ProxyError(IOError):
128
+ """Socket_err contains original socket.error exception."""
129
+ def __init__(self, msg, socket_err=None):
130
+ self.msg = msg
131
+ self.socket_err = socket_err
132
+
133
+ if socket_err:
134
+ self.msg += ": {0}".format(socket_err)
135
+
136
+ def __str__(self):
137
+ return self.msg
138
+
139
+
140
+ class GeneralProxyError(ProxyError):
141
+ pass
142
+
143
+
144
+ class ProxyConnectionError(ProxyError):
145
+ pass
146
+
147
+
148
+ class SOCKS5AuthError(ProxyError):
149
+ pass
150
+
151
+
152
+ class SOCKS5Error(ProxyError):
153
+ pass
154
+
155
+
156
+ class SOCKS4Error(ProxyError):
157
+ pass
158
+
159
+
160
+ class HTTPError(ProxyError):
161
+ pass
162
+
163
+ SOCKS4_ERRORS = {
164
+ 0x5B: "Request rejected or failed",
165
+ 0x5C: ("Request rejected because SOCKS server cannot connect to identd on"
166
+ " the client"),
167
+ 0x5D: ("Request rejected because the client program and identd report"
168
+ " different user-ids")
169
+ }
170
+
171
+ SOCKS5_ERRORS = {
172
+ 0x01: "General SOCKS server failure",
173
+ 0x02: "Connection not allowed by ruleset",
174
+ 0x03: "Network unreachable",
175
+ 0x04: "Host unreachable",
176
+ 0x05: "Connection refused",
177
+ 0x06: "TTL expired",
178
+ 0x07: "Command not supported, or protocol error",
179
+ 0x08: "Address type not supported"
180
+ }
181
+
182
+ DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080}
183
+
184
+
185
+ def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True,
186
+ username=None, password=None):
187
+ """Sets a default proxy.
188
+
189
+ All further socksocket objects will use the default unless explicitly
190
+ changed. All parameters are as for socket.set_proxy()."""
191
+ socksocket.default_proxy = (proxy_type, addr, port, rdns,
192
+ username.encode() if username else None,
193
+ password.encode() if password else None)
194
+
195
+
196
+ def setdefaultproxy(*args, **kwargs):
197
+ if "proxytype" in kwargs:
198
+ kwargs["proxy_type"] = kwargs.pop("proxytype")
199
+ return set_default_proxy(*args, **kwargs)
200
+
201
+
202
+ def get_default_proxy():
203
+ """Returns the default proxy, set by set_default_proxy."""
204
+ return socksocket.default_proxy
205
+
206
+ getdefaultproxy = get_default_proxy
207
+
208
+
209
+ def wrap_module(module):
210
+ """Attempts to replace a module's socket library with a SOCKS socket.
211
+
212
+ Must set a default proxy using set_default_proxy(...) first. This will
213
+ only work on modules that import socket directly into the namespace;
214
+ most of the Python Standard Library falls into this category."""
215
+ if socksocket.default_proxy:
216
+ module.socket.socket = socksocket
217
+ else:
218
+ raise GeneralProxyError("No default proxy specified")
219
+
220
+ wrapmodule = wrap_module
221
+
222
+
223
+ def create_connection(dest_pair,
224
+ timeout=None, source_address=None,
225
+ proxy_type=None, proxy_addr=None,
226
+ proxy_port=None, proxy_rdns=True,
227
+ proxy_username=None, proxy_password=None,
228
+ socket_options=None):
229
+ """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
230
+
231
+ Like socket.create_connection(), but connects to proxy
232
+ before returning the socket object.
233
+
234
+ dest_pair - 2-tuple of (IP/hostname, port).
235
+ **proxy_args - Same args passed to socksocket.set_proxy() if present.
236
+ timeout - Optional socket timeout value, in seconds.
237
+ source_address - tuple (host, port) for the socket to bind to as its source
238
+ address before connecting (only for compatibility)
239
+ """
240
+ # Remove IPv6 brackets on the remote address and proxy address.
241
+ remote_host, remote_port = dest_pair
242
+ if remote_host.startswith("["):
243
+ remote_host = remote_host.strip("[]")
244
+ if proxy_addr and proxy_addr.startswith("["):
245
+ proxy_addr = proxy_addr.strip("[]")
246
+
247
+ err = None
248
+
249
+ # Allow the SOCKS proxy to be on IPv4 or IPv6 addresses.
250
+ for r in socket.getaddrinfo(proxy_addr, proxy_port, 0, socket.SOCK_STREAM):
251
+ family, socket_type, proto, canonname, sa = r
252
+ sock = None
253
+ try:
254
+ sock = socksocket(family, socket_type, proto)
255
+
256
+ if socket_options:
257
+ for opt in socket_options:
258
+ sock.setsockopt(*opt)
259
+
260
+ if isinstance(timeout, (int, float)):
261
+ sock.settimeout(timeout)
262
+
263
+ if proxy_type:
264
+ sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns,
265
+ proxy_username, proxy_password)
266
+ if source_address:
267
+ sock.bind(source_address)
268
+
269
+ sock.connect((remote_host, remote_port))
270
+ return sock
271
+
272
+ except (socket.error, ProxyConnectionError) as e:
273
+ err = e
274
+ if sock:
275
+ sock.close()
276
+ sock = None
277
+
278
+ if err:
279
+ raise err
280
+
281
+ raise socket.error("gai returned empty list.")
282
+
283
+
284
+ class _BaseSocket(socket.socket):
285
+ """Allows Python 2 delegated methods such as send() to be overridden."""
286
+ def __init__(self, *pos, **kw):
287
+ _orig_socket.__init__(self, *pos, **kw)
288
+
289
+ self._savedmethods = dict()
290
+ for name in self._savenames:
291
+ self._savedmethods[name] = getattr(self, name)
292
+ delattr(self, name) # Allows normal overriding mechanism to work
293
+
294
+ _savenames = list()
295
+
296
+
297
+ def _makemethod(name):
298
+ return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
299
+ for name in ("sendto", "send", "recvfrom", "recv"):
300
+ method = getattr(_BaseSocket, name, None)
301
+
302
+ # Determine if the method is not defined the usual way
303
+ # as a function in the class.
304
+ # Python 2 uses __slots__, so there are descriptors for each method,
305
+ # but they are not functions.
306
+ if not isinstance(method, Callable):
307
+ _BaseSocket._savenames.append(name)
308
+ setattr(_BaseSocket, name, _makemethod(name))
309
+
310
+
311
+ class socksocket(_BaseSocket):
312
+ """socksocket([family[, type[, proto]]]) -> socket object
313
+
314
+ Open a SOCKS enabled socket. The parameters are the same as
315
+ those of the standard socket init. In order for SOCKS to work,
316
+ you must specify family=AF_INET and proto=0.
317
+ The "type" argument must be either SOCK_STREAM or SOCK_DGRAM.
318
+ """
319
+
320
+ default_proxy = None
321
+
322
+ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM,
323
+ proto=0, *args, **kwargs):
324
+ if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
325
+ msg = "Socket type must be stream or datagram, not {!r}"
326
+ raise ValueError(msg.format(type))
327
+
328
+ super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
329
+ self._proxyconn = None # TCP connection to keep UDP relay alive
330
+
331
+ if self.default_proxy:
332
+ self.proxy = self.default_proxy
333
+ else:
334
+ self.proxy = (None, None, None, None, None, None)
335
+ self.proxy_sockname = None
336
+ self.proxy_peername = None
337
+
338
+ self._timeout = None
339
+
340
+ def _readall(self, file, count):
341
+ """Receive EXACTLY the number of bytes requested from the file object.
342
+
343
+ Blocks until the required number of bytes have been received."""
344
+ data = b""
345
+ while len(data) < count:
346
+ d = file.read(count - len(data))
347
+ if not d:
348
+ raise GeneralProxyError("Connection closed unexpectedly")
349
+ data += d
350
+ return data
351
+
352
+ def settimeout(self, timeout):
353
+ self._timeout = timeout
354
+ try:
355
+ # test if we're connected, if so apply timeout
356
+ peer = self.get_proxy_peername()
357
+ super(socksocket, self).settimeout(self._timeout)
358
+ except socket.error:
359
+ pass
360
+
361
+ def gettimeout(self):
362
+ return self._timeout
363
+
364
+ def setblocking(self, v):
365
+ if v:
366
+ self.settimeout(None)
367
+ else:
368
+ self.settimeout(0.0)
369
+
370
+ def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True,
371
+ username=None, password=None):
372
+ """ Sets the proxy to be used.
373
+
374
+ proxy_type - The type of the proxy to be used. Three types
375
+ are supported: PROXY_TYPE_SOCKS4 (including socks4a),
376
+ PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
377
+ addr - The address of the server (IP or DNS).
378
+ port - The port of the server. Defaults to 1080 for SOCKS
379
+ servers and 8080 for HTTP proxy servers.
380
+ rdns - Should DNS queries be performed on the remote side
381
+ (rather than the local side). The default is True.
382
+ Note: This has no effect with SOCKS4 servers.
383
+ username - Username to authenticate with to the server.
384
+ The default is no authentication.
385
+ password - Password to authenticate with to the server.
386
+ Only relevant when username is also provided."""
387
+ self.proxy = (proxy_type, addr, port, rdns,
388
+ username.encode() if username else None,
389
+ password.encode() if password else None)
390
+
391
+ def setproxy(self, *args, **kwargs):
392
+ if "proxytype" in kwargs:
393
+ kwargs["proxy_type"] = kwargs.pop("proxytype")
394
+ return self.set_proxy(*args, **kwargs)
395
+
396
+ def bind(self, *pos, **kw):
397
+ """Implements proxy connection for UDP sockets.
398
+
399
+ Happens during the bind() phase."""
400
+ (proxy_type, proxy_addr, proxy_port, rdns, username,
401
+ password) = self.proxy
402
+ if not proxy_type or self.type != socket.SOCK_DGRAM:
403
+ return _orig_socket.bind(self, *pos, **kw)
404
+
405
+ if self._proxyconn:
406
+ raise socket.error(EINVAL, "Socket already bound to an address")
407
+ if proxy_type != SOCKS5:
408
+ msg = "UDP only supported by SOCKS5 proxy type"
409
+ raise socket.error(EOPNOTSUPP, msg)
410
+ super(socksocket, self).bind(*pos, **kw)
411
+
412
+ # Need to specify actual local port because
413
+ # some relays drop packets if a port of zero is specified.
414
+ # Avoid specifying host address in case of NAT though.
415
+ _, port = self.getsockname()
416
+ dst = ("0", port)
417
+
418
+ self._proxyconn = _orig_socket()
419
+ proxy = self._proxy_addr()
420
+ self._proxyconn.connect(proxy)
421
+
422
+ UDP_ASSOCIATE = b"\x03"
423
+ _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
424
+
425
+ # The relay is most likely on the same host as the SOCKS proxy,
426
+ # but some proxies return a private IP address (10.x.y.z)
427
+ host, _ = proxy
428
+ _, port = relay
429
+ super(socksocket, self).connect((host, port))
430
+ super(socksocket, self).settimeout(self._timeout)
431
+ self.proxy_sockname = ("0.0.0.0", 0) # Unknown
432
+
433
+ def sendto(self, bytes, *args, **kwargs):
434
+ if self.type != socket.SOCK_DGRAM:
435
+ return super(socksocket, self).sendto(bytes, *args, **kwargs)
436
+ if not self._proxyconn:
437
+ self.bind(("", 0))
438
+
439
+ address = args[-1]
440
+ flags = args[:-1]
441
+
442
+ header = BytesIO()
443
+ RSV = b"\x00\x00"
444
+ header.write(RSV)
445
+ STANDALONE = b"\x00"
446
+ header.write(STANDALONE)
447
+ self._write_SOCKS5_address(address, header)
448
+
449
+ sent = super(socksocket, self).send(header.getvalue() + bytes, *flags,
450
+ **kwargs)
451
+ return sent - header.tell()
452
+
453
+ def send(self, bytes, flags=0, **kwargs):
454
+ if self.type == socket.SOCK_DGRAM:
455
+ return self.sendto(bytes, flags, self.proxy_peername, **kwargs)
456
+ else:
457
+ return super(socksocket, self).send(bytes, flags, **kwargs)
458
+
459
+ def recvfrom(self, bufsize, flags=0):
460
+ if self.type != socket.SOCK_DGRAM:
461
+ return super(socksocket, self).recvfrom(bufsize, flags)
462
+ if not self._proxyconn:
463
+ self.bind(("", 0))
464
+
465
+ buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags))
466
+ buf.seek(2, SEEK_CUR)
467
+ frag = buf.read(1)
468
+ if ord(frag):
469
+ raise NotImplementedError("Received UDP packet fragment")
470
+ fromhost, fromport = self._read_SOCKS5_address(buf)
471
+
472
+ if self.proxy_peername:
473
+ peerhost, peerport = self.proxy_peername
474
+ if fromhost != peerhost or peerport not in (0, fromport):
475
+ raise socket.error(EAGAIN, "Packet filtered")
476
+
477
+ return (buf.read(bufsize), (fromhost, fromport))
478
+
479
+ def recv(self, *pos, **kw):
480
+ bytes, _ = self.recvfrom(*pos, **kw)
481
+ return bytes
482
+
483
+ def close(self):
484
+ if self._proxyconn:
485
+ self._proxyconn.close()
486
+ return super(socksocket, self).close()
487
+
488
+ def get_proxy_sockname(self):
489
+ """Returns the bound IP address and port number at the proxy."""
490
+ return self.proxy_sockname
491
+
492
+ getproxysockname = get_proxy_sockname
493
+
494
+ def get_proxy_peername(self):
495
+ """
496
+ Returns the IP and port number of the proxy.
497
+ """
498
+ return self.getpeername()
499
+
500
+ getproxypeername = get_proxy_peername
501
+
502
+ def get_peername(self):
503
+ """Returns the IP address and port number of the destination machine.
504
+
505
+ Note: get_proxy_peername returns the proxy."""
506
+ return self.proxy_peername
507
+
508
+ getpeername = get_peername
509
+
510
+ def _negotiate_SOCKS5(self, *dest_addr):
511
+ """Negotiates a stream connection through a SOCKS5 server."""
512
+ CONNECT = b"\x01"
513
+ self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
514
+ self, CONNECT, dest_addr)
515
+
516
+ def _SOCKS5_request(self, conn, cmd, dst):
517
+ """
518
+ Send SOCKS5 request with given command (CMD field) and
519
+ address (DST field). Returns resolved DST address that was used.
520
+ """
521
+ proxy_type, addr, port, rdns, username, password = self.proxy
522
+
523
+ writer = conn.makefile("wb")
524
+ reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3
525
+ try:
526
+ # First we'll send the authentication packages we support.
527
+ if username and password:
528
+ # The username/password details were supplied to the
529
+ # set_proxy method so we support the USERNAME/PASSWORD
530
+ # authentication (in addition to the standard none).
531
+ writer.write(b"\x05\x02\x00\x02")
532
+ else:
533
+ # No username/password were entered, therefore we
534
+ # only support connections with no authentication.
535
+ writer.write(b"\x05\x01\x00")
536
+
537
+ # We'll receive the server's response to determine which
538
+ # method was selected
539
+ writer.flush()
540
+ chosen_auth = self._readall(reader, 2)
541
+
542
+ if chosen_auth[0:1] != b"\x05":
543
+ # Note: string[i:i+1] is used because indexing of a bytestring
544
+ # via bytestring[i] yields an integer in Python 3
545
+ raise GeneralProxyError(
546
+ "SOCKS5 proxy server sent invalid data")
547
+
548
+ # Check the chosen authentication method
549
+
550
+ if chosen_auth[1:2] == b"\x02":
551
+ # Okay, we need to perform a basic username/password
552
+ # authentication.
553
+ writer.write(b"\x01" + chr(len(username)).encode()
554
+ + username
555
+ + chr(len(password)).encode()
556
+ + password)
557
+ writer.flush()
558
+ auth_status = self._readall(reader, 2)
559
+ if auth_status[0:1] != b"\x01":
560
+ # Bad response
561
+ raise GeneralProxyError(
562
+ "SOCKS5 proxy server sent invalid data")
563
+ if auth_status[1:2] != b"\x00":
564
+ # Authentication failed
565
+ raise SOCKS5AuthError("SOCKS5 authentication failed")
566
+
567
+ # Otherwise, authentication succeeded
568
+
569
+ # No authentication is required if 0x00
570
+ elif chosen_auth[1:2] != b"\x00":
571
+ # Reaching here is always bad
572
+ if chosen_auth[1:2] == b"\xFF":
573
+ raise SOCKS5AuthError(
574
+ "All offered SOCKS5 authentication methods were"
575
+ " rejected")
576
+ else:
577
+ raise GeneralProxyError(
578
+ "SOCKS5 proxy server sent invalid data")
579
+
580
+ # Now we can request the actual connection
581
+ writer.write(b"\x05" + cmd + b"\x00")
582
+ resolved = self._write_SOCKS5_address(dst, writer)
583
+ writer.flush()
584
+
585
+ # Get the response
586
+ resp = self._readall(reader, 3)
587
+ if resp[0:1] != b"\x05":
588
+ raise GeneralProxyError(
589
+ "SOCKS5 proxy server sent invalid data")
590
+
591
+ status = ord(resp[1:2])
592
+ if status != 0x00:
593
+ # Connection failed: server returned an error
594
+ error = SOCKS5_ERRORS.get(status, "Unknown error")
595
+ raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
596
+
597
+ # Get the bound address/port
598
+ bnd = self._read_SOCKS5_address(reader)
599
+
600
+ super(socksocket, self).settimeout(self._timeout)
601
+ return (resolved, bnd)
602
+ finally:
603
+ reader.close()
604
+ writer.close()
605
+
606
+ def _write_SOCKS5_address(self, addr, file):
607
+ """
608
+ Return the host and port packed for the SOCKS5 protocol,
609
+ and the resolved address as a tuple object.
610
+ """
611
+ host, port = addr
612
+ proxy_type, _, _, rdns, username, password = self.proxy
613
+ family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}
614
+
615
+ # If the given destination address is an IP address, we'll
616
+ # use the IP address request even if remote resolving was specified.
617
+ # Detect whether the address is IPv4/6 directly.
618
+ for family in (socket.AF_INET, socket.AF_INET6):
619
+ try:
620
+ addr_bytes = socket.inet_pton(family, host)
621
+ file.write(family_to_byte[family] + addr_bytes)
622
+ host = socket.inet_ntop(family, addr_bytes)
623
+ file.write(struct.pack(">H", port))
624
+ return host, port
625
+ except socket.error:
626
+ continue
627
+
628
+ # Well it's not an IP number, so it's probably a DNS name.
629
+ if rdns:
630
+ # Resolve remotely
631
+ host_bytes = host.encode("idna")
632
+ file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
633
+ else:
634
+ # Resolve locally
635
+ addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
636
+ socket.SOCK_STREAM,
637
+ socket.IPPROTO_TCP,
638
+ socket.AI_ADDRCONFIG)
639
+ # We can't really work out what IP is reachable, so just pick the
640
+ # first.
641
+ target_addr = addresses[0]
642
+ family = target_addr[0]
643
+ host = target_addr[4][0]
644
+
645
+ addr_bytes = socket.inet_pton(family, host)
646
+ file.write(family_to_byte[family] + addr_bytes)
647
+ host = socket.inet_ntop(family, addr_bytes)
648
+ file.write(struct.pack(">H", port))
649
+ return host, port
650
+
651
+ def _read_SOCKS5_address(self, file):
652
+ atyp = self._readall(file, 1)
653
+ if atyp == b"\x01":
654
+ addr = socket.inet_ntoa(self._readall(file, 4))
655
+ elif atyp == b"\x03":
656
+ length = self._readall(file, 1)
657
+ addr = self._readall(file, ord(length))
658
+ elif atyp == b"\x04":
659
+ addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
660
+ else:
661
+ raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
662
+
663
+ port = struct.unpack(">H", self._readall(file, 2))[0]
664
+ return addr, port
665
+
666
+ def _negotiate_SOCKS4(self, dest_addr, dest_port):
667
+ """Negotiates a connection through a SOCKS4 server."""
668
+ proxy_type, addr, port, rdns, username, password = self.proxy
669
+
670
+ writer = self.makefile("wb")
671
+ reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3
672
+ try:
673
+ # Check if the destination address provided is an IP address
674
+ remote_resolve = False
675
+ try:
676
+ addr_bytes = socket.inet_aton(dest_addr)
677
+ except socket.error:
678
+ # It's a DNS name. Check where it should be resolved.
679
+ if rdns:
680
+ addr_bytes = b"\x00\x00\x00\x01"
681
+ remote_resolve = True
682
+ else:
683
+ addr_bytes = socket.inet_aton(
684
+ socket.gethostbyname(dest_addr))
685
+
686
+ # Construct the request packet
687
+ writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port))
688
+ writer.write(addr_bytes)
689
+
690
+ # The username parameter is considered userid for SOCKS4
691
+ if username:
692
+ writer.write(username)
693
+ writer.write(b"\x00")
694
+
695
+ # DNS name if remote resolving is required
696
+ # NOTE: This is actually an extension to the SOCKS4 protocol
697
+ # called SOCKS4A and may not be supported in all cases.
698
+ if remote_resolve:
699
+ writer.write(dest_addr.encode("idna") + b"\x00")
700
+ writer.flush()
701
+
702
+ # Get the response from the server
703
+ resp = self._readall(reader, 8)
704
+ if resp[0:1] != b"\x00":
705
+ # Bad data
706
+ raise GeneralProxyError(
707
+ "SOCKS4 proxy server sent invalid data")
708
+
709
+ status = ord(resp[1:2])
710
+ if status != 0x5A:
711
+ # Connection failed: server returned an error
712
+ error = SOCKS4_ERRORS.get(status, "Unknown error")
713
+ raise SOCKS4Error("{0:#04x}: {1}".format(status, error))
714
+
715
+ # Get the bound address/port
716
+ self.proxy_sockname = (socket.inet_ntoa(resp[4:]),
717
+ struct.unpack(">H", resp[2:4])[0])
718
+ if remote_resolve:
719
+ self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
720
+ else:
721
+ self.proxy_peername = dest_addr, dest_port
722
+ finally:
723
+ reader.close()
724
+ writer.close()
725
+
726
+ def _negotiate_HTTP(self, dest_addr, dest_port):
727
+ """Negotiates a connection through an HTTP server.
728
+
729
+ NOTE: This currently only supports HTTP CONNECT-style proxies."""
730
+ proxy_type, addr, port, rdns, username, password = self.proxy
731
+
732
+ # If we need to resolve locally, we do this now
733
+ addr = dest_addr if rdns else socket.gethostbyname(dest_addr)
734
+
735
+ http_headers = [
736
+ (b"CONNECT " + addr.encode("idna") + b":"
737
+ + str(dest_port).encode() + b" HTTP/1.1"),
738
+ b"Host: " + dest_addr.encode("idna")
739
+ ]
740
+
741
+ if username and password:
742
+ http_headers.append(b"Proxy-Authorization: basic "
743
+ + b64encode(username + b":" + password))
744
+
745
+ http_headers.append(b"\r\n")
746
+
747
+ self.sendall(b"\r\n".join(http_headers))
748
+
749
+ # We just need the first line to check if the connection was successful
750
+ fobj = self.makefile()
751
+ status_line = fobj.readline()
752
+ fobj.close()
753
+
754
+ if not status_line:
755
+ raise GeneralProxyError("Connection closed unexpectedly")
756
+
757
+ try:
758
+ proto, status_code, status_msg = status_line.split(" ", 2)
759
+ except ValueError:
760
+ raise GeneralProxyError("HTTP proxy server sent invalid response")
761
+
762
+ if not proto.startswith("HTTP/"):
763
+ raise GeneralProxyError(
764
+ "Proxy server does not appear to be an HTTP proxy")
765
+
766
+ try:
767
+ status_code = int(status_code)
768
+ except ValueError:
769
+ raise HTTPError(
770
+ "HTTP proxy server did not return a valid HTTP status")
771
+
772
+ if status_code != 200:
773
+ error = "{0}: {1}".format(status_code, status_msg)
774
+ if status_code in (400, 403, 405):
775
+ # It's likely that the HTTP proxy server does not support the
776
+ # CONNECT tunneling method
777
+ error += ("\n[*] Note: The HTTP proxy server may not be"
778
+ " supported by PySocks (must be a CONNECT tunnel"
779
+ " proxy)")
780
+ raise HTTPError(error)
781
+
782
+ self.proxy_sockname = (b"0.0.0.0", 0)
783
+ self.proxy_peername = addr, dest_port
784
+
785
+ _proxy_negotiators = {
786
+ SOCKS4: _negotiate_SOCKS4,
787
+ SOCKS5: _negotiate_SOCKS5,
788
+ HTTP: _negotiate_HTTP
789
+ }
790
+
791
+ @set_self_blocking
792
+ def connect(self, dest_pair):
793
+ """
794
+ Connects to the specified destination through a proxy.
795
+ Uses the same API as socket's connect().
796
+ To select the proxy server, use set_proxy().
797
+
798
+ dest_pair - 2-tuple of (IP/hostname, port).
799
+ """
800
+ if len(dest_pair) != 2 or dest_pair[0].startswith("["):
801
+ # Probably IPv6, not supported -- raise an error, and hope
802
+ # Happy Eyeballs (RFC6555) makes sure at least the IPv4
803
+ # connection works...
804
+ raise socket.error("PySocks doesn't support IPv6: %s"
805
+ % str(dest_pair))
806
+
807
+ dest_addr, dest_port = dest_pair
808
+
809
+ if self.type == socket.SOCK_DGRAM:
810
+ if not self._proxyconn:
811
+ self.bind(("", 0))
812
+ dest_addr = socket.gethostbyname(dest_addr)
813
+
814
+ # If the host address is INADDR_ANY or similar, reset the peer
815
+ # address so that packets are received from any peer
816
+ if dest_addr == "0.0.0.0" and not dest_port:
817
+ self.proxy_peername = None
818
+ else:
819
+ self.proxy_peername = (dest_addr, dest_port)
820
+ return
821
+
822
+ (proxy_type, proxy_addr, proxy_port, rdns, username,
823
+ password) = self.proxy
824
+
825
+ # Do a minimal input check first
826
+ if (not isinstance(dest_pair, (list, tuple))
827
+ or len(dest_pair) != 2
828
+ or not dest_addr
829
+ or not isinstance(dest_port, int)):
830
+ # Inputs failed, raise an error
831
+ raise GeneralProxyError(
832
+ "Invalid destination-connection (host, port) pair")
833
+
834
+ # We set the timeout here so that we don't hang in connection or during
835
+ # negotiation.
836
+ super(socksocket, self).settimeout(self._timeout)
837
+
838
+ if proxy_type is None:
839
+ # Treat like regular socket object
840
+ self.proxy_peername = dest_pair
841
+ super(socksocket, self).settimeout(self._timeout)
842
+ super(socksocket, self).connect((dest_addr, dest_port))
843
+ return
844
+
845
+ proxy_addr = self._proxy_addr()
846
+
847
+ try:
848
+ # Initial connection to proxy server.
849
+ super(socksocket, self).connect(proxy_addr)
850
+
851
+ except socket.error as error:
852
+ # Error while connecting to proxy
853
+ self.close()
854
+ proxy_addr, proxy_port = proxy_addr
855
+ proxy_server = "{0}:{1}".format(proxy_addr, proxy_port)
856
+ printable_type = PRINTABLE_PROXY_TYPES[proxy_type]
857
+
858
+ msg = "Error connecting to {0} proxy {1}".format(printable_type,
859
+ proxy_server)
860
+ log.debug("%s due to: %s", msg, error)
861
+ raise ProxyConnectionError(msg, error)
862
+
863
+ else:
864
+ # Connected to proxy server, now negotiate
865
+ try:
866
+ # Calls negotiate_{SOCKS4, SOCKS5, HTTP}
867
+ negotiate = self._proxy_negotiators[proxy_type]
868
+ negotiate(self, dest_addr, dest_port)
869
+ except socket.error as error:
870
+ # Wrap socket errors
871
+ self.close()
872
+ raise GeneralProxyError("Socket error", error)
873
+ except ProxyError:
874
+ # Protocol error while negotiating with proxy
875
+ self.close()
876
+ raise
877
+
878
+ def _proxy_addr(self):
879
+ """
880
+ Return proxy address to connect to as tuple object
881
+ """
882
+ (proxy_type, proxy_addr, proxy_port, rdns, username,
883
+ password) = self.proxy
884
+ proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type)
885
+ if not proxy_port:
886
+ raise GeneralProxyError("Invalid proxy type")
887
+ return proxy_addr, proxy_port