##// END OF EJS Templates
s/==/is/
Kyle Kelley -
Show More
@@ -1,142 +1,142 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 same_origin(self):
46 def same_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 no header is provided, assume we can't verify origin
51 # If no header is provided, assume we can't verify origin
52 if(origin_header == None or host == None):
52 if(origin_header is None or host is None):
53 return False
53 return False
54
54
55 parsed_origin = urlparse(origin_header)
55 parsed_origin = urlparse(origin_header)
56 origin = parsed_origin.netloc
56 origin = parsed_origin.netloc
57
57
58 # Check to see that origin matches host directly, including ports
58 # Check to see that origin matches host directly, including ports
59 return origin == host
59 return origin == host
60
60
61 def clear_cookie(self, *args, **kwargs):
61 def clear_cookie(self, *args, **kwargs):
62 """meaningless for websockets"""
62 """meaningless for websockets"""
63 pass
63 pass
64
64
65 def _reserialize_reply(self, msg_list):
65 def _reserialize_reply(self, msg_list):
66 """Reserialize a reply message using JSON.
66 """Reserialize a reply message using JSON.
67
67
68 This takes the msg list from the ZMQ socket, unserializes it using
68 This takes the msg list from the ZMQ socket, unserializes it using
69 self.session and then serializes the result using JSON. This method
69 self.session and then serializes the result using JSON. This method
70 should be used by self._on_zmq_reply to build messages that can
70 should be used by self._on_zmq_reply to build messages that can
71 be sent back to the browser.
71 be sent back to the browser.
72 """
72 """
73 idents, msg_list = self.session.feed_identities(msg_list)
73 idents, msg_list = self.session.feed_identities(msg_list)
74 msg = self.session.unserialize(msg_list)
74 msg = self.session.unserialize(msg_list)
75 try:
75 try:
76 msg['header'].pop('date')
76 msg['header'].pop('date')
77 except KeyError:
77 except KeyError:
78 pass
78 pass
79 try:
79 try:
80 msg['parent_header'].pop('date')
80 msg['parent_header'].pop('date')
81 except KeyError:
81 except KeyError:
82 pass
82 pass
83 msg.pop('buffers')
83 msg.pop('buffers')
84 return jsonapi.dumps(msg, default=date_default)
84 return jsonapi.dumps(msg, default=date_default)
85
85
86 def _on_zmq_reply(self, msg_list):
86 def _on_zmq_reply(self, msg_list):
87 # Sometimes this gets triggered when the on_close method is scheduled in the
87 # Sometimes this gets triggered when the on_close method is scheduled in the
88 # eventloop but hasn't been called.
88 # eventloop but hasn't been called.
89 if self.stream.closed(): return
89 if self.stream.closed(): return
90 try:
90 try:
91 msg = self._reserialize_reply(msg_list)
91 msg = self._reserialize_reply(msg_list)
92 except Exception:
92 except Exception:
93 self.log.critical("Malformed message: %r" % msg_list, exc_info=True)
93 self.log.critical("Malformed message: %r" % msg_list, exc_info=True)
94 else:
94 else:
95 self.write_message(msg)
95 self.write_message(msg)
96
96
97 def allow_draft76(self):
97 def allow_draft76(self):
98 """Allow draft 76, until browsers such as Safari update to RFC 6455.
98 """Allow draft 76, until browsers such as Safari update to RFC 6455.
99
99
100 This has been disabled by default in tornado in release 2.2.0, and
100 This has been disabled by default in tornado in release 2.2.0, and
101 support will be removed in later versions.
101 support will be removed in later versions.
102 """
102 """
103 return True
103 return True
104
104
105
105
106 class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
106 class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
107
107
108 def open(self, kernel_id):
108 def open(self, kernel_id):
109 # Check to see that origin matches host directly, including ports
109 # Check to see that origin matches host directly, including ports
110 if not self.same_origin():
110 if not self.same_origin():
111 self.log.warn("Cross Origin WebSocket Attempt.")
111 self.log.warn("Cross Origin WebSocket Attempt.")
112 raise web.HTTPError(404)
112 raise web.HTTPError(404)
113
113
114 self.kernel_id = cast_unicode(kernel_id, 'ascii')
114 self.kernel_id = cast_unicode(kernel_id, 'ascii')
115 self.session = Session(config=self.config)
115 self.session = Session(config=self.config)
116 self.save_on_message = self.on_message
116 self.save_on_message = self.on_message
117 self.on_message = self.on_first_message
117 self.on_message = self.on_first_message
118
118
119 def _inject_cookie_message(self, msg):
119 def _inject_cookie_message(self, msg):
120 """Inject the first message, which is the document cookie,
120 """Inject the first message, which is the document cookie,
121 for authentication."""
121 for authentication."""
122 if not PY3 and isinstance(msg, unicode):
122 if not PY3 and isinstance(msg, unicode):
123 # Cookie constructor doesn't accept unicode strings
123 # Cookie constructor doesn't accept unicode strings
124 # under Python 2.x for some reason
124 # under Python 2.x for some reason
125 msg = msg.encode('utf8', 'replace')
125 msg = msg.encode('utf8', 'replace')
126 try:
126 try:
127 identity, msg = msg.split(':', 1)
127 identity, msg = msg.split(':', 1)
128 self.session.session = cast_unicode(identity, 'ascii')
128 self.session.session = cast_unicode(identity, 'ascii')
129 except Exception:
129 except Exception:
130 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
130 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
131
131
132 try:
132 try:
133 self.request._cookies = SimpleCookie(msg)
133 self.request._cookies = SimpleCookie(msg)
134 except:
134 except:
135 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
135 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
136
136
137 def on_first_message(self, msg):
137 def on_first_message(self, msg):
138 self._inject_cookie_message(msg)
138 self._inject_cookie_message(msg)
139 if self.get_current_user() is None:
139 if self.get_current_user() is None:
140 self.log.warn("Couldn't authenticate WebSocket connection")
140 self.log.warn("Couldn't authenticate WebSocket connection")
141 raise web.HTTPError(403)
141 raise web.HTTPError(403)
142 self.on_message = self.save_on_message
142 self.on_message = self.save_on_message
General Comments 0
You need to be logged in to leave comments. Login now