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;
19 local muc_domain = nil; --module:get_host();
20 local history_length = 20;
23 local function filter_xmlns_from_array(array, filters)
26 local attr = array[i].attr;
27 if filters[attr and attr.xmlns] then
34 local function filter_xmlns_from_stanza(stanza, filters)
36 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
37 return stanza, filter_xmlns_from_array(stanza, filters);
42 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
43 local function get_filtered_presence(stanza)
44 return filter_xmlns_from_stanza(st.clone(stanza), presence_filters);
46 local kickable_error_conditions = {
48 ["internal-server-error"] = true;
49 ["item-not-found"] = true;
50 ["jid-malformed"] = true;
51 ["recipient-unavailable"] = true;
53 ["remote-server-not-found"] = true;
54 ["remote-server-timeout"] = true;
55 ["service-unavailable"] = true;
57 local function get_kickable_error(stanza)
58 for _, tag in ipairs(stanza.tags) do
59 if tag.name == "error" and tag.attr.xmlns == "jabber:client" then
60 for _, cond in ipairs(tag.tags) do
61 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
62 return kickable_error_conditions[cond.name] and cond.name;
65 return true; -- malformed error message
68 return true; -- malformed error message
70 local function getUsingPath(stanza, path, getText)
72 for _, name in ipairs(path) do
73 if type(tag) ~= 'table' then return; end
74 tag = tag:child_with_name(name);
76 if tag and getText then tag = table.concat(tag); end
79 local function getTag(stanza, path) return getUsingPath(stanza, path); end
80 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
83 --[[function get_room_disco_info(room, stanza)
84 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
85 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
86 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
88 function get_room_disco_items(room, stanza)
89 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
90 end -- TODO allow non-private rooms]]
94 local function room_broadcast_presence(room, stanza, code, nick)
95 stanza = get_filtered_presence(stanza);
96 local data = room._participants[stanza.attr.from];
97 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
98 :tag("item", {affiliation=data.affiliation, role=data.role, nick=nick}):up();
100 stanza:tag("status", {code=code}):up();
103 for occupant, o_data in pairs(room._participants) do
104 if occupant ~= stanza.attr.from then
105 for jid in pairs(o_data.sessions) do
106 stanza.attr.to = jid;
107 room:route_stanza(stanza);
114 stanza:tag("status", {code='110'});
115 for jid in pairs(me.sessions) do
116 stanza.attr.to = jid;
117 room:route_stanza(stanza);
121 local function room_broadcast_message(room, stanza, historic)
122 for occupant, o_data in pairs(room._participants) do
123 for jid in pairs(o_data.sessions) do
124 stanza.attr.to = jid;
125 room:route_stanza(stanza);
128 if historic then -- add to history
129 local history = room._data['history'];
130 if not history then history = {}; room._data['history'] = history; end
131 -- stanza = st.clone(stanza);
132 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
133 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
134 t_insert(history, st.clone(st.preserialize(stanza)));
135 while #history > history_length do t_remove(history, 1) end
140 local function room_send_occupant_list(room, to)
141 local current_nick = room._jid_nick[to];
142 for occupant, o_data in pairs(room._participants) do
143 if occupant ~= current_nick then
144 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
145 pres.attr.to, pres.attr.from = to, occupant;
146 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
147 :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
148 room:route_stanza(pres);
152 local function room_send_history(room, to)
153 local history = room._data['history']; -- send discussion history
155 for _, msg in ipairs(history) do
156 msg = st.deserialize(msg);
158 room:route_stanza(msg);
161 if room._data['subject'] then
162 room:route_stanza(st.message({type='groupchat', from=room, to=to}):tag("subject"):text(room._data['subject']));
166 local function room_get_disco_info(self, stanza) end
167 local function room_get_disco_items(self, stanza) end
168 local function room_set_subject(room, current_nick, room, subject)
169 -- TODO check nick's authority
170 if subject == "" then subject = nil; end
171 room._data['subject'] = subject;
172 local msg = st.message({type='groupchat', from=current_nick})
173 :tag('subject'):text(subject):up();
174 room_broadcast_message(room, msg, false);
178 local function room_handle_to_occupant(self, origin, stanza) -- PM, vCards, etc
179 local from, to = stanza.attr.from, stanza.attr.to;
180 local room = jid_bare(to);
181 local current_nick = self._jid_nick[from];
182 local type = stanza.attr.type;
183 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
184 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
185 if stanza.name == "presence" then
186 local pr = get_filtered_presence(stanza);
187 pr.attr.from = current_nick;
188 if type == "error" then -- error, kick em out!
190 log("debug", "kicking %s from %s", current_nick, room);
191 room_handle_to_occupant(self, origin, st.presence({type='unavailable', from=from, to=to}):tag('status'):text('This participant is kicked from the room because he sent an error presence')); -- send unavailable
193 elseif type == "unavailable" then -- unavailable
195 log("debug", "%s leaving %s", current_nick, room);
196 local data = self._participants[current_nick];
198 room_broadcast_presence(self, pr);
199 self._participants[current_nick] = nil;
200 self._jid_nick[from] = nil;
202 elseif not type then -- available
204 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
205 if current_nick == to then -- simple presence
206 log("debug", "%s broadcasted presence", current_nick);
207 self._participants[current_nick].sessions[from] = pr;
208 room_broadcast_presence(self, pr);
210 if self._participants[to] then
211 log("debug", "%s couldn't change nick", current_nick);
212 origin.send(st.error_reply(stanza, "cancel", "conflict"));
214 local data = self._participants[current_nick];
215 local to_nick = select(3, jid_split(to));
217 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
218 local p = st.presence({type='unavailable', from=current_nick});
219 room_broadcast_presence(self, p, '303', to_nick);
220 self._participants[current_nick] = nil;
221 self._participants[to] = data;
222 self._jid_nick[from] = to;
224 self._participants[to].sessions[from] = pr;
225 room_broadcast_presence(self, pr);
231 --else -- possible rejoin
232 -- log("debug", "%s had connection replaced", current_nick);
233 -- handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to}):tag('status'):text('Replaced by new connection'):up()); -- send unavailable
234 -- handle_to_occupant(origin, stanza); -- resend available
238 if self._participants[to] then
242 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
243 origin.send(st.error_reply(stanza, "cancel", "conflict"));
245 log("debug", "%s joining as %s", from, to);
247 -- if not rooms:get(room) and not rooms_info:get(room) then -- new room
248 -- rooms_info:set(room, 'name', (jid_split(room)));
249 -- data = {affiliation='owner', role='moderator', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
251 if not data then -- new occupant
252 data = {affiliation='none', role='participant', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
254 self._participants[to] = data;
255 self._jid_nick[from] = to;
256 room_send_occupant_list(self, from);
258 room_broadcast_presence(self, pr);
259 room_send_history(self, from);
262 elseif type ~= 'result' then -- bad type
263 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
265 elseif not current_nick and type ~= "error" and type ~= "result" then -- not in room
266 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
267 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
268 origin.send(st.error_reply(stanza, "modify", "bad-request"));
269 elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
270 log("debug", "%s kicked from %s for sending an error message", current_nick, room);
271 room_handle_to_occupant(self, 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
272 else -- private stanza
273 local o_data = self._participants[to];
275 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
276 local jid = o_data.jid;
277 -- TODO if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then jid = jid_bare(jid); end
278 stanza.attr.to, stanza.attr.from = jid, current_nick;
279 self:route_stanza(stanza);
280 elseif type ~= "error" and type ~= "result" then -- recipient not in room
281 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
286 local function room_handle_to_room(self, origin, stanza) -- presence changes and groupchat messages, along with disco/etc
287 local type = stanza.attr.type;
288 if stanza.name == "iq" and type == "get" then -- disco requests
289 local xmlns = stanza.tags[1].attr.xmlns;
290 if xmlns == "http://jabber.org/protocol/disco#info" then
291 origin.send(room_get_disco_info(self, stanza));
292 elseif xmlns == "http://jabber.org/protocol/disco#items" then
293 origin.send(room_get_disco_items(self, stanza));
295 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
297 elseif stanza.name == "message" and type == "groupchat" then
298 local from, to = stanza.attr.from, stanza.attr.to;
299 local room = jid_bare(to);
300 local current_nick = self._jid_nick[from];
301 if not current_nick then -- not in room
302 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
304 local from = stanza.attr.from;
305 stanza.attr.from = current_nick;
306 local subject = getText(stanza, {"subject"});
308 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
310 room_broadcast_message(self, stanza, true);
313 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
314 local to = stanza.attr.to;
315 local current_nick = self._jid_nick[stanza.attr.from];
317 stanza.attr.to = current_nick;
318 room_handle_to_occupant(origin, stanza);
320 elseif type ~= "error" and type ~= "result" then
321 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
323 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
324 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
325 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
326 local _from, _to = stanza.attr.from, stanza.attr.to;
327 local _invitee = stanza.tags[1].tags[1].attr.to;
328 stanza.attr.from, stanza.attr.to = _to, _invitee;
329 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
330 self:route_stanza(stanza);
331 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
332 stanza.attr.from, stanza.attr.to = _from, _to;
334 if type == "error" or type == "result" then return; end
335 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
339 local function room_handle_stanza(self, origin, stanza)
340 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
342 room_handle_to_occupant(self, origin, stanza);
344 room_handle_to_room(self, origin, stanza);
350 function new_room(jid)
353 handle_stanza = room_handle_stanza;
354 set_subject = room_set_subject;
355 route_stanza = function(room, stanza) end; -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
364 --[[function get_disco_info(stanza)
365 return st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
366 :tag("identity", {category='conference', type='text', name=muc_name}):up()
367 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
369 function get_disco_items(stanza)
370 local reply = st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
371 for room in pairs(rooms_info:get()) do
372 reply:tag("item", {jid=room, name=rooms_info:get(room, "name")}):up();
374 return reply; -- TODO cache disco reply
377 --[[function handle_to_domain(origin, stanza)
378 local type = stanza.attr.type;
379 if type == "error" or type == "result" then return; end
380 if stanza.name == "iq" and type == "get" then
381 local xmlns = stanza.tags[1].attr.xmlns;
382 if xmlns == "http://jabber.org/protocol/disco#info" then
383 origin.send(get_disco_info(stanza));
384 elseif xmlns == "http://jabber.org/protocol/disco#items" then
385 origin.send(get_disco_items(stanza));
387 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
390 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
394 register_component(muc_domain, function(origin, stanza)
395 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
396 if to_resource and not to_node then
397 if type == "error" or type == "result" then return; end
398 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- host/resource
399 elseif to_resource then
400 handle_to_occupant(origin, stanza);
402 handle_to_room(origin, stanza)
403 else -- to the main muc domain
404 if type == "error" or type == "result" then return; end
405 handle_to_domain(origin, stanza);
409 --[[module.unload = function()
410 deregister_component(muc_domain);
412 module.save = function()
413 return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
415 module.restore = function(data)
416 rooms.data, jid_nick.data, rooms_info.data, persist_list =
417 data.rooms or {}, data.jid_nick or {}, data.rooms_info or {}, data.persist_list or {};