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