_core.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. """
  2. websocket - WebSocket client library for Python
  3. Copyright (C) 2010 Hiroki Ohtani(liris)
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with this library; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin Street, Fifth Floor,
  15. Boston, MA 02110-1335 USA
  16. """
  17. from __future__ import print_function
  18. import socket
  19. import struct
  20. import threading
  21. import time
  22. import six
  23. # websocket modules
  24. from ._abnf import *
  25. from ._exceptions import *
  26. from ._handshake import *
  27. from ._http import *
  28. from ._logging import *
  29. from ._socket import *
  30. from ._ssl_compat import *
  31. from ._utils import *
  32. __all__ = ['WebSocket', 'create_connection']
  33. """
  34. websocket python client.
  35. =========================
  36. This version support only hybi-13.
  37. Please see http://tools.ietf.org/html/rfc6455 for protocol.
  38. """
  39. class WebSocket(object):
  40. """
  41. Low level WebSocket interface.
  42. This class is based on
  43. The WebSocket protocol draft-hixie-thewebsocketprotocol-76
  44. http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
  45. We can connect to the websocket server and send/receive data.
  46. The following example is an echo client.
  47. >>> import websocket
  48. >>> ws = websocket.WebSocket()
  49. >>> ws.connect("ws://echo.websocket.org")
  50. >>> ws.send("Hello, Server")
  51. >>> ws.recv()
  52. 'Hello, Server'
  53. >>> ws.close()
  54. get_mask_key: a callable to produce new mask keys, see the set_mask_key
  55. function's docstring for more details
  56. sockopt: values for socket.setsockopt.
  57. sockopt must be tuple and each element is argument of sock.setsockopt.
  58. sslopt: dict object for ssl socket option.
  59. fire_cont_frame: fire recv event for each cont frame. default is False
  60. enable_multithread: if set to True, lock send method.
  61. skip_utf8_validation: skip utf8 validation.
  62. """
  63. def __init__(self, get_mask_key=None, sockopt=None, sslopt=None,
  64. fire_cont_frame=False, enable_multithread=False,
  65. skip_utf8_validation=False, **_):
  66. """
  67. Initialize WebSocket object.
  68. """
  69. self.sock_opt = sock_opt(sockopt, sslopt)
  70. self.handshake_response = None
  71. self.sock = None
  72. self.connected = False
  73. self.get_mask_key = get_mask_key
  74. # These buffer over the build-up of a single frame.
  75. self.frame_buffer = frame_buffer(self._recv, skip_utf8_validation)
  76. self.cont_frame = continuous_frame(
  77. fire_cont_frame, skip_utf8_validation)
  78. if enable_multithread:
  79. self.lock = threading.Lock()
  80. self.readlock = threading.Lock()
  81. else:
  82. self.lock = NoLock()
  83. self.readlock = NoLock()
  84. def __iter__(self):
  85. """
  86. Allow iteration over websocket, implying sequential `recv` executions.
  87. """
  88. while True:
  89. yield self.recv()
  90. def __next__(self):
  91. return self.recv()
  92. def next(self):
  93. return self.__next__()
  94. def fileno(self):
  95. return self.sock.fileno()
  96. def set_mask_key(self, func):
  97. """
  98. set function to create musk key. You can customize mask key generator.
  99. Mainly, this is for testing purpose.
  100. func: callable object. the func takes 1 argument as integer.
  101. The argument means length of mask key.
  102. This func must return string(byte array),
  103. which length is argument specified.
  104. """
  105. self.get_mask_key = func
  106. def gettimeout(self):
  107. """
  108. Get the websocket timeout(second).
  109. """
  110. return self.sock_opt.timeout
  111. def settimeout(self, timeout):
  112. """
  113. Set the timeout to the websocket.
  114. timeout: timeout time(second).
  115. """
  116. self.sock_opt.timeout = timeout
  117. if self.sock:
  118. self.sock.settimeout(timeout)
  119. timeout = property(gettimeout, settimeout)
  120. def getsubprotocol(self):
  121. """
  122. get subprotocol
  123. """
  124. if self.handshake_response:
  125. return self.handshake_response.subprotocol
  126. else:
  127. return None
  128. subprotocol = property(getsubprotocol)
  129. def getstatus(self):
  130. """
  131. get handshake status
  132. """
  133. if self.handshake_response:
  134. return self.handshake_response.status
  135. else:
  136. return None
  137. status = property(getstatus)
  138. def getheaders(self):
  139. """
  140. get handshake response header
  141. """
  142. if self.handshake_response:
  143. return self.handshake_response.headers
  144. else:
  145. return None
  146. def is_ssl(self):
  147. return isinstance(self.sock, ssl.SSLSocket)
  148. headers = property(getheaders)
  149. def connect(self, url, **options):
  150. """
  151. Connect to url. url is websocket url scheme.
  152. ie. ws://host:port/resource
  153. You can customize using 'options'.
  154. If you set "header" list object, you can set your own custom header.
  155. >>> ws = WebSocket()
  156. >>> ws.connect("ws://echo.websocket.org/",
  157. ... header=["User-Agent: MyProgram",
  158. ... "x-custom: header"])
  159. timeout: socket timeout time. This value is integer.
  160. if you set None for this value,
  161. it means "use default_timeout value"
  162. options: "header" -> custom http header list or dict.
  163. "cookie" -> cookie value.
  164. "origin" -> custom origin url.
  165. "suppress_origin" -> suppress outputting origin header.
  166. "host" -> custom host header string.
  167. "http_proxy_host" - http proxy host name.
  168. "http_proxy_port" - http proxy port. If not set, set to 80.
  169. "http_no_proxy" - host names, which doesn't use proxy.
  170. "http_proxy_auth" - http proxy auth information.
  171. tuple of username and password.
  172. default is None
  173. "redirect_limit" -> number of redirects to follow.
  174. "subprotocols" - array of available sub protocols.
  175. default is None.
  176. "socket" - pre-initialized stream socket.
  177. """
  178. # FIXME: "subprotocols" are getting lost, not passed down
  179. # FIXME: "header", "cookie", "origin" and "host" too
  180. self.sock_opt.timeout = options.get('timeout', self.sock_opt.timeout)
  181. self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),
  182. options.pop('socket', None))
  183. try:
  184. self.handshake_response = handshake(self.sock, *addrs, **options)
  185. for attempt in range(options.pop('redirect_limit', 3)):
  186. if self.handshake_response.status in SUPPORTED_REDIRECT_STATUSES:
  187. url = self.handshake_response.headers['location']
  188. self.sock.close()
  189. self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),
  190. options.pop('socket', None))
  191. self.handshake_response = handshake(self.sock, *addrs, **options)
  192. self.connected = True
  193. except:
  194. if self.sock:
  195. self.sock.close()
  196. self.sock = None
  197. raise
  198. def send(self, payload, opcode=ABNF.OPCODE_TEXT):
  199. """
  200. Send the data as string.
  201. payload: Payload must be utf-8 string or unicode,
  202. if the opcode is OPCODE_TEXT.
  203. Otherwise, it must be string(byte array)
  204. opcode: operation code to send. Please see OPCODE_XXX.
  205. """
  206. frame = ABNF.create_frame(payload, opcode)
  207. return self.send_frame(frame)
  208. def send_frame(self, frame):
  209. """
  210. Send the data frame.
  211. frame: frame data created by ABNF.create_frame
  212. >>> ws = create_connection("ws://echo.websocket.org/")
  213. >>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT)
  214. >>> ws.send_frame(frame)
  215. >>> cont_frame = ABNF.create_frame("My name is ", ABNF.OPCODE_CONT, 0)
  216. >>> ws.send_frame(frame)
  217. >>> cont_frame = ABNF.create_frame("Foo Bar", ABNF.OPCODE_CONT, 1)
  218. >>> ws.send_frame(frame)
  219. """
  220. if self.get_mask_key:
  221. frame.get_mask_key = self.get_mask_key
  222. data = frame.format()
  223. length = len(data)
  224. trace("send: " + repr(data))
  225. with self.lock:
  226. while data:
  227. l = self._send(data)
  228. data = data[l:]
  229. return length
  230. def send_binary(self, payload):
  231. return self.send(payload, ABNF.OPCODE_BINARY)
  232. def ping(self, payload=""):
  233. """
  234. send ping data.
  235. payload: data payload to send server.
  236. """
  237. if isinstance(payload, six.text_type):
  238. payload = payload.encode("utf-8")
  239. self.send(payload, ABNF.OPCODE_PING)
  240. def pong(self, payload):
  241. """
  242. send pong data.
  243. payload: data payload to send server.
  244. """
  245. if isinstance(payload, six.text_type):
  246. payload = payload.encode("utf-8")
  247. self.send(payload, ABNF.OPCODE_PONG)
  248. def recv(self):
  249. """
  250. Receive string data(byte array) from the server.
  251. return value: string(byte array) value.
  252. """
  253. with self.readlock:
  254. opcode, data = self.recv_data()
  255. if six.PY3 and opcode == ABNF.OPCODE_TEXT:
  256. return data.decode("utf-8")
  257. elif opcode == ABNF.OPCODE_TEXT or opcode == ABNF.OPCODE_BINARY:
  258. return data
  259. else:
  260. return ''
  261. def recv_data(self, control_frame=False):
  262. """
  263. Receive data with operation code.
  264. control_frame: a boolean flag indicating whether to return control frame
  265. data, defaults to False
  266. return value: tuple of operation code and string(byte array) value.
  267. """
  268. opcode, frame = self.recv_data_frame(control_frame)
  269. return opcode, frame.data
  270. def recv_data_frame(self, control_frame=False):
  271. """
  272. Receive data with operation code.
  273. control_frame: a boolean flag indicating whether to return control frame
  274. data, defaults to False
  275. return value: tuple of operation code and string(byte array) value.
  276. """
  277. while True:
  278. frame = self.recv_frame()
  279. if not frame:
  280. # handle error:
  281. # 'NoneType' object has no attribute 'opcode'
  282. raise WebSocketProtocolException(
  283. "Not a valid frame %s" % frame)
  284. elif frame.opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY, ABNF.OPCODE_CONT):
  285. self.cont_frame.validate(frame)
  286. self.cont_frame.add(frame)
  287. if self.cont_frame.is_fire(frame):
  288. return self.cont_frame.extract(frame)
  289. elif frame.opcode == ABNF.OPCODE_CLOSE:
  290. self.send_close()
  291. return frame.opcode, frame
  292. elif frame.opcode == ABNF.OPCODE_PING:
  293. if len(frame.data) < 126:
  294. self.pong(frame.data)
  295. else:
  296. raise WebSocketProtocolException(
  297. "Ping message is too long")
  298. if control_frame:
  299. return frame.opcode, frame
  300. elif frame.opcode == ABNF.OPCODE_PONG:
  301. if control_frame:
  302. return frame.opcode, frame
  303. def recv_frame(self):
  304. """
  305. receive data as frame from server.
  306. return value: ABNF frame object.
  307. """
  308. return self.frame_buffer.recv_frame()
  309. def send_close(self, status=STATUS_NORMAL, reason=six.b("")):
  310. """
  311. send close data to the server.
  312. status: status code to send. see STATUS_XXX.
  313. reason: the reason to close. This must be string or bytes.
  314. """
  315. if status < 0 or status >= ABNF.LENGTH_16:
  316. raise ValueError("code is invalid range")
  317. self.connected = False
  318. self.send(struct.pack('!H', status) + reason, ABNF.OPCODE_CLOSE)
  319. def close(self, status=STATUS_NORMAL, reason=six.b(""), timeout=3):
  320. """
  321. Close Websocket object
  322. status: status code to send. see STATUS_XXX.
  323. reason: the reason to close. This must be string.
  324. timeout: timeout until receive a close frame.
  325. If None, it will wait forever until receive a close frame.
  326. """
  327. if self.connected:
  328. if status < 0 or status >= ABNF.LENGTH_16:
  329. raise ValueError("code is invalid range")
  330. try:
  331. self.connected = False
  332. self.send(struct.pack('!H', status) +
  333. reason, ABNF.OPCODE_CLOSE)
  334. sock_timeout = self.sock.gettimeout()
  335. self.sock.settimeout(timeout)
  336. start_time = time.time()
  337. while timeout is None or time.time() - start_time < timeout:
  338. try:
  339. frame = self.recv_frame()
  340. if frame.opcode != ABNF.OPCODE_CLOSE:
  341. continue
  342. if isEnabledForError():
  343. recv_status = struct.unpack("!H", frame.data[0:2])[0]
  344. if recv_status != STATUS_NORMAL:
  345. error("close status: " + repr(recv_status))
  346. break
  347. except:
  348. break
  349. self.sock.settimeout(sock_timeout)
  350. self.sock.shutdown(socket.SHUT_RDWR)
  351. except:
  352. pass
  353. self.shutdown()
  354. def abort(self):
  355. """
  356. Low-level asynchronous abort, wakes up other threads that are waiting in recv_*
  357. """
  358. if self.connected:
  359. self.sock.shutdown(socket.SHUT_RDWR)
  360. def shutdown(self):
  361. """close socket, immediately."""
  362. if self.sock:
  363. self.sock.close()
  364. self.sock = None
  365. self.connected = False
  366. def _send(self, data):
  367. return send(self.sock, data)
  368. def _recv(self, bufsize):
  369. try:
  370. return recv(self.sock, bufsize)
  371. except WebSocketConnectionClosedException:
  372. if self.sock:
  373. self.sock.close()
  374. self.sock = None
  375. self.connected = False
  376. raise
  377. def create_connection(url, timeout=None, class_=WebSocket, **options):
  378. """
  379. connect to url and return websocket object.
  380. Connect to url and return the WebSocket object.
  381. Passing optional timeout parameter will set the timeout on the socket.
  382. If no timeout is supplied,
  383. the global default timeout setting returned by getdefauttimeout() is used.
  384. You can customize using 'options'.
  385. If you set "header" list object, you can set your own custom header.
  386. >>> conn = create_connection("ws://echo.websocket.org/",
  387. ... header=["User-Agent: MyProgram",
  388. ... "x-custom: header"])
  389. timeout: socket timeout time. This value is integer.
  390. if you set None for this value,
  391. it means "use default_timeout value"
  392. class_: class to instantiate when creating the connection. It has to implement
  393. settimeout and connect. It's __init__ should be compatible with
  394. WebSocket.__init__, i.e. accept all of it's kwargs.
  395. options: "header" -> custom http header list or dict.
  396. "cookie" -> cookie value.
  397. "origin" -> custom origin url.
  398. "suppress_origin" -> suppress outputting origin header.
  399. "host" -> custom host header string.
  400. "http_proxy_host" - http proxy host name.
  401. "http_proxy_port" - http proxy port. If not set, set to 80.
  402. "http_no_proxy" - host names, which doesn't use proxy.
  403. "http_proxy_auth" - http proxy auth information.
  404. tuple of username and password.
  405. default is None
  406. "enable_multithread" -> enable lock for multithread.
  407. "redirect_limit" -> number of redirects to follow.
  408. "sockopt" -> socket options
  409. "sslopt" -> ssl option
  410. "subprotocols" - array of available sub protocols.
  411. default is None.
  412. "skip_utf8_validation" - skip utf8 validation.
  413. "socket" - pre-initialized stream socket.
  414. """
  415. sockopt = options.pop("sockopt", [])
  416. sslopt = options.pop("sslopt", {})
  417. fire_cont_frame = options.pop("fire_cont_frame", False)
  418. enable_multithread = options.pop("enable_multithread", False)
  419. skip_utf8_validation = options.pop("skip_utf8_validation", False)
  420. websock = class_(sockopt=sockopt, sslopt=sslopt,
  421. fire_cont_frame=fire_cont_frame,
  422. enable_multithread=enable_multithread,
  423. skip_utf8_validation=skip_utf8_validation, **options)
  424. websock.settimeout(timeout if timeout is not None else getdefaulttimeout())
  425. websock.connect(url, **options)
  426. return websock