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 function send_history(room, to)
209         local history = rooms_info:get(room, 'history'); -- send discussion history
210         if history then
211                 for _, msg in ipairs(history) do
212                         msg = st.deserialize(msg);
213                         msg.attr.to=to;
214                         core_route_stanza(component, msg);
215                 end
216         end
217         if rooms_info:get(room, 'subject') then
218                 core_route_stanza(component, st.message({type='groupchat', from=room, to=to}):tag("subject"):text(rooms_info:get(room, 'subject')));
219         end
220 end
221 function send_occupant_list(room, to)
222         local r = rooms:get(room);
223         if r then
224                 local current_nick = jid_nick:get(to, room);
225                 for occupant, o_data in pairs(r) do
226                         if occupant ~= current_nick then
227                                 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
228                                 pres.attr.to, pres.attr.from = to, occupant;
229                                 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
230                                         :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
231                                 core_route_stanza(component, pres);
232                         end
233                 end
234         end
235 end
236
237 function handle_to_occupant(origin, stanza) -- PM, vCards, etc
238         local from, to = stanza.attr.from, stanza.attr.to;
239         local room = jid_bare(to);
240         local current_nick = jid_nick:get(from, room);
241         local type = stanza.attr.type;
242         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
243         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
244         if stanza.name == "presence" then
245                 local pr = get_filtered_presence(stanza);
246                 pr.attr.from = current_nick;
247                 if type == "error" then -- error, kick em out!
248                         if current_nick then
249                                 log("debug", "kicking %s from %s", current_nick, room);
250                                 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
251                         end
252                 elseif type == "unavailable" then -- unavailable
253                         if current_nick then
254                                 log("debug", "%s leaving %s", current_nick, room);
255                                 local data = rooms:get(room, current_nick);
256                                 data.role = 'none';
257                                 broadcast_presence_stanza(room, pr);
258                                 rooms:remove(room, current_nick);
259                                 jid_nick:remove(from, room);
260                         end
261                 elseif not type then -- available
262                         if current_nick then
263                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
264                                         if current_nick == to then -- simple presence
265                                                 log("debug", "%s broadcasted presence", current_nick);
266                                                 rooms:get(room, current_nick).sessions[from] = pr;
267                                                 broadcast_presence_stanza(room, pr);
268                                         else -- change nick
269                                                 if rooms:get(room, to) then
270                                                         log("debug", "%s couldn't change nick", current_nick);
271                                                         origin.send(st.error_reply(stanza, "cancel", "conflict"));
272                                                 else
273                                                         local data = rooms:get(room, current_nick);
274                                                         local to_nick = select(3, jid_split(to));
275                                                         if to_nick then
276                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
277                                                                 local p = st.presence({type='unavailable', from=current_nick});
278                                                                 broadcast_presence_stanza(room, p, '303', to_nick);
279                                                                 rooms:remove(room, current_nick);
280                                                                 rooms:set(room, to, data);
281                                                                 jid_nick:set(from, room, to);
282                                                                 pr.attr.from = to;
283                                                                 rooms:get(room, to).sessions[from] = pr;
284                                                                 broadcast_presence_stanza(room, pr);
285                                                         else
286                                                                 --TODO malformed-jid
287                                                         end
288                                                 end
289                                         end
290                                 --else -- possible rejoin
291                                 --      log("debug", "%s had connection replaced", current_nick);
292                                 --      handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to}):tag('status'):text('Replaced by new connection'):up()); -- send unavailable
293                                 --      handle_to_occupant(origin, stanza); -- resend available
294                                 --end
295                         else -- enter room
296                                 local new_nick = to;
297                                 if rooms:get(room, to) then
298                                         new_nick = nil;
299                                 end
300                                 if not new_nick then
301                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
302                                         origin.send(st.error_reply(stanza, "cancel", "conflict"));
303                                 else
304                                         log("debug", "%s joining as %s", from, to);
305                                         local data;
306                                         if not rooms:get(room) and not rooms_info:get(room) then -- new room
307                                                 rooms_info:set(room, 'name', (jid_split(room)));
308                                                 data = {affiliation='owner', role='moderator', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
309                                         end
310                                         if not data then -- new occupant
311                                                 data = {affiliation='none', role='participant', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
312                                         end
313                                         rooms:set(room, to, data);
314                                         jid_nick:set(from, room, to);
315                                         send_occupant_list(room, from);
316                                         pr.attr.from = to;
317                                         broadcast_presence_stanza(room, pr);
318                                         send_history(room, from);
319                                 end
320                         end
321                 elseif type ~= 'result' then -- bad type
322                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
323                 end
324         elseif not current_nick and type ~= "error" then -- not in room
325                 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
326         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
327                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
328         elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
329                 log("debug", "%s kicked from %s for sending an error message", current_nick, room);
330                 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
331         else -- private stanza
332                 local o_data = rooms:get(room, to);
333                 if o_data then
334                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
335                         local jid = o_data.jid;
336                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then jid = jid_bare(jid); end
337                         stanza.attr.to, stanza.attr.from = jid, current_nick;
338                         core_route_stanza(component, stanza);
339                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
340                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
341                 end
342         end
343 end
344
345 function handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
346         local type = stanza.attr.type;
347         if stanza.name == "iq" and type == "get" then -- disco requests
348                 local xmlns = stanza.tags[1].attr.xmlns;
349                 if xmlns == "http://jabber.org/protocol/disco#info" then
350                         origin.send(get_room_disco_info(stanza));
351                 elseif xmlns == "http://jabber.org/protocol/disco#items" then
352                         origin.send(get_room_disco_items(stanza));
353                 else
354                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
355                 end
356         elseif stanza.name == "message" and type == "groupchat" then
357                 local from, to = stanza.attr.from, stanza.attr.to;
358                 local room = jid_bare(to);
359                 local current_nick = jid_nick:get(from, room);
360                 if not current_nick then -- not in room
361                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
362                 else
363                         local from = stanza.attr.from;
364                         stanza.attr.from = current_nick;
365                         local subject = getText(stanza, {"subject"});
366                         if subject then
367                                 set_subject(current_nick, room, subject); -- TODO use broadcast_message_stanza
368                         else
369                                 broadcast_message_stanza(room, stanza, true);
370                         end
371                 end
372         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
373                 local to = stanza.attr.to;
374                 local current_nick = jid_nick:get(stanza.attr.from, to);
375                 if current_nick then
376                         stanza.attr.to = current_nick;
377                         handle_to_occupant(origin, stanza);
378                         stanza.attr.to = to;
379                 elseif type ~= "error" and type ~= "result" then
380                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
381                 end
382         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and jid_nick:get(stanza.attr.from, stanza.attr.to)
383                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
384                 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
385                 local _from, _to = stanza.attr.from, stanza.attr.to;
386                 local _invitee = stanza.tags[1].tags[1].attr.to;
387                 stanza.attr.from, stanza.attr.to = _to, _invitee;
388                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
389                 core_route_stanza(component, stanza);
390                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
391                 stanza.attr.from, stanza.attr.to = _from, _to;
392         else
393                 if type == "error" or type == "result" then return; end
394                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
395         end
396 end
397
398 function handle_to_domain(origin, stanza)
399         local type = stanza.attr.type;
400         if type == "error" or type == "result" then return; end
401         if stanza.name == "iq" and type == "get" then
402                 local xmlns = stanza.tags[1].attr.xmlns;
403                 if xmlns == "http://jabber.org/protocol/disco#info" then
404                         origin.send(get_disco_info(stanza));
405                 elseif xmlns == "http://jabber.org/protocol/disco#items" then
406                         origin.send(get_disco_items(stanza));
407                 else
408                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
409                 end
410         else
411                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
412         end
413 end
414
415 register_component(muc_domain, function(origin, stanza)
416         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
417         if to_resource and not to_node then
418                 if type == "error" or type == "result" then return; end
419                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- host/resource
420         elseif to_resource then
421                 handle_to_occupant(origin, stanza);
422         elseif to_node then
423                 handle_to_room(origin, stanza)
424         else -- to the main muc domain
425                 if type == "error" or type == "result" then return; end
426                 handle_to_domain(origin, stanza);
427         end
428 end);
429
430 module.unload = function()
431         deregister_component(muc_domain);
432 end
433 module.save = function()
434         return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
435 end
436 module.restore = function(data)
437         rooms.data, jid_nick.data, rooms_info.data, persist_list =
438         data.rooms or {}, data.jid_nick or {}, data.rooms_info or {}, data.persist_list or {};
439 end