_core.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. """
  2. _core.py
  3. ====================================
  4. WebSocket Python client
  5. """
  6. """
  7. _core.py
  8. websocket - WebSocket client library for Python
  9. Copyright 2021 engn33r
  10. Licensed under the Apache License, Version 2.0 (the "License");
  11. you may not use this file except in compliance with the License.
  12. You may obtain a copy of the License at
  13. http://www.apache.org/licenses/LICENSE-2.0
  14. Unless required by applicable law or agreed to in writing, software
  15. distributed under the License is distributed on an "AS IS" BASIS,
  16. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. See the License for the specific language governing permissions and
  18. limitations under the License.
  19. """
  20. import socket
  21. import struct
  22. import threading
  23. import time
  24. # websocket modules
  25. from ._abnf import *
  26. from ._exceptions import *
  27. from ._handshake import *
  28. from ._http import *
  29. from ._logging import *
  30. from ._socket import *
  31. from ._ssl_compat import *
  32. from ._utils import *
  33. __all__ = ['WebSocket', 'create_connection']
  34. class WebSocket:
  35. """
  36. Low level WebSocket interface.
  37. This class is based on the WebSocket protocol `draft-hixie-thewebsocketprotocol-76 <http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76>`_
  38. We can connect to the websocket server and send/receive data.
  39. The following example is an echo client.
  40. >>> import websocket
  41. >>> ws = websocket.WebSocket()
  42. >>> ws.connect("ws://echo.websocket.org")
  43. >>> ws.send("Hello, Server")
  44. >>> ws.recv()
  45. 'Hello, Server'
  46. >>> ws.close()
  47. Parameters
  48. ----------
  49. get_mask_key: func
  50. A callable function to get new mask keys, see the
  51. WebSocket.set_mask_key's docstring for more information.
  52. sockopt: tuple
  53. Values for socket.setsockopt.
  54. sockopt must be tuple and each element is argument of sock.setsockopt.
  55. sslopt: dict
  56. Optional dict object for ssl socket options. See FAQ for details.
  57. fire_cont_frame: bool
  58. Fire recv event for each cont frame. Default is False.
  59. enable_multithread: bool
  60. If set to True, lock send method.
  61. skip_utf8_validation: bool
  62. Skip utf8 validation.
  63. """
  64. def __init__(self, get_mask_key=None, sockopt=None, sslopt=None,
  65. fire_cont_frame=False, enable_multithread=True,
  66. skip_utf8_validation=False, **_):
  67. """
  68. Initialize WebSocket object.
  69. Parameters
  70. ----------
  71. sslopt: dict
  72. Optional dict object for ssl socket options. See FAQ for details.
  73. """
  74. self.sock_opt = sock_opt(sockopt, sslopt)
  75. self.handshake_response = None
  76. self.sock = None
  77. self.connected = False
  78. self.get_mask_key = get_mask_key
  79. # These buffer over the build-up of a single frame.
  80. self.frame_buffer = frame_buffer(self._recv, skip_utf8_validation)
  81. self.cont_frame = continuous_frame(
  82. fire_cont_frame, skip_utf8_validation)
  83. if enable_multithread:
  84. self.lock = threading.Lock()
  85. self.readlock = threading.Lock()
  86. else:
  87. self.lock = NoLock()
  88. self.readlock = NoLock()
  89. def __iter__(self):
  90. """
  91. Allow iteration over websocket, implying sequential `recv` executions.
  92. """
  93. while True:
  94. yield self.recv()
  95. def __next__(self):
  96. return self.recv()
  97. def next(self):
  98. return self.__next__()
  99. def fileno(self):
  100. return self.sock.fileno()
  101. def set_mask_key(self, func):
  102. """
  103. Set function to create mask key. You can customize mask key generator.
  104. Mainly, this is for testing purpose.
  105. Parameters
  106. ----------
  107. func: func
  108. callable object. the func takes 1 argument as integer.
  109. The argument means length of mask key.
  110. This func must return string(byte array),
  111. which length is argument specified.
  112. """
  113. self.get_mask_key = func
  114. def gettimeout(self):
  115. """
  116. Get the websocket timeout (in seconds) as an int or float
  117. Returns
  118. ----------
  119. timeout: int or float
  120. returns timeout value (in seconds). This value could be either float/integer.
  121. """
  122. return self.sock_opt.timeout
  123. def settimeout(self, timeout):
  124. """
  125. Set the timeout to the websocket.
  126. Parameters
  127. ----------
  128. timeout: int or float
  129. timeout time (in seconds). This value could be either float/integer.
  130. """
  131. self.sock_opt.timeout = timeout
  132. if self.sock:
  133. self.sock.settimeout(timeout)
  134. timeout = property(gettimeout, settimeout)
  135. def getsubprotocol(self):
  136. """
  137. Get subprotocol
  138. """
  139. if self.handshake_response:
  140. return self.handshake_response.subprotocol
  141. else:
  142. return None
  143. subprotocol = property(getsubprotocol)
  144. def getstatus(self):
  145. """
  146. Get handshake status
  147. """
  148. if self.handshake_response:
  149. return self.handshake_response.status
  150. else:
  151. return None
  152. status = property(getstatus)
  153. def getheaders(self):
  154. """
  155. Get handshake response header
  156. """
  157. if self.handshake_response:
  158. return self.handshake_response.headers
  159. else:
  160. return None
  161. def is_ssl(self):
  162. try:
  163. return isinstance(self.sock, ssl.SSLSocket)
  164. except:
  165. return False
  166. headers = property(getheaders)
  167. def connect(self, url, **options):
  168. """
  169. Connect to url. url is websocket url scheme.
  170. ie. ws://host:port/resource
  171. You can customize using 'options'.
  172. If you set "header" list object, you can set your own custom header.
  173. >>> ws = WebSocket()
  174. >>> ws.connect("ws://echo.websocket.org/",
  175. ... header=["User-Agent: MyProgram",
  176. ... "x-custom: header"])
  177. Parameters
  178. ----------
  179. header: list or dict
  180. Custom http header list or dict.
  181. cookie: str
  182. Cookie value.
  183. origin: str
  184. Custom origin url.
  185. connection: str
  186. Custom connection header value.
  187. Default value "Upgrade" set in _handshake.py
  188. suppress_origin: bool
  189. Suppress outputting origin header.
  190. host: str
  191. Custom host header string.
  192. timeout: int or float
  193. Socket timeout time. This value is an integer or float.
  194. If you set None for this value, it means "use default_timeout value"
  195. http_proxy_host: str
  196. HTTP proxy host name.
  197. http_proxy_port: str or int
  198. HTTP proxy port. Default is 80.
  199. http_no_proxy: list
  200. Whitelisted host names that don't use the proxy.
  201. http_proxy_auth: tuple
  202. HTTP proxy auth information. Tuple of username and password. Default is None.
  203. redirect_limit: int
  204. Number of redirects to follow.
  205. subprotocols: list
  206. List of available subprotocols. Default is None.
  207. socket: socket
  208. Pre-initialized stream socket.
  209. """
  210. self.sock_opt.timeout = options.get('timeout', self.sock_opt.timeout)
  211. self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),
  212. options.pop('socket', None))
  213. try:
  214. self.handshake_response = handshake(self.sock, *addrs, **options)
  215. for attempt in range(options.pop('redirect_limit', 3)):
  216. if self.handshake_response.status in SUPPORTED_REDIRECT_STATUSES:
  217. url = self.handshake_response.headers['location']
  218. self.sock.close()
  219. self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),
  220. options.pop('socket', None))
  221. self.handshake_response = handshake(self.sock, *addrs, **options)
  222. self.connected = True
  223. except:
  224. if self.sock:
  225. self.sock.close()
  226. self.sock = None
  227. raise
  228. def send(self, payload, opcode=ABNF.OPCODE_TEXT):
  229. """
  230. Send the data as string.
  231. Parameters
  232. ----------
  233. payload: str
  234. Payload must be utf-8 string or unicode,
  235. If the opcode is OPCODE_TEXT.
  236. Otherwise, it must be string(byte array).
  237. opcode: int
  238. Operation code (opcode) to send.
  239. """
  240. frame = ABNF.create_frame(payload, opcode)
  241. return self.send_frame(frame)
  242. def send_frame(self, frame):
  243. """
  244. Send the data frame.
  245. >>> ws = create_connection("ws://echo.websocket.org/")
  246. >>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT)
  247. >>> ws.send_frame(frame)
  248. >>> cont_frame = ABNF.create_frame("My name is ", ABNF.OPCODE_CONT, 0)
  249. >>> ws.send_frame(frame)
  250. >>> cont_frame = ABNF.create_frame("Foo Bar", ABNF.OPCODE_CONT, 1)
  251. >>> ws.send_frame(frame)
  252. Parameters
  253. ----------
  254. frame: ABNF frame
  255. frame data created by ABNF.create_frame
  256. """
  257. if self.get_mask_key:
  258. frame.get_mask_key = self.get_mask_key
  259. data = frame.format()
  260. length = len(data)
  261. #if (isEnabledForTrace() and f):
  262. #trace("++Sent raw: " + repr(data))
  263. #trace("++Sent decoded: " + frame.__str__())
  264. with self.lock:
  265. while data:
  266. l = self._send(data)
  267. data = data[l:]
  268. return length
  269. def send_binary(self, payload):
  270. """
  271. Send a binary message (OPCODE_BINARY).
  272. Parameters
  273. ----------
  274. payload: bytes
  275. payload of message to send.
  276. """
  277. return self.send(payload, ABNF.OPCODE_BINARY)
  278. def ping(self, payload=""):
  279. """
  280. Send ping data.
  281. Parameters
  282. ----------
  283. payload: str
  284. data payload to send server.
  285. """
  286. if isinstance(payload, str):
  287. payload = payload.encode("utf-8")
  288. self.send(payload, ABNF.OPCODE_PING)
  289. def pong(self, payload=""):
  290. """
  291. Send pong data.
  292. Parameters
  293. ----------
  294. payload: str
  295. data payload to send server.
  296. """
  297. if isinstance(payload, str):
  298. payload = payload.encode("utf-8")
  299. self.send(payload, ABNF.OPCODE_PONG)
  300. def recv(self):
  301. """
  302. Receive string data(byte array) from the server.
  303. Returns
  304. ----------
  305. data: string (byte array) value.
  306. """
  307. with self.readlock:
  308. opcode, data = self.recv_data()
  309. if opcode == ABNF.OPCODE_TEXT:
  310. return data.decode("utf-8")
  311. elif opcode == ABNF.OPCODE_TEXT or opcode == ABNF.OPCODE_BINARY:
  312. return data
  313. else:
  314. return ''
  315. def recv_data(self, control_frame=False):
  316. """
  317. Receive data with operation code.
  318. Parameters
  319. ----------
  320. control_frame: bool
  321. a boolean flag indicating whether to return control frame
  322. data, defaults to False
  323. Returns
  324. -------
  325. opcode, frame.data: tuple
  326. tuple of operation code and string(byte array) value.
  327. """
  328. opcode, frame = self.recv_data_frame(control_frame)
  329. return opcode, frame.data
  330. def recv_data_frame(self, control_frame=False):
  331. """
  332. Receive data with operation code.
  333. If a valid ping message is received, a pong response is sent.
  334. Parameters
  335. ----------
  336. control_frame: bool
  337. a boolean flag indicating whether to return control frame
  338. data, defaults to False
  339. Returns
  340. -------
  341. frame.opcode, frame: tuple
  342. tuple of operation code and string(byte array) value.
  343. """
  344. while True:
  345. frame = self.recv_frame()
  346. #if (isEnabledForTrace()):
  347. #trace("++Rcv raw: " + repr(frame.format()))
  348. #trace("++Rcv decoded: " + frame.__str__())
  349. if not frame:
  350. # handle error:
  351. # 'NoneType' object has no attribute 'opcode'
  352. raise WebSocketProtocolException(
  353. "Not a valid frame %s" % frame)
  354. elif frame.opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY, ABNF.OPCODE_CONT):
  355. self.cont_frame.validate(frame)
  356. self.cont_frame.add(frame)
  357. if self.cont_frame.is_fire(frame):
  358. return self.cont_frame.extract(frame)
  359. elif frame.opcode == ABNF.OPCODE_CLOSE:
  360. self.send_close()
  361. return frame.opcode, frame
  362. elif frame.opcode == ABNF.OPCODE_PING:
  363. if len(frame.data) < 126:
  364. self.pong(frame.data)
  365. else:
  366. raise WebSocketProtocolException(
  367. "Ping message is too long")
  368. if control_frame:
  369. return frame.opcode, frame
  370. elif frame.opcode == ABNF.OPCODE_PONG:
  371. if control_frame:
  372. return frame.opcode, frame
  373. def recv_frame(self):
  374. """
  375. Receive data as frame from server.
  376. Returns
  377. -------
  378. self.frame_buffer.recv_frame(): ABNF frame object
  379. """
  380. return self.frame_buffer.recv_frame()
  381. def send_close(self, status=STATUS_NORMAL, reason=bytes('', encoding='utf-8')):
  382. """
  383. Send close data to the server.
  384. Parameters
  385. ----------
  386. status: int
  387. Status code to send. See STATUS_XXX.
  388. reason: str or bytes
  389. The reason to close. This must be string or bytes.
  390. """
  391. if status < 0 or status >= ABNF.LENGTH_16:
  392. raise ValueError("code is invalid range")
  393. self.connected = False
  394. self.send(struct.pack('!H', status) + reason, ABNF.OPCODE_CLOSE)
  395. def close(self, status=STATUS_NORMAL, reason=bytes('', encoding='utf-8'), timeout=3):
  396. """
  397. Close Websocket object
  398. Parameters
  399. ----------
  400. status: int
  401. Status code to send. See STATUS_XXX.
  402. reason: bytes
  403. The reason to close.
  404. timeout: int or float
  405. Timeout until receive a close frame.
  406. If None, it will wait forever until receive a close frame.
  407. """
  408. if self.connected:
  409. if status < 0 or status >= ABNF.LENGTH_16:
  410. raise ValueError("code is invalid range")
  411. try:
  412. self.connected = False
  413. self.send(struct.pack('!H', status) + reason, ABNF.OPCODE_CLOSE)
  414. sock_timeout = self.sock.gettimeout()
  415. self.sock.settimeout(timeout)
  416. start_time = time.time()
  417. while timeout is None or time.time() - start_time < timeout:
  418. try:
  419. frame = self.recv_frame()
  420. if frame.opcode != ABNF.OPCODE_CLOSE:
  421. continue
  422. if isEnabledForError():
  423. recv_status = struct.unpack("!H", frame.data[0:2])[0]
  424. if recv_status >= 3000 and recv_status <= 4999:
  425. debug("close status: " + repr(recv_status))
  426. elif recv_status != STATUS_NORMAL:
  427. error("close status: " + repr(recv_status))
  428. break
  429. except:
  430. break
  431. self.sock.settimeout(sock_timeout)
  432. self.sock.shutdown(socket.SHUT_RDWR)
  433. except:
  434. pass
  435. self.shutdown()
  436. def abort(self):
  437. """
  438. Low-level asynchronous abort, wakes up other threads that are waiting in recv_*
  439. """
  440. if self.connected:
  441. self.sock.shutdown(socket.SHUT_RDWR)
  442. def shutdown(self):
  443. """
  444. close socket, immediately.
  445. """
  446. if self.sock:
  447. self.sock.close()
  448. self.sock = None
  449. self.connected = False
  450. def _send(self, data):
  451. return send(self.sock, data)
  452. def _recv(self, bufsize):
  453. try:
  454. return recv(self.sock, bufsize)
  455. except WebSocketConnectionClosedException:
  456. if self.sock:
  457. self.sock.close()
  458. self.sock = None
  459. self.connected = False
  460. raise
  461. def create_connection(url, timeout=None, class_=WebSocket, **options):
  462. """
  463. Connect to url and return websocket object.
  464. Connect to url and return the WebSocket object.
  465. Passing optional timeout parameter will set the timeout on the socket.
  466. If no timeout is supplied,
  467. the global default timeout setting returned by getdefaulttimeout() is used.
  468. You can customize using 'options'.
  469. If you set "header" list object, you can set your own custom header.
  470. >>> conn = create_connection("ws://echo.websocket.org/",
  471. ... header=["User-Agent: MyProgram",
  472. ... "x-custom: header"])
  473. Parameters
  474. ----------
  475. class_: class
  476. class to instantiate when creating the connection. It has to implement
  477. settimeout and connect. It's __init__ should be compatible with
  478. WebSocket.__init__, i.e. accept all of it's kwargs.
  479. header: list or dict
  480. custom http header list or dict.
  481. cookie: str
  482. Cookie value.
  483. origin: str
  484. custom origin url.
  485. suppress_origin: bool
  486. suppress outputting origin header.
  487. host: str
  488. custom host header string.
  489. timeout: int or float
  490. socket timeout time. This value could be either float/integer.
  491. If set to None, it uses the default_timeout value.
  492. http_proxy_host: str
  493. HTTP proxy host name.
  494. http_proxy_port: str or int
  495. HTTP proxy port. If not set, set to 80.
  496. http_no_proxy: list
  497. Whitelisted host names that don't use the proxy.
  498. http_proxy_auth: tuple
  499. HTTP proxy auth information. tuple of username and password. Default is None.
  500. enable_multithread: bool
  501. Enable lock for multithread.
  502. redirect_limit: int
  503. Number of redirects to follow.
  504. sockopt: tuple
  505. Values for socket.setsockopt.
  506. sockopt must be a tuple and each element is an argument of sock.setsockopt.
  507. sslopt: dict
  508. Optional dict object for ssl socket options. See FAQ for details.
  509. subprotocols: list
  510. List of available subprotocols. Default is None.
  511. skip_utf8_validation: bool
  512. Skip utf8 validation.
  513. socket: socket
  514. Pre-initialized stream socket.
  515. """
  516. sockopt = options.pop("sockopt", [])
  517. sslopt = options.pop("sslopt", {})
  518. fire_cont_frame = options.pop("fire_cont_frame", False)
  519. enable_multithread = options.pop("enable_multithread", True)
  520. skip_utf8_validation = options.pop("skip_utf8_validation", False)
  521. websock = class_(sockopt=sockopt, sslopt=sslopt,
  522. fire_cont_frame=fire_cont_frame,
  523. enable_multithread=enable_multithread,
  524. skip_utf8_validation=skip_utf8_validation, **options)
  525. websock.settimeout(timeout if timeout is not None else getdefaulttimeout())
  526. websock.connect(url, **options)
  527. return websock