| 1 |
import base64 |
| 2 |
import hashlib |
| 3 |
|
| 4 |
from gevent.pywsgi import WSGIHandler |
| 5 |
from ._compat import PY3 |
| 6 |
from .websocket import WebSocket, Stream |
| 7 |
from .logging import create_logger |
| 8 |
|
| 9 |
|
| 10 |
class Client(object): |
| 11 |
def __init__(self, address, ws): |
| 12 |
self.address = address |
| 13 |
self.ws = ws |
| 14 |
|
| 15 |
|
| 16 |
class WebSocketHandler(WSGIHandler): |
| 17 |
""" |
| 18 |
Automatically upgrades the connection to a websocket. |
| 19 |
|
| 20 |
To prevent the WebSocketHandler to call the underlying WSGI application, |
| 21 |
but only setup the WebSocket negotiations, do: |
| 22 |
|
| 23 |
mywebsockethandler.prevent_wsgi_call = True |
| 24 |
|
| 25 |
before calling run_application(). This is useful if you want to do more |
| 26 |
things before calling the app, and want to off-load the WebSocket |
| 27 |
negotiations to this library. Socket.IO needs this for example, to send |
| 28 |
the 'ack' before yielding the control to your WSGI app. |
| 29 |
""" |
| 30 |
|
| 31 |
SUPPORTED_VERSIONS = ('13', '8', '7') |
| 32 |
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" |
| 33 |
|
| 34 |
def run_websocket(self): |
| 35 |
""" |
| 36 |
Called when a websocket has been created successfully. |
| 37 |
""" |
| 38 |
|
| 39 |
if getattr(self, 'prevent_wsgi_call', False): |
| 40 |
return |
| 41 |
|
| 42 |
|
| 43 |
if not hasattr(self.server, 'clients'): |
| 44 |
self.server.clients = {} |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
try: |
| 50 |
self.server.clients[self.client_address] = Client( |
| 51 |
self.client_address, self.websocket) |
| 52 |
list(self.application(self.environ, lambda s, h, e=None: [])) |
| 53 |
finally: |
| 54 |
del self.server.clients[self.client_address] |
| 55 |
if not self.websocket.closed: |
| 56 |
self.websocket.close() |
| 57 |
self.environ.update({ |
| 58 |
'wsgi.websocket': None |
| 59 |
}) |
| 60 |
self.websocket = None |
| 61 |
|
| 62 |
def run_application(self): |
| 63 |
if (hasattr(self.server, 'pre_start_hook') and self.server.pre_start_hook): |
| 64 |
self.logger.debug("Calling pre-start hook") |
| 65 |
if self.server.pre_start_hook(self): |
| 66 |
return super(WebSocketHandler, self).run_application() |
| 67 |
|
| 68 |
self.logger.debug("Initializing WebSocket") |
| 69 |
self.result = self.upgrade_websocket() |
| 70 |
|
| 71 |
if hasattr(self, 'websocket'): |
| 72 |
if self.status and not self.headers_sent: |
| 73 |
self.write('') |
| 74 |
|
| 75 |
self.run_websocket() |
| 76 |
else: |
| 77 |
if self.status: |
| 78 |
|
| 79 |
if not self.result: |
| 80 |
self.result = [] |
| 81 |
|
| 82 |
self.process_result() |
| 83 |
return |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
return super(WebSocketHandler, self).run_application() |
| 88 |
|
| 89 |
def upgrade_websocket(self): |
| 90 |
""" |
| 91 |
Attempt to upgrade the current environ into a websocket enabled |
| 92 |
connection. If successful, the environ dict with be updated with two |
| 93 |
new entries, `wsgi.websocket` and `wsgi.websocket_version`. |
| 94 |
|
| 95 |
:returns: Whether the upgrade was successful. |
| 96 |
""" |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
self.logger.debug("Validating WebSocket request") |
| 101 |
|
| 102 |
if self.environ.get('REQUEST_METHOD', '') != 'GET': |
| 103 |
|
| 104 |
self.logger.debug('Can only upgrade connection if using GET method.') |
| 105 |
return |
| 106 |
|
| 107 |
upgrade = self.environ.get('HTTP_UPGRADE', '').lower() |
| 108 |
|
| 109 |
if upgrade == 'websocket': |
| 110 |
connection = self.environ.get('HTTP_CONNECTION', '').lower() |
| 111 |
|
| 112 |
if 'upgrade' not in connection: |
| 113 |
|
| 114 |
self.logger.warning("Client didn't ask for a connection " |
| 115 |
"upgrade") |
| 116 |
return |
| 117 |
else: |
| 118 |
|
| 119 |
return |
| 120 |
|
| 121 |
if self.request_version != 'HTTP/1.1': |
| 122 |
self.start_response('402 Bad Request', []) |
| 123 |
self.logger.warning("Bad server protocol in headers") |
| 124 |
|
| 125 |
return ['Bad protocol version'] |
| 126 |
|
| 127 |
if self.environ.get('HTTP_SEC_WEBSOCKET_VERSION'): |
| 128 |
return self.upgrade_connection() |
| 129 |
else: |
| 130 |
self.logger.warning("No protocol defined") |
| 131 |
self.start_response('426 Upgrade Required', [ |
| 132 |
('Sec-WebSocket-Version', ', '.join(self.SUPPORTED_VERSIONS))]) |
| 133 |
|
| 134 |
return ['No Websocket protocol version defined'] |
| 135 |
|
| 136 |
def upgrade_connection(self): |
| 137 |
""" |
| 138 |
Validate and 'upgrade' the HTTP request to a WebSocket request. |
| 139 |
|
| 140 |
If an upgrade succeeded then then handler will have `start_response` |
| 141 |
with a status of `101`, the environ will also be updated with |
| 142 |
`wsgi.websocket` and `wsgi.websocket_version` keys. |
| 143 |
|
| 144 |
:param environ: The WSGI environ dict. |
| 145 |
:param start_response: The callable used to start the response. |
| 146 |
:param stream: File like object that will be read from/written to by |
| 147 |
the underlying WebSocket object, if created. |
| 148 |
:return: The WSGI response iterator is something went awry. |
| 149 |
""" |
| 150 |
|
| 151 |
self.logger.debug("Attempting to upgrade connection") |
| 152 |
|
| 153 |
version = self.environ.get("HTTP_SEC_WEBSOCKET_VERSION") |
| 154 |
|
| 155 |
if version not in self.SUPPORTED_VERSIONS: |
| 156 |
msg = "Unsupported WebSocket Version: {0}".format(version) |
| 157 |
|
| 158 |
self.logger.warning(msg) |
| 159 |
self.start_response('400 Bad Request', [ |
| 160 |
('Sec-WebSocket-Version', ', '.join(self.SUPPORTED_VERSIONS)) |
| 161 |
]) |
| 162 |
|
| 163 |
return [msg] |
| 164 |
|
| 165 |
key = self.environ.get("HTTP_SEC_WEBSOCKET_KEY", '').strip() |
| 166 |
|
| 167 |
if not key: |
| 168 |
|
| 169 |
msg = "Sec-WebSocket-Key header is missing/empty" |
| 170 |
|
| 171 |
self.logger.warning(msg) |
| 172 |
self.start_response('400 Bad Request', []) |
| 173 |
|
| 174 |
return [msg] |
| 175 |
|
| 176 |
try: |
| 177 |
key_len = len(base64.b64decode(key)) |
| 178 |
except TypeError: |
| 179 |
msg = "Invalid key: {0}".format(key) |
| 180 |
|
| 181 |
self.logger.warning(msg) |
| 182 |
self.start_response('400 Bad Request', []) |
| 183 |
|
| 184 |
return [msg] |
| 185 |
|
| 186 |
if key_len != 16: |
| 187 |
|
| 188 |
msg = "Invalid key: {0}".format(key) |
| 189 |
|
| 190 |
self.logger.warning(msg) |
| 191 |
self.start_response('400 Bad Request', []) |
| 192 |
|
| 193 |
return [msg] |
| 194 |
|
| 195 |
|
| 196 |
requested_protocols = self.environ.get( |
| 197 |
'HTTP_SEC_WEBSOCKET_PROTOCOL', '') |
| 198 |
protocol = None |
| 199 |
|
| 200 |
if hasattr(self.application, 'app_protocol'): |
| 201 |
allowed_protocol = self.application.app_protocol( |
| 202 |
self.environ['PATH_INFO']) |
| 203 |
|
| 204 |
if allowed_protocol and allowed_protocol in requested_protocols: |
| 205 |
protocol = allowed_protocol |
| 206 |
self.logger.debug("Protocol allowed: {0}".format(protocol)) |
| 207 |
|
| 208 |
self.websocket = WebSocket(self.environ, Stream(self), self) |
| 209 |
self.environ.update({ |
| 210 |
'wsgi.websocket_version': version, |
| 211 |
'wsgi.websocket': self.websocket |
| 212 |
}) |
| 213 |
|
| 214 |
if PY3: |
| 215 |
accept = base64.b64encode( |
| 216 |
hashlib.sha1((key + self.GUID).encode("latin-1")).digest() |
| 217 |
).decode("latin-1") |
| 218 |
else: |
| 219 |
accept = base64.b64encode(hashlib.sha1(key + self.GUID).digest()) |
| 220 |
|
| 221 |
headers = [ |
| 222 |
("Upgrade", "websocket"), |
| 223 |
("Connection", "Upgrade"), |
| 224 |
("Sec-WebSocket-Accept", accept) |
| 225 |
] |
| 226 |
|
| 227 |
if protocol: |
| 228 |
headers.append(("Sec-WebSocket-Protocol", protocol)) |
| 229 |
|
| 230 |
self.logger.debug("WebSocket request accepted, switching protocols") |
| 231 |
self.start_response("101 Switching Protocols", headers) |
| 232 |
|
| 233 |
@property |
| 234 |
def logger(self): |
| 235 |
if not hasattr(self.server, 'logger'): |
| 236 |
self.server.logger = create_logger(__name__) |
| 237 |
|
| 238 |
return self.server.logger |
| 239 |
|
| 240 |
def log_request(self): |
| 241 |
if '101' not in str(self.status): |
| 242 |
self.logger.info(self.format_request()) |
| 243 |
|
| 244 |
@property |
| 245 |
def active_client(self): |
| 246 |
return self.server.clients[self.client_address] |
| 247 |
|
| 248 |
def start_response(self, status, headers, exc_info=None): |
| 249 |
""" |
| 250 |
Called when the handler is ready to send a response back to the remote |
| 251 |
endpoint. A websocket connection may have not been created. |
| 252 |
""" |
| 253 |
writer = super(WebSocketHandler, self).start_response( |
| 254 |
status, headers, exc_info=exc_info) |
| 255 |
|
| 256 |
self._prepare_response() |
| 257 |
|
| 258 |
return writer |
| 259 |
|
| 260 |
def _prepare_response(self): |
| 261 |
""" |
| 262 |
Sets up the ``pywsgi.Handler`` to work with a websocket response. |
| 263 |
|
| 264 |
This is used by other projects that need to support WebSocket |
| 265 |
connections as part of a larger effort. |
| 266 |
""" |
| 267 |
assert not self.headers_sent |
| 268 |
|
| 269 |
if not self.environ.get('wsgi.websocket'): |
| 270 |
|
| 271 |
return |
| 272 |
|
| 273 |
|
| 274 |
self.provided_content_length = False |
| 275 |
|
| 276 |
|
| 277 |
self.response_use_chunked = False |
| 278 |
|
| 279 |
|
| 280 |
self.close_connection = True |
| 281 |
|
| 282 |
|
| 283 |
self.provided_date = True |