Merge 0.10->trunk
[prosody.git] / plugins / mod_websocket.lua
1 -- Prosody IM
2 -- Copyright (C) 2012-2014 Florian Zeitz
3 --
4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information.
6 --
7 -- luacheck: ignore 431/log
8
9 module:set_global();
10
11 local add_task = require "util.timer".add_task;
12 local add_filter = require "util.filters".add_filter;
13 local sha1 = require "util.hashes".sha1;
14 local base64 = require "util.encodings".base64.encode;
15 local st = require "util.stanza";
16 local parse_xml = require "util.xml".parse;
17 local portmanager = require "core.portmanager";
18 local sm_destroy_session = require"core.sessionmanager".destroy_session;
19 local log = module._log;
20
21 local websocket_frames = require"net.websocket.frames";
22 local parse_frame = websocket_frames.parse;
23 local build_frame = websocket_frames.build;
24 local build_close = websocket_frames.build_close;
25 local parse_close = websocket_frames.parse_close;
26
27 local t_concat = table.concat;
28
29 local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5);
30 local consider_websocket_secure = module:get_option_boolean("consider_websocket_secure");
31 local cross_domain = module:get_option("cross_domain_websocket");
32 if cross_domain then
33         if cross_domain == true then
34                 cross_domain = "*";
35         elseif type(cross_domain) == "table" then
36                 cross_domain = t_concat(cross_domain, ", ");
37         end
38         if type(cross_domain) ~= "string" then
39                 cross_domain = nil;
40         end
41 end
42
43 local xmlns_framing = "urn:ietf:params:xml:ns:xmpp-framing";
44 local xmlns_streams = "http://etherx.jabber.org/streams";
45 local xmlns_client = "jabber:client";
46 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
47
48 module:depends("c2s")
49 local sessions = module:shared("c2s/sessions");
50 local c2s_listener = portmanager.get_service("c2s").listener;
51
52 --- Session methods
53 local function session_open_stream(session)
54         local attr = {
55                 xmlns = xmlns_framing,
56                 version = "1.0",
57                 id = session.streamid or "",
58                 from = session.host
59         };
60         session.send(st.stanza("open", attr));
61 end
62
63 local function session_close(session, reason)
64         local log = session.log or log;
65         if session.conn then
66                 if session.notopen then
67                         session:open_stream();
68                 end
69                 if reason then -- nil == no err, initiated by us, false == initiated by client
70                         local stream_error = st.stanza("stream:error");
71                         if type(reason) == "string" then -- assume stream error
72                                 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
73                         elseif type(reason) == "table" then
74                                 if reason.condition then
75                                         stream_error:tag(reason.condition, stream_xmlns_attr):up();
76                                         if reason.text then
77                                                 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
78                                         end
79                                         if reason.extra then
80                                                 stream_error:add_child(reason.extra);
81                                         end
82                                 elseif reason.name then -- a stanza
83                                         stream_error = reason;
84                                 end
85                         end
86                         log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stream_error));
87                         session.send(stream_error);
88                 end
89
90                 session.send(st.stanza("close", { xmlns = xmlns_framing }));
91                 function session.send() return false; end
92
93                 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
94                 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
95
96                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
97                 local conn = session.conn;
98                 if reason == nil and not session.notopen and session.type == "c2s" then
99                         -- Grace time to process data from authenticated cleanly-closed stream
100                         add_task(stream_close_timeout, function ()
101                                 if not session.destroyed then
102                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
103                                         sm_destroy_session(session, reason);
104                                         conn:write(build_close(1000, "Stream closed"));
105                                         conn:close();
106                                 end
107                         end);
108                 else
109                         sm_destroy_session(session, reason);
110                         conn:write(build_close(1000, "Stream closed"));
111                         conn:close();
112                 end
113         end
114 end
115
116
117 --- Filters
118 local function filter_open_close(data)
119         if not data:find(xmlns_framing, 1, true) then return data; end
120
121         local oc = parse_xml(data);
122         if not oc then return data; end
123         if oc.attr.xmlns ~= xmlns_framing then return data; end
124         if oc.name == "close" then return "</stream:stream>"; end
125         if oc.name == "open" then
126                 oc.name = "stream:stream";
127                 oc.attr.xmlns = nil;
128                 oc.attr["xmlns:stream"] = xmlns_streams;
129                 return oc:top_tag();
130         end
131
132         return data;
133 end
134 function handle_request(event)
135         local request, response = event.request, event.response;
136         local conn = response.conn;
137
138         if not request.headers.sec_websocket_key then
139                 response.headers.content_type = "text/html";
140                 return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
141                         <p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
142                         </body></html>]];
143         end
144
145         local wants_xmpp = false;
146         (request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
147                 if proto == "xmpp" then wants_xmpp = true; end
148         end);
149
150         if not wants_xmpp then
151                 return 501;
152         end
153
154         local function websocket_close(code, message)
155                 conn:write(build_close(code, message));
156                 conn:close();
157         end
158
159         local dataBuffer;
160         local function handle_frame(frame)
161                 local opcode = frame.opcode;
162                 local length = frame.length;
163                 module:log("debug", "Websocket received frame: opcode=%0x, %i bytes", frame.opcode, #frame.data);
164
165                 -- Error cases
166                 if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
167                         websocket_close(1002, "Reserved bits not zero");
168                         return false;
169                 end
170
171                 if opcode == 0x8 then -- close frame
172                         if length == 1 then
173                                 websocket_close(1002, "Close frame with payload, but too short for status code");
174                                 return false;
175                         elseif length >= 2 then
176                                 local status_code = parse_close(frame.data)
177                                 if status_code < 1000 then
178                                         websocket_close(1002, "Closed with invalid status code");
179                                         return false;
180                                 elseif ((status_code > 1003 and status_code < 1007) or status_code > 1011) and status_code < 3000 then
181                                         websocket_close(1002, "Closed with reserved status code");
182                                         return false;
183                                 end
184                         end
185                 end
186
187                 if opcode >= 0x8 then
188                         if length > 125 then -- Control frame with too much payload
189                                 websocket_close(1002, "Payload too large");
190                                 return false;
191                         end
192
193                         if not frame.FIN then -- Fragmented control frame
194                                 websocket_close(1002, "Fragmented control frame");
195                                 return false;
196                         end
197                 end
198
199                 if (opcode > 0x2 and opcode < 0x8) or (opcode > 0xA) then
200                         websocket_close(1002, "Reserved opcode");
201                         return false;
202                 end
203
204                 if opcode == 0x0 and not dataBuffer then
205                         websocket_close(1002, "Unexpected continuation frame");
206                         return false;
207                 end
208
209                 if (opcode == 0x1 or opcode == 0x2) and dataBuffer then
210                         websocket_close(1002, "Continuation frame expected");
211                         return false;
212                 end
213
214                 -- Valid cases
215                 if opcode == 0x0 then -- Continuation frame
216                         dataBuffer[#dataBuffer+1] = frame.data;
217                 elseif opcode == 0x1 then -- Text frame
218                         dataBuffer = {frame.data};
219                 elseif opcode == 0x2 then -- Binary frame
220                         websocket_close(1003, "Only text frames are supported");
221                         return;
222                 elseif opcode == 0x8 then -- Close request
223                         websocket_close(1000, "Goodbye");
224                         return;
225                 elseif opcode == 0x9 then -- Ping frame
226                         frame.opcode = 0xA;
227                         conn:write(build_frame(frame));
228                         return "";
229                 elseif opcode == 0xA then -- Pong frame, MAY be sent unsolicited, eg as keepalive
230                         return "";
231                 else
232                         log("warn", "Received frame with unsupported opcode %i", opcode);
233                         return "";
234                 end
235
236                 if frame.FIN then
237                         local data = t_concat(dataBuffer, "");
238                         dataBuffer = nil;
239                         return data;
240                 end
241                 return "";
242         end
243
244         conn:setlistener(c2s_listener);
245         c2s_listener.onconnect(conn);
246
247         local session = sessions[conn];
248
249         session.secure = consider_websocket_secure or session.secure;
250
251         session.open_stream = session_open_stream;
252         session.close = session_close;
253
254         local frameBuffer = "";
255         add_filter(session, "bytes/in", function(data)
256                 local cache = {};
257                 frameBuffer = frameBuffer .. data;
258                 local frame, length = parse_frame(frameBuffer);
259
260                 while frame do
261                         frameBuffer = frameBuffer:sub(length + 1);
262                         local result = handle_frame(frame);
263                         if not result then return; end
264                         cache[#cache+1] = filter_open_close(result);
265                         frame, length = parse_frame(frameBuffer);
266                 end
267                 return t_concat(cache, "");
268         end);
269
270         add_filter(session, "stanzas/out", function(stanza)
271                 local attr = stanza.attr;
272                 attr.xmlns = attr.xmlns or xmlns_client;
273                 if stanza.name:find("^stream:") then
274                         attr["xmlns:stream"] = attr["xmlns:stream"] or xmlns_streams;
275                 end
276                 return stanza;
277         end, -1000);
278
279         add_filter(session, "bytes/out", function(data)
280                 return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
281         end);
282
283         response.status_code = 101;
284         response.headers.upgrade = "websocket";
285         response.headers.connection = "Upgrade";
286         response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
287         response.headers.sec_webSocket_protocol = "xmpp";
288         response.headers.access_control_allow_origin = cross_domain;
289
290         return "";
291 end
292
293 local function keepalive(event)
294         local session = event.session;
295         if session.open_stream == session_open_stream then
296                 return session.conn:write(build_frame({ opcode = 0x9, }));
297         end
298 end
299
300 module:hook("c2s-read-timeout", keepalive, -0.9);
301
302 function module.add_host(module)
303         module:depends("http");
304         module:provides("http", {
305                 name = "websocket";
306                 default_path = "xmpp-websocket";
307                 route = {
308                         ["GET"] = handle_request;
309                         ["GET /"] = handle_request;
310                 };
311         });
312         module:hook("c2s-read-timeout", keepalive, -0.9);
313 end