2 -- Copyright (C) 2012-2014 Florian Zeitz
4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information.
10 local add_filter = require "util.filters".add_filter;
11 local sha1 = require "util.hashes".sha1;
12 local base64 = require "util.encodings".base64.encode;
13 local st = require "util.stanza";
14 local parse_xml = require "util.xml".parse;
15 local portmanager = require "core.portmanager";
16 local sm_destroy_session = sessionmanager.destroy_session;
17 local log = module._log;
19 local websocket_frames = require"net.websocket.frames";
20 local parse_frame = websocket_frames.parse;
21 local build_frame = websocket_frames.build;
22 local build_close = websocket_frames.build_close;
23 local parse_close = websocket_frames.parse_close;
25 local t_concat = table.concat;
27 local consider_websocket_secure = module:get_option_boolean("consider_websocket_secure");
28 local cross_domain = module:get_option("cross_domain_websocket");
30 if cross_domain == true then
32 elseif type(cross_domain) == "table" then
33 cross_domain = t_concat(cross_domain, ", ");
35 if type(cross_domain) ~= "string" then
40 local xmlns_framing = "urn:ietf:params:xml:ns:xmpp-framing";
41 local xmlns_streams = "http://etherx.jabber.org/streams";
42 local xmlns_client = "jabber:client";
43 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
46 local sessions = module:shared("c2s/sessions");
47 local c2s_listener = portmanager.get_service("c2s").listener;
50 local function session_open_stream(session)
52 xmlns = xmlns_framing,
54 id = session.streamid or "",
57 session.send(st.stanza("open", attr));
60 local function session_close(session, reason)
61 local log = session.log or log;
63 if session.notopen then
64 session:open_stream();
66 if reason then -- nil == no err, initiated by us, false == initiated by client
67 local stream_error = st.stanza("stream:error");
68 if type(reason) == "string" then -- assume stream error
69 stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' });
70 elseif type(reason) == "table" then
71 if reason.condition then
72 stream_error:tag(reason.condition, stream_xmlns_attr):up();
74 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
77 stream_error:add_child(reason.extra);
79 elseif reason.name then -- a stanza
80 stream_error = reason;
83 log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stream_error));
84 session.send(stream_error);
87 session.send(st.stanza("close", { xmlns = xmlns_framing }));
88 function session.send() return false; end
90 local reason = (reason and (reason.name or reason.text or reason.condition)) or reason;
91 session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed");
93 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
94 local conn = session.conn;
95 if reason == nil and not session.notopen and session.type == "c2s" then
96 -- Grace time to process data from authenticated cleanly-closed stream
97 add_task(stream_close_timeout, function ()
98 if not session.destroyed then
99 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
100 sm_destroy_session(session, reason);
101 conn:write(build_close(1000, "Stream closed"));
106 sm_destroy_session(session, reason);
107 conn:write(build_close(1000, "Stream closed"));
115 local function filter_open_close(data)
116 if not data:find(xmlns_framing, 1, true) then return data; end
118 local oc = parse_xml(data);
119 if not oc then return data; end
120 if oc.attr.xmlns ~= xmlns_framing then return data; end
121 if oc.name == "close" then return "</stream:stream>"; end
122 if oc.name == "open" then
123 oc.name = "stream:stream";
125 oc.attr["xmlns:stream"] = xmlns_streams;
131 function handle_request(event, path)
132 local request, response = event.request, event.response;
133 local conn = response.conn;
135 if not request.headers.sec_websocket_key then
136 response.headers.content_type = "text/html";
137 return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
138 <p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
142 local wants_xmpp = false;
143 (request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
144 if proto == "xmpp" then wants_xmpp = true; end
147 if not wants_xmpp then
151 local function websocket_close(code, message)
152 conn:write(build_close(code, message));
157 local function handle_frame(frame)
158 local opcode = frame.opcode;
159 local length = frame.length;
160 module:log("debug", "Websocket received frame: opcode=%0x, %i bytes", frame.opcode, #frame.data);
163 if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
164 websocket_close(1002, "Reserved bits not zero");
168 if opcode == 0x8 then -- close frame
170 websocket_close(1002, "Close frame with payload, but too short for status code");
172 elseif length >= 2 then
173 local status_code = parse_close(frame.data)
174 if status_code < 1000 then
175 websocket_close(1002, "Closed with invalid status code");
177 elseif ((status_code > 1003 and status_code < 1007) or status_code > 1011) and status_code < 3000 then
178 websocket_close(1002, "Closed with reserved status code");
184 if opcode >= 0x8 then
185 if length > 125 then -- Control frame with too much payload
186 websocket_close(1002, "Payload too large");
190 if not frame.FIN then -- Fragmented control frame
191 websocket_close(1002, "Fragmented control frame");
196 if (opcode > 0x2 and opcode < 0x8) or (opcode > 0xA) then
197 websocket_close(1002, "Reserved opcode");
201 if opcode == 0x0 and not dataBuffer then
202 websocket_close(1002, "Unexpected continuation frame");
206 if (opcode == 0x1 or opcode == 0x2) and dataBuffer then
207 websocket_close(1002, "Continuation frame expected");
212 if opcode == 0x0 then -- Continuation frame
213 dataBuffer[#dataBuffer+1] = frame.data;
214 elseif opcode == 0x1 then -- Text frame
215 dataBuffer = {frame.data};
216 elseif opcode == 0x2 then -- Binary frame
217 websocket_close(1003, "Only text frames are supported");
219 elseif opcode == 0x8 then -- Close request
220 websocket_close(1000, "Goodbye");
222 elseif opcode == 0x9 then -- Ping frame
224 conn:write(build_frame(frame));
226 elseif opcode == 0xA then -- Pong frame
227 module:log("warn", "Received unexpected pong frame: " .. tostring(frame.data));
230 log("warn", "Received frame with unsupported opcode %i", opcode);
235 local data = t_concat(dataBuffer, "");
242 conn:setlistener(c2s_listener);
243 c2s_listener.onconnect(conn);
245 local session = sessions[conn];
247 session.secure = consider_websocket_secure or session.secure;
249 session.open_stream = session_open_stream;
250 session.close = session_close;
252 local frameBuffer = "";
253 add_filter(session, "bytes/in", function(data)
255 frameBuffer = frameBuffer .. data;
256 local frame, length = parse_frame(frameBuffer);
259 frameBuffer = frameBuffer:sub(length + 1);
260 local result = handle_frame(frame);
261 if not result then return; end
262 cache[#cache+1] = filter_open_close(result);
263 frame, length = parse_frame(frameBuffer);
265 return t_concat(cache, "");
268 add_filter(session, "stanzas/out", function(stanza)
269 local attr = stanza.attr;
270 attr.xmlns = attr.xmlns or xmlns_client;
271 if stanza.name:find("^stream:") then
272 attr["xmlns:stream"] = attr["xmlns:stream"] or xmlns_streams;
277 add_filter(session, "bytes/out", function(data)
278 return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
281 response.status_code = 101;
282 response.headers.upgrade = "websocket";
283 response.headers.connection = "Upgrade";
284 response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
285 response.headers.sec_webSocket_protocol = "xmpp";
286 response.headers.access_control_allow_origin = cross_domain;
291 function module.add_host(module)
292 module:depends("http");
293 module:provides("http", {
295 default_path = "xmpp-websocket";
297 ["GET"] = handle_request;
298 ["GET /"] = handle_request;