_app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. self.has_teardown = False
  153. def update_args(self, *args):
  154. self.callback_args = args
  155. #print(self.callback_args)
  156. def send(self, data, opcode=ABNF.OPCODE_TEXT):
  157. """
  158. send message
  159. Parameters
  160. ----------
  161. data: str
  162. Message to send. If you set opcode to OPCODE_TEXT,
  163. data must be utf-8 string or unicode.
  164. opcode: int
  165. Operation code of data. Default is OPCODE_TEXT.
  166. """
  167. if not self.sock or self.sock.send(data, opcode) == 0:
  168. raise WebSocketConnectionClosedException(
  169. "Connection is already closed.")
  170. def close(self, **kwargs):
  171. """
  172. Close websocket connection.
  173. """
  174. self.keep_running = False
  175. if self.sock:
  176. self.sock.close(**kwargs)
  177. self.sock = None
  178. def _send_ping(self, interval, event, payload):
  179. while not event.wait(interval):
  180. self.last_ping_tm = time.time()
  181. if self.sock:
  182. try:
  183. self.sock.ping(payload)
  184. except Exception as ex:
  185. _logging.warning("send_ping routine terminated: {}".format(ex))
  186. break
  187. def run_forever(self, sockopt=None, sslopt=None,
  188. ping_interval=0, ping_timeout=None,
  189. ping_payload="",
  190. http_proxy_host=None, http_proxy_port=None,
  191. http_no_proxy=None, http_proxy_auth=None,
  192. skip_utf8_validation=False,
  193. host=None, origin=None, dispatcher=None,
  194. suppress_origin=False, proxy_type=None):
  195. """
  196. Run event loop for WebSocket framework.
  197. This loop is an infinite loop and is alive while websocket is available.
  198. Parameters
  199. ----------
  200. sockopt: tuple
  201. Values for socket.setsockopt.
  202. sockopt must be tuple
  203. and each element is argument of sock.setsockopt.
  204. sslopt: dict
  205. Optional dict object for ssl socket option.
  206. ping_interval: int or float
  207. Automatically send "ping" command
  208. every specified period (in seconds).
  209. If set to 0, no ping is sent periodically.
  210. ping_timeout: int or float
  211. Timeout (in seconds) if the pong message is not received.
  212. ping_payload: str
  213. Payload message to send with each ping.
  214. http_proxy_host: str
  215. HTTP proxy host name.
  216. http_proxy_port: int or str
  217. HTTP proxy port. If not set, set to 80.
  218. http_no_proxy: list
  219. Whitelisted host names that don't use the proxy.
  220. skip_utf8_validation: bool
  221. skip utf8 validation.
  222. host: str
  223. update host header.
  224. origin: str
  225. update origin header.
  226. dispatcher: Dispatcher object
  227. customize reading data from socket.
  228. suppress_origin: bool
  229. suppress outputting origin header.
  230. Returns
  231. -------
  232. teardown: bool
  233. False if caught KeyboardInterrupt, True if other exception was raised during a loop
  234. """
  235. if ping_timeout is not None and ping_timeout <= 0:
  236. raise WebSocketException("Ensure ping_timeout > 0")
  237. if ping_interval is not None and ping_interval < 0:
  238. raise WebSocketException("Ensure ping_interval >= 0")
  239. if ping_timeout and ping_interval and ping_interval <= ping_timeout:
  240. raise WebSocketException("Ensure ping_interval > ping_timeout")
  241. if not sockopt:
  242. sockopt = []
  243. if not sslopt:
  244. sslopt = {}
  245. if self.sock:
  246. raise WebSocketException("socket is already opened")
  247. thread = None
  248. self.keep_running = True
  249. self.last_ping_tm = 0
  250. self.last_pong_tm = 0
  251. def teardown(close_frame=None):
  252. """
  253. Tears down the connection.
  254. Parameters
  255. ----------
  256. close_frame: ABNF frame
  257. If close_frame is set, the on_close handler is invoked
  258. with the statusCode and reason from the provided frame.
  259. """
  260. if self.has_teardown:
  261. return
  262. self.has_teardown = True
  263. if thread and thread.is_alive():
  264. event.set()
  265. thread.join()
  266. self.keep_running = False
  267. if self.sock:
  268. self.sock.close()
  269. close_status_code, close_reason = self._get_close_args(
  270. close_frame if close_frame else None)
  271. self.sock = None
  272. # Finally call the callback AFTER all teardown is complete
  273. self._callback(self.on_close, close_status_code, close_reason,
  274. self.callback_args)
  275. try:
  276. self.sock = WebSocket(
  277. self.get_mask_key, sockopt=sockopt, sslopt=sslopt,
  278. fire_cont_frame=self.on_cont_message is not None,
  279. skip_utf8_validation=skip_utf8_validation,
  280. enable_multithread=True)
  281. self.sock.settimeout(getdefaulttimeout())
  282. self.sock.connect(
  283. self.url, header=self.header, cookie=self.cookie,
  284. http_proxy_host=http_proxy_host,
  285. http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy,
  286. http_proxy_auth=http_proxy_auth, subprotocols=self.subprotocols,
  287. host=host, origin=origin, suppress_origin=suppress_origin,
  288. proxy_type=proxy_type)
  289. if not dispatcher:
  290. dispatcher = self.create_dispatcher(ping_timeout)
  291. self._callback(self.on_open, self.callback_args)
  292. if ping_interval:
  293. event = threading.Event()
  294. thread = threading.Thread(
  295. target=self._send_ping, args=(ping_interval, event, ping_payload))
  296. thread.daemon = True
  297. thread.start()
  298. def read():
  299. if not self.keep_running:
  300. return teardown()
  301. op_code, frame = self.sock.recv_data_frame(True)
  302. if op_code == ABNF.OPCODE_CLOSE:
  303. return teardown(frame)
  304. elif op_code == ABNF.OPCODE_PING:
  305. self._callback(self.on_ping, frame.data, self.callback_args)
  306. elif op_code == ABNF.OPCODE_PONG:
  307. self.last_pong_tm = time.time()
  308. self._callback(self.on_pong, frame.data, self.callback_args)
  309. elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:
  310. self._callback(self.on_data, frame.data,
  311. frame.opcode, frame.fin, self.callback_args)
  312. self._callback(self.on_cont_message,
  313. frame.data, frame.fin, self.callback_args)
  314. else:
  315. data = frame.data
  316. if op_code == ABNF.OPCODE_TEXT:
  317. data = data.decode("utf-8")
  318. self._callback(self.on_message, data, self.callback_args)
  319. else:
  320. self._callback(self.on_data, data, frame.opcode, True,
  321. self.callback_args)
  322. return True
  323. def check():
  324. if (ping_timeout):
  325. has_timeout_expired = time.time() - self.last_ping_tm > ping_timeout
  326. has_pong_not_arrived_after_last_ping = self.last_pong_tm - self.last_ping_tm < 0
  327. has_pong_arrived_too_late = self.last_pong_tm - self.last_ping_tm > ping_timeout
  328. if (self.last_ping_tm and
  329. has_timeout_expired and
  330. (has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late)):
  331. raise WebSocketTimeoutException("ping/pong timed out")
  332. return True
  333. dispatcher.read(self.sock.sock, read, check)
  334. except (Exception, KeyboardInterrupt, SystemExit) as e:
  335. self._callback(self.on_error, e, self.callback_args)
  336. if isinstance(e, SystemExit):
  337. # propagate SystemExit further
  338. raise
  339. teardown()
  340. return not isinstance(e, KeyboardInterrupt)
  341. else:
  342. teardown()
  343. return True
  344. def create_dispatcher(self, ping_timeout):
  345. timeout = ping_timeout or 10
  346. if self.sock.is_ssl():
  347. return SSLDispatcher(self, timeout)
  348. return Dispatcher(self, timeout)
  349. def _get_close_args(self, close_frame):
  350. """
  351. _get_close_args extracts the close code and reason from the close body
  352. if it exists (RFC6455 says WebSocket Connection Close Code is optional)
  353. """
  354. # Need to catch the case where close_frame is None
  355. # Otherwise the following if statement causes an error
  356. if not self.on_close or not close_frame:
  357. return [None, None]
  358. # Extract close frame status code
  359. if close_frame.data and len(close_frame.data) >= 2:
  360. close_status_code = 256 * close_frame.data[0] + close_frame.data[1]
  361. reason = close_frame.data[2:].decode('utf-8')
  362. return [close_status_code, reason]
  363. else:
  364. # Most likely reached this because len(close_frame_data.data) < 2
  365. return [None, None]
  366. def _callback(self, callback, *args):
  367. if callback:
  368. try:
  369. callback(self, *args)
  370. except Exception as e:
  371. _logging.error("error from callback {}: {}".format(callback, e))
  372. if self.on_error:
  373. self.on_error(self, e)