mod_muc: The default room name is the room node
[prosody.git] / plugins / mod_muc.lua
1 -- Prosody IM v0.4
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local register_component = require "core.componentmanager".register_component;
11 local deregister_component = require "core.componentmanager".deregister_component;
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
19 if module:get_host_type() ~= "component" then
20         error("MUC should be loaded as a component, please see http://prosody.im/doc/components", 0);
21 end
22
23 local muc_domain = module:get_host();
24 local muc_name = "MUCMUCMUC!!!";
25 local history_length = 20;
26
27 -- room_name -> room
28         -- occupant_room_nick -> data
29                 -- affiliation = ...
30                 -- role
31                 -- jid = occupant's real jid
32 local rooms = multitable_new();
33
34 local jid_nick = multitable_new(); -- real jid -> room's jid -> room nick
35
36 -- room_name -> info
37         -- name - the room's friendly name
38         -- subject - the room's subject
39         -- non-anonymous = true|nil
40         -- persistent = true|nil
41         -- history = {preserialized stanzas}
42 local rooms_info = multitable_new();
43
44 local persist_list = datamanager.load(nil, muc_domain, 'room_list') or {};
45 for room in pairs(persist_list) do
46         rooms_info:set(room, datamanager.store(room, muc_domain, 'rooms') or nil);
47 end
48
49 local component;
50
51 function filter_xmlns_from_array(array, filters)
52         local count = 0;
53         for i=#array,1,-1 do
54                 local attr = array[i].attr;
55                 if filters[attr and attr.xmlns] then
56                         t_remove(array, i);
57                         count = count + 1;
58                 end
59         end
60         return count;
61 end
62 function filter_xmlns_from_stanza(stanza, filters)
63         if filters then
64                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
65                         return stanza, filter_xmlns_from_array(stanza, filters);
66                 end
67         end
68         return stanza, 0;
69 end
70 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
71 function get_filtered_presence(stanza)
72         return filter_xmlns_from_stanza(st.clone(stanza), presence_filters);
73 end
74 local kickable_error_conditions = {
75         ["gone"] = true;
76         ["internal-server-error"] = true;
77         ["item-not-found"] = true;
78         ["jid-malformed"] = true;
79         ["recipient-unavailable"] = true;
80         ["redirect"] = true;
81         ["remote-server-not-found"] = true;
82         ["remote-server-timeout"] = true;
83         ["service-unavailable"] = true;
84 };
85 function get_kickable_error(stanza)
86         for _, tag in ipairs(stanza.tags) do
87                 if tag.name == "error" and tag.attr.xmlns == "jabber:client" then
88                         for _, cond in ipairs(tag.tags) do
89                                 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
90                                         return kickable_error_conditions[cond.name] and cond.name;
91                                 end
92                         end
93                         return true; -- malformed error message
94                 end
95         end
96         return true; -- malformed error message
97 end
98 function getUsingPath(stanza, path, getText)
99         local tag = stanza;
100         for _, name in ipairs(path) do
101                 if type(tag) ~= 'table' then return; end
102                 tag = tag:child_with_name(name);
103         end
104         if tag and getText then tag = table.concat(tag); end
105         return tag;
106 end
107 function getTag(stanza, path) return getUsingPath(stanza, path); end
108 function getText(stanza, path) return getUsingPath(stanza, path, true); end
109
110 function get_disco_info(stanza)
111         return st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
112                 :tag("identity", {category='conference', type='text', name=muc_name}):up()
113                 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
114 end
115 function get_disco_items(stanza)
116         local reply = st.iq({type='result', id=stanza.attr.id, from=muc_domain, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
117         for room in pairs(rooms_info:get()) do
118                 reply:tag("item", {jid=room, name=rooms_info:get(room, "name")}):up();
119         end
120         return reply; -- TODO cache disco reply
121 end
122 function get_room_disco_info(stanza)
123         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
124                 :tag("identity", {category='conference', type='text', name=rooms_info:get(stanza.attr.to, "name")}):up()
125                 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
126 end
127 function get_room_disco_items(stanza)
128         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
129 end -- TODO allow non-private rooms
130
131 function save_room(room)
132         local persistent = rooms_info:get(room, 'persistent');
133         if persistent then
134                 datamanager.store(room, muc_domain, 'rooms', rooms_info:get(room));
135         end
136         if persistent ~= persist_list[room] then
137                 if not persistent then
138                         datamanager.store(room, muc_domain, 'rooms', nil);
139                 end
140                 persist_list[room] = persistent;
141                 datamanager.store(nil, muc_domain, 'room_list', persist_list);
142         end
143 end
144
145 function set_subject(current_nick, room, subject)
146         -- TODO check nick's authority
147         if subject == "" then subject = nil; end
148         rooms_info:set(room, 'subject', subject);
149         save_room();
150         local msg = st.message({type='groupchat', from=current_nick})
151                 :tag('subject'):text(subject):up();
152         broadcast_message_stanza(room, msg, false);
153         return true;
154 end
155
156 function broadcast_message_stanza(room, stanza, historic)
157         local r = rooms:get(room);
158         if r then
159                 for occupant, o_data in pairs(r) do
160                         for jid in pairs(o_data.sessions) do
161                                 stanza.attr.to = jid;
162                                 core_route_stanza(component, stanza);
163                         end
164                 end
165                 if historic then -- add to history
166                         local history = rooms_info:get(room, 'history');
167                         if not history then history = {}; rooms_info:set(room, 'history', history); end
168                         -- stanza = st.clone(stanza);
169                         stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
170                         stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
171                         t_insert(history, st.clone(st.preserialize(stanza)));
172                         while #history > history_length do t_remove(history, 1) end
173                 end
174         end
175 end
176 function broadcast_presence_stanza(room, stanza, code, nick)
177         stanza = get_filtered_presence(stanza);
178         local data = rooms:get(room, stanza.attr.from);
179         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
180                 :tag("item", {affiliation=data.affiliation, role=data.role, nick=nick}):up();
181         if code then
182                 stanza:tag("status", {code=code}):up();
183         end
184         local me;
185         local r = rooms:get(room);
186         if r then
187                 for occupant, o_data in pairs(r) do
188                         if occupant ~= stanza.attr.from then
189                                 for jid in pairs(o_data.sessions) do
190                                         stanza.attr.to = jid;
191                                         core_route_stanza(component, stanza);
192                                 end
193                         else
194                                 me = o_data;
195                         end
196                 end
197         end
198         if me then
199                 stanza:tag("status", {code='110'});
200                 for jid in pairs(me.sessions) do
201                         stanza.attr.to = jid;
202                         core_route_stanza(component, stanza);
203                 end
204         end
205 end
206
207 function handle_to_occupant(origin, stanza) -- PM, vCards, etc
208         local from, to = stanza.attr.from, stanza.attr.to;
209         local room = jid_bare(to);
210         local current_nick = jid_nick:get(from, room);
211         local type = stanza.attr.type;
212         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
213         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
214         if stanza.name == "presence" then
215                 local pr = get_filtered_presence(stanza);
216                 pr.attr.from = current_nick;
217                 if type == "error" then -- error, kick em out!
218                         if current_nick then
219                                 log("debug", "kicking %s from %s", current_nick, room);
220                                 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 presence')); -- send unavailable
221                         end
222                 elseif type == "unavailable" then -- unavailable
223                         if current_nick then
224                                 log("debug", "%s leaving %s", current_nick, room);
225                                 local data = rooms:get(room, current_nick);
226                                 data.role = 'none';
227                                 broadcast_presence_stanza(room, pr);
228                                 rooms:remove(room, current_nick);
229                                 jid_nick:remove(from, room);
230                         end
231                 elseif not type then -- available
232                         if current_nick then
233                                 if #pr == #stanza or current_nick ~= to then
234                                         if current_nick == to then -- simple presence
235                                                 log("debug", "%s broadcasted presence", current_nick);
236                                                 rooms:get(room, current_nick).sessions[from] = pr;
237                                                 broadcast_presence_stanza(room, pr);
238                                         else -- change nick
239                                                 if rooms:get(room, to) then
240                                                         log("debug", "%s couldn't change nick", current_nick);
241                                                         origin.send(st.error_reply(stanza, "cancel", "conflict"));
242                                                 else
243                                                         local data = rooms:get(room, current_nick);
244                                                         local to_nick = select(3, jid_split(to));
245                                                         if to_nick then
246                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
247                                                                 local p = st.presence({type='unavailable', from=current_nick});
248                                                                 broadcast_presence_stanza(room, p, '303', to_nick);
249                                                                 rooms:remove(room, current_nick);
250                                                                 rooms:set(room, to, data);
251                                                                 jid_nick:set(from, room, to);
252                                                                 pr.attr.from = to;
253                                                                 rooms:get(room, to).sessions[from] = pr;
254                                                                 broadcast_presence_stanza(room, pr);
255                                                         else
256                                                                 --TODO malformed-jid
257                                                         end
258                                                 end
259                                         end
260                                 else -- possible rejoin
261                                         log("debug", "%s had connection replaced", current_nick);
262                                         handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to}):tag('status'):text('Replaced by new connection'):up()); -- send unavailable
263                                         handle_to_occupant(origin, stanza); -- resend available
264                                 end
265                         else -- enter room
266                                 local new_nick = to;
267                                 if rooms:get(room, to) then
268                                         new_nick = nil;
269                                 end
270                                 if not new_nick then
271                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
272                                         origin.send(st.error_reply(stanza, "cancel", "conflict"));
273                                 else
274                                         log("debug", "%s joining as %s", from, to);
275                                         local data;
276                                         if not rooms:get(room) and not rooms_info:get(room) then -- new room
277                                                 rooms_info:set(room, 'name', (jid_split(room)));
278                                                 data = {affiliation='owner', role='moderator', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
279                                         end
280                                         if not data then -- new occupant
281                                                 data = {affiliation='none', role='participant', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
282                                         end
283                                         rooms:set(room, to, data);
284                                         jid_nick:set(from, room, to);
285                                         local r = rooms:get(room);
286                                         if r then
287                                                 for occupant, o_data in pairs(r) do
288                                                         if occupant ~= to then
289                                                                 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
290                                                                 pres.attr.to, pres.attr.from = from, occupant;
291                                                                 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
292                                                                         :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
293                                                                 core_route_stanza(component, pres);
294                                                         end
295                                                 end
296                                         end
297                                         pr.attr.from = to;
298                                         broadcast_presence_stanza(room, pr);
299                                         local history = rooms_info:get(room, 'history'); -- send discussion history
300                                         if history then
301                                                 for _, msg in ipairs(history) do
302                                                         msg = st.deserialize(msg);
303                                                         msg.attr.to=from;
304                                                         core_route_stanza(component, msg);
305                                                 end
306                                         end
307                                         if rooms_info:get(room, 'subject') then
308                                                 core_route_stanza(component, st.message({type='groupchat', from=room, to=from}):tag("subject"):text(rooms_info:get(room, 'subject')));
309                                         end
310                                 end
311                         end
312                 elseif type ~= 'result' then -- bad type
313                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
314                 end
315         elseif not current_nick and type ~= "error" then -- not in room
316                 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
317         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
318                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
319         elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
320                 log("debug", "%s kicked from %s for sending an error message", current_nick, room);
321                 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
322         else -- private stanza
323                 local o_data = rooms:get(room, to);
324                 if o_data then
325                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
326                         local jid = o_data.jid;
327                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then jid = jid_bare(jid); end
328                         stanza.attr.to, stanza.attr.from = jid, current_nick;
329                         core_route_stanza(component, stanza);
330                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
331                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
332                 end
333         end
334 end
335
336 function handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
337         local type = stanza.attr.type;
338         if stanza.name == "iq" and type == "get" then -- disco requests
339                 local xmlns = stanza.tags[1].attr.xmlns;
340                 if xmlns == "http://jabber.org/protocol/disco#info" then
341                         origin.send(get_room_disco_info(stanza));
342                 elseif xmlns == "http://jabber.org/protocol/disco#items" then
343                         origin.send(get_room_disco_items(stanza));
344                 else
345                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
346                 end
347         elseif stanza.name == "message" and type == "groupchat" then
348                 local from, to = stanza.attr.from, stanza.attr.to;
349                 local room = jid_bare(to);
350                 local current_nick = jid_nick:get(from, room);
351                 if not current_nick then -- not in room
352                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
353                 else
354                         local from = stanza.attr.from;
355                         stanza.attr.from = current_nick;
356                         local subject = getText(stanza, {"subject"});
357                         if subject then
358                                 set_subject(current_nick, room, subject); -- TODO use broadcast_message_stanza
359                         else
360                                 broadcast_message_stanza(room, stanza, true);
361                         end
362                 end
363         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
364                 local to = stanza.attr.to;
365                 local current_nick = jid_nick:get(stanza.attr.from, to);
366                 if current_nick then
367                         stanza.attr.to = current_nick;
368                         handle_to_occupant(origin, stanza);
369                         stanza.attr.to = to;
370                 elseif type ~= "error" and type ~= "result" then
371                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
372                 end
373         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and jid_nick:get(stanza.attr.from, stanza.attr.to)
374                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
375                 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
376                 local _from, _to = stanza.attr.from, stanza.attr.to;
377                 local _invitee = stanza.tags[1].tags[1].attr.to;
378                 stanza.attr.from, stanza.attr.to = _to, _invitee;
379                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
380                 core_route_stanza(component, stanza);
381                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
382                 stanza.attr.from, stanza.attr.to = _from, _to;
383         else
384                 if type == "error" or type == "result" then return; end
385                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
386         end
387 end
388
389 function handle_to_domain(origin, stanza)
390         local type = stanza.attr.type;
391         if type == "error" or type == "result" then return; end
392         if stanza.name == "iq" and type == "get" then
393                 local xmlns = stanza.tags[1].attr.xmlns;
394                 if xmlns == "http://jabber.org/protocol/disco#info" then
395                         origin.send(get_disco_info(stanza));
396                 elseif xmlns == "http://jabber.org/protocol/disco#items" then
397                         origin.send(get_disco_items(stanza));
398                 else
399                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
400                 end
401         else
402                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
403         end
404 end
405
406 register_component(muc_domain, function(origin, stanza)
407         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
408         if to_resource and not to_node then
409                 if type == "error" or type == "result" then return; end
410                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- host/resource
411         elseif to_resource then
412                 handle_to_occupant(origin, stanza);
413         elseif to_node then
414                 handle_to_room(origin, stanza)
415         else -- to the main muc domain
416                 if type == "error" or type == "result" then return; end
417                 handle_to_domain(origin, stanza);
418         end
419 end);
420
421 module.unload = function()
422         deregister_component(muc_domain);
423 end
424 module.save = function()
425         return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
426 end
427 module.restore = function(data)
428         rooms.data, jid_nick.data, rooms_info.data, persist_list =
429         data.rooms or {}, data.jid_nick or {}, data.rooms_info or {}, data.persist_list or {};
430 end