4806e3452bf6b1d55925dc37fbfab5f3a9182747
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60         ["malformed error"] = true;
61 };
62
63 local function get_error_condition(stanza)
64         local _, condition = stanza:get_error();
65         return condition or "malformed error";
66 end
67
68 local function is_kickable_error(stanza)
69         local cond = get_error_condition(stanza);
70         return kickable_error_conditions[cond] and cond;
71 end
72 local function getUsingPath(stanza, path, getText)
73         local tag = stanza;
74         for _, name in ipairs(path) do
75                 if type(tag) ~= 'table' then return; end
76                 tag = tag:child_with_name(name);
77         end
78         if tag and getText then tag = table.concat(tag); end
79         return tag;
80 end
81 local function getTag(stanza, path) return getUsingPath(stanza, path); end
82 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
83 -----------
84
85 local room_mt = {};
86 room_mt.__index = room_mt;
87
88 function room_mt:get_default_role(affiliation)
89         if affiliation == "owner" or affiliation == "admin" then
90                 return "moderator";
91         elseif affiliation == "member" or not affiliation then
92                 return "participant";
93         end
94 end
95
96 function room_mt:broadcast_presence(stanza, sid, code, nick)
97         stanza = get_filtered_presence(stanza);
98         local occupant = self._occupants[stanza.attr.from];
99         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
100                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
101         if code then
102                 stanza:tag("status", {code=code}):up();
103         end
104         self:broadcast_except_nick(stanza, stanza.attr.from);
105         local me = self._occupants[stanza.attr.from];
106         if me then
107                 stanza:tag("status", {code='110'});
108                 stanza.attr.to = sid;
109                 self:_route_stanza(stanza);
110         end
111 end
112 function room_mt:broadcast_message(stanza, historic)
113         local to = stanza.attr.to;
114         for occupant, o_data in pairs(self._occupants) do
115                 for jid in pairs(o_data.sessions) do
116                         stanza.attr.to = jid;
117                         self:_route_stanza(stanza);
118                 end
119         end
120         stanza.attr.to = to;
121         if historic then -- add to history
122                 local history = self._data['history'];
123                 if not history then history = {}; self._data['history'] = history; end
124                 stanza = st.clone(stanza);
125                 stanza.attr.to = "";
126                 local stamp = datetime.datetime();
127                 local chars = #tostring(stanza);
128                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
129                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
130                 local entry = { stanza = stanza, stamp = stamp };
131                 t_insert(history, entry);
132                 while #history > history_length do t_remove(history, 1) end
133         end
134 end
135 function room_mt:broadcast_except_nick(stanza, nick)
136         for rnick, occupant in pairs(self._occupants) do
137                 if rnick ~= nick then
138                         for jid in pairs(occupant.sessions) do
139                                 stanza.attr.to = jid;
140                                 self:_route_stanza(stanza);
141                         end
142                 end
143         end
144 end
145
146 function room_mt:send_occupant_list(to)
147         local current_nick = self._jid_nick[to];
148         for occupant, o_data in pairs(self._occupants) do
149                 if occupant ~= current_nick then
150                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
151                         pres.attr.to, pres.attr.from = to, occupant;
152                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
153                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
154                         self:_route_stanza(pres);
155                 end
156         end
157 end
158 function room_mt:send_history(to, stanza)
159         local history = self._data['history']; -- send discussion history
160         if history then
161                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
162                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
163                 
164                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
165                 if maxchars then maxchars = math.floor(maxchars); end
166                 
167                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
168                 if not history_tag then maxstanzas = 20; end
169
170                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
171                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
172
173                 local since = history_tag and history_tag.attr.since;
174                 if since and not since:match("^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ$") then since = nil; end -- FIXME timezone support
175                 if seconds and (not since or since < seconds) then since = seconds; end
176
177                 local n = 0;
178                 local charcount = 0;
179                 local stanzacount = 0;
180                 
181                 for i=#history,1,-1 do
182                         local entry = history[i];
183                         if maxchars then
184                                 if not entry.chars then
185                                         entry.stanza.attr.to = "";
186                                         entry.chars = #tostring(entry.stanza);
187                                 end
188                                 charcount = charcount + entry.chars + #to;
189                                 if charcount > maxchars then break; end
190                         end
191                         if since and since > entry.stamp then break; end
192                         if n + 1 > maxstanzas then break; end
193                         n = n + 1;
194                 end
195                 for i=#history-n+1,#history do
196                         local msg = history[i].stanza;
197                         msg.attr.to = to;
198                         self:_route_stanza(msg);
199                 end
200         end
201         if self._data['subject'] then
202                 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
203         end
204 end
205
206 function room_mt:get_disco_info(stanza)
207         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
208                 :tag("identity", {category="conference", type="text"}):up()
209                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
210                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
211         ;
212 end
213 function room_mt:get_disco_items(stanza)
214         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
215         for room_jid in pairs(self._occupants) do
216                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
217         end
218         return reply;
219 end
220 function room_mt:set_subject(current_nick, subject)
221         -- TODO check nick's authority
222         if subject == "" then subject = nil; end
223         self._data['subject'] = subject;
224         if self.save then self:save(); end
225         local msg = st.message({type='groupchat', from=current_nick})
226                 :tag('subject'):text(subject):up();
227         self:broadcast_message(msg, false);
228         return true;
229 end
230
231 local function build_unavailable_presence_from_error(stanza)
232         local type, condition, text = stanza:get_error();
233         local error_message = "Kicked: "..condition:gsub("%-", " ");
234         if text then
235                 error_message = error_message..": "..text;
236         end
237         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
238                 :tag('status'):text(error_message);
239 end
240
241 function room_mt:set_password(password)
242         if password == "" or type(password) ~= "string" then password = nil; end
243         self._data.password = password;
244         return password;
245 end
246 function room_mt:get_password()
247         return self._data.password;
248 end
249
250 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
251         local from, to = stanza.attr.from, stanza.attr.to;
252         local room = jid_bare(to);
253         local current_nick = self._jid_nick[from];
254         local type = stanza.attr.type;
255         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
256         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
257         if stanza.name == "presence" then
258                 local pr = get_filtered_presence(stanza);
259                 pr.attr.from = current_nick;
260                 if type == "error" then -- error, kick em out!
261                         if current_nick then
262                                 log("debug", "kicking %s from %s", current_nick, room);
263                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
264                         end
265                 elseif type == "unavailable" then -- unavailable
266                         if current_nick then
267                                 log("debug", "%s leaving %s", current_nick, room);
268                                 local occupant = self._occupants[current_nick];
269                                 local new_jid = next(occupant.sessions);
270                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
271                                 if new_jid then
272                                         local jid = occupant.jid;
273                                         occupant.jid = new_jid;
274                                         occupant.sessions[from] = nil;
275                                         pr.attr.to = from;
276                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
277                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
278                                                 :tag("status", {code='110'});
279                                         self:_route_stanza(pr);
280                                         if jid ~= new_jid then
281                                                 pr = st.clone(occupant.sessions[new_jid])
282                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
283                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
284                                                 pr.attr.from = current_nick;
285                                                 self:broadcast_except_nick(pr, current_nick);
286                                         end
287                                 else
288                                         occupant.role = 'none';
289                                         self:broadcast_presence(pr, from);
290                                         self._occupants[current_nick] = nil;
291                                 end
292                                 self._jid_nick[from] = nil;
293                         end
294                 elseif not type then -- available
295                         if current_nick then
296                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
297                                         if current_nick == to then -- simple presence
298                                                 log("debug", "%s broadcasted presence", current_nick);
299                                                 self._occupants[current_nick].sessions[from] = pr;
300                                                 self:broadcast_presence(pr, from);
301                                         else -- change nick
302                                                 local occupant = self._occupants[current_nick];
303                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
304                                                 if self._occupants[to] or is_multisession then
305                                                         log("debug", "%s couldn't change nick", current_nick);
306                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
307                                                         reply.tags[1].attr.code = "409";
308                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
309                                                 else
310                                                         local data = self._occupants[current_nick];
311                                                         local to_nick = select(3, jid_split(to));
312                                                         if to_nick then
313                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
314                                                                 local p = st.presence({type='unavailable', from=current_nick});
315                                                                 self:broadcast_presence(p, from, '303', to_nick);
316                                                                 self._occupants[current_nick] = nil;
317                                                                 self._occupants[to] = data;
318                                                                 self._jid_nick[from] = to;
319                                                                 pr.attr.from = to;
320                                                                 self._occupants[to].sessions[from] = pr;
321                                                                 self:broadcast_presence(pr, from);
322                                                         else
323                                                                 --TODO malformed-jid
324                                                         end
325                                                 end
326                                         end
327                                 --else -- possible rejoin
328                                 --      log("debug", "%s had connection replaced", current_nick);
329                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
330                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
331                                 --      self:handle_to_occupant(origin, stanza); -- resend available
332                                 --end
333                         else -- enter room
334                                 local new_nick = to;
335                                 local is_merge;
336                                 if self._occupants[to] then
337                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
338                                                 new_nick = nil;
339                                         end
340                                         is_merge = true;
341                                 end
342                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
343                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
344                                 password = password and password[1] ~= "" and password[1];
345                                 if self:get_password() and self:get_password() ~= password then
346                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
347                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
348                                         reply.tags[1].attr.code = "401";
349                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
350                                 elseif not new_nick then
351                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
352                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
353                                         reply.tags[1].attr.code = "409";
354                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
355                                 else
356                                         log("debug", "%s joining as %s", from, to);
357                                         if not next(self._affiliations) then -- new room, no owners
358                                                 self._affiliations[jid_bare(from)] = "owner";
359                                         end
360                                         local affiliation = self:get_affiliation(from);
361                                         local role = self:get_default_role(affiliation)
362                                         if role then -- new occupant
363                                                 if not is_merge then
364                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
365                                                 else
366                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
367                                                 end
368                                                 self._jid_nick[from] = to;
369                                                 self:send_occupant_list(from);
370                                                 pr.attr.from = to;
371                                                 if not is_merge then
372                                                         self:broadcast_presence(pr, from);
373                                                 else
374                                                         pr.attr.to = from;
375                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
376                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
377                                                                 :tag("status", {code='110'}));
378                                                 end
379                                                 self:send_history(from, stanza);
380                                         else -- banned
381                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
382                                                 reply.tags[1].attr.code = "403";
383                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
384                                         end
385                                 end
386                         end
387                 elseif type ~= 'result' then -- bad type
388                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
389                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
390                         end
391                 end
392         elseif not current_nick then -- not in room
393                 if type == "error" or type == "result" then
394                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
395                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
396                         local occupant = self._occupants[stanza.attr.to];
397                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
398                                 local id, _to = stanza.attr.id;
399                                 for jid in pairs(occupant.sessions) do
400                                         if md5(jid) == _hash then
401                                                 _to = jid;
402                                                 break;
403                                         end
404                                 end
405                                 if _to then
406                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
407                                         self:_route_stanza(stanza);
408                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
409                                 end
410                         end
411                 else
412                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
413                 end
414         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
415                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
416         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
417                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
418                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
419         else -- private stanza
420                 local o_data = self._occupants[to];
421                 if o_data then
422                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
423                         local jid = o_data.jid;
424                         local bare = jid_bare(jid);
425                         stanza.attr.to, stanza.attr.from = jid, current_nick;
426                         local id = stanza.attr.id;
427                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
428                                 stanza.attr.to = bare;
429                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
430                         end
431                         self:_route_stanza(stanza);
432                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
433                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
434                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
435                 end
436         end
437 end
438
439 function room_mt:send_form(origin, stanza)
440         local title = "Configuration for "..self.jid;
441         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
442                 :tag("x", {xmlns='jabber:x:data', type='form'})
443                         :tag("title"):text(title):up()
444                         :tag("instructions"):text(title):up()
445                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
446                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
447                                 :tag("value"):text(self._data.persistent and "1" or "0"):up()
448                         :up()
449                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
450                                 :tag("value"):text(self._data.hidden and "0" or "1"):up()
451                         :up()
452                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
453                             :tag("value"):text(self._data.whois or 'moderators'):up()
454                             :tag("option", {label = 'Moderators Only'})
455                                 :tag("value"):text('moderators'):up()
456                                 :up()
457                             :tag("option", {label = 'Anyone'})
458                                 :tag("value"):text('anyone'):up()
459                                 :up()
460                         :up()
461         );
462 end
463
464 local valid_whois = {
465     moderators = true,
466     anyone = true,
467 }
468
469 function room_mt:process_form(origin, stanza)
470         local query = stanza.tags[1];
471         local form;
472         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
473         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
474         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
475         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
476         local fields = {};
477         for _, field in pairs(form.tags) do
478                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
479                         fields[field.attr.var] = field.tags[1][1] or "";
480                 end
481         end
482         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
483
484         local dirty = false
485
486         local persistent = fields['muc#roomconfig_persistentroom'];
487         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
488         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
489         dirty = dirty or (self._data.persistent ~= persistent)
490         self._data.persistent = persistent;
491         module:log("debug", "persistent=%s", tostring(persistent));
492
493         local public = fields['muc#roomconfig_publicroom'];
494         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
495         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
496         dirty = dirty or (self._data.hidden ~= (not public and true or nil))
497         self._data.hidden = not public and true or nil;
498
499         local whois = fields['muc#roomconfig_whois'];
500         if not valid_whois[whois] then
501             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
502             return;
503         end
504         local whois_changed = self._data.whois ~= whois
505         self._data.whois = whois
506         module:log('debug', 'whois=%s', tostring(whois))
507
508         if self.save then self:save(true); end
509         origin.send(st.reply(stanza));
510
511         if dirty or whois_changed then
512             local msg = st.message({type='groupchat', from=self.jid})
513                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
514
515             if dirty then
516                 msg.tags[1]:tag('status', {code = '104'})
517             end
518             if whois_changed then
519                 local code = (whois == 'moderators') and 173 or 172
520                 msg.tags[1]:tag('status', {code = code})
521             end
522
523             self:broadcast_message(msg, false)
524         end
525 end
526
527 function room_mt:destroy(newjid, reason, password)
528         local pr = st.presence({type = "unavailable"})
529                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
530                         :tag("item", { affiliation='none', role='none' }):up()
531                         :tag("destroy", {jid=newjid})
532         if reason then pr:tag("reason"):text(reason):up(); end
533         if password then pr:tag("password"):text(password):up(); end
534         for nick, occupant in pairs(self._occupants) do
535                 pr.attr.from = nick;
536                 for jid in pairs(occupant.sessions) do
537                         pr.attr.to = jid;
538                         self:_route_stanza(pr);
539                         self._jid_nick[jid] = nil;
540                 end
541                 self._occupants[nick] = nil;
542         end
543         self._data.persistent = nil;
544         if self.save then self:save(true); end
545 end
546
547 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
548         local type = stanza.attr.type;
549         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
550         if stanza.name == "iq" then
551                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
552                         origin.send(self:get_disco_info(stanza));
553                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
554                         origin.send(self:get_disco_items(stanza));
555                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
556                         local actor = stanza.attr.from;
557                         local affiliation = self:get_affiliation(actor);
558                         local current_nick = self._jid_nick[actor];
559                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
560                         local item = stanza.tags[1].tags[1];
561                         if item and item.name == "item" then
562                                 if type == "set" then
563                                         local callback = function() origin.send(st.reply(stanza)); end
564                                         if item.attr.jid then -- Validate provided JID
565                                                 item.attr.jid = jid_prep(item.attr.jid);
566                                                 if not item.attr.jid then
567                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
568                                                         return;
569                                                 end
570                                         end
571                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
572                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
573                                                 if occupant then item.attr.jid = occupant.jid; end
574                                         elseif not item.attr.nick and item.attr.jid then
575                                                 local nick = self._jid_nick[item.attr.jid];
576                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
577                                         end
578                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
579                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
580                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
581                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
582                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
583                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
584                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
585                                         else
586                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
587                                         end
588                                 elseif type == "get" then
589                                         local _aff = item.attr.affiliation;
590                                         local _rol = item.attr.role;
591                                         if _aff and not _rol then
592                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
593                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
594                                                         for jid, affiliation in pairs(self._affiliations) do
595                                                                 if affiliation == _aff then
596                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
597                                                                 end
598                                                         end
599                                                         origin.send(reply);
600                                                 else
601                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
602                                                 end
603                                         elseif _rol and not _aff then
604                                                 if role == "moderator" then
605                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
606                                                         if _rol == "none" then _rol = nil; end
607                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
608                                                         for occupant_jid, occupant in pairs(self._occupants) do
609                                                                 if occupant.role == _rol then
610                                                                         reply:tag("item", {
611                                                                                 nick = select(3, jid_split(occupant_jid)),
612                                                                                 role = _rol or "none",
613                                                                                 affiliation = occupant.affiliation or "none",
614                                                                                 jid = occupant.jid
615                                                                                 }):up();
616                                                                 end
617                                                         end
618                                                         origin.send(reply);
619                                                 else
620                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
621                                                 end
622                                         else
623                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
624                                         end
625                                 end
626                         elseif type == "set" or type == "get" then
627                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
628                         end
629                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
630                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
631                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
632                         elseif stanza.attr.type == "get" then
633                                 self:send_form(origin, stanza);
634                         elseif stanza.attr.type == "set" then
635                                 local child = stanza.tags[1].tags[1];
636                                 if not child then
637                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
638                                 elseif child.name == "destroy" then
639                                         local newjid = child.attr.jid;
640                                         local reason, password;
641                                         for _,tag in ipairs(child.tags) do
642                                                 if tag.name == "reason" then
643                                                         reason = #tag.tags == 0 and tag[1];
644                                                 elseif tag.name == "password" then
645                                                         password = #tag.tags == 0 and tag[1];
646                                                 end
647                                         end
648                                         self:destroy(newjid, reason, password);
649                                         origin.send(st.reply(stanza));
650                                 else
651                                         self:process_form(origin, stanza);
652                                 end
653                         end
654                 elseif type == "set" or type == "get" then
655                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
656                 end
657         elseif stanza.name == "message" and type == "groupchat" then
658                 local from, to = stanza.attr.from, stanza.attr.to;
659                 local room = jid_bare(to);
660                 local current_nick = self._jid_nick[from];
661                 local occupant = self._occupants[current_nick];
662                 if not occupant then -- not in room
663                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
664                 elseif occupant.role == "visitor" then
665                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
666                 else
667                         local from = stanza.attr.from;
668                         stanza.attr.from = current_nick;
669                         local subject = getText(stanza, {"subject"});
670                         if subject then
671                                 if occupant.role == "moderator" then
672                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
673                                 else
674                                         stanza.attr.from = from;
675                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
676                                 end
677                         else
678                                 self:broadcast_message(stanza, true);
679                         end
680                         stanza.attr.from = from;
681                 end
682         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
683                 local current_nick = self._jid_nick[stanza.attr.from];
684                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
685                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
686         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
687                 local to = stanza.attr.to;
688                 local current_nick = self._jid_nick[stanza.attr.from];
689                 if current_nick then
690                         stanza.attr.to = current_nick;
691                         self:handle_to_occupant(origin, stanza);
692                         stanza.attr.to = to;
693                 elseif type ~= "error" and type ~= "result" then
694                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
695                 end
696         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
697                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
698                 local x = stanza.tags[1];
699                 local payload = (#x.tags == 1 and x.tags[1]);
700                 if payload and payload.name == "invite" and payload.attr.to then
701                         local _from, _to = stanza.attr.from, stanza.attr.to;
702                         local _invitee = jid_prep(payload.attr.to);
703                         if _invitee then
704                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
705                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
706                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
707                                                 :tag('invite', {from=_from})
708                                                         :tag('reason'):text(_reason or ""):up()
709                                                 :up()
710                                         :up()
711                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
712                                                 :text(_reason or "")
713                                         :up()
714                                         :tag('body') -- Add a plain message for clients which don't support invites
715                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
716                                         :up();
717                                 self:_route_stanza(invite);
718                         else
719                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
720                         end
721                 else
722                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
723                 end
724         else
725                 if type == "error" or type == "result" then return; end
726                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
727         end
728 end
729
730 function room_mt:handle_stanza(origin, stanza)
731         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
732         if to_resource then
733                 self:handle_to_occupant(origin, stanza);
734         else
735                 self:handle_to_room(origin, stanza);
736         end
737 end
738
739 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
740
741 function room_mt:get_affiliation(jid)
742         local node, host, resource = jid_split(jid);
743         local bare = node and node.."@"..host or host;
744         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
745         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
746         return result;
747 end
748 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
749         jid = jid_bare(jid);
750         if affiliation == "none" then affiliation = nil; end
751         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
752                 return nil, "modify", "not-acceptable";
753         end
754         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
755         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
756         self._affiliations[jid] = affiliation;
757         local role = self:get_default_role(affiliation);
758         local p = st.presence()
759                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
760                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
761                                 :tag("reason"):text(reason or ""):up()
762                         :up();
763         local x = p.tags[1];
764         local item = x.tags[1];
765         if not role then -- getting kicked
766                 p.attr.type = "unavailable";
767                 if affiliation == "outcast" then
768                         x:tag("status", {code="301"}):up(); -- banned
769                 else
770                         x:tag("status", {code="321"}):up(); -- affiliation change
771                 end
772         end
773         local modified_nicks = {};
774         for nick, occupant in pairs(self._occupants) do
775                 if jid_bare(occupant.jid) == jid then
776                         if not role then -- getting kicked
777                                 self._occupants[nick] = nil;
778                         else
779                                 t_insert(modified_nicks, nick);
780                                 occupant.affiliation, occupant.role = affiliation, role;
781                         end
782                         p.attr.from = nick;
783                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
784                                 if not role then self._jid_nick[jid] = nil; end
785                                 p.attr.to = jid;
786                                 self:_route_stanza(p);
787                         end
788                 end
789         end
790         if self.save then self:save(); end
791         if callback then callback(); end
792         for _, nick in ipairs(modified_nicks) do
793                 p.attr.from = nick;
794                 self:broadcast_except_nick(p, nick);
795         end
796         return true;
797 end
798
799 function room_mt:get_role(nick)
800         local session = self._occupants[nick];
801         return session and session.role or nil;
802 end
803 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
804         if role == "none" then role = nil; end
805         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
806         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
807         local occupant = self._occupants[occupant_jid];
808         if not occupant then return nil, "modify", "not-acceptable"; end
809         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
810         local p = st.presence({from = occupant_jid})
811                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
812                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
813                                 :tag("reason"):text(reason or ""):up()
814                         :up();
815         if not role then -- kick
816                 p.attr.type = "unavailable";
817                 self._occupants[occupant_jid] = nil;
818                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
819                         self._jid_nick[jid] = nil;
820                 end
821                 p:tag("status", {code = "307"}):up();
822         else
823                 occupant.role = role;
824         end
825         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
826                 p.attr.to = jid;
827                 self:_route_stanza(p);
828         end
829         if callback then callback(); end
830         self:broadcast_except_nick(p, occupant_jid);
831         return true;
832 end
833
834 function room_mt:_route_stanza(stanza)
835         local muc_child;
836         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
837         local from_occupant = self._occupants[stanza.attr.from];
838         if stanza.name == "presence" then
839                 if to_occupant and from_occupant then
840                         if self._data.whois == 'anyone' then
841                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
842                         else
843                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
844                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
845                                 end
846                         end
847                 end
848         end
849         if muc_child then
850                 for _, item in pairs(muc_child.tags) do
851                         if item.name == "item" then
852                                 if from_occupant == to_occupant then
853                                         item.attr.jid = stanza.attr.to;
854                                 else
855                                         item.attr.jid = from_occupant.jid;
856                                 end
857                         end
858                 end
859                 if self._data.whois == 'anyone' then
860                     muc_child:tag('status', { code = '100' });
861                 end
862         end
863         self:route_stanza(stanza);
864         if muc_child then
865                 for _, item in pairs(muc_child.tags) do
866                         if item.name == "item" then
867                                 item.attr.jid = nil;
868                         end
869                 end
870         end
871 end
872
873 local _M = {}; -- module "muc"
874
875 function _M.new_room(jid)
876         return setmetatable({
877                 jid = jid;
878                 _jid_nick = {};
879                 _occupants = {};
880                 _data = {
881                     whois = 'moderators',
882                 };
883                 _affiliations = {};
884         }, room_mt);
885 end
886
887 return _M;