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]]
96 room_mt.__index = room_mt;
98 function room_mt:get_default_role(affiliation)
99 if affiliation == "owner" or affiliation == "admin" then
101 elseif affiliation == "member" or not affiliation then
102 return "participant";
106 function room_mt:broadcast_presence(stanza, code, nick)
107 stanza = get_filtered_presence(stanza);
108 local data = self._occupants[stanza.attr.from];
109 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
110 :tag("item", {affiliation=data.affiliation, role=data.role, nick=nick}):up();
112 stanza:tag("status", {code=code}):up();
115 for occupant, o_data in pairs(self._occupants) do
116 if occupant ~= stanza.attr.from then
117 for jid in pairs(o_data.sessions) do
118 stanza.attr.to = jid;
119 self:route_stanza(stanza);
126 stanza:tag("status", {code='110'});
127 for jid in pairs(me.sessions) do
128 stanza.attr.to = jid;
129 self:route_stanza(stanza);
133 function room_mt:broadcast_message(stanza, historic)
134 for occupant, o_data in pairs(self._occupants) do
135 for jid in pairs(o_data.sessions) do
136 stanza.attr.to = jid;
137 self:route_stanza(stanza);
140 if historic then -- add to history
141 local history = self._data['history'];
142 if not history then history = {}; self._data['history'] = history; end
143 -- stanza = st.clone(stanza);
144 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
145 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
146 t_insert(history, st.clone(st.preserialize(stanza)));
147 while #history > history_length do t_remove(history, 1) end
150 function room_mt:broadcast_except_nick(stanza, nick)
151 for rnick, occupant in pairs(self._occupants) do
152 if rnick ~= nick then
153 for jid in pairs(occupant.sessions) do
154 stanza.attr.to = jid;
155 self:route_stanza(stanza);
161 function room_mt:send_occupant_list(to)
162 local current_nick = self._jid_nick[to];
163 for occupant, o_data in pairs(self._occupants) do
164 if occupant ~= current_nick then
165 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
166 pres.attr.to, pres.attr.from = to, occupant;
167 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
168 :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
169 self:route_stanza(pres);
173 function room_mt:send_history(to)
174 local history = self._data['history']; -- send discussion history
176 for _, msg in ipairs(history) do
177 msg = st.deserialize(msg);
179 self:route_stanza(msg);
182 if self._data['subject'] then
183 self:route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
187 local function room_get_disco_info(self, stanza) end
188 local function room_get_disco_items(self, stanza) end
189 function room_mt:set_subject(current_nick, subject)
190 -- TODO check nick's authority
191 if subject == "" then subject = nil; end
192 self._data['subject'] = subject;
193 local msg = st.message({type='groupchat', from=current_nick})
194 :tag('subject'):text(subject):up();
195 self:broadcast_message(msg, false);
199 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
200 local from, to = stanza.attr.from, stanza.attr.to;
201 local room = jid_bare(to);
202 local current_nick = self._jid_nick[from];
203 local type = stanza.attr.type;
204 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
205 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
206 if stanza.name == "presence" then
207 local pr = get_filtered_presence(stanza);
208 pr.attr.from = current_nick;
209 if type == "error" then -- error, kick em out!
211 log("debug", "kicking %s from %s", current_nick, room);
212 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
213 :tag('status'):text('This participant is kicked from the room because he sent an error presence')); -- send unavailable
215 elseif type == "unavailable" then -- unavailable
217 log("debug", "%s leaving %s", current_nick, room);
218 local data = self._occupants[current_nick];
220 self:broadcast_presence(pr);
221 self._occupants[current_nick] = nil;
222 self._jid_nick[from] = nil;
224 elseif not type then -- available
226 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
227 if current_nick == to then -- simple presence
228 log("debug", "%s broadcasted presence", current_nick);
229 self._occupants[current_nick].sessions[from] = pr;
230 self:broadcast_presence(pr);
232 if self._occupants[to] then
233 log("debug", "%s couldn't change nick", current_nick);
234 origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
236 local data = self._occupants[current_nick];
237 local to_nick = select(3, jid_split(to));
239 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
240 local p = st.presence({type='unavailable', from=current_nick});
241 self:broadcast_presence(p, '303', to_nick);
242 self._occupants[current_nick] = nil;
243 self._occupants[to] = data;
244 self._jid_nick[from] = to;
246 self._occupants[to].sessions[from] = pr;
247 self:broadcast_presence(pr);
253 --else -- possible rejoin
254 -- log("debug", "%s had connection replaced", current_nick);
255 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
256 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
257 -- self:handle_to_occupant(origin, stanza); -- resend available
261 if self._occupants[to] then
265 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
266 origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
268 log("debug", "%s joining as %s", from, to);
269 if not next(self._affiliations) then -- new room, no owners
270 self._affiliations[jid_bare(from)] = "owner";
272 local affiliation = self:get_affiliation(from);
273 local role = self:get_default_role(affiliation)
274 if role then -- new occupant
275 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
276 self._jid_nick[from] = to;
277 self:send_occupant_list(from);
279 self:broadcast_presence(pr);
280 self:send_history(from);
282 origin.send(st.error_reply(stanza, "auth", "forbidden"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
286 elseif type ~= 'result' then -- bad type
287 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
289 elseif not current_nick and type ~= "error" and type ~= "result" then -- not in room
290 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
291 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
292 origin.send(st.error_reply(stanza, "modify", "bad-request"));
293 elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
294 log("debug", "%s kicked from %s for sending an error message", current_nick, room);
295 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
296 else -- private stanza
297 local o_data = self._occupants[to];
299 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
300 local jid = o_data.jid;
301 -- TODO if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then jid = jid_bare(jid); end
302 stanza.attr.to, stanza.attr.from = jid, current_nick;
303 self:route_stanza(stanza);
304 elseif type ~= "error" and type ~= "result" then -- recipient not in room
305 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
310 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
311 local type = stanza.attr.type;
312 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
313 if stanza.name == "iq" and type == "get" and xmlns ~= "http://jabber.org/protocol/muc#admin" then -- disco requests
314 if xmlns == "http://jabber.org/protocol/disco#info" then
315 origin.send(room_get_disco_info(self, stanza));
316 elseif xmlns == "http://jabber.org/protocol/disco#items" then
317 origin.send(room_get_disco_items(self, stanza));
319 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
321 elseif stanza.name == "iq" and xmlns == "http://jabber.org/protocol/muc#admin" then
322 local actor = stanza.attr.from;
323 local affiliation = self:get_affiliation(actor);
324 local current_nick = self._jid_nick[actor];
325 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
326 local item = stanza.tags[1].tags[1];
327 if item and item.name == "item" then
328 if type == "set" then
329 local callback = function() origin.send(st.reply(stanza)); end
330 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
331 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
332 if occupant then item.attr.jid = occupant.jid; end
334 if item.attr.affiliation and item.attr.jid and not item.attr.role then
335 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback);
336 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
337 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
338 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback);
339 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
341 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
343 elseif type == "get" then
344 local _aff = item.attr.affiliation;
345 local _rol = item.attr.role;
346 if _aff and not _rol then
347 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
348 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
349 for jid, affiliation in pairs(self._affiliations) do
350 if affiliation == _aff then
351 reply:tag("item", {affiliation = _aff, jid = jid}):up();
356 origin.send(st.error_reply(stanza, "auth", "forbidden"));
358 elseif _rol and not _aff then
359 if role == "moderator" then -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
360 if _rol == "none" then _rol = nil; end
361 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
362 for nick, occupant in pairs(self._occupants) do
363 if occupant.role == _rol then
364 reply:tag("item", {nick = nick, role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid}):up();
369 origin.send(st.error_reply(stanza, "auth", "forbidden"));
372 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
375 elseif type == "set" or type == "get" then
376 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
378 elseif stanza.name == "message" and type == "groupchat" then
379 local from, to = stanza.attr.from, stanza.attr.to;
380 local room = jid_bare(to);
381 local current_nick = self._jid_nick[from];
382 if not current_nick then -- not in room
383 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
385 local from = stanza.attr.from;
386 stanza.attr.from = current_nick;
387 local subject = getText(stanza, {"subject"});
389 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
391 self:broadcast_message(stanza, true);
394 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
395 local to = stanza.attr.to;
396 local current_nick = self._jid_nick[stanza.attr.from];
398 stanza.attr.to = current_nick;
399 self:handle_to_occupant(origin, stanza);
401 elseif type ~= "error" and type ~= "result" then
402 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
404 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
405 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
406 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
407 local _from, _to = stanza.attr.from, stanza.attr.to;
408 local _invitee = stanza.tags[1].tags[1].attr.to;
409 stanza.attr.from, stanza.attr.to = _to, _invitee;
410 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
411 self:route_stanza(stanza);
412 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
413 stanza.attr.from, stanza.attr.to = _from, _to;
415 if type == "error" or type == "result" then return; end
416 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
420 function room_mt:handle_stanza(origin, stanza)
421 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
423 self:handle_to_occupant(origin, stanza);
425 self:handle_to_room(origin, stanza);
429 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
431 function room_mt:get_affiliation(jid)
432 local node, host, resource = jid_split(jid);
433 local bare = node and node.."@"..host or host;
434 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
435 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
438 function room_mt:set_affiliation(actor, jid, affiliation, callback)
440 if affiliation == "none" then affiliation = nil; end
441 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
442 return nil, "modify", "not-acceptable";
444 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
445 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
446 self._affiliations[jid] = affiliation;
447 local role = self:get_default_role(affiliation);
448 local p = st.presence()
449 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
450 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
452 local item = x.tags[1];
453 if not role then -- getting kicked
454 p.attr.type = "unavailable";
455 if affiliation == "outcast" then
456 x:tag("status", {code="301"}):up(); -- banned
458 x:tag("status", {code="321"}):up(); -- affiliation change
461 local modified_nicks = {};
462 for nick, occupant in pairs(self._occupants) do
463 if jid_bare(occupant.jid) == jid then
464 if not role then -- getting kicked
465 self._occupants[nick] = nil;
467 t_insert(modified_nicks, nick);
468 occupant.affiliation, occupant.role = affiliation, role;
471 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
472 if not role then self._jid_nick[jid] = nil; end
474 self:route_stanza(p);
478 if callback then callback(); end
479 for _, nick in ipairs(modified_nicks) do
481 self:broadcast_except_nick(p, nick);
486 function room_mt:get_role(nick)
487 local session = self._occupants[nick];
488 return session and session.role or nil;
490 function room_mt:set_role(actor, nick, role, callback)
491 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
492 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
493 local occupant = self._occupants[nick];
494 if not occupant then return nil, "modify", "not-acceptable"; end
495 if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
496 local p = st.presence({from = nick})
497 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
498 :tag("item", {affiliation=occupant.affiliation or "none", nick=nick, role=role or "none"}):up();
499 if not role then -- kick
500 p.attr.type = "unavailable";
501 self._occupants[nick] = nil;
502 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
503 self._jid_nick[jid] = nil;
505 p:tag("status", {code = "307"}):up();
507 occupant.role = role;
509 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
511 self:route_stanza(p);
513 if callback then callback(); end
514 self:broadcast_except_nick(p, nick);
518 local _M = {}; -- module "muc"
520 function _M.new_room(jid)
521 return setmetatable({
532 --[[function get_disco_info(stanza)
533 return st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
534 :tag("identity", {category='conference', type='text', name=muc_name}):up()
535 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
537 function get_disco_items(stanza)
538 local reply = st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
539 for room in pairs(rooms_info:get()) do
540 reply:tag("item", {jid=room, name=rooms_info:get(room, "name")}):up();
542 return reply; -- TODO cache disco reply
545 --[[function handle_to_domain(origin, stanza)
546 local type = stanza.attr.type;
547 if type == "error" or type == "result" then return; end
548 if stanza.name == "iq" and type == "get" then
549 local xmlns = stanza.tags[1].attr.xmlns;
550 if xmlns == "http://jabber.org/protocol/disco#info" then
551 origin.send(get_disco_info(stanza));
552 elseif xmlns == "http://jabber.org/protocol/disco#items" then
553 origin.send(get_disco_items(stanza));
555 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
558 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
562 register_component(muc_domain, function(origin, stanza)
563 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
564 if to_resource and not to_node then
565 if type == "error" or type == "result" then return; end
566 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- host/resource
567 elseif to_resource then
568 handle_to_occupant(origin, stanza);
570 handle_to_room(origin, stanza)
571 else -- to the main muc domain
572 if type == "error" or type == "result" then return; end
573 handle_to_domain(origin, stanza);
577 --[[module.unload = function()
578 deregister_component(muc_domain);
580 module.save = function()
581 return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
583 module.restore = function(data)
584 rooms.data, jid_nick.data, rooms_info.data, persist_list =
585 data.rooms or {}, data.jid_nick or {}, data.rooms_info or {}, data.persist_list or {};