No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

660 líneas
27KB

  1. import gzip
  2. import importlib
  3. import logging
  4. import uuid
  5. import zlib
  6. import six
  7. from six.moves import urllib
  8. from . import exceptions
  9. from . import packet
  10. from . import payload
  11. from . import socket
  12. default_logger = logging.getLogger('engineio.server')
  13. class Server(object):
  14. """An Engine.IO server.
  15. This class implements a fully compliant Engine.IO web server with support
  16. for websocket and long-polling transports.
  17. :param async_mode: The asynchronous model to use. See the Deployment
  18. section in the documentation for a description of the
  19. available options. Valid async modes are "threading",
  20. "eventlet", "gevent" and "gevent_uwsgi". If this
  21. argument is not given, "eventlet" is tried first, then
  22. "gevent_uwsgi", then "gevent", and finally "threading".
  23. The first async mode that has all its dependencies
  24. installed is the one that is chosen.
  25. :param ping_timeout: The time in seconds that the client waits for the
  26. server to respond before disconnecting. The default
  27. is 60 seconds.
  28. :param ping_interval: The interval in seconds at which the client pings
  29. the server. The default is 25 seconds.
  30. :param max_http_buffer_size: The maximum size of a message when using the
  31. polling transport. The default is 100,000,000
  32. bytes.
  33. :param allow_upgrades: Whether to allow transport upgrades or not. The
  34. default is ``True``.
  35. :param http_compression: Whether to compress packages when using the
  36. polling transport. The default is ``True``.
  37. :param compression_threshold: Only compress messages when their byte size
  38. is greater than this value. The default is
  39. 1024 bytes.
  40. :param cookie: Name of the HTTP cookie that contains the client session
  41. id. If set to ``None``, a cookie is not sent to the client.
  42. The default is ``'io'``.
  43. :param cors_allowed_origins: Origin or list of origins that are allowed to
  44. connect to this server. Only the same origin
  45. is allowed by default. Set this argument to
  46. ``'*'`` to allow all origins, or to ``[]`` to
  47. disable CORS handling.
  48. :param cors_credentials: Whether credentials (cookies, authentication) are
  49. allowed in requests to this server. The default
  50. is ``True``.
  51. :param logger: To enable logging set to ``True`` or pass a logger object to
  52. use. To disable logging set to ``False``. The default is
  53. ``False``.
  54. :param json: An alternative json module to use for encoding and decoding
  55. packets. Custom json modules must have ``dumps`` and ``loads``
  56. functions that are compatible with the standard library
  57. versions.
  58. :param async_handlers: If set to ``True``, run message event handlers in
  59. non-blocking threads. To run handlers synchronously,
  60. set to ``False``. The default is ``True``.
  61. :param monitor_clients: If set to ``True``, a background task will ensure
  62. inactive clients are closed. Set to ``False`` to
  63. disable the monitoring task (not recommended). The
  64. default is ``True``.
  65. :param kwargs: Reserved for future extensions, any additional parameters
  66. given as keyword arguments will be silently ignored.
  67. """
  68. compression_methods = ['gzip', 'deflate']
  69. event_names = ['connect', 'disconnect', 'message']
  70. _default_monitor_clients = True
  71. def __init__(self, async_mode=None, ping_timeout=60, ping_interval=25,
  72. max_http_buffer_size=100000000, allow_upgrades=True,
  73. http_compression=True, compression_threshold=1024,
  74. cookie='io', cors_allowed_origins=None,
  75. cors_credentials=True, logger=False, json=None,
  76. async_handlers=True, monitor_clients=None, **kwargs):
  77. self.ping_timeout = ping_timeout
  78. self.ping_interval = ping_interval
  79. self.max_http_buffer_size = max_http_buffer_size
  80. self.allow_upgrades = allow_upgrades
  81. self.http_compression = http_compression
  82. self.compression_threshold = compression_threshold
  83. self.cookie = cookie
  84. self.cors_allowed_origins = cors_allowed_origins
  85. self.cors_credentials = cors_credentials
  86. self.async_handlers = async_handlers
  87. self.sockets = {}
  88. self.handlers = {}
  89. self.start_service_task = monitor_clients \
  90. if monitor_clients is not None else self._default_monitor_clients
  91. if json is not None:
  92. packet.Packet.json = json
  93. if not isinstance(logger, bool):
  94. self.logger = logger
  95. else:
  96. self.logger = default_logger
  97. if not logging.root.handlers and \
  98. self.logger.level == logging.NOTSET:
  99. if logger:
  100. self.logger.setLevel(logging.INFO)
  101. else:
  102. self.logger.setLevel(logging.ERROR)
  103. self.logger.addHandler(logging.StreamHandler())
  104. modes = self.async_modes()
  105. if async_mode is not None:
  106. modes = [async_mode] if async_mode in modes else []
  107. self._async = None
  108. self.async_mode = None
  109. for mode in modes:
  110. try:
  111. self._async = importlib.import_module(
  112. 'engineio.async_drivers.' + mode)._async
  113. asyncio_based = self._async['asyncio'] \
  114. if 'asyncio' in self._async else False
  115. if asyncio_based != self.is_asyncio_based():
  116. continue # pragma: no cover
  117. self.async_mode = mode
  118. break
  119. except ImportError:
  120. pass
  121. if self.async_mode is None:
  122. raise ValueError('Invalid async_mode specified')
  123. if self.is_asyncio_based() and \
  124. ('asyncio' not in self._async or not
  125. self._async['asyncio']): # pragma: no cover
  126. raise ValueError('The selected async_mode is not asyncio '
  127. 'compatible')
  128. if not self.is_asyncio_based() and 'asyncio' in self._async and \
  129. self._async['asyncio']: # pragma: no cover
  130. raise ValueError('The selected async_mode requires asyncio and '
  131. 'must use the AsyncServer class')
  132. self.logger.info('Server initialized for %s.', self.async_mode)
  133. def is_asyncio_based(self):
  134. return False
  135. def async_modes(self):
  136. return ['eventlet', 'gevent_uwsgi', 'gevent', 'threading']
  137. def on(self, event, handler=None):
  138. """Register an event handler.
  139. :param event: The event name. Can be ``'connect'``, ``'message'`` or
  140. ``'disconnect'``.
  141. :param handler: The function that should be invoked to handle the
  142. event. When this parameter is not given, the method
  143. acts as a decorator for the handler function.
  144. Example usage::
  145. # as a decorator:
  146. @eio.on('connect')
  147. def connect_handler(sid, environ):
  148. print('Connection request')
  149. if environ['REMOTE_ADDR'] in blacklisted:
  150. return False # reject
  151. # as a method:
  152. def message_handler(sid, msg):
  153. print('Received message: ', msg)
  154. eio.send(sid, 'response')
  155. eio.on('message', message_handler)
  156. The handler function receives the ``sid`` (session ID) for the
  157. client as first argument. The ``'connect'`` event handler receives the
  158. WSGI environment as a second argument, and can return ``False`` to
  159. reject the connection. The ``'message'`` handler receives the message
  160. payload as a second argument. The ``'disconnect'`` handler does not
  161. take a second argument.
  162. """
  163. if event not in self.event_names:
  164. raise ValueError('Invalid event')
  165. def set_handler(handler):
  166. self.handlers[event] = handler
  167. return handler
  168. if handler is None:
  169. return set_handler
  170. set_handler(handler)
  171. def send(self, sid, data, binary=None):
  172. """Send a message to a client.
  173. :param sid: The session id of the recipient client.
  174. :param data: The data to send to the client. Data can be of type
  175. ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
  176. or ``dict``, the data will be serialized as JSON.
  177. :param binary: ``True`` to send packet as binary, ``False`` to send
  178. as text. If not given, unicode (Python 2) and str
  179. (Python 3) are sent as text, and str (Python 2) and
  180. bytes (Python 3) are sent as binary.
  181. """
  182. try:
  183. socket = self._get_socket(sid)
  184. except KeyError:
  185. # the socket is not available
  186. self.logger.warning('Cannot send to sid %s', sid)
  187. return
  188. socket.send(packet.Packet(packet.MESSAGE, data=data, binary=binary))
  189. def get_session(self, sid):
  190. """Return the user session for a client.
  191. :param sid: The session id of the client.
  192. The return value is a dictionary. Modifications made to this
  193. dictionary are not guaranteed to be preserved unless
  194. ``save_session()`` is called, or when the ``session`` context manager
  195. is used.
  196. """
  197. socket = self._get_socket(sid)
  198. return socket.session
  199. def save_session(self, sid, session):
  200. """Store the user session for a client.
  201. :param sid: The session id of the client.
  202. :param session: The session dictionary.
  203. """
  204. socket = self._get_socket(sid)
  205. socket.session = session
  206. def session(self, sid):
  207. """Return the user session for a client with context manager syntax.
  208. :param sid: The session id of the client.
  209. This is a context manager that returns the user session dictionary for
  210. the client. Any changes that are made to this dictionary inside the
  211. context manager block are saved back to the session. Example usage::
  212. @eio.on('connect')
  213. def on_connect(sid, environ):
  214. username = authenticate_user(environ)
  215. if not username:
  216. return False
  217. with eio.session(sid) as session:
  218. session['username'] = username
  219. @eio.on('message')
  220. def on_message(sid, msg):
  221. with eio.session(sid) as session:
  222. print('received message from ', session['username'])
  223. """
  224. class _session_context_manager(object):
  225. def __init__(self, server, sid):
  226. self.server = server
  227. self.sid = sid
  228. self.session = None
  229. def __enter__(self):
  230. self.session = self.server.get_session(sid)
  231. return self.session
  232. def __exit__(self, *args):
  233. self.server.save_session(sid, self.session)
  234. return _session_context_manager(self, sid)
  235. def disconnect(self, sid=None):
  236. """Disconnect a client.
  237. :param sid: The session id of the client to close. If this parameter
  238. is not given, then all clients are closed.
  239. """
  240. if sid is not None:
  241. try:
  242. socket = self._get_socket(sid)
  243. except KeyError: # pragma: no cover
  244. # the socket was already closed or gone
  245. pass
  246. else:
  247. socket.close()
  248. del self.sockets[sid]
  249. else:
  250. for client in six.itervalues(self.sockets):
  251. client.close()
  252. self.sockets = {}
  253. def transport(self, sid):
  254. """Return the name of the transport used by the client.
  255. The two possible values returned by this function are ``'polling'``
  256. and ``'websocket'``.
  257. :param sid: The session of the client.
  258. """
  259. return 'websocket' if self._get_socket(sid).upgraded else 'polling'
  260. def handle_request(self, environ, start_response):
  261. """Handle an HTTP request from the client.
  262. This is the entry point of the Engine.IO application, using the same
  263. interface as a WSGI application. For the typical usage, this function
  264. is invoked by the :class:`Middleware` instance, but it can be invoked
  265. directly when the middleware is not used.
  266. :param environ: The WSGI environment.
  267. :param start_response: The WSGI ``start_response`` function.
  268. This function returns the HTTP response body to deliver to the client
  269. as a byte sequence.
  270. """
  271. if self.cors_allowed_origins != []:
  272. # Validate the origin header if present
  273. # This is important for WebSocket more than for HTTP, since
  274. # browsers only apply CORS controls to HTTP.
  275. origin = environ.get('HTTP_ORIGIN')
  276. if origin:
  277. allowed_origins = self._cors_allowed_origins(environ)
  278. if allowed_origins is not None and origin not in \
  279. allowed_origins:
  280. self.logger.info(origin + ' is not an accepted origin.')
  281. r = self._bad_request()
  282. start_response(r['status'], r['headers'])
  283. return [r['response']]
  284. method = environ['REQUEST_METHOD']
  285. query = urllib.parse.parse_qs(environ.get('QUERY_STRING', ''))
  286. sid = query['sid'][0] if 'sid' in query else None
  287. b64 = False
  288. jsonp = False
  289. jsonp_index = None
  290. if 'b64' in query:
  291. if query['b64'][0] == "1" or query['b64'][0].lower() == "true":
  292. b64 = True
  293. if 'j' in query:
  294. jsonp = True
  295. try:
  296. jsonp_index = int(query['j'][0])
  297. except (ValueError, KeyError, IndexError):
  298. # Invalid JSONP index number
  299. pass
  300. if jsonp and jsonp_index is None:
  301. self.logger.warning('Invalid JSONP index number')
  302. r = self._bad_request()
  303. elif method == 'GET':
  304. if sid is None:
  305. transport = query.get('transport', ['polling'])[0]
  306. if transport != 'polling' and transport != 'websocket':
  307. self.logger.warning('Invalid transport %s', transport)
  308. r = self._bad_request()
  309. else:
  310. r = self._handle_connect(environ, start_response,
  311. transport, b64, jsonp_index)
  312. else:
  313. if sid not in self.sockets:
  314. self.logger.warning('Invalid session %s', sid)
  315. r = self._bad_request()
  316. else:
  317. socket = self._get_socket(sid)
  318. try:
  319. packets = socket.handle_get_request(
  320. environ, start_response)
  321. if isinstance(packets, list):
  322. r = self._ok(packets, b64=b64,
  323. jsonp_index=jsonp_index)
  324. else:
  325. r = packets
  326. except exceptions.EngineIOError:
  327. if sid in self.sockets: # pragma: no cover
  328. self.disconnect(sid)
  329. r = self._bad_request()
  330. if sid in self.sockets and self.sockets[sid].closed:
  331. del self.sockets[sid]
  332. elif method == 'POST':
  333. if sid is None or sid not in self.sockets:
  334. self.logger.warning('Invalid session %s', sid)
  335. r = self._bad_request()
  336. else:
  337. socket = self._get_socket(sid)
  338. try:
  339. socket.handle_post_request(environ)
  340. r = self._ok(jsonp_index=jsonp_index)
  341. except exceptions.EngineIOError:
  342. if sid in self.sockets: # pragma: no cover
  343. self.disconnect(sid)
  344. r = self._bad_request()
  345. except: # pragma: no cover
  346. # for any other unexpected errors, we log the error
  347. # and keep going
  348. self.logger.exception('post request handler error')
  349. r = self._ok(jsonp_index=jsonp_index)
  350. elif method == 'OPTIONS':
  351. r = self._ok()
  352. else:
  353. self.logger.warning('Method %s not supported', method)
  354. r = self._method_not_found()
  355. if not isinstance(r, dict):
  356. return r or []
  357. if self.http_compression and \
  358. len(r['response']) >= self.compression_threshold:
  359. encodings = [e.split(';')[0].strip() for e in
  360. environ.get('HTTP_ACCEPT_ENCODING', '').split(',')]
  361. for encoding in encodings:
  362. if encoding in self.compression_methods:
  363. r['response'] = \
  364. getattr(self, '_' + encoding)(r['response'])
  365. r['headers'] += [('Content-Encoding', encoding)]
  366. break
  367. cors_headers = self._cors_headers(environ)
  368. start_response(r['status'], r['headers'] + cors_headers)
  369. return [r['response']]
  370. def start_background_task(self, target, *args, **kwargs):
  371. """Start a background task using the appropriate async model.
  372. This is a utility function that applications can use to start a
  373. background task using the method that is compatible with the
  374. selected async mode.
  375. :param target: the target function to execute.
  376. :param args: arguments to pass to the function.
  377. :param kwargs: keyword arguments to pass to the function.
  378. This function returns an object compatible with the `Thread` class in
  379. the Python standard library. The `start()` method on this object is
  380. already called by this function.
  381. """
  382. th = self._async['thread'](target=target, args=args, kwargs=kwargs)
  383. th.start()
  384. return th # pragma: no cover
  385. def sleep(self, seconds=0):
  386. """Sleep for the requested amount of time using the appropriate async
  387. model.
  388. This is a utility function that applications can use to put a task to
  389. sleep without having to worry about using the correct call for the
  390. selected async mode.
  391. """
  392. return self._async['sleep'](seconds)
  393. def create_queue(self, *args, **kwargs):
  394. """Create a queue object using the appropriate async model.
  395. This is a utility function that applications can use to create a queue
  396. without having to worry about using the correct call for the selected
  397. async mode.
  398. """
  399. return self._async['queue'](*args, **kwargs)
  400. def get_queue_empty_exception(self):
  401. """Return the queue empty exception for the appropriate async model.
  402. This is a utility function that applications can use to work with a
  403. queue without having to worry about using the correct call for the
  404. selected async mode.
  405. """
  406. return self._async['queue_empty']
  407. def create_event(self, *args, **kwargs):
  408. """Create an event object using the appropriate async model.
  409. This is a utility function that applications can use to create an
  410. event without having to worry about using the correct call for the
  411. selected async mode.
  412. """
  413. return self._async['event'](*args, **kwargs)
  414. def _generate_id(self):
  415. """Generate a unique session id."""
  416. return uuid.uuid4().hex
  417. def _handle_connect(self, environ, start_response, transport, b64=False,
  418. jsonp_index=None):
  419. """Handle a client connection request."""
  420. if self.start_service_task:
  421. # start the service task to monitor connected clients
  422. self.start_service_task = False
  423. self.start_background_task(self._service_task)
  424. sid = self._generate_id()
  425. s = socket.Socket(self, sid)
  426. self.sockets[sid] = s
  427. pkt = packet.Packet(
  428. packet.OPEN, {'sid': sid,
  429. 'upgrades': self._upgrades(sid, transport),
  430. 'pingTimeout': int(self.ping_timeout * 1000),
  431. 'pingInterval': int(self.ping_interval * 1000)})
  432. s.send(pkt)
  433. ret = self._trigger_event('connect', sid, environ, run_async=False)
  434. if ret is False:
  435. del self.sockets[sid]
  436. self.logger.warning('Application rejected connection')
  437. return self._unauthorized()
  438. if transport == 'websocket':
  439. ret = s.handle_get_request(environ, start_response)
  440. if s.closed:
  441. # websocket connection ended, so we are done
  442. del self.sockets[sid]
  443. return ret
  444. else:
  445. s.connected = True
  446. headers = None
  447. if self.cookie:
  448. headers = [('Set-Cookie', self.cookie + '=' + sid)]
  449. try:
  450. return self._ok(s.poll(), headers=headers, b64=b64,
  451. jsonp_index=jsonp_index)
  452. except exceptions.QueueEmpty:
  453. return self._bad_request()
  454. def _upgrades(self, sid, transport):
  455. """Return the list of possible upgrades for a client connection."""
  456. if not self.allow_upgrades or self._get_socket(sid).upgraded or \
  457. self._async['websocket'] is None or transport == 'websocket':
  458. return []
  459. return ['websocket']
  460. def _trigger_event(self, event, *args, **kwargs):
  461. """Invoke an event handler."""
  462. run_async = kwargs.pop('run_async', False)
  463. if event in self.handlers:
  464. if run_async:
  465. return self.start_background_task(self.handlers[event], *args)
  466. else:
  467. try:
  468. return self.handlers[event](*args)
  469. except:
  470. self.logger.exception(event + ' handler error')
  471. if event == 'connect':
  472. # if connect handler raised error we reject the
  473. # connection
  474. return False
  475. def _get_socket(self, sid):
  476. """Return the socket object for a given session."""
  477. try:
  478. s = self.sockets[sid]
  479. except KeyError:
  480. raise KeyError('Session not found')
  481. if s.closed:
  482. del self.sockets[sid]
  483. raise KeyError('Session is disconnected')
  484. return s
  485. def _ok(self, packets=None, headers=None, b64=False, jsonp_index=None):
  486. """Generate a successful HTTP response."""
  487. if packets is not None:
  488. if headers is None:
  489. headers = []
  490. if b64:
  491. headers += [('Content-Type', 'text/plain; charset=UTF-8')]
  492. else:
  493. headers += [('Content-Type', 'application/octet-stream')]
  494. return {'status': '200 OK',
  495. 'headers': headers,
  496. 'response': payload.Payload(packets=packets).encode(
  497. b64=b64, jsonp_index=jsonp_index)}
  498. else:
  499. return {'status': '200 OK',
  500. 'headers': [('Content-Type', 'text/plain')],
  501. 'response': b'OK'}
  502. def _bad_request(self):
  503. """Generate a bad request HTTP error response."""
  504. return {'status': '400 BAD REQUEST',
  505. 'headers': [('Content-Type', 'text/plain')],
  506. 'response': b'Bad Request'}
  507. def _method_not_found(self):
  508. """Generate a method not found HTTP error response."""
  509. return {'status': '405 METHOD NOT FOUND',
  510. 'headers': [('Content-Type', 'text/plain')],
  511. 'response': b'Method Not Found'}
  512. def _unauthorized(self):
  513. """Generate a unauthorized HTTP error response."""
  514. return {'status': '401 UNAUTHORIZED',
  515. 'headers': [('Content-Type', 'text/plain')],
  516. 'response': b'Unauthorized'}
  517. def _cors_allowed_origins(self, environ):
  518. default_origin = None
  519. if 'wsgi.url_scheme' in environ and 'HTTP_HOST' in environ:
  520. default_origin = '{scheme}://{host}'.format(
  521. scheme=environ['wsgi.url_scheme'], host=environ['HTTP_HOST'])
  522. if self.cors_allowed_origins is None:
  523. allowed_origins = [default_origin] \
  524. if default_origin is not None else []
  525. elif self.cors_allowed_origins == '*':
  526. allowed_origins = None
  527. elif isinstance(self.cors_allowed_origins, six.string_types):
  528. allowed_origins = [self.cors_allowed_origins]
  529. else:
  530. allowed_origins = self.cors_allowed_origins
  531. return allowed_origins
  532. def _cors_headers(self, environ):
  533. """Return the cross-origin-resource-sharing headers."""
  534. if self.cors_allowed_origins == []:
  535. # special case, CORS handling is completely disabled
  536. return []
  537. headers = []
  538. allowed_origins = self._cors_allowed_origins(environ)
  539. if 'HTTP_ORIGIN' in environ and \
  540. (allowed_origins is None or environ['HTTP_ORIGIN'] in
  541. allowed_origins):
  542. headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])]
  543. if environ['REQUEST_METHOD'] == 'OPTIONS':
  544. headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')]
  545. if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ:
  546. headers += [('Access-Control-Allow-Headers',
  547. environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])]
  548. if self.cors_credentials:
  549. headers += [('Access-Control-Allow-Credentials', 'true')]
  550. return headers
  551. def _gzip(self, response):
  552. """Apply gzip compression to a response."""
  553. bytesio = six.BytesIO()
  554. with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:
  555. gz.write(response)
  556. return bytesio.getvalue()
  557. def _deflate(self, response):
  558. """Apply deflate compression to a response."""
  559. return zlib.compress(response)
  560. def _service_task(self): # pragma: no cover
  561. """Monitor connected clients and clean up those that time out."""
  562. while True:
  563. if len(self.sockets) == 0:
  564. # nothing to do
  565. self.sleep(self.ping_timeout)
  566. continue
  567. # go through the entire client list in a ping interval cycle
  568. sleep_interval = self.ping_timeout / len(self.sockets)
  569. try:
  570. # iterate over the current clients
  571. for s in self.sockets.copy().values():
  572. if not s.closing and not s.closed:
  573. s.check_ping_timeout()
  574. self.sleep(sleep_interval)
  575. except (SystemExit, KeyboardInterrupt):
  576. self.logger.info('service task canceled')
  577. break
  578. except:
  579. # an unexpected exception has occurred, log it and continue
  580. self.logger.exception('service task exception')