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,396 @@
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
+ from __future__ import absolute_import
16
+ import errno
17
+ import warnings
18
+ import hmac
19
+ import socket
20
+
21
+ from binascii import hexlify, unhexlify
22
+ from hashlib import md5, sha1, sha256
23
+
24
+ from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning
25
+ from ..packages import six
26
+
27
+
28
+ SSLContext = None
29
+ HAS_SNI = False
30
+ IS_PYOPENSSL = False
31
+ IS_SECURETRANSPORT = False
32
+
33
+ # Maps the length of a digest to a possible hash function producing this digest
34
+ HASHFUNC_MAP = {
35
+ 32: md5,
36
+ 40: sha1,
37
+ 64: sha256,
38
+ }
39
+
40
+
41
+ def _const_compare_digest_backport(a, b):
42
+ """
43
+ Compare two digests of equal length in constant time.
44
+
45
+ The digests must be of type str/bytes.
46
+ Returns True if the digests match, and False otherwise.
47
+ """
48
+ result = abs(len(a) - len(b))
49
+ for l, r in zip(bytearray(a), bytearray(b)):
50
+ result |= l ^ r
51
+ return result == 0
52
+
53
+
54
+ _const_compare_digest = getattr(hmac, 'compare_digest',
55
+ _const_compare_digest_backport)
56
+
57
+
58
+ try: # Test for SSL features
59
+ import ssl
60
+ from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
61
+ from ssl import HAS_SNI # Has SNI?
62
+ except ImportError:
63
+ pass
64
+
65
+
66
+ try:
67
+ from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION
68
+ except ImportError:
69
+ OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
70
+ OP_NO_COMPRESSION = 0x20000
71
+
72
+
73
+ # Python 2.7 doesn't have inet_pton on non-Linux so we fallback on inet_aton in
74
+ # those cases. This means that we can only detect IPv4 addresses in this case.
75
+ if hasattr(socket, 'inet_pton'):
76
+ inet_pton = socket.inet_pton
77
+ else:
78
+ # Maybe we can use ipaddress if the user has urllib3[secure]?
79
+ try:
80
+ import ipaddress
81
+
82
+ def inet_pton(_, host):
83
+ if isinstance(host, bytes):
84
+ host = host.decode('ascii')
85
+ return ipaddress.ip_address(host)
86
+
87
+ except ImportError: # Platform-specific: Non-Linux
88
+ def inet_pton(_, host):
89
+ return socket.inet_aton(host)
90
+
91
+
92
+ # A secure default.
93
+ # Sources for more information on TLS ciphers:
94
+ #
95
+ # - https://wiki.mozilla.org/Security/Server_Side_TLS
96
+ # - https://www.ssllabs.com/projects/best-practices/index.html
97
+ # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
98
+ #
99
+ # The general intent is:
100
+ # - Prefer TLS 1.3 cipher suites
101
+ # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
102
+ # - prefer ECDHE over DHE for better performance,
103
+ # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
104
+ # security,
105
+ # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
106
+ # - disable NULL authentication, MD5 MACs and DSS for security reasons.
107
+ DEFAULT_CIPHERS = ':'.join([
108
+ 'TLS13-AES-256-GCM-SHA384',
109
+ 'TLS13-CHACHA20-POLY1305-SHA256',
110
+ 'TLS13-AES-128-GCM-SHA256',
111
+ 'ECDH+AESGCM',
112
+ 'ECDH+CHACHA20',
113
+ 'DH+AESGCM',
114
+ 'DH+CHACHA20',
115
+ 'ECDH+AES256',
116
+ 'DH+AES256',
117
+ 'ECDH+AES128',
118
+ 'DH+AES',
119
+ 'RSA+AESGCM',
120
+ 'RSA+AES',
121
+ '!aNULL',
122
+ '!eNULL',
123
+ '!MD5',
124
+ ])
125
+
126
+ try:
127
+ from ssl import SSLContext # Modern SSL?
128
+ except ImportError:
129
+ class SSLContext(object): # Platform-specific: Python 2
130
+ def __init__(self, protocol_version):
131
+ self.protocol = protocol_version
132
+ # Use default values from a real SSLContext
133
+ self.check_hostname = False
134
+ self.verify_mode = ssl.CERT_NONE
135
+ self.ca_certs = None
136
+ self.options = 0
137
+ self.certfile = None
138
+ self.keyfile = None
139
+ self.ciphers = None
140
+
141
+ def load_cert_chain(self, certfile, keyfile):
142
+ self.certfile = certfile
143
+ self.keyfile = keyfile
144
+
145
+ def load_verify_locations(self, cafile=None, capath=None):
146
+ self.ca_certs = cafile
147
+
148
+ if capath is not None:
149
+ raise SSLError("CA directories not supported in older Pythons")
150
+
151
+ def set_ciphers(self, cipher_suite):
152
+ self.ciphers = cipher_suite
153
+
154
+ def wrap_socket(self, socket, server_hostname=None, server_side=False):
155
+ warnings.warn(
156
+ 'A true SSLContext object is not available. This prevents '
157
+ 'urllib3 from configuring SSL appropriately and may cause '
158
+ 'certain SSL connections to fail. You can upgrade to a newer '
159
+ 'version of Python to solve this. For more information, see '
160
+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
161
+ '#ssl-warnings',
162
+ InsecurePlatformWarning
163
+ )
164
+ kwargs = {
165
+ 'keyfile': self.keyfile,
166
+ 'certfile': self.certfile,
167
+ 'ca_certs': self.ca_certs,
168
+ 'cert_reqs': self.verify_mode,
169
+ 'ssl_version': self.protocol,
170
+ 'server_side': server_side,
171
+ }
172
+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
173
+
174
+
175
+ def assert_fingerprint(cert, fingerprint):
176
+ """
177
+ Checks if given fingerprint matches the supplied certificate.
178
+
179
+ :param cert:
180
+ Certificate as bytes object.
181
+ :param fingerprint:
182
+ Fingerprint as string of hexdigits, can be interspersed by colons.
183
+ """
184
+
185
+ fingerprint = fingerprint.replace(':', '').lower()
186
+ digest_length = len(fingerprint)
187
+ hashfunc = HASHFUNC_MAP.get(digest_length)
188
+ if not hashfunc:
189
+ raise SSLError(
190
+ 'Fingerprint of invalid length: {0}'.format(fingerprint))
191
+
192
+ # We need encode() here for py32; works on py2 and p33.
193
+ fingerprint_bytes = unhexlify(fingerprint.encode())
194
+
195
+ cert_digest = hashfunc(cert).digest()
196
+
197
+ if not _const_compare_digest(cert_digest, fingerprint_bytes):
198
+ raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
199
+ .format(fingerprint, hexlify(cert_digest)))
200
+
201
+
202
+ def resolve_cert_reqs(candidate):
203
+ """
204
+ Resolves the argument to a numeric constant, which can be passed to
205
+ the wrap_socket function/method from the ssl module.
206
+ Defaults to :data:`ssl.CERT_NONE`.
207
+ If given a string it is assumed to be the name of the constant in the
208
+ :mod:`ssl` module or its abbreviation.
209
+ (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
210
+ If it's neither `None` nor a string we assume it is already the numeric
211
+ constant which can directly be passed to wrap_socket.
212
+ """
213
+ if candidate is None:
214
+ return CERT_NONE
215
+
216
+ if isinstance(candidate, str):
217
+ res = getattr(ssl, candidate, None)
218
+ if res is None:
219
+ res = getattr(ssl, 'CERT_' + candidate)
220
+ return res
221
+
222
+ return candidate
223
+
224
+
225
+ def resolve_ssl_version(candidate):
226
+ """
227
+ like resolve_cert_reqs
228
+ """
229
+ if candidate is None:
230
+ return PROTOCOL_SSLv23
231
+
232
+ if isinstance(candidate, str):
233
+ res = getattr(ssl, candidate, None)
234
+ if res is None:
235
+ res = getattr(ssl, 'PROTOCOL_' + candidate)
236
+ return res
237
+
238
+ return candidate
239
+
240
+
241
+ def create_urllib3_context(ssl_version=None, cert_reqs=None,
242
+ options=None, ciphers=None):
243
+ """All arguments have the same meaning as ``ssl_wrap_socket``.
244
+
245
+ By default, this function does a lot of the same work that
246
+ ``ssl.create_default_context`` does on Python 3.4+. It:
247
+
248
+ - Disables SSLv2, SSLv3, and compression
249
+ - Sets a restricted set of server ciphers
250
+
251
+ If you wish to enable SSLv3, you can do::
252
+
253
+ from urllib3.util import ssl_
254
+ context = ssl_.create_urllib3_context()
255
+ context.options &= ~ssl_.OP_NO_SSLv3
256
+
257
+ You can do the same to enable compression (substituting ``COMPRESSION``
258
+ for ``SSLv3`` in the last line above).
259
+
260
+ :param ssl_version:
261
+ The desired protocol version to use. This will default to
262
+ PROTOCOL_SSLv23 which will negotiate the highest protocol that both
263
+ the server and your installation of OpenSSL support.
264
+ :param cert_reqs:
265
+ Whether to require the certificate verification. This defaults to
266
+ ``ssl.CERT_REQUIRED``.
267
+ :param options:
268
+ Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
269
+ ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
270
+ :param ciphers:
271
+ Which cipher suites to allow the server to select.
272
+ :returns:
273
+ Constructed SSLContext object with specified options
274
+ :rtype: SSLContext
275
+ """
276
+ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
277
+
278
+ context.set_ciphers(ciphers or DEFAULT_CIPHERS)
279
+
280
+ # Setting the default here, as we may have no ssl module on import
281
+ cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
282
+
283
+ if options is None:
284
+ options = 0
285
+ # SSLv2 is easily broken and is considered harmful and dangerous
286
+ options |= OP_NO_SSLv2
287
+ # SSLv3 has several problems and is now dangerous
288
+ options |= OP_NO_SSLv3
289
+ # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
290
+ # (issue #309)
291
+ options |= OP_NO_COMPRESSION
292
+
293
+ context.options |= options
294
+
295
+ context.verify_mode = cert_reqs
296
+ if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
297
+ # We do our own verification, including fingerprints and alternative
298
+ # hostnames. So disable it here
299
+ context.check_hostname = False
300
+ return context
301
+
302
+
303
+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
304
+ ca_certs=None, server_hostname=None,
305
+ ssl_version=None, ciphers=None, ssl_context=None,
306
+ ca_cert_dir=None):
307
+ """
308
+ All arguments except for server_hostname, ssl_context, and ca_cert_dir have
309
+ the same meaning as they do when using :func:`ssl.wrap_socket`.
310
+
311
+ :param server_hostname:
312
+ When SNI is supported, the expected hostname of the certificate
313
+ :param ssl_context:
314
+ A pre-made :class:`SSLContext` object. If none is provided, one will
315
+ be created using :func:`create_urllib3_context`.
316
+ :param ciphers:
317
+ A string of ciphers we wish the client to support.
318
+ :param ca_cert_dir:
319
+ A directory containing CA certificates in multiple separate files, as
320
+ supported by OpenSSL's -CApath flag or the capath argument to
321
+ SSLContext.load_verify_locations().
322
+ """
323
+ context = ssl_context
324
+ if context is None:
325
+ # Note: This branch of code and all the variables in it are no longer
326
+ # used by urllib3 itself. We should consider deprecating and removing
327
+ # this code.
328
+ context = create_urllib3_context(ssl_version, cert_reqs,
329
+ ciphers=ciphers)
330
+
331
+ if ca_certs or ca_cert_dir:
332
+ try:
333
+ context.load_verify_locations(ca_certs, ca_cert_dir)
334
+ except IOError as e: # Platform-specific: Python 2.7
335
+ raise SSLError(e)
336
+ # Py33 raises FileNotFoundError which subclasses OSError
337
+ # These are not equivalent unless we check the errno attribute
338
+ except OSError as e: # Platform-specific: Python 3.3 and beyond
339
+ if e.errno == errno.ENOENT:
340
+ raise SSLError(e)
341
+ raise
342
+
343
+ # Don't load system certs unless there were no CA certs or
344
+ # SSLContext object specified manually.
345
+ elif ssl_context is None and hasattr(context, 'load_default_certs'):
346
+ # try to load OS default certs; works well on Windows (require Python3.4+)
347
+ context.load_default_certs()
348
+
349
+ if certfile:
350
+ context.load_cert_chain(certfile, keyfile)
351
+
352
+ # If we detect server_hostname is an IP address then the SNI
353
+ # extension should not be used according to RFC3546 Section 3.1
354
+ # We shouldn't warn the user if SNI isn't available but we would
355
+ # not be using SNI anyways due to IP address for server_hostname.
356
+ if ((server_hostname is not None and not is_ipaddress(server_hostname))
357
+ or IS_SECURETRANSPORT):
358
+ if HAS_SNI and server_hostname is not None:
359
+ return context.wrap_socket(sock, server_hostname=server_hostname)
360
+
361
+ warnings.warn(
362
+ 'An HTTPS request has been made, but the SNI (Server Name '
363
+ 'Indication) extension to TLS is not available on this platform. '
364
+ 'This may cause the server to present an incorrect TLS '
365
+ 'certificate, which can cause validation failures. You can upgrade to '
366
+ 'a newer version of Python to solve this. For more information, see '
367
+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
368
+ '#ssl-warnings',
369
+ SNIMissingWarning
370
+ )
371
+
372
+ return context.wrap_socket(sock)
373
+
374
+
375
+ def is_ipaddress(hostname):
376
+ """Detects whether the hostname given is an IP address.
377
+
378
+ :param str hostname: Hostname to examine.
379
+ :return: True if the hostname is an IP address, False otherwise.
380
+ """
381
+ if six.PY3 and isinstance(hostname, bytes):
382
+ # IDN A-label bytes are ASCII compatible.
383
+ hostname = hostname.decode('ascii')
384
+
385
+ families = [socket.AF_INET]
386
+ if hasattr(socket, 'AF_INET6'):
387
+ families.append(socket.AF_INET6)
388
+
389
+ for af in families:
390
+ try:
391
+ inet_pton(af, hostname)
392
+ except (socket.error, ValueError, OSError):
393
+ pass
394
+ else:
395
+ return True
396
+ return False
@@ -0,0 +1,256 @@
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
+ from __future__ import absolute_import
16
+ # The default socket timeout, used by httplib to indicate that no timeout was
17
+ # specified by the user
18
+ from socket import _GLOBAL_DEFAULT_TIMEOUT
19
+ import time
20
+
21
+ from ..exceptions import TimeoutStateError
22
+
23
+ # A sentinel value to indicate that no timeout was specified by the user in
24
+ # urllib3
25
+ _Default = object()
26
+
27
+
28
+ # Use time.monotonic if available.
29
+ current_time = getattr(time, "monotonic", time.time)
30
+
31
+
32
+ class Timeout(object):
33
+ """ Timeout configuration.
34
+
35
+ Timeouts can be defined as a default for a pool::
36
+
37
+ timeout = Timeout(connect=2.0, read=7.0)
38
+ http = PoolManager(timeout=timeout)
39
+ response = http.request('GET', 'http://example.com/')
40
+
41
+ Or per-request (which overrides the default for the pool)::
42
+
43
+ response = http.request('GET', 'http://example.com/', timeout=Timeout(10))
44
+
45
+ Timeouts can be disabled by setting all the parameters to ``None``::
46
+
47
+ no_timeout = Timeout(connect=None, read=None)
48
+ response = http.request('GET', 'http://example.com/, timeout=no_timeout)
49
+
50
+
51
+ :param total:
52
+ This combines the connect and read timeouts into one; the read timeout
53
+ will be set to the time leftover from the connect attempt. In the
54
+ event that both a connect timeout and a total are specified, or a read
55
+ timeout and a total are specified, the shorter timeout will be applied.
56
+
57
+ Defaults to None.
58
+
59
+ :type total: integer, float, or None
60
+
61
+ :param connect:
62
+ The maximum amount of time to wait for a connection attempt to a server
63
+ to succeed. Omitting the parameter will default the connect timeout to
64
+ the system default, probably `the global default timeout in socket.py
65
+ <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
66
+ None will set an infinite timeout for connection attempts.
67
+
68
+ :type connect: integer, float, or None
69
+
70
+ :param read:
71
+ The maximum amount of time to wait between consecutive
72
+ read operations for a response from the server. Omitting
73
+ the parameter will default the read timeout to the system
74
+ default, probably `the global default timeout in socket.py
75
+ <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
76
+ None will set an infinite timeout.
77
+
78
+ :type read: integer, float, or None
79
+
80
+ .. note::
81
+
82
+ Many factors can affect the total amount of time for urllib3 to return
83
+ an HTTP response.
84
+
85
+ For example, Python's DNS resolver does not obey the timeout specified
86
+ on the socket. Other factors that can affect total request time include
87
+ high CPU load, high swap, the program running at a low priority level,
88
+ or other behaviors.
89
+
90
+ In addition, the read and total timeouts only measure the time between
91
+ read operations on the socket connecting the client and the server,
92
+ not the total amount of time for the request to return a complete
93
+ response. For most requests, the timeout is raised because the server
94
+ has not sent the first byte in the specified time. This is not always
95
+ the case; if a server streams one byte every fifteen seconds, a timeout
96
+ of 20 seconds will not trigger, even though the request will take
97
+ several minutes to complete.
98
+
99
+ If your goal is to cut off any request after a set amount of wall clock
100
+ time, consider having a second "watcher" thread to cut off a slow
101
+ request.
102
+ """
103
+
104
+ #: A sentinel object representing the default timeout value
105
+ DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT
106
+
107
+ def __init__(self, total=None, connect=_Default, read=_Default):
108
+ self._connect = self._validate_timeout(connect, 'connect')
109
+ self._read = self._validate_timeout(read, 'read')
110
+ self.total = self._validate_timeout(total, 'total')
111
+ self._start_connect = None
112
+
113
+ def __str__(self):
114
+ return '%s(connect=%r, read=%r, total=%r)' % (
115
+ type(self).__name__, self._connect, self._read, self.total)
116
+
117
+ @classmethod
118
+ def _validate_timeout(cls, value, name):
119
+ """ Check that a timeout attribute is valid.
120
+
121
+ :param value: The timeout value to validate
122
+ :param name: The name of the timeout attribute to validate. This is
123
+ used to specify in error messages.
124
+ :return: The validated and casted version of the given value.
125
+ :raises ValueError: If it is a numeric value less than or equal to
126
+ zero, or the type is not an integer, float, or None.
127
+ """
128
+ if value is _Default:
129
+ return cls.DEFAULT_TIMEOUT
130
+
131
+ if value is None or value is cls.DEFAULT_TIMEOUT:
132
+ return value
133
+
134
+ if isinstance(value, bool):
135
+ raise ValueError("Timeout cannot be a boolean value. It must "
136
+ "be an int, float or None.")
137
+ try:
138
+ float(value)
139
+ except (TypeError, ValueError):
140
+ raise ValueError("Timeout value %s was %s, but it must be an "
141
+ "int, float or None." % (name, value))
142
+
143
+ try:
144
+ if value <= 0:
145
+ raise ValueError("Attempted to set %s timeout to %s, but the "
146
+ "timeout cannot be set to a value less "
147
+ "than or equal to 0." % (name, value))
148
+ except TypeError: # Python 3
149
+ raise ValueError("Timeout value %s was %s, but it must be an "
150
+ "int, float or None." % (name, value))
151
+
152
+ return value
153
+
154
+ @classmethod
155
+ def from_float(cls, timeout):
156
+ """ Create a new Timeout from a legacy timeout value.
157
+
158
+ The timeout value used by httplib.py sets the same timeout on the
159
+ connect(), and recv() socket requests. This creates a :class:`Timeout`
160
+ object that sets the individual timeouts to the ``timeout`` value
161
+ passed to this function.
162
+
163
+ :param timeout: The legacy timeout value.
164
+ :type timeout: integer, float, sentinel default object, or None
165
+ :return: Timeout object
166
+ :rtype: :class:`Timeout`
167
+ """
168
+ return Timeout(read=timeout, connect=timeout)
169
+
170
+ def clone(self):
171
+ """ Create a copy of the timeout object
172
+
173
+ Timeout properties are stored per-pool but each request needs a fresh
174
+ Timeout object to ensure each one has its own start/stop configured.
175
+
176
+ :return: a copy of the timeout object
177
+ :rtype: :class:`Timeout`
178
+ """
179
+ # We can't use copy.deepcopy because that will also create a new object
180
+ # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
181
+ # detect the user default.
182
+ return Timeout(connect=self._connect, read=self._read,
183
+ total=self.total)
184
+
185
+ def start_connect(self):
186
+ """ Start the timeout clock, used during a connect() attempt
187
+
188
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
189
+ to start a timer that has been started already.
190
+ """
191
+ if self._start_connect is not None:
192
+ raise TimeoutStateError("Timeout timer has already been started.")
193
+ self._start_connect = current_time()
194
+ return self._start_connect
195
+
196
+ def get_connect_duration(self):
197
+ """ Gets the time elapsed since the call to :meth:`start_connect`.
198
+
199
+ :return: Elapsed time.
200
+ :rtype: float
201
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
202
+ to get duration for a timer that hasn't been started.
203
+ """
204
+ if self._start_connect is None:
205
+ raise TimeoutStateError("Can't get connect duration for timer "
206
+ "that has not started.")
207
+ return current_time() - self._start_connect
208
+
209
+ @property
210
+ def connect_timeout(self):
211
+ """ Get the value to use when setting a connection timeout.
212
+
213
+ This will be a positive float or integer, the value None
214
+ (never timeout), or the default system timeout.
215
+
216
+ :return: Connect timeout.
217
+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
218
+ """
219
+ if self.total is None:
220
+ return self._connect
221
+
222
+ if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
223
+ return self.total
224
+
225
+ return min(self._connect, self.total)
226
+
227
+ @property
228
+ def read_timeout(self):
229
+ """ Get the value for the read timeout.
230
+
231
+ This assumes some time has elapsed in the connection timeout and
232
+ computes the read timeout appropriately.
233
+
234
+ If self.total is set, the read timeout is dependent on the amount of
235
+ time taken by the connect timeout. If the connection time has not been
236
+ established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
237
+ raised.
238
+
239
+ :return: Value to use for the read timeout.
240
+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
241
+ :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
242
+ has not yet been called on this object.
243
+ """
244
+ if (self.total is not None and
245
+ self.total is not self.DEFAULT_TIMEOUT and
246
+ self._read is not None and
247
+ self._read is not self.DEFAULT_TIMEOUT):
248
+ # In case the connect timeout has not yet been established.
249
+ if self._start_connect is None:
250
+ return self._read
251
+ return max(0, min(self.total - self.get_connect_duration(),
252
+ self._read))
253
+ elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
254
+ return max(0, self.total - self.get_connect_duration())
255
+ else:
256
+ return self._read