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