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.
7 -- luacheck: ignore 431/log
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;
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;
27 local t_concat = table.concat;
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");
33 if cross_domain == true then
35 elseif type(cross_domain) == "table" then
36 cross_domain = t_concat(cross_domain, ", ");
38 if type(cross_domain) ~= "string" then
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'};
49 local sessions = module:shared("c2s/sessions");
50 local c2s_listener = portmanager.get_service("c2s").listener;
53 local function session_open_stream(session)
55 xmlns = xmlns_framing,
57 id = session.streamid or "",
60 session.send(st.stanza("open", attr));
63 local function session_close(session, reason)
64 local log = session.log or log;
66 if session.notopen then
67 session:open_stream();
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();
77 stream_error:tag("text", stream_xmlns_attr):text(reason.text):up();
80 stream_error:add_child(reason.extra);
82 elseif reason.name then -- a stanza
83 stream_error = reason;
86 log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stream_error));
87 session.send(stream_error);
90 session.send(st.stanza("close", { xmlns = xmlns_framing }));
91 function session.send() return false; end
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");
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"));
109 sm_destroy_session(session, reason);
110 conn:write(build_close(1000, "Stream closed"));
118 local function filter_open_close(data)
119 if not data:find(xmlns_framing, 1, true) then return data; end
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";
128 oc.attr["xmlns:stream"] = xmlns_streams;
134 function handle_request(event)
135 local request, response = event.request, event.response;
136 local conn = response.conn;
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>
145 local wants_xmpp = false;
146 (request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
147 if proto == "xmpp" then wants_xmpp = true; end
150 if not wants_xmpp then
154 local function websocket_close(code, message)
155 conn:write(build_close(code, message));
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);
166 if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
167 websocket_close(1002, "Reserved bits not zero");
171 if opcode == 0x8 then -- close frame
173 websocket_close(1002, "Close frame with payload, but too short for status code");
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");
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");
187 if opcode >= 0x8 then
188 if length > 125 then -- Control frame with too much payload
189 websocket_close(1002, "Payload too large");
193 if not frame.FIN then -- Fragmented control frame
194 websocket_close(1002, "Fragmented control frame");
199 if (opcode > 0x2 and opcode < 0x8) or (opcode > 0xA) then
200 websocket_close(1002, "Reserved opcode");
204 if opcode == 0x0 and not dataBuffer then
205 websocket_close(1002, "Unexpected continuation frame");
209 if (opcode == 0x1 or opcode == 0x2) and dataBuffer then
210 websocket_close(1002, "Continuation frame expected");
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");
222 elseif opcode == 0x8 then -- Close request
223 websocket_close(1000, "Goodbye");
225 elseif opcode == 0x9 then -- Ping frame
227 conn:write(build_frame(frame));
229 elseif opcode == 0xA then -- Pong frame
230 module:log("warn", "Received unexpected pong frame: " .. tostring(frame.data));
233 log("warn", "Received frame with unsupported opcode %i", opcode);
238 local data = t_concat(dataBuffer, "");
245 conn:setlistener(c2s_listener);
246 c2s_listener.onconnect(conn);
248 local session = sessions[conn];
250 session.secure = consider_websocket_secure or session.secure;
252 session.open_stream = session_open_stream;
253 session.close = session_close;
255 local frameBuffer = "";
256 add_filter(session, "bytes/in", function(data)
258 frameBuffer = frameBuffer .. data;
259 local frame, length = parse_frame(frameBuffer);
262 frameBuffer = frameBuffer:sub(length + 1);
263 local result = handle_frame(frame);
264 if not result then return; end
265 cache[#cache+1] = filter_open_close(result);
266 frame, length = parse_frame(frameBuffer);
268 return t_concat(cache, "");
271 add_filter(session, "stanzas/out", function(stanza)
272 local attr = stanza.attr;
273 attr.xmlns = attr.xmlns or xmlns_client;
274 if stanza.name:find("^stream:") then
275 attr["xmlns:stream"] = attr["xmlns:stream"] or xmlns_streams;
280 add_filter(session, "bytes/out", function(data)
281 return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
284 response.status_code = 101;
285 response.headers.upgrade = "websocket";
286 response.headers.connection = "Upgrade";
287 response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
288 response.headers.sec_webSocket_protocol = "xmpp";
289 response.headers.access_control_allow_origin = cross_domain;
294 function module.add_host(module)
295 module:depends("http");
296 module:provides("http", {
298 default_path = "xmpp-websocket";
300 ["GET"] = handle_request;
301 ["GET /"] = handle_request;