2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local st = require "util.stanza";
15 local log = require "util.logger".init("mod_muc");
16 local multitable_new = require "util.multitable".new;
17 local t_insert, t_remove = table.insert, table.remove;
18 local setmetatable = setmetatable;
20 local muc_domain = nil; --module:get_host();
21 local history_length = 20;
24 local function filter_xmlns_from_array(array, filters)
27 local attr = array[i].attr;
28 if filters[attr and attr.xmlns] then
35 local function filter_xmlns_from_stanza(stanza, filters)
37 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
38 return stanza, filter_xmlns_from_array(stanza, filters);
43 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
44 local function get_filtered_presence(stanza)
45 return filter_xmlns_from_stanza(st.clone(stanza), presence_filters);
47 local kickable_error_conditions = {
49 ["internal-server-error"] = true;
50 ["item-not-found"] = true;
51 ["jid-malformed"] = true;
52 ["recipient-unavailable"] = true;
54 ["remote-server-not-found"] = true;
55 ["remote-server-timeout"] = true;
56 ["service-unavailable"] = true;
58 local function get_kickable_error(stanza)
59 for _, tag in ipairs(stanza.tags) do
60 if tag.name == "error" and tag.attr.xmlns == "jabber:client" then
61 for _, cond in ipairs(tag.tags) do
62 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
63 return kickable_error_conditions[cond.name] and cond.name;
66 return true; -- malformed error message
69 return true; -- malformed error message
71 local function getUsingPath(stanza, path, getText)
73 for _, name in ipairs(path) do
74 if type(tag) ~= 'table' then return; end
75 tag = tag:child_with_name(name);
77 if tag and getText then tag = table.concat(tag); end
80 local function getTag(stanza, path) return getUsingPath(stanza, path); end
81 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
84 --[[function get_room_disco_info(room, stanza)
85 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
86 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
87 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
89 function get_room_disco_items(room, stanza)
90 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
91 end -- TODO allow non-private rooms]]
97 function room_mt:broadcast_presence(stanza, code, nick)
98 stanza = get_filtered_presence(stanza);
99 local data = self._participants[stanza.attr.from];
100 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
101 :tag("item", {affiliation=data.affiliation, role=data.role, nick=nick}):up();
103 stanza:tag("status", {code=code}):up();
106 for occupant, o_data in pairs(self._participants) do
107 if occupant ~= stanza.attr.from then
108 for jid in pairs(o_data.sessions) do
109 stanza.attr.to = jid;
110 self:route_stanza(stanza);
117 stanza:tag("status", {code='110'});
118 for jid in pairs(me.sessions) do
119 stanza.attr.to = jid;
120 self:route_stanza(stanza);
124 function room_mt:broadcast_message(stanza, historic)
125 for occupant, o_data in pairs(self._participants) do
126 for jid in pairs(o_data.sessions) do
127 stanza.attr.to = jid;
128 self:route_stanza(stanza);
131 if historic then -- add to history
132 local history = self._data['history'];
133 if not history then history = {}; self._data['history'] = history; end
134 -- stanza = st.clone(stanza);
135 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
136 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
137 t_insert(history, st.clone(st.preserialize(stanza)));
138 while #history > history_length do t_remove(history, 1) end
143 function room_mt:send_occupant_list(to)
144 local current_nick = self._jid_nick[to];
145 for occupant, o_data in pairs(self._participants) do
146 if occupant ~= current_nick then
147 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
148 pres.attr.to, pres.attr.from = to, occupant;
149 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
150 :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
151 self:route_stanza(pres);
155 function room_mt:send_history(to)
156 local history = self._data['history']; -- send discussion history
158 for _, msg in ipairs(history) do
159 msg = st.deserialize(msg);
161 self:route_stanza(msg);
164 if self._data['subject'] then
165 self:route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
169 local function room_get_disco_info(self, stanza) end
170 local function room_get_disco_items(self, stanza) end
171 function room_mt:set_subject(current_nick, subject)
172 -- TODO check nick's authority
173 if subject == "" then subject = nil; end
174 self._data['subject'] = subject;
175 local msg = st.message({type='groupchat', from=current_nick})
176 :tag('subject'):text(subject):up();
177 self:broadcast_message(msg, false);
181 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
182 local from, to = stanza.attr.from, stanza.attr.to;
183 local room = jid_bare(to);
184 local current_nick = self._jid_nick[from];
185 local type = stanza.attr.type;
186 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
187 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
188 if stanza.name == "presence" then
189 local pr = get_filtered_presence(stanza);
190 pr.attr.from = current_nick;
191 if type == "error" then -- error, kick em out!
193 log("debug", "kicking %s from %s", current_nick, room);
194 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
195 :tag('status'):text('This participant is kicked from the room because he sent an error presence')); -- send unavailable
197 elseif type == "unavailable" then -- unavailable
199 log("debug", "%s leaving %s", current_nick, room);
200 local data = self._participants[current_nick];
202 self:broadcast_presence(pr);
203 self._participants[current_nick] = nil;
204 self._jid_nick[from] = nil;
206 elseif not type then -- available
208 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
209 if current_nick == to then -- simple presence
210 log("debug", "%s broadcasted presence", current_nick);
211 self._participants[current_nick].sessions[from] = pr;
212 self:broadcast_presence(pr);
214 if self._participants[to] then
215 log("debug", "%s couldn't change nick", current_nick);
216 origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
218 local data = self._participants[current_nick];
219 local to_nick = select(3, jid_split(to));
221 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
222 local p = st.presence({type='unavailable', from=current_nick});
223 self:broadcast_presence(p, '303', to_nick);
224 self._participants[current_nick] = nil;
225 self._participants[to] = data;
226 self._jid_nick[from] = to;
228 self._participants[to].sessions[from] = pr;
229 self:broadcast_presence(pr);
235 --else -- possible rejoin
236 -- log("debug", "%s had connection replaced", current_nick);
237 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
238 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
239 -- self:handle_to_occupant(origin, stanza); -- resend available
243 if self._participants[to] then
247 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
248 origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
250 log("debug", "%s joining as %s", from, to);
252 -- if not rooms:get(room) and not rooms_info:get(room) then -- new room
253 -- rooms_info:set(room, 'name', (jid_split(room)));
254 -- data = {affiliation='owner', role='moderator', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
256 if not data then -- new occupant
257 data = {affiliation='none', role='participant', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
259 self._participants[to] = data;
260 self._jid_nick[from] = to;
261 self:send_occupant_list(from);
263 self:broadcast_presence(pr);
264 self:send_history(from);
267 elseif type ~= 'result' then -- bad type
268 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
270 elseif not current_nick and type ~= "error" and type ~= "result" then -- not in room
271 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
272 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
273 origin.send(st.error_reply(stanza, "modify", "bad-request"));
274 elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
275 log("debug", "%s kicked from %s for sending an error message", current_nick, room);
276 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to}):tag('status'):text('This participant is kicked from the room because he sent an error message to another occupant')); -- send unavailable
277 else -- private stanza
278 local o_data = self._participants[to];
280 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
281 local jid = o_data.jid;
282 -- TODO if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then jid = jid_bare(jid); end
283 stanza.attr.to, stanza.attr.from = jid, current_nick;
284 self:route_stanza(stanza);
285 elseif type ~= "error" and type ~= "result" then -- recipient not in room
286 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
291 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
292 local type = stanza.attr.type;
293 if stanza.name == "iq" and type == "get" then -- disco requests
294 local xmlns = stanza.tags[1].attr.xmlns;
295 if xmlns == "http://jabber.org/protocol/disco#info" then
296 origin.send(room_get_disco_info(self, stanza));
297 elseif xmlns == "http://jabber.org/protocol/disco#items" then
298 origin.send(room_get_disco_items(self, stanza));
300 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
302 elseif stanza.name == "message" and type == "groupchat" then
303 local from, to = stanza.attr.from, stanza.attr.to;
304 local room = jid_bare(to);
305 local current_nick = self._jid_nick[from];
306 if not current_nick then -- not in room
307 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
309 local from = stanza.attr.from;
310 stanza.attr.from = current_nick;
311 local subject = getText(stanza, {"subject"});
313 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
315 self:broadcast_message(stanza, true);
318 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
319 local to = stanza.attr.to;
320 local current_nick = self._jid_nick[stanza.attr.from];
322 stanza.attr.to = current_nick;
323 self:handle_to_occupant(origin, stanza);
325 elseif type ~= "error" and type ~= "result" then
326 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
328 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
329 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
330 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
331 local _from, _to = stanza.attr.from, stanza.attr.to;
332 local _invitee = stanza.tags[1].tags[1].attr.to;
333 stanza.attr.from, stanza.attr.to = _to, _invitee;
334 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
335 self:route_stanza(stanza);
336 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
337 stanza.attr.from, stanza.attr.to = _from, _to;
339 if type == "error" or type == "result" then return; end
340 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
344 function room_mt:handle_stanza(origin, stanza)
345 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
347 self:handle_to_occupant(origin, stanza);
349 self:handle_to_room(origin, stanza);
353 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
357 function new_room(jid)
358 return setmetatable({
368 --[[function get_disco_info(stanza)
369 return st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
370 :tag("identity", {category='conference', type='text', name=muc_name}):up()
371 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
373 function get_disco_items(stanza)
374 local reply = st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
375 for room in pairs(rooms_info:get()) do
376 reply:tag("item", {jid=room, name=rooms_info:get(room, "name")}):up();
378 return reply; -- TODO cache disco reply
381 --[[function handle_to_domain(origin, stanza)
382 local type = stanza.attr.type;
383 if type == "error" or type == "result" then return; end
384 if stanza.name == "iq" and type == "get" then
385 local xmlns = stanza.tags[1].attr.xmlns;
386 if xmlns == "http://jabber.org/protocol/disco#info" then
387 origin.send(get_disco_info(stanza));
388 elseif xmlns == "http://jabber.org/protocol/disco#items" then
389 origin.send(get_disco_items(stanza));
391 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
394 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
398 register_component(muc_domain, function(origin, stanza)
399 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
400 if to_resource and not to_node then
401 if type == "error" or type == "result" then return; end
402 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- host/resource
403 elseif to_resource then
404 handle_to_occupant(origin, stanza);
406 handle_to_room(origin, stanza)
407 else -- to the main muc domain
408 if type == "error" or type == "result" then return; end
409 handle_to_domain(origin, stanza);
413 --[[module.unload = function()
414 deregister_component(muc_domain);
416 module.save = function()
417 return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
419 module.restore = function(data)
420 rooms.data, jid_nick.data, rooms_info.data, persist_list =
421 data.rooms or {}, data.jid_nick or {}, data.rooms_info or {}, data.persist_list or {};