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