6d74c7ba9613ecddf4599918470081d0c23c4633
[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 st = require "util.stanza";
15 local log = require "util.logger".init("mod_muc");
16 local multitable_new = require "util.multitable".new;
17 local t_insert, t_remove = table.insert, table.remove;
18 local setmetatable = setmetatable;
19 local base64 = require "util.encodings".base64;
20 local md5 = require "util.hashes".md5;
21
22 local muc_domain = nil; --module:get_host();
23 local history_length = 20;
24
25 ------------
26 local function filter_xmlns_from_array(array, filters)
27         local count = 0;
28         for i=#array,1,-1 do
29                 local attr = array[i].attr;
30                 if filters[attr and attr.xmlns] then
31                         t_remove(array, i);
32                         count = count + 1;
33                 end
34         end
35         return count;
36 end
37 local function filter_xmlns_from_stanza(stanza, filters)
38         if filters then
39                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
40                         return stanza, filter_xmlns_from_array(stanza, filters);
41                 end
42         end
43         return stanza, 0;
44 end
45 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
46 local function get_filtered_presence(stanza)
47         return filter_xmlns_from_stanza(st.clone(stanza), presence_filters);
48 end
49 local kickable_error_conditions = {
50         ["gone"] = true;
51         ["internal-server-error"] = true;
52         ["item-not-found"] = true;
53         ["jid-malformed"] = true;
54         ["recipient-unavailable"] = true;
55         ["redirect"] = true;
56         ["remote-server-not-found"] = true;
57         ["remote-server-timeout"] = true;
58         ["service-unavailable"] = true;
59 };
60 local function get_kickable_error(stanza)
61         for _, tag in ipairs(stanza.tags) do
62                 if tag.name == "error" and tag.attr.xmlns == "jabber:client" then
63                         for _, cond in ipairs(tag.tags) do
64                                 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
65                                         return kickable_error_conditions[cond.name] and cond.name;
66                                 end
67                         end
68                         return true; -- malformed error message
69                 end
70         end
71         return true; -- malformed error message
72 end
73 local function getUsingPath(stanza, path, getText)
74         local tag = stanza;
75         for _, name in ipairs(path) do
76                 if type(tag) ~= 'table' then return; end
77                 tag = tag:child_with_name(name);
78         end
79         if tag and getText then tag = table.concat(tag); end
80         return tag;
81 end
82 local function getTag(stanza, path) return getUsingPath(stanza, path); end
83 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
84 -----------
85
86 --[[function get_room_disco_info(room, stanza)
87         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
88                 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
89                 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
90 end
91 function get_room_disco_items(room, stanza)
92         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
93 end -- TODO allow non-private rooms]]
94
95 --
96
97 local room_mt = {};
98 room_mt.__index = room_mt;
99
100 function room_mt:get_default_role(affiliation)
101         if affiliation == "owner" or affiliation == "admin" then
102                 return "moderator";
103         elseif affiliation == "member" or not affiliation then
104                 return "participant";
105         end
106 end
107
108 function room_mt:broadcast_presence(stanza, code, nick)
109         stanza = get_filtered_presence(stanza);
110         local data = self._occupants[stanza.attr.from];
111         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
112                 :tag("item", {affiliation=data.affiliation, role=data.role, nick=nick}):up();
113         if code then
114                 stanza:tag("status", {code=code}):up();
115         end
116         local me;
117         for occupant, o_data in pairs(self._occupants) do
118                 if occupant ~= stanza.attr.from then
119                         for jid in pairs(o_data.sessions) do
120                                 stanza.attr.to = jid;
121                                 self:route_stanza(stanza);
122                         end
123                 else
124                         me = o_data;
125                 end
126         end
127         if me then
128                 stanza:tag("status", {code='110'});
129                 for jid in pairs(me.sessions) do
130                         stanza.attr.to = jid;
131                         self:route_stanza(stanza);
132                 end
133         end
134 end
135 function room_mt:broadcast_message(stanza, historic)
136         for occupant, o_data in pairs(self._occupants) do
137                 for jid in pairs(o_data.sessions) do
138                         stanza.attr.to = jid;
139                         self:route_stanza(stanza);
140                 end
141         end
142         if historic then -- add to history
143                 local history = self._data['history'];
144                 if not history then history = {}; self._data['history'] = history; end
145                 -- stanza = st.clone(stanza);
146                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
147                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
148                 t_insert(history, st.clone(st.preserialize(stanza)));
149                 while #history > history_length do t_remove(history, 1) end
150         end
151 end
152 function room_mt:broadcast_except_nick(stanza, nick)
153         for rnick, occupant in pairs(self._occupants) do
154                 if rnick ~= nick then
155                         for jid in pairs(occupant.sessions) do
156                                 stanza.attr.to = jid;
157                                 self:route_stanza(stanza);
158                         end
159                 end
160         end
161 end
162
163 function room_mt:send_occupant_list(to)
164         local current_nick = self._jid_nick[to];
165         for occupant, o_data in pairs(self._occupants) do
166                 if occupant ~= current_nick then
167                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
168                         pres.attr.to, pres.attr.from = to, occupant;
169                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
170                                 :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
171                         self:route_stanza(pres);
172                 end
173         end
174 end
175 function room_mt:send_history(to)
176         local history = self._data['history']; -- send discussion history
177         if history then
178                 for _, msg in ipairs(history) do
179                         msg = st.deserialize(msg);
180                         msg.attr.to=to;
181                         self:route_stanza(msg);
182                 end
183         end
184         if self._data['subject'] then
185                 self:route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
186         end
187 end
188
189 local function room_get_disco_info(self, stanza)
190         return st.reply(stanza):query("http://jabber.org/protocol/disco#info"):tag("identity", {category="conference", type="text"});
191 end
192 local function room_get_disco_items(self, stanza)
193         return st.reply(stanza):query("http://jabber.org/protocol/disco#items");
194 end
195 function room_mt:set_subject(current_nick, subject)
196         -- TODO check nick's authority
197         if subject == "" then subject = nil; end
198         self._data['subject'] = subject;
199         if self.save then self:save(); end
200         local msg = st.message({type='groupchat', from=current_nick})
201                 :tag('subject'):text(subject):up();
202         self:broadcast_message(msg, false);
203         return true;
204 end
205
206 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
207         local from, to = stanza.attr.from, stanza.attr.to;
208         local room = jid_bare(to);
209         local current_nick = self._jid_nick[from];
210         local type = stanza.attr.type;
211         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
212         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
213         if stanza.name == "presence" then
214                 local pr = get_filtered_presence(stanza);
215                 pr.attr.from = current_nick;
216                 if type == "error" then -- error, kick em out!
217                         if current_nick then
218                                 log("debug", "kicking %s from %s", current_nick, room);
219                                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
220                                         :tag('status'):text('This participant is kicked from the room because he sent an error presence')); -- send unavailable
221                         end
222                 elseif type == "unavailable" then -- unavailable
223                         if current_nick then
224                                 log("debug", "%s leaving %s", current_nick, room);
225                                 local data = self._occupants[current_nick];
226                                 data.role = 'none';
227                                 self:broadcast_presence(pr);
228                                 self._occupants[current_nick] = nil;
229                                 self._jid_nick[from] = nil;
230                         end
231                 elseif not type then -- available
232                         if current_nick then
233                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
234                                         if current_nick == to then -- simple presence
235                                                 log("debug", "%s broadcasted presence", current_nick);
236                                                 self._occupants[current_nick].sessions[from] = pr;
237                                                 self:broadcast_presence(pr);
238                                         else -- change nick
239                                                 if self._occupants[to] then
240                                                         log("debug", "%s couldn't change nick", current_nick);
241                                                         origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
242                                                 else
243                                                         local data = self._occupants[current_nick];
244                                                         local to_nick = select(3, jid_split(to));
245                                                         if to_nick then
246                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
247                                                                 local p = st.presence({type='unavailable', from=current_nick});
248                                                                 self:broadcast_presence(p, '303', to_nick);
249                                                                 self._occupants[current_nick] = nil;
250                                                                 self._occupants[to] = data;
251                                                                 self._jid_nick[from] = to;
252                                                                 pr.attr.from = to;
253                                                                 self._occupants[to].sessions[from] = pr;
254                                                                 self:broadcast_presence(pr);
255                                                         else
256                                                                 --TODO malformed-jid
257                                                         end
258                                                 end
259                                         end
260                                 --else -- possible rejoin
261                                 --      log("debug", "%s had connection replaced", current_nick);
262                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
263                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
264                                 --      self:handle_to_occupant(origin, stanza); -- resend available
265                                 --end
266                         else -- enter room
267                                 local new_nick = to;
268                                 if self._occupants[to] then
269                                         new_nick = nil;
270                                 end
271                                 if not new_nick then
272                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
273                                         origin.send(st.error_reply(stanza, "cancel", "conflict"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
274                                 else
275                                         log("debug", "%s joining as %s", from, to);
276                                         if not next(self._affiliations) then -- new room, no owners
277                                                 self._affiliations[jid_bare(from)] = "owner";
278                                         end
279                                         local affiliation = self:get_affiliation(from);
280                                         local role = self:get_default_role(affiliation)
281                                         if role then -- new occupant
282                                                 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
283                                                 self._jid_nick[from] = to;
284                                                 self:send_occupant_list(from);
285                                                 pr.attr.from = to;
286                                                 self:broadcast_presence(pr);
287                                                 self:send_history(from);
288                                         else -- banned
289                                                 origin.send(st.error_reply(stanza, "auth", "forbidden"):tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
290                                         end
291                                 end
292                         end
293                 elseif type ~= 'result' then -- bad type
294                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
295                 end
296         elseif not current_nick then -- not in room
297                 if type == "error" or type == "result" then
298                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
299                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
300                         local occupant = self._occupants[stanza.attr.to];
301                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
302                                 local id, _to = stanza.attr.id;
303                                 for jid in pairs(occupant.sessions) do
304                                         if md5(jid) == _hash then
305                                                 _to = jid;
306                                                 break;
307                                         end
308                                 end
309                                 if _to then
310                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
311                                         self:route_stanza(stanza);
312                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
313                                 end
314                         end
315                 else
316                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
317                 end
318         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
319                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
320         else -- private stanza
321                 local o_data = self._occupants[to];
322                 if o_data then
323                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
324                         local jid = o_data.jid;
325                         local bare = jid_bare(jid);
326                         stanza.attr.to, stanza.attr.from = jid, current_nick;
327                         local id = stanza.attr.id;
328                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
329                                 stanza.attr.to = bare;
330                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
331                         end
332                         self:route_stanza(stanza);
333                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
334                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
335                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
336                 end
337         end
338 end
339
340 function room_mt:handle_form(origin, stanza)
341         if self:get_affiliation(stanza.attr.from) ~= "owner" then origin.send(st.error_reply(stanza, "auth", "forbidden")); return; end
342         if stanza.attr.type == "get" then
343                 local title = "Configuration for "..self.jid;
344                 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
345                         :tag("x", {xmlns='jabber:x:data', type='form'})
346                                 :tag("title"):text(title):up()
347                                 :tag("instructions"):text(title):up()
348                                 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
349                                 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
350                                         :tag("value"):text(self._data.persistent and "1" or "0"):up()
351                                 :up()
352                                 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
353                                         :tag("value"):text(self._data.hidden and "0" or "1"):up()
354                                 :up()
355                 );
356         elseif stanza.attr.type == "set" then
357                 local query = stanza.tags[1];
358                 local form;
359                 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
360                 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
361                 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
362                 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
363                 local fields = {};
364                 for _, field in pairs(form.tags) do
365                         if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
366                                 fields[field.attr.var] = field.tags[1][1] or "";
367                         end
368                 end
369                 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
370
371                 local persistent = fields['muc#roomconfig_persistentroom'];
372                 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
373                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
374                 self._data.persistent = persistent;
375                 module:log("debug", "persistent=%s", tostring(persistent));
376
377                 local public = fields['muc#roomconfig_publicroom'];
378                 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
379                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
380                 self._data.hidden = not public and true or nil;
381
382                 if self.save then self:save(true); end
383                 origin.send(st.reply(stanza));
384         end
385 end
386
387 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
388         local type = stanza.attr.type;
389         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
390         if stanza.name == "iq" then
391                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
392                         origin.send(room_get_disco_info(self, stanza));
393                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
394                         origin.send(room_get_disco_items(self, stanza));
395                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
396                         local actor = stanza.attr.from;
397                         local affiliation = self:get_affiliation(actor);
398                         local current_nick = self._jid_nick[actor];
399                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
400                         local item = stanza.tags[1].tags[1];
401                         if item and item.name == "item" then
402                                 if type == "set" then
403                                         local callback = function() origin.send(st.reply(stanza)); end
404                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
405                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
406                                                 if occupant then item.attr.jid = occupant.jid; end
407                                         end
408                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
409                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback);
410                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
411                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
412                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback);
413                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
414                                         else
415                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
416                                         end
417                                 elseif type == "get" then
418                                         local _aff = item.attr.affiliation;
419                                         local _rol = item.attr.role;
420                                         if _aff and not _rol then
421                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
422                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
423                                                         for jid, affiliation in pairs(self._affiliations) do
424                                                                 if affiliation == _aff then
425                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
426                                                                 end
427                                                         end
428                                                         origin.send(reply);
429                                                 else
430                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
431                                                 end
432                                         elseif _rol and not _aff then
433                                                 if role == "moderator" then
434                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
435                                                         if _rol == "none" then _rol = nil; end
436                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
437                                                         for nick, occupant in pairs(self._occupants) do
438                                                                 if occupant.role == _rol then
439                                                                         reply:tag("item", {nick = nick, role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid}):up();
440                                                                 end
441                                                         end
442                                                         origin.send(reply);
443                                                 else
444                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
445                                                 end
446                                         else
447                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
448                                         end
449                                 end
450                         elseif type == "set" or type == "get" then
451                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
452                         end
453                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
454                         self:handle_form(origin, stanza);
455                 elseif type == "set" or type == "get" then
456                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
457                 end
458         elseif stanza.name == "message" and type == "groupchat" then
459                 local from, to = stanza.attr.from, stanza.attr.to;
460                 local room = jid_bare(to);
461                 local current_nick = self._jid_nick[from];
462                 if not current_nick then -- not in room
463                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
464                 else
465                         local from = stanza.attr.from;
466                         stanza.attr.from = current_nick;
467                         local subject = getText(stanza, {"subject"});
468                         if subject then
469                                 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
470                         else
471                                 self:broadcast_message(stanza, true);
472                         end
473                 end
474         elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
475                 local current_nick = self._jid_nick[stanza.attr.from];
476                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
477                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
478                         :tag('status'):text('This participant is kicked from the room because he sent an error message to another occupant')); -- send unavailable
479         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
480                 local to = stanza.attr.to;
481                 local current_nick = self._jid_nick[stanza.attr.from];
482                 if current_nick then
483                         stanza.attr.to = current_nick;
484                         self:handle_to_occupant(origin, stanza);
485                         stanza.attr.to = to;
486                 elseif type ~= "error" and type ~= "result" then
487                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
488                 end
489         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
490                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
491                 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
492                 local _from, _to = stanza.attr.from, stanza.attr.to;
493                 local _invitee = stanza.tags[1].tags[1].attr.to;
494                 stanza.attr.from, stanza.attr.to = _to, _invitee;
495                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
496                 self:route_stanza(stanza);
497                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
498                 stanza.attr.from, stanza.attr.to = _from, _to;
499         else
500                 if type == "error" or type == "result" then return; end
501                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
502         end
503 end
504
505 function room_mt:handle_stanza(origin, stanza)
506         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
507         if to_resource then
508                 self:handle_to_occupant(origin, stanza);
509         else
510                 self:handle_to_room(origin, stanza);
511         end
512 end
513
514 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
515
516 function room_mt:get_affiliation(jid)
517         local node, host, resource = jid_split(jid);
518         local bare = node and node.."@"..host or host;
519         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
520         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
521         return result;
522 end
523 function room_mt:set_affiliation(actor, jid, affiliation, callback)
524         jid = jid_bare(jid);
525         if affiliation == "none" then affiliation = nil; end
526         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
527                 return nil, "modify", "not-acceptable";
528         end
529         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
530         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
531         self._affiliations[jid] = affiliation;
532         local role = self:get_default_role(affiliation);
533         local p = st.presence()
534                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
535                         :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
536         local x = p.tags[1];
537         local item = x.tags[1];
538         if not role then -- getting kicked
539                 p.attr.type = "unavailable";
540                 if affiliation == "outcast" then
541                         x:tag("status", {code="301"}):up(); -- banned
542                 else
543                         x:tag("status", {code="321"}):up(); -- affiliation change
544                 end
545         end
546         local modified_nicks = {};
547         for nick, occupant in pairs(self._occupants) do
548                 if jid_bare(occupant.jid) == jid then
549                         if not role then -- getting kicked
550                                 self._occupants[nick] = nil;
551                         else
552                                 t_insert(modified_nicks, nick);
553                                 occupant.affiliation, occupant.role = affiliation, role;
554                         end
555                         p.attr.from = nick;
556                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
557                                 if not role then self._jid_nick[jid] = nil; end
558                                 p.attr.to = jid;
559                                 self:route_stanza(p);
560                         end
561                 end
562         end
563         if self.save then self:save(); end
564         if callback then callback(); end
565         for _, nick in ipairs(modified_nicks) do
566                 p.attr.from = nick;
567                 self:broadcast_except_nick(p, nick);
568         end
569         return true;
570 end
571
572 function room_mt:get_role(nick)
573         local session = self._occupants[nick];
574         return session and session.role or nil;
575 end
576 function room_mt:set_role(actor, nick, role, callback)
577         if role == "none" then role = nil; end
578         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
579         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
580         local occupant = self._occupants[nick];
581         if not occupant then return nil, "modify", "not-acceptable"; end
582         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
583         local p = st.presence({from = nick})
584                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
585                         :tag("item", {affiliation=occupant.affiliation or "none", nick=nick, role=role or "none"}):up();
586         if not role then -- kick
587                 p.attr.type = "unavailable";
588                 self._occupants[nick] = nil;
589                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
590                         self._jid_nick[jid] = nil;
591                 end
592                 p:tag("status", {code = "307"}):up();
593         else
594                 occupant.role = role;
595         end
596         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
597                 p.attr.to = jid;
598                 self:route_stanza(p);
599         end
600         if callback then callback(); end
601         self:broadcast_except_nick(p, nick);
602         return true;
603 end
604
605 local _M = {}; -- module "muc"
606
607 function _M.new_room(jid)
608         return setmetatable({
609                 jid = jid;
610                 _jid_nick = {};
611                 _occupants = {};
612                 _data = {};
613                 _affiliations = {};
614         }, room_mt);
615 end
616
617 return _M;