Another unwanted spaces at the end of a line.
[prosody.git] / util / muc.lua
1 -- Prosody IM
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 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 local muc_domain = nil; --module:get_host();
20 local history_length = 20;
21
22 ------------
23 local function filter_xmlns_from_array(array, filters)
24         local count = 0;
25         for i=#array,1,-1 do
26                 local attr = array[i].attr;
27                 if filters[attr and attr.xmlns] then
28                         t_remove(array, i);
29                         count = count + 1;
30                 end
31         end
32         return count;
33 end
34 local function filter_xmlns_from_stanza(stanza, filters)
35         if filters then
36                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
37                         return stanza, filter_xmlns_from_array(stanza, filters);
38                 end
39         end
40         return stanza, 0;
41 end
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);
45 end
46 local kickable_error_conditions = {
47         ["gone"] = true;
48         ["internal-server-error"] = true;
49         ["item-not-found"] = true;
50         ["jid-malformed"] = true;
51         ["recipient-unavailable"] = true;
52         ["redirect"] = true;
53         ["remote-server-not-found"] = true;
54         ["remote-server-timeout"] = true;
55         ["service-unavailable"] = true;
56 };
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;
63                                 end
64                         end
65                         return true; -- malformed error message
66                 end
67         end
68         return true; -- malformed error message
69 end
70 local function getUsingPath(stanza, path, getText)
71         local tag = stanza;
72         for _, name in ipairs(path) do
73                 if type(tag) ~= 'table' then return; end
74                 tag = tag:child_with_name(name);
75         end
76         if tag and getText then tag = table.concat(tag); end
77         return tag;
78 end
79 local function getTag(stanza, path) return getUsingPath(stanza, path); end
80 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
81 -----------
82
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
87 end
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]]
91
92 --
93
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();
99         if code then
100                 stanza:tag("status", {code=code}):up();
101         end
102         local me;
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);
108                         end
109                 else
110                         me = o_data;
111                 end
112         end
113         if me then
114                 stanza:tag("status", {code='110'});
115                 for jid in pairs(me.sessions) do
116                         stanza.attr.to = jid;
117                         room:route_stanza(stanza);
118                 end
119         end
120 end
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);
126                 end
127         end
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
136         end
137 end
138
139
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);
149                 end
150         end
151 end
152 local function room_send_history(room, to)
153         local history = room._data['history']; -- send discussion history
154         if history then
155                 for _, msg in ipairs(history) do
156                         msg = st.deserialize(msg);
157                         msg.attr.to=to;
158                         room:route_stanza(msg);
159                 end
160         end
161         if room._data['subject'] then
162                 room:route_stanza(st.message({type='groupchat', from=room.jid, to=to}):tag("subject"):text(room._data['subject']));
163         end
164 end
165
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, 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);
175         return true;
176 end
177
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!
189                         if current_nick then
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
192                         end
193                 elseif type == "unavailable" then -- unavailable
194                         if current_nick then
195                                 log("debug", "%s leaving %s", current_nick, room);
196                                 local data = self._participants[current_nick];
197                                 data.role = 'none';
198                                 room_broadcast_presence(self, pr);
199                                 self._participants[current_nick] = nil;
200                                 self._jid_nick[from] = nil;
201                         end
202                 elseif not type then -- available
203                         if current_nick then
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);
209                                         else -- change nick
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"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
213                                                 else
214                                                         local data = self._participants[current_nick];
215                                                         local to_nick = select(3, jid_split(to));
216                                                         if to_nick then
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;
223                                                                 pr.attr.from = to;
224                                                                 self._participants[to].sessions[from] = pr;
225                                                                 room_broadcast_presence(self, pr);
226                                                         else
227                                                                 --TODO malformed-jid
228                                                         end
229                                                 end
230                                         end
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
235                                 --end
236                         else -- enter room
237                                 local new_nick = to;
238                                 if self._participants[to] then
239                                         new_nick = nil;
240                                 end
241                                 if not new_nick then
242                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
243                                         origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
244                                 else
245                                         log("debug", "%s joining as %s", from, to);
246                                         local data;
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)}};
250 --                                      end
251                                         if not data then -- new occupant
252                                                 data = {affiliation='none', role='participant', jid=from, sessions={[from]=get_filtered_presence(stanza)}};
253                                         end
254                                         self._participants[to] = data;
255                                         self._jid_nick[from] = to;
256                                         room_send_occupant_list(self, from);
257                                         pr.attr.from = to;
258                                         room_broadcast_presence(self, pr);
259                                         room_send_history(self, from);
260                                 end
261                         end
262                 elseif type ~= 'result' then -- bad type
263                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
264                 end
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];
274                 if o_data then
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"));
282                 end
283         end
284 end
285
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));
294                 else
295                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
296                 end
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"));
303                 else
304                         local from = stanza.attr.from;
305                         stanza.attr.from = current_nick;
306                         local subject = getText(stanza, {"subject"});
307                         if subject then
308                                 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
309                         else
310                                 room_broadcast_message(self, stanza, true);
311                         end
312                 end
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];
316                 if current_nick then
317                         stanza.attr.to = current_nick;
318                         room_handle_to_occupant(self, origin, stanza);
319                         stanza.attr.to = to;
320                 elseif type ~= "error" and type ~= "result" then
321                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
322                 end
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;
333         else
334                 if type == "error" or type == "result" then return; end
335                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
336         end
337 end
338
339 local function room_handle_stanza(self, origin, stanza)
340         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
341         if to_resource then
342                 room_handle_to_occupant(self, origin, stanza);
343         else
344                 room_handle_to_room(self, origin, stanza);
345         end
346 end
347
348 module "muc"
349
350 function new_room(jid)
351         return {
352                 jid = 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
356                 _jid_nick = {};
357                 _participants = {};
358                 _data = {};
359         }
360 end
361
362 return _M;
363
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
368 end
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();
373         end
374         return reply; -- TODO cache disco reply
375 end]]
376
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));
386                 else
387                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); -- TODO disco/etc
388                 end
389         else
390                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "The muc server doesn't deal with messages and presence directed at it"));
391         end
392 end
393
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);
401         elseif to_node then
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);
406         end
407 end);]]
408
409 --[[module.unload = function()
410         deregister_component(muc_domain);
411 end
412 module.save = function()
413         return {rooms = rooms.data; jid_nick = jid_nick.data; rooms_info = rooms_info.data; persist_list = persist_list};
414 end
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 {};
418 end]]