_app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """
  2. """
  3. """
  4. _app.py
  5. websocket - WebSocket client library for Python
  6. Copyright 2021 engn33r
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. import selectors
  18. import sys
  19. import threading
  20. import time
  21. import traceback
  22. from ._abnf import ABNF
  23. from ._core import WebSocket, getdefaulttimeout
  24. from ._exceptions import *
  25. from . import _logging
  26. __all__ = ["WebSocketApp"]
  27. class Dispatcher:
  28. """
  29. Dispatcher
  30. """
  31. def __init__(self, app, ping_timeout):
  32. self.app = app
  33. self.ping_timeout = ping_timeout
  34. def read(self, sock, read_callback, check_callback):
  35. while self.app.keep_running:
  36. sel = selectors.DefaultSelector()
  37. sel.register(self.app.sock.sock, selectors.EVENT_READ)
  38. r = sel.select(self.ping_timeout)
  39. if r:
  40. if not read_callback():
  41. break
  42. check_callback()
  43. sel.close()
  44. class SSLDispatcher:
  45. """
  46. SSLDispatcher
  47. """
  48. def __init__(self, app, ping_timeout):
  49. self.app = app
  50. self.ping_timeout = ping_timeout
  51. def read(self, sock, read_callback, check_callback):
  52. while self.app.keep_running:
  53. r = self.select()
  54. if r:
  55. if not read_callback():
  56. break
  57. check_callback()
  58. def select(self):
  59. sock = self.app.sock.sock
  60. if sock.pending():
  61. return [sock,]
  62. sel = selectors.DefaultSelector()
  63. sel.register(sock, selectors.EVENT_READ)
  64. r = sel.select(self.ping_timeout)
  65. sel.close()
  66. if len(r) > 0:
  67. return r[0][0]
  68. class WebSocketApp:
  69. """
  70. Higher level of APIs are provided. The interface is like JavaScript WebSocket object.
  71. """
  72. def __init__(self, url, header=None,
  73. on_open=None, on_message=None, on_error=None,
  74. on_close=None, on_ping=None, on_pong=None,
  75. on_cont_message=None,
  76. keep_running=True, get_mask_key=None, cookie=None,
  77. subprotocols=None,
  78. on_data=None, callback_args=[]):
  79. """
  80. WebSocketApp initialization
  81. Parameters
  82. ----------
  83. url: str
  84. Websocket url.
  85. header: list or dict
  86. Custom header for websocket handshake.
  87. on_open: function
  88. Callback object which is called at opening websocket.
  89. on_open has one argument.
  90. The 1st argument is this class object.
  91. on_message: function
  92. Callback object which is called when received data.
  93. on_message has 2 arguments.
  94. The 1st argument is this class object.
  95. The 2nd argument is utf-8 data received from the server.
  96. on_error: function
  97. Callback object which is called when we get error.
  98. on_error has 2 arguments.
  99. The 1st argument is this class object.
  100. The 2nd argument is exception object.
  101. on_close: function
  102. Callback object which is called when connection is closed.
  103. on_close has 3 arguments.
  104. The 1st argument is this class object.
  105. The 2nd argument is close_status_code.
  106. The 3rd argument is close_msg.
  107. on_cont_message: function
  108. Callback object which is called when a continuation
  109. frame is received.
  110. on_cont_message has 3 arguments.
  111. The 1st argument is this class object.
  112. The 2nd argument is utf-8 string which we get from the server.
  113. The 3rd argument is continue flag. if 0, the data continue
  114. to next frame data
  115. on_data: function
  116. Callback object which is called when a message received.
  117. This is called before on_message or on_cont_message,
  118. and then on_message or on_cont_message is called.
  119. on_data has 4 argument.
  120. The 1st argument is this class object.
  121. The 2nd argument is utf-8 string which we get from the server.
  122. The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
  123. The 4th argument is continue flag. If 0, the data continue
  124. keep_running: bool
  125. This parameter is obsolete and ignored.
  126. get_mask_key: function
  127. A callable function to get new mask keys, see the
  128. WebSocket.set_mask_key's docstring for more information.
  129. cookie: str
  130. Cookie value.
  131. subprotocols: list
  132. List of available sub protocols. Default is None.
  133. """
  134. self.url = url
  135. self.header = header if header is not None else []
  136. self.cookie = cookie
  137. self.on_open = on_open
  138. self.on_message = on_message
  139. self.on_data = on_data
  140. self.on_error = on_error
  141. self.on_close = on_close
  142. self.on_ping = on_ping
  143. self.on_pong = on_pong
  144. self.on_cont_message = on_cont_message
  145. self.keep_running = False
  146. self.get_mask_key = get_mask_key
  147. self.sock = None
  148. self.last_ping_tm = 0
  149. self.last_pong_tm = 0
  150. self.subprotocols = subprotocols
  151. self.callback_args = callback_args
  152. def update_args(self, *args):
  153. self.callback_args = args
  154. #print(self.callback_args)
  155. def send(self, data, opcode=ABNF.OPCODE_TEXT):
  156. """
  157. send message
  158. Parameters
  159. ----------
  160. data: str
  161. Message to send. If you set opcode to OPCODE_TEXT,
  162. data must be utf-8 string or unicode.
  163. opcode: int
  164. Operation code of data. Default is OPCODE_TEXT.
  165. """
  166. if not self.sock or self.sock.send(data, opcode) == 0:
  167. raise WebSocketConnectionClosedException(
  168. "Connection is already closed.")
  169. def close(self, **kwargs):
  170. """
  171. Close websocket connection.
  172. """
  173. self.keep_running = False
  174. if self.sock:
  175. self.sock.close(**kwargs)
  176. self.sock = None
  177. def _send_ping(self, interval, event, payload):
  178. while not event.wait(interval):
  179. self.last_ping_tm = time.time()
  180. if self.sock:
  181. try:
  182. self.sock.ping(payload)
  183. except Exception as ex:
  184. _logging.warning("send_ping routine terminated: {}".format(ex))
  185. break
  186. def run_forever(self, sockopt=None, sslopt=None,
  187. ping_interval=0, ping_timeout=None,
  188. ping_payload="",
  189. http_proxy_host=None, http_proxy_port=None,
  190. http_no_proxy=None, http_proxy_auth=None,
  191. skip_utf8_validation=False,
  192. host=None, origin=None, dispatcher=None,
  193. suppress_origin=False, proxy_type=None):
  194. """
  195. Run event loop for WebSocket framework.
  196. This loop is an infinite loop and is alive while websocket is available.
  197. Parameters
  198. ----------
  199. sockopt: tuple
  200. Values for socket.setsockopt.
  201. sockopt must be tuple
  202. and each element is argument of sock.setsockopt.
  203. sslopt: dict
  204. Optional dict object for ssl socket option.
  205. ping_interval: int or float
  206. Automatically send "ping" command
  207. every specified period (in seconds).
  208. If set to 0, no ping is sent periodically.
  209. ping_timeout: int or float
  210. Timeout (in seconds) if the pong message is not received.
  211. ping_payload: str
  212. Payload message to send with each ping.
  213. http_proxy_host: str
  214. HTTP proxy host name.
  215. http_proxy_port: int or str
  216. HTTP proxy port. If not set, set to 80.
  217. http_no_proxy: list
  218. Whitelisted host names that don't use the proxy.
  219. skip_utf8_validation: bool
  220. skip utf8 validation.
  221. host: str
  222. update host header.
  223. origin: str
  224. update origin header.
  225. dispatcher: Dispatcher object
  226. customize reading data from socket.
  227. suppress_origin: bool
  228. suppress outputting origin header.
  229. Returns
  230. -------
  231. teardown: bool
  232. False if caught KeyboardInterrupt, True if other exception was raised during a loop
  233. """
  234. if ping_timeout is not None and ping_timeout <= 0:
  235. raise WebSocketException("Ensure ping_timeout > 0")
  236. if ping_interval is not None and ping_interval < 0:
  237. raise WebSocketException("Ensure ping_interval >= 0")
  238. if ping_timeout and ping_interval and ping_interval <= ping_timeout:
  239. raise WebSocketException("Ensure ping_interval > ping_timeout")
  240. if not sockopt:
  241. sockopt = []
  242. if not sslopt:
  243. sslopt = {}
  244. if self.sock:
  245. raise WebSocketException("socket is already opened")
  246. thread = None
  247. self.keep_running = True
  248. self.last_ping_tm = 0
  249. self.last_pong_tm = 0
  250. def teardown(close_frame=None):
  251. """
  252. Tears down the connection.
  253. Parameters
  254. ----------
  255. close_frame: ABNF frame
  256. If close_frame is set, the on_close handler is invoked
  257. with the statusCode and reason from the provided frame.
  258. """
  259. if thread and thread.is_alive():
  260. event.set()
  261. thread.join()
  262. self.keep_running = False
  263. if self.sock:
  264. self.sock.close()
  265. close_status_code, close_reason = self._get_close_args(
  266. close_frame if close_frame else None)
  267. self.sock = None
  268. # Finally call the callback AFTER all teardown is complete
  269. self._callback(self.on_close, close_status_code, close_reason,
  270. self.callback_args)
  271. try:
  272. self.sock = WebSocket(
  273. self.get_mask_key, sockopt=sockopt, sslopt=sslopt,
  274. fire_cont_frame=self.on_cont_message is not None,
  275. skip_utf8_validation=skip_utf8_validation,
  276. enable_multithread=True)
  277. self.sock.settimeout(getdefaulttimeout())
  278. self.sock.connect(
  279. self.url, header=self.header, cookie=self.cookie,
  280. http_proxy_host=http_proxy_host,
  281. http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy,
  282. http_proxy_auth=http_proxy_auth, subprotocols=self.subprotocols,
  283. host=host, origin=origin, suppress_origin=suppress_origin,
  284. proxy_type=proxy_type)
  285. if not dispatcher:
  286. dispatcher = self.create_dispatcher(ping_timeout)
  287. self._callback(self.on_open, self.callback_args)
  288. if ping_interval:
  289. event = threading.Event()
  290. thread = threading.Thread(
  291. target=self._send_ping, args=(ping_interval, event, ping_payload))
  292. thread.daemon = True
  293. thread.start()
  294. def read():
  295. if not self.keep_running:
  296. return teardown()
  297. op_code, frame = self.sock.recv_data_frame(True)
  298. if op_code == ABNF.OPCODE_CLOSE:
  299. return teardown(frame)
  300. elif op_code == ABNF.OPCODE_PING:
  301. self._callback(self.on_ping, frame.data, self.callback_args)
  302. elif op_code == ABNF.OPCODE_PONG:
  303. self.last_pong_tm = time.time()
  304. self._callback(self.on_pong, frame.data, self.callback_args)
  305. elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:
  306. self._callback(self.on_data, frame.data,
  307. frame.opcode, frame.fin, self.callback_args)
  308. self._callback(self.on_cont_message,
  309. frame.data, frame.fin, self.callback_args)
  310. else:
  311. data = frame.data
  312. if op_code == ABNF.OPCODE_TEXT:
  313. data = data.decode("utf-8")
  314. self._callback(self.on_message, data, self.callback_args)
  315. else:
  316. self._callback(self.on_data, data, frame.opcode, True,
  317. self.callback_args)
  318. return True
  319. def check():
  320. if (ping_timeout):
  321. has_timeout_expired = time.time() - self.last_ping_tm > ping_timeout
  322. has_pong_not_arrived_after_last_ping = self.last_pong_tm - self.last_ping_tm < 0
  323. has_pong_arrived_too_late = self.last_pong_tm - self.last_ping_tm > ping_timeout
  324. if (self.last_ping_tm and
  325. has_timeout_expired and
  326. (has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late)):
  327. raise WebSocketTimeoutException("ping/pong timed out")
  328. return True
  329. dispatcher.read(self.sock.sock, read, check)
  330. except (Exception, KeyboardInterrupt, SystemExit) as e:
  331. self._callback(self.on_error, e, self.callback_args)
  332. if isinstance(e, SystemExit):
  333. # propagate SystemExit further
  334. raise
  335. teardown()
  336. return not isinstance(e, KeyboardInterrupt)
  337. else:
  338. teardown()
  339. return True
  340. def create_dispatcher(self, ping_timeout):
  341. timeout = ping_timeout or 10
  342. if self.sock.is_ssl():
  343. return SSLDispatcher(self, timeout)
  344. return Dispatcher(self, timeout)
  345. def _get_close_args(self, close_frame):
  346. """
  347. _get_close_args extracts the close code and reason from the close body
  348. if it exists (RFC6455 says WebSocket Connection Close Code is optional)
  349. """
  350. # Need to catch the case where close_frame is None
  351. # Otherwise the following if statement causes an error
  352. if not self.on_close or not close_frame:
  353. return [None, None]
  354. # Extract close frame status code
  355. if close_frame.data and len(close_frame.data) >= 2:
  356. close_status_code = 256 * close_frame.data[0] + close_frame.data[1]
  357. reason = close_frame.data[2:].decode('utf-8')
  358. return [close_status_code, reason]
  359. else:
  360. # Most likely reached this because len(close_frame_data.data) < 2
  361. return [None, None]
  362. def _callback(self, callback, *args):
  363. if callback:
  364. try:
  365. callback(self, *args)
  366. except Exception as e:
  367. _logging.error("error from callback {}: {}".format(callback, e))
  368. if self.on_error:
  369. self.on_error(self, e)