/usr/lib/python3/dist-packages/tornadio2/polling.py is in python3-tornadio2 0.0.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2011 by the Serge S. Koval, see AUTHORS for more details.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
tornadio2.polling
~~~~~~~~~~~~~~~~~
This module implements socket.io polling transports.
"""
import time
import logging
try:
from urllib import unquote_plus # Python 2
except ImportError:
from urllib.parse import unquote_plus # Python 3
from tornado.web import HTTPError, asynchronous
from tornadio2 import proto, preflight, stats
class TornadioPollingHandlerBase(preflight.PreflightHandler):
"""Polling handler base"""
def initialize(self, server):
self.server = server
self.session = None
logging.debug('Initializing %s transport.' % self.name)
def _get_session(self, session_id):
"""Get session if exists and checks if session is closed.
"""
# Get session
session = self.server.get_session(session_id)
# If session was not found, ignore it
if session is None:
raise HTTPError(401, 'Invalid session')
# If session is closed, but there are some pending messages left - make sure to send them
if session.is_closed and not session.send_queue:
raise HTTPError(401, 'Invalid session')
return session
def _detach(self):
"""Detach from the session"""
if self.session:
if not self.server.settings['global_heartbeats']:
self.session.stop_heartbeat()
self.session.remove_handler(self)
self.session = None
@asynchronous
def get(self, session_id):
"""Default GET handler."""
raise NotImplementedError()
def post(self, session_id):
"""Handle incoming POST request"""
try:
# Stats
self.server.stats.connection_opened()
# Get session
self.session = self._get_session(session_id)
# Can not send messages to closed session or if preflight() failed
if self.session.is_closed or not self.preflight():
raise HTTPError(401)
# Grab body and decode it (socket.io always sends data in utf-8)
data = self.request.body.decode('utf-8')
# IE XDomainRequest support
if data.startswith(u'data='):
data = data[5:]
# Process packets one by one
packets = proto.decode_frames(data)
# Tracking
self.server.stats.on_packet_recv(len(packets))
for p in packets:
try:
self.session.raw_message(p)
except Exception:
# Close session if something went wrong
self.session.close()
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.finish()
finally:
self.server.stats.connection_closed()
def check_xsrf_cookie(self):
pass
def send_messages(self, messages):
"""Called by the session when some data is available"""
raise NotImplementedError()
def session_closed(self):
"""Called by the session when it was closed"""
self._detach()
def on_connection_close(self):
"""Called by Tornado, when connection was closed"""
self._detach()
class TornadioXHRPollingHandler(TornadioPollingHandlerBase):
"""xhr-polling transport implementation"""
# Transport name
name = 'xhr-polling'
def initialize(self, server):
super(TornadioXHRPollingHandler, self).initialize(server)
self._timeout = None
# TODO: Move me out, there's no need to read timeout for POST requests
self._timeout_interval = self.server.settings['xhr_polling_timeout']
@asynchronous
def get(self, session_id):
# Get session
self.session = self._get_session(session_id)
if not self.session.set_handler(self):
# TODO: Error logging
raise HTTPError(401)
if not self.session.send_queue:
self._bump_timeout()
else:
self.session.flush()
def _stop_timeout(self):
if self._timeout is not None:
self.server.io_loop.remove_timeout(self._timeout)
self._timeout = None
def _bump_timeout(self):
self._stop_timeout()
self._timeout = self.server.io_loop.add_timeout(
time.time() + self._timeout_interval,
self._polling_timeout
)
def _polling_timeout(self):
try:
self.send_messages([proto.noop()])
except Exception:
logging.debug('Exception', exc_info=True)
finally:
self._detach()
def _detach(self):
self._stop_timeout()
super(TornadioXHRPollingHandler, self)._detach()
def send_messages(self, messages):
# Tracking
self.server.stats.on_packet_sent(len(messages))
# Encode multiple messages as UTF-8 string
data = proto.encode_frames(messages)
# Send data to client
self.preflight()
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.set_header('Content-Length', len(data))
self.write(data)
# Detach connection from session
self._detach()
# Close connection
self.finish()
def session_closed(self):
try:
self.finish()
except Exception:
logging.debug('Exception', exc_info=True)
finally:
self._detach()
class TornadioHtmlFileHandler(TornadioPollingHandlerBase):
"""IE HtmlFile protocol implementation.
Uses hidden frame to stream data from the server in one connection.
"""
# Transport name
name = 'htmlfile'
@asynchronous
def get(self, session_id):
# Get session
self.session = self._get_session(session_id)
if not self.session.set_handler(self):
raise HTTPError(401)
self.set_header('Content-Type', 'text/html; charset=UTF-8')
self.set_header('Connection', 'keep-alive')
self.write('<html><body><script>var _ = function (msg) { parent.s._(msg, document); };</script>' + (' ' * 174))
self.flush()
# Dump any queued messages
self.session.flush()
# If hearbeats were not started by `HandshakeHandler`, start them.
if not self.server.settings['global_heartbeats']:
self.session.reset_heartbeat()
def send_messages(self, messages):
# Tracking
self.server.stats.on_packet_sent(len(messages))
# Encode frames and send data
data = proto.encode_frames(messages)
self.write(
'<script>_(%s);</script>' % proto.json_dumps(data)
)
self.flush()
if not self.server.settings['global_heartbeats']:
self.session.delay_heartbeat()
def session_closed(self):
try:
self.finish()
except Exception:
logging.debug('Exception', exc_info=True)
finally:
self._detach()
class TornadioJSONPHandler(TornadioXHRPollingHandler):
# Transport name
name = 'jsonp'
def initialize(self, server):
self._index = None
super(TornadioJSONPHandler, self).initialize(server)
@asynchronous
def get(self, session_id):
self._index = self.get_argument('i', 0)
super(TornadioJSONPHandler, self).get(session_id)
def post(self, session_id):
try:
# Stats
self.server.stats.connection_opened()
# Get session
self.session = self._get_session(session_id)
# Can not send messages to closed session or if preflight() failed
if self.session.is_closed or not self.preflight():
raise HTTPError(401)
# Socket.io always send data utf-8 encoded.
data = self.request.body
# IE XDomainRequest support
if not data.startswith('d='):
logging.error('Malformed JSONP POST request')
raise HTTPError(403)
# Grab data
data = unquote_plus(data[2:]).decode('utf-8')
# If starts with double quote, it is json encoded (socket.io workaround)
if data.startswith(u'"'):
data = proto.json_load(data)
# Process packets one by one
packets = proto.decode_frames(data)
# Tracking
self.server.stats.on_packet_recv(len(packets))
for p in packets:
try:
self.session.raw_message(p)
except Exception:
# Close session if something went wrong
self.session.close()
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.finish()
finally:
self.server.stats.connection_closed()
def send_messages(self, messages):
if self._index is None:
raise HTTPError(401)
# Tracking
self.server.stats.on_packet_sent(len(messages))
data = proto.encode_frames(messages)
message = 'io.j[%s](%s);' % (
self._index,
proto.json_dumps(data)
)
self.preflight()
self.set_header('Content-Type', 'text/javascript; charset=UTF-8')
self.set_header('Content-Length', len(message))
self.set_header('X-XSS-Protection', '0')
self.set_header('Connection', 'Keep-Alive')
self.write(message)
self._detach()
self.finish()
|