Show More
@@ -1,138 +1,141 b'' | |||||
1 | """Tornado handlers for WebSocket <-> ZMQ sockets. |
|
1 | """Tornado handlers for WebSocket <-> ZMQ sockets. | |
2 |
|
2 | |||
3 | Authors: |
|
3 | Authors: | |
4 |
|
4 | |||
5 | * Brian Granger |
|
5 | * Brian Granger | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 | # Copyright (C) 2008-2011 The IPython Development Team |
|
9 | # Copyright (C) 2008-2011 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | try: |
|
19 | try: | |
20 | from urllib.parse import urlparse # Py 3 |
|
20 | from urllib.parse import urlparse # Py 3 | |
21 | except ImportError: |
|
21 | except ImportError: | |
22 | from urlparse import urlparse # Py 2 |
|
22 | from urlparse import urlparse # Py 2 | |
23 |
|
23 | |||
24 | try: |
|
24 | try: | |
25 | from http.cookies import SimpleCookie # Py 3 |
|
25 | from http.cookies import SimpleCookie # Py 3 | |
26 | except ImportError: |
|
26 | except ImportError: | |
27 | from Cookie import SimpleCookie # Py 2 |
|
27 | from Cookie import SimpleCookie # Py 2 | |
28 | import logging |
|
28 | import logging | |
29 | from tornado import web |
|
29 | from tornado import web | |
30 | from tornado import websocket |
|
30 | from tornado import websocket | |
31 |
|
31 | |||
32 | from zmq.utils import jsonapi |
|
32 | from zmq.utils import jsonapi | |
33 |
|
33 | |||
34 | from IPython.kernel.zmq.session import Session |
|
34 | from IPython.kernel.zmq.session import Session | |
35 | from IPython.utils.jsonutil import date_default |
|
35 | from IPython.utils.jsonutil import date_default | |
36 | from IPython.utils.py3compat import PY3, cast_unicode |
|
36 | from IPython.utils.py3compat import PY3, cast_unicode | |
37 |
|
37 | |||
38 | from .handlers import IPythonHandler |
|
38 | from .handlers import IPythonHandler | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # ZMQ handlers |
|
41 | # ZMQ handlers | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | class ZMQStreamHandler(websocket.WebSocketHandler): |
|
44 | class ZMQStreamHandler(websocket.WebSocketHandler): | |
45 |
|
45 | |||
46 | def is_cross_origin(self): |
|
46 | def is_cross_origin(self): | |
47 | """Check to see that origin and host match in the headers.""" |
|
47 | """Check to see that origin and host match in the headers.""" | |
48 | origin_header = self.request.headers.get("Origin") |
|
48 | origin_header = self.request.headers.get("Origin") | |
49 | host = self.request.headers.get("Host") |
|
49 | host = self.request.headers.get("Host") | |
50 |
|
50 | |||
|
51 | if(origin_header == None or host == None): | |||
|
52 | return True | |||
|
53 | ||||
51 | parsed_origin = urlparse(origin_header) |
|
54 | parsed_origin = urlparse(origin_header) | |
52 | origin = parsed_origin.netloc |
|
55 | origin = parsed_origin.netloc | |
53 |
|
56 | |||
54 | # Check to see that origin matches host directly, including ports |
|
57 | # Check to see that origin matches host directly, including ports | |
55 | return origin != host |
|
58 | return origin != host | |
56 |
|
59 | |||
57 | def clear_cookie(self, *args, **kwargs): |
|
60 | def clear_cookie(self, *args, **kwargs): | |
58 | """meaningless for websockets""" |
|
61 | """meaningless for websockets""" | |
59 | pass |
|
62 | pass | |
60 |
|
63 | |||
61 | def _reserialize_reply(self, msg_list): |
|
64 | def _reserialize_reply(self, msg_list): | |
62 | """Reserialize a reply message using JSON. |
|
65 | """Reserialize a reply message using JSON. | |
63 |
|
66 | |||
64 | This takes the msg list from the ZMQ socket, unserializes it using |
|
67 | This takes the msg list from the ZMQ socket, unserializes it using | |
65 | self.session and then serializes the result using JSON. This method |
|
68 | self.session and then serializes the result using JSON. This method | |
66 | should be used by self._on_zmq_reply to build messages that can |
|
69 | should be used by self._on_zmq_reply to build messages that can | |
67 | be sent back to the browser. |
|
70 | be sent back to the browser. | |
68 | """ |
|
71 | """ | |
69 | idents, msg_list = self.session.feed_identities(msg_list) |
|
72 | idents, msg_list = self.session.feed_identities(msg_list) | |
70 | msg = self.session.unserialize(msg_list) |
|
73 | msg = self.session.unserialize(msg_list) | |
71 | try: |
|
74 | try: | |
72 | msg['header'].pop('date') |
|
75 | msg['header'].pop('date') | |
73 | except KeyError: |
|
76 | except KeyError: | |
74 | pass |
|
77 | pass | |
75 | try: |
|
78 | try: | |
76 | msg['parent_header'].pop('date') |
|
79 | msg['parent_header'].pop('date') | |
77 | except KeyError: |
|
80 | except KeyError: | |
78 | pass |
|
81 | pass | |
79 | msg.pop('buffers') |
|
82 | msg.pop('buffers') | |
80 | return jsonapi.dumps(msg, default=date_default) |
|
83 | return jsonapi.dumps(msg, default=date_default) | |
81 |
|
84 | |||
82 | def _on_zmq_reply(self, msg_list): |
|
85 | def _on_zmq_reply(self, msg_list): | |
83 | # Sometimes this gets triggered when the on_close method is scheduled in the |
|
86 | # Sometimes this gets triggered when the on_close method is scheduled in the | |
84 | # eventloop but hasn't been called. |
|
87 | # eventloop but hasn't been called. | |
85 | if self.stream.closed(): return |
|
88 | if self.stream.closed(): return | |
86 | try: |
|
89 | try: | |
87 | msg = self._reserialize_reply(msg_list) |
|
90 | msg = self._reserialize_reply(msg_list) | |
88 | except Exception: |
|
91 | except Exception: | |
89 | self.log.critical("Malformed message: %r" % msg_list, exc_info=True) |
|
92 | self.log.critical("Malformed message: %r" % msg_list, exc_info=True) | |
90 | else: |
|
93 | else: | |
91 | self.write_message(msg) |
|
94 | self.write_message(msg) | |
92 |
|
95 | |||
93 | def allow_draft76(self): |
|
96 | def allow_draft76(self): | |
94 | """Allow draft 76, until browsers such as Safari update to RFC 6455. |
|
97 | """Allow draft 76, until browsers such as Safari update to RFC 6455. | |
95 |
|
98 | |||
96 | This has been disabled by default in tornado in release 2.2.0, and |
|
99 | This has been disabled by default in tornado in release 2.2.0, and | |
97 | support will be removed in later versions. |
|
100 | support will be removed in later versions. | |
98 | """ |
|
101 | """ | |
99 | return True |
|
102 | return True | |
100 |
|
103 | |||
101 |
|
104 | |||
102 | class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler): |
|
105 | class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler): | |
103 |
|
106 | |||
104 | def open(self, kernel_id): |
|
107 | def open(self, kernel_id): | |
105 | # Check to see that origin matches host directly, including ports |
|
108 | # Check to see that origin matches host directly, including ports | |
106 | if self.is_cross_origin(): |
|
109 | if self.is_cross_origin(): | |
107 | self.log.warn("Cross Origin WebSocket Attempt.") |
|
110 | self.log.warn("Cross Origin WebSocket Attempt.") | |
108 | raise web.HTTPError(404) |
|
111 | raise web.HTTPError(404) | |
109 |
|
112 | |||
110 | self.kernel_id = cast_unicode(kernel_id, 'ascii') |
|
113 | self.kernel_id = cast_unicode(kernel_id, 'ascii') | |
111 | self.session = Session(config=self.config) |
|
114 | self.session = Session(config=self.config) | |
112 | self.save_on_message = self.on_message |
|
115 | self.save_on_message = self.on_message | |
113 | self.on_message = self.on_first_message |
|
116 | self.on_message = self.on_first_message | |
114 |
|
117 | |||
115 | def _inject_cookie_message(self, msg): |
|
118 | def _inject_cookie_message(self, msg): | |
116 | """Inject the first message, which is the document cookie, |
|
119 | """Inject the first message, which is the document cookie, | |
117 | for authentication.""" |
|
120 | for authentication.""" | |
118 | if not PY3 and isinstance(msg, unicode): |
|
121 | if not PY3 and isinstance(msg, unicode): | |
119 | # Cookie constructor doesn't accept unicode strings |
|
122 | # Cookie constructor doesn't accept unicode strings | |
120 | # under Python 2.x for some reason |
|
123 | # under Python 2.x for some reason | |
121 | msg = msg.encode('utf8', 'replace') |
|
124 | msg = msg.encode('utf8', 'replace') | |
122 | try: |
|
125 | try: | |
123 | identity, msg = msg.split(':', 1) |
|
126 | identity, msg = msg.split(':', 1) | |
124 | self.session.session = cast_unicode(identity, 'ascii') |
|
127 | self.session.session = cast_unicode(identity, 'ascii') | |
125 | except Exception: |
|
128 | except Exception: | |
126 | logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg) |
|
129 | logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg) | |
127 |
|
130 | |||
128 | try: |
|
131 | try: | |
129 | self.request._cookies = SimpleCookie(msg) |
|
132 | self.request._cookies = SimpleCookie(msg) | |
130 | except: |
|
133 | except: | |
131 | self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True) |
|
134 | self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True) | |
132 |
|
135 | |||
133 | def on_first_message(self, msg): |
|
136 | def on_first_message(self, msg): | |
134 | self._inject_cookie_message(msg) |
|
137 | self._inject_cookie_message(msg) | |
135 | if self.get_current_user() is None: |
|
138 | if self.get_current_user() is None: | |
136 | self.log.warn("Couldn't authenticate WebSocket connection") |
|
139 | self.log.warn("Couldn't authenticate WebSocket connection") | |
137 | raise web.HTTPError(403) |
|
140 | raise web.HTTPError(403) | |
138 | self.on_message = self.save_on_message |
|
141 | self.on_message = self.save_on_message |
General Comments 0
You need to be logged in to leave comments.
Login now