69b013364359d8d0bd4a4e49e81a8aa3936d04bc
[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"});
210 end
211 function room_mt:get_disco_items(stanza)
212         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
213         for room_jid in pairs(self._occupants) do
214                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
215         end
216         return reply;
217 end
218 function room_mt:set_subject(current_nick, subject)
219         -- TODO check nick's authority
220         if subject == "" then subject = nil; end
221         self._data['subject'] = subject;
222         if self.save then self:save(); end
223         local msg = st.message({type='groupchat', from=current_nick})
224                 :tag('subject'):text(subject):up();
225         self:broadcast_message(msg, false);
226         return true;
227 end
228
229 local function build_unavailable_presence_from_error(stanza)
230         local type, condition, text = stanza:get_error();
231         local error_message = "Kicked: "..condition:gsub("%-", " ");
232         if text then
233                 error_message = error_message..": "..text;
234         end
235         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
236                 :tag('status'):text(error_message);
237 end
238
239 function room_mt:set_password(password)
240         if password == "" or type(password) ~= "string" then password = nil; end
241         self._data.password = password;
242         return password;
243 end
244 function room_mt:get_password()
245         return self._data.password;
246 end
247
248 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
249         local from, to = stanza.attr.from, stanza.attr.to;
250         local room = jid_bare(to);
251         local current_nick = self._jid_nick[from];
252         local type = stanza.attr.type;
253         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
254         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
255         if stanza.name == "presence" then
256                 local pr = get_filtered_presence(stanza);
257                 pr.attr.from = current_nick;
258                 if type == "error" then -- error, kick em out!
259                         if current_nick then
260                                 log("debug", "kicking %s from %s", current_nick, room);
261                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
262                         end
263                 elseif type == "unavailable" then -- unavailable
264                         if current_nick then
265                                 log("debug", "%s leaving %s", current_nick, room);
266                                 local occupant = self._occupants[current_nick];
267                                 local new_jid = next(occupant.sessions);
268                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
269                                 if new_jid then
270                                         local jid = occupant.jid;
271                                         occupant.jid = new_jid;
272                                         occupant.sessions[from] = nil;
273                                         pr.attr.to = from;
274                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
275                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
276                                                 :tag("status", {code='110'});
277                                         self:_route_stanza(pr);
278                                         if jid ~= new_jid then
279                                                 pr = st.clone(occupant.sessions[new_jid])
280                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
281                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
282                                                 pr.attr.from = current_nick;
283                                                 self:broadcast_except_nick(pr, current_nick);
284                                         end
285                                 else
286                                         occupant.role = 'none';
287                                         self:broadcast_presence(pr, from);
288                                         self._occupants[current_nick] = nil;
289                                 end
290                                 self._jid_nick[from] = nil;
291                         end
292                 elseif not type then -- available
293                         if current_nick then
294                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
295                                         if current_nick == to then -- simple presence
296                                                 log("debug", "%s broadcasted presence", current_nick);
297                                                 self._occupants[current_nick].sessions[from] = pr;
298                                                 self:broadcast_presence(pr, from);
299                                         else -- change nick
300                                                 local occupant = self._occupants[current_nick];
301                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
302                                                 if self._occupants[to] or is_multisession then
303                                                         log("debug", "%s couldn't change nick", current_nick);
304                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
305                                                         reply.tags[1].attr.code = "409";
306                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
307                                                 else
308                                                         local data = self._occupants[current_nick];
309                                                         local to_nick = select(3, jid_split(to));
310                                                         if to_nick then
311                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
312                                                                 local p = st.presence({type='unavailable', from=current_nick});
313                                                                 self:broadcast_presence(p, from, '303', to_nick);
314                                                                 self._occupants[current_nick] = nil;
315                                                                 self._occupants[to] = data;
316                                                                 self._jid_nick[from] = to;
317                                                                 pr.attr.from = to;
318                                                                 self._occupants[to].sessions[from] = pr;
319                                                                 self:broadcast_presence(pr, from);
320                                                         else
321                                                                 --TODO malformed-jid
322                                                         end
323                                                 end
324                                         end
325                                 --else -- possible rejoin
326                                 --      log("debug", "%s had connection replaced", current_nick);
327                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
328                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
329                                 --      self:handle_to_occupant(origin, stanza); -- resend available
330                                 --end
331                         else -- enter room
332                                 local new_nick = to;
333                                 local is_merge;
334                                 if self._occupants[to] then
335                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
336                                                 new_nick = nil;
337                                         end
338                                         is_merge = true;
339                                 end
340                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
341                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
342                                 password = password and password[1] ~= "" and password[1];
343                                 if self:get_password() and self:get_password() ~= password then
344                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
345                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
346                                         reply.tags[1].attr.code = "401";
347                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
348                                 elseif not new_nick then
349                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
350                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
351                                         reply.tags[1].attr.code = "409";
352                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
353                                 else
354                                         log("debug", "%s joining as %s", from, to);
355                                         if not next(self._affiliations) then -- new room, no owners
356                                                 self._affiliations[jid_bare(from)] = "owner";
357                                         end
358                                         local affiliation = self:get_affiliation(from);
359                                         local role = self:get_default_role(affiliation)
360                                         if role then -- new occupant
361                                                 if not is_merge then
362                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
363                                                 else
364                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
365                                                 end
366                                                 self._jid_nick[from] = to;
367                                                 self:send_occupant_list(from);
368                                                 pr.attr.from = to;
369                                                 if not is_merge then
370                                                         self:broadcast_presence(pr, from);
371                                                 else
372                                                         pr.attr.to = from;
373                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
374                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
375                                                                 :tag("status", {code='110'}));
376                                                 end
377                                                 self:send_history(from, stanza);
378                                         else -- banned
379                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
380                                                 reply.tags[1].attr.code = "403";
381                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
382                                         end
383                                 end
384                         end
385                 elseif type ~= 'result' then -- bad type
386                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
387                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
388                         end
389                 end
390         elseif not current_nick then -- not in room
391                 if type == "error" or type == "result" then
392                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
393                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
394                         local occupant = self._occupants[stanza.attr.to];
395                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
396                                 local id, _to = stanza.attr.id;
397                                 for jid in pairs(occupant.sessions) do
398                                         if md5(jid) == _hash then
399                                                 _to = jid;
400                                                 break;
401                                         end
402                                 end
403                                 if _to then
404                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
405                                         self:_route_stanza(stanza);
406                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
407                                 end
408                         end
409                 else
410                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
411                 end
412         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
413                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
414         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
415                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
416                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
417         else -- private stanza
418                 local o_data = self._occupants[to];
419                 if o_data then
420                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
421                         local jid = o_data.jid;
422                         local bare = jid_bare(jid);
423                         stanza.attr.to, stanza.attr.from = jid, current_nick;
424                         local id = stanza.attr.id;
425                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
426                                 stanza.attr.to = bare;
427                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
428                         end
429                         self:_route_stanza(stanza);
430                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
431                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
432                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
433                 end
434         end
435 end
436
437 function room_mt:send_form(origin, stanza)
438         local title = "Configuration for "..self.jid;
439         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
440                 :tag("x", {xmlns='jabber:x:data', type='form'})
441                         :tag("title"):text(title):up()
442                         :tag("instructions"):text(title):up()
443                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
444                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
445                                 :tag("value"):text(self._data.persistent and "1" or "0"):up()
446                         :up()
447                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
448                                 :tag("value"):text(self._data.hidden and "0" or "1"):up()
449                         :up()
450                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
451                             :tag("value"):text(self._data.whois or 'moderators'):up()
452                             :tag("option", {label = 'Moderators Only'})
453                                 :tag("value"):text('moderators'):up()
454                                 :up()
455                             :tag("option", {label = 'Anyone'})
456                                 :tag("value"):text('anyone'):up()
457                                 :up()
458                         :up()
459         );
460 end
461
462 local valid_whois = {
463     moderators = true,
464     anyone = true,
465 }
466
467 function room_mt:process_form(origin, stanza)
468         local query = stanza.tags[1];
469         local form;
470         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
471         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
472         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
473         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
474         local fields = {};
475         for _, field in pairs(form.tags) do
476                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
477                         fields[field.attr.var] = field.tags[1][1] or "";
478                 end
479         end
480         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
481
482         local dirty = false
483
484         local persistent = fields['muc#roomconfig_persistentroom'];
485         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
486         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
487         dirty = dirty or (self._data.persistent ~= persistent)
488         self._data.persistent = persistent;
489         module:log("debug", "persistent=%s", tostring(persistent));
490
491         local public = fields['muc#roomconfig_publicroom'];
492         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
493         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
494         dirty = dirty or (self._data.hidden ~= (not public and true or nil))
495         self._data.hidden = not public and true or nil;
496
497         local whois = fields['muc#roomconfig_whois'];
498         if not valid_whois[whois] then
499             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
500             return;
501         end
502         local whois_changed = self._data.whois ~= whois
503         self._data.whois = whois
504         module:log('debug', 'whois=%s', tostring(whois))
505
506         if self.save then self:save(true); end
507         origin.send(st.reply(stanza));
508
509         if dirty or whois_changed then
510             local msg = st.message({type='groupchat', from=self.jid})
511                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
512
513             if dirty then
514                 msg.tags[1]:tag('status', {code = '104'})
515             end
516             if whois_changed then
517                 local code = (whois == 'moderators') and 173 or 172
518                 msg.tags[1]:tag('status', {code = code})
519             end
520
521             self:broadcast_message(msg, false)
522         end
523 end
524
525 function room_mt:destroy(newjid, reason, password)
526         local pr = st.presence({type = "unavailable"})
527                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
528                         :tag("item", { affiliation='none', role='none' }):up()
529                         :tag("destroy", {jid=newjid})
530         if reason then pr:tag("reason"):text(reason):up(); end
531         if password then pr:tag("password"):text(password):up(); end
532         for nick, occupant in pairs(self._occupants) do
533                 pr.attr.from = nick;
534                 for jid in pairs(occupant.sessions) do
535                         pr.attr.to = jid;
536                         self:_route_stanza(pr);
537                         self._jid_nick[jid] = nil;
538                 end
539                 self._occupants[nick] = nil;
540         end
541         self._data.persistent = nil;
542         if self.save then self:save(true); end
543 end
544
545 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
546         local type = stanza.attr.type;
547         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
548         if stanza.name == "iq" then
549                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
550                         origin.send(self:get_disco_info(stanza));
551                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
552                         origin.send(self:get_disco_items(stanza));
553                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
554                         local actor = stanza.attr.from;
555                         local affiliation = self:get_affiliation(actor);
556                         local current_nick = self._jid_nick[actor];
557                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
558                         local item = stanza.tags[1].tags[1];
559                         if item and item.name == "item" then
560                                 if type == "set" then
561                                         local callback = function() origin.send(st.reply(stanza)); end
562                                         if item.attr.jid then -- Validate provided JID
563                                                 item.attr.jid = jid_prep(item.attr.jid);
564                                                 if not item.attr.jid then
565                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
566                                                         return;
567                                                 end
568                                         end
569                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
570                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
571                                                 if occupant then item.attr.jid = occupant.jid; end
572                                         elseif not item.attr.nick and item.attr.jid then
573                                                 local nick = self._jid_nick[item.attr.jid];
574                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
575                                         end
576                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
577                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
578                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
579                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
580                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
581                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
582                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
583                                         else
584                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
585                                         end
586                                 elseif type == "get" then
587                                         local _aff = item.attr.affiliation;
588                                         local _rol = item.attr.role;
589                                         if _aff and not _rol then
590                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
591                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
592                                                         for jid, affiliation in pairs(self._affiliations) do
593                                                                 if affiliation == _aff then
594                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
595                                                                 end
596                                                         end
597                                                         origin.send(reply);
598                                                 else
599                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
600                                                 end
601                                         elseif _rol and not _aff then
602                                                 if role == "moderator" then
603                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
604                                                         if _rol == "none" then _rol = nil; end
605                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
606                                                         for occupant_jid, occupant in pairs(self._occupants) do
607                                                                 if occupant.role == _rol then
608                                                                         reply:tag("item", {
609                                                                                 nick = select(3, jid_split(occupant_jid)),
610                                                                                 role = _rol or "none",
611                                                                                 affiliation = occupant.affiliation or "none",
612                                                                                 jid = occupant.jid
613                                                                                 }):up();
614                                                                 end
615                                                         end
616                                                         origin.send(reply);
617                                                 else
618                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
619                                                 end
620                                         else
621                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
622                                         end
623                                 end
624                         elseif type == "set" or type == "get" then
625                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
626                         end
627                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
628                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
629                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
630                         elseif stanza.attr.type == "get" then
631                                 self:send_form(origin, stanza);
632                         elseif stanza.attr.type == "set" then
633                                 local child = stanza.tags[1].tags[1];
634                                 if not child then
635                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
636                                 elseif child.name == "destroy" then
637                                         local newjid = child.attr.jid;
638                                         local reason, password;
639                                         for _,tag in ipairs(child.tags) do
640                                                 if tag.name == "reason" then
641                                                         reason = #tag.tags == 0 and tag[1];
642                                                 elseif tag.name == "password" then
643                                                         password = #tag.tags == 0 and tag[1];
644                                                 end
645                                         end
646                                         self:destroy(newjid, reason, password);
647                                         origin.send(st.reply(stanza));
648                                 else
649                                         self:process_form(origin, stanza);
650                                 end
651                         end
652                 elseif type == "set" or type == "get" then
653                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
654                 end
655         elseif stanza.name == "message" and type == "groupchat" then
656                 local from, to = stanza.attr.from, stanza.attr.to;
657                 local room = jid_bare(to);
658                 local current_nick = self._jid_nick[from];
659                 local occupant = self._occupants[current_nick];
660                 if not occupant then -- not in room
661                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
662                 elseif occupant.role == "visitor" then
663                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
664                 else
665                         local from = stanza.attr.from;
666                         stanza.attr.from = current_nick;
667                         local subject = getText(stanza, {"subject"});
668                         if subject then
669                                 if occupant.role == "moderator" then
670                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
671                                 else
672                                         stanza.attr.from = from;
673                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
674                                 end
675                         else
676                                 self:broadcast_message(stanza, true);
677                         end
678                         stanza.attr.from = from;
679                 end
680         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
681                 local current_nick = self._jid_nick[stanza.attr.from];
682                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
683                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
684         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
685                 local to = stanza.attr.to;
686                 local current_nick = self._jid_nick[stanza.attr.from];
687                 if current_nick then
688                         stanza.attr.to = current_nick;
689                         self:handle_to_occupant(origin, stanza);
690                         stanza.attr.to = to;
691                 elseif type ~= "error" and type ~= "result" then
692                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
693                 end
694         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
695                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
696                 local x = stanza.tags[1];
697                 local payload = (#x.tags == 1 and x.tags[1]);
698                 if payload and payload.name == "invite" and payload.attr.to then
699                         local _from, _to = stanza.attr.from, stanza.attr.to;
700                         local _invitee = jid_prep(payload.attr.to);
701                         if _invitee then
702                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
703                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
704                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
705                                                 :tag('invite', {from=_from})
706                                                         :tag('reason'):text(_reason or ""):up()
707                                                 :up()
708                                         :up()
709                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
710                                                 :text(_reason or "")
711                                         :up()
712                                         :tag('body') -- Add a plain message for clients which don't support invites
713                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
714                                         :up();
715                                 self:_route_stanza(invite);
716                         else
717                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
718                         end
719                 else
720                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
721                 end
722         else
723                 if type == "error" or type == "result" then return; end
724                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
725         end
726 end
727
728 function room_mt:handle_stanza(origin, stanza)
729         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
730         if to_resource then
731                 self:handle_to_occupant(origin, stanza);
732         else
733                 self:handle_to_room(origin, stanza);
734         end
735 end
736
737 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
738
739 function room_mt:get_affiliation(jid)
740         local node, host, resource = jid_split(jid);
741         local bare = node and node.."@"..host or host;
742         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
743         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
744         return result;
745 end
746 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
747         jid = jid_bare(jid);
748         if affiliation == "none" then affiliation = nil; end
749         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
750                 return nil, "modify", "not-acceptable";
751         end
752         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
753         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
754         self._affiliations[jid] = affiliation;
755         local role = self:get_default_role(affiliation);
756         local p = st.presence()
757                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
758                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
759                                 :tag("reason"):text(reason or ""):up()
760                         :up();
761         local x = p.tags[1];
762         local item = x.tags[1];
763         if not role then -- getting kicked
764                 p.attr.type = "unavailable";
765                 if affiliation == "outcast" then
766                         x:tag("status", {code="301"}):up(); -- banned
767                 else
768                         x:tag("status", {code="321"}):up(); -- affiliation change
769                 end
770         end
771         local modified_nicks = {};
772         for nick, occupant in pairs(self._occupants) do
773                 if jid_bare(occupant.jid) == jid then
774                         if not role then -- getting kicked
775                                 self._occupants[nick] = nil;
776                         else
777                                 t_insert(modified_nicks, nick);
778                                 occupant.affiliation, occupant.role = affiliation, role;
779                         end
780                         p.attr.from = nick;
781                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
782                                 if not role then self._jid_nick[jid] = nil; end
783                                 p.attr.to = jid;
784                                 self:_route_stanza(p);
785                         end
786                 end
787         end
788         if self.save then self:save(); end
789         if callback then callback(); end
790         for _, nick in ipairs(modified_nicks) do
791                 p.attr.from = nick;
792                 self:broadcast_except_nick(p, nick);
793         end
794         return true;
795 end
796
797 function room_mt:get_role(nick)
798         local session = self._occupants[nick];
799         return session and session.role or nil;
800 end
801 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
802         if role == "none" then role = nil; end
803         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
804         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
805         local occupant = self._occupants[occupant_jid];
806         if not occupant then return nil, "modify", "not-acceptable"; end
807         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
808         local p = st.presence({from = occupant_jid})
809                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
810                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
811                                 :tag("reason"):text(reason or ""):up()
812                         :up();
813         if not role then -- kick
814                 p.attr.type = "unavailable";
815                 self._occupants[occupant_jid] = nil;
816                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
817                         self._jid_nick[jid] = nil;
818                 end
819                 p:tag("status", {code = "307"}):up();
820         else
821                 occupant.role = role;
822         end
823         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
824                 p.attr.to = jid;
825                 self:_route_stanza(p);
826         end
827         if callback then callback(); end
828         self:broadcast_except_nick(p, occupant_jid);
829         return true;
830 end
831
832 function room_mt:_route_stanza(stanza)
833         local muc_child;
834         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
835         local from_occupant = self._occupants[stanza.attr.from];
836         if stanza.name == "presence" then
837                 if to_occupant and from_occupant then
838                         if self._data.whois == 'anyone' then
839                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
840                         else
841                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
842                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
843                                 end
844                         end
845                 end
846         end
847         if muc_child then
848                 for _, item in pairs(muc_child.tags) do
849                         if item.name == "item" then
850                                 if from_occupant == to_occupant then
851                                         item.attr.jid = stanza.attr.to;
852                                 else
853                                         item.attr.jid = from_occupant.jid;
854                                 end
855                         end
856                 end
857                 if self._data.whois == 'anyone' then
858                     muc_child:tag('status', { code = '100' });
859                 end
860         end
861         self:route_stanza(stanza);
862         if muc_child then
863                 for _, item in pairs(muc_child.tags) do
864                         if item.name == "item" then
865                                 item.attr.jid = nil;
866                         end
867                 end
868         end
869 end
870
871 local _M = {}; -- module "muc"
872
873 function _M.new_room(jid)
874         return setmetatable({
875                 jid = jid;
876                 _jid_nick = {};
877                 _occupants = {};
878                 _data = {
879                     whois = 'moderators',
880                 };
881                 _affiliations = {};
882         }, room_mt);
883 end
884
885 return _M;