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