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