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