87353ad1cf27ef9a0e88bc9986e0a0bef1e3ea80
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
11
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60         ["malformed error"] = true;
61 };
62
63 local function get_error_condition(stanza)
64         local _, condition = stanza:get_error();
65         return condition or "malformed error";
66 end
67
68 local function is_kickable_error(stanza)
69         local cond = get_error_condition(stanza);
70         return kickable_error_conditions[cond] and cond;
71 end
72 local function getUsingPath(stanza, path, getText)
73         local tag = stanza;
74         for _, name in ipairs(path) do
75                 if type(tag) ~= 'table' then return; end
76                 tag = tag:child_with_name(name);
77         end
78         if tag and getText then tag = table.concat(tag); end
79         return tag;
80 end
81 local function getTag(stanza, path) return getUsingPath(stanza, path); end
82 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
83 -----------
84
85 local room_mt = {};
86 room_mt.__index = room_mt;
87
88 function room_mt:get_default_role(affiliation)
89         if affiliation == "owner" or affiliation == "admin" then
90                 return "moderator";
91         elseif affiliation == "member" then
92                 return "participant";
93         elseif not affiliation then
94                 if not self:is_members_only() then
95                         return self:is_moderated() and "visitor" or "participant";
96                 end
97         end
98 end
99
100 function room_mt:broadcast_presence(stanza, sid, code, nick)
101         stanza = get_filtered_presence(stanza);
102         local occupant = self._occupants[stanza.attr.from];
103         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
104                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
105         if code then
106                 stanza:tag("status", {code=code}):up();
107         end
108         self:broadcast_except_nick(stanza, stanza.attr.from);
109         local me = self._occupants[stanza.attr.from];
110         if me then
111                 stanza:tag("status", {code='110'});
112                 stanza.attr.to = sid;
113                 self:_route_stanza(stanza);
114         end
115 end
116 function room_mt:broadcast_message(stanza, historic)
117         local to = stanza.attr.to;
118         for occupant, o_data in pairs(self._occupants) do
119                 for jid in pairs(o_data.sessions) do
120                         stanza.attr.to = jid;
121                         self:_route_stanza(stanza);
122                 end
123         end
124         stanza.attr.to = to;
125         if historic then -- add to history
126                 local history = self._data['history'];
127                 if not history then history = {}; self._data['history'] = history; end
128                 stanza = st.clone(stanza);
129                 stanza.attr.to = "";
130                 local stamp = datetime.datetime();
131                 local chars = #tostring(stanza);
132                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
133                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
134                 local entry = { stanza = stanza, stamp = stamp };
135                 t_insert(history, entry);
136                 while #history > history_length do t_remove(history, 1) end
137         end
138 end
139 function room_mt:broadcast_except_nick(stanza, nick)
140         for rnick, occupant in pairs(self._occupants) do
141                 if rnick ~= nick then
142                         for jid in pairs(occupant.sessions) do
143                                 stanza.attr.to = jid;
144                                 self:_route_stanza(stanza);
145                         end
146                 end
147         end
148 end
149
150 function room_mt:send_occupant_list(to)
151         local current_nick = self._jid_nick[to];
152         for occupant, o_data in pairs(self._occupants) do
153                 if occupant ~= current_nick then
154                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
155                         pres.attr.to, pres.attr.from = to, occupant;
156                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
157                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
158                         self:_route_stanza(pres);
159                 end
160         end
161 end
162 function room_mt:send_history(to, stanza)
163         local history = self._data['history']; -- send discussion history
164         if history then
165                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
166                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
167                 
168                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
169                 if maxchars then maxchars = math.floor(maxchars); end
170                 
171                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
172                 if not history_tag then maxstanzas = 20; end
173
174                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
175                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
176
177                 local since = history_tag and history_tag.attr.since;
178                 if since and not since:match("^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ$") then since = nil; end -- FIXME timezone support
179                 if seconds and (not since or since < seconds) then since = seconds; end
180
181                 local n = 0;
182                 local charcount = 0;
183                 local stanzacount = 0;
184                 
185                 for i=#history,1,-1 do
186                         local entry = history[i];
187                         if maxchars then
188                                 if not entry.chars then
189                                         entry.stanza.attr.to = "";
190                                         entry.chars = #tostring(entry.stanza);
191                                 end
192                                 charcount = charcount + entry.chars + #to;
193                                 if charcount > maxchars then break; end
194                         end
195                         if since and since > entry.stamp then break; end
196                         if n + 1 > maxstanzas then break; end
197                         n = n + 1;
198                 end
199                 for i=#history-n+1,#history do
200                         local msg = history[i].stanza;
201                         msg.attr.to = to;
202                         self:_route_stanza(msg);
203                 end
204         end
205         if self._data['subject'] then
206                 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
207         end
208 end
209
210 function room_mt:get_disco_info(stanza)
211         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
212                 :tag("identity", {category="conference", type="text"}):up()
213                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
214                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
215                 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
216                 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
217                 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
218         ;
219 end
220 function room_mt:get_disco_items(stanza)
221         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
222         for room_jid in pairs(self._occupants) do
223                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
224         end
225         return reply;
226 end
227 function room_mt:set_subject(current_nick, subject)
228         -- TODO check nick's authority
229         if subject == "" then subject = nil; end
230         self._data['subject'] = subject;
231         if self.save then self:save(); end
232         local msg = st.message({type='groupchat', from=current_nick})
233                 :tag('subject'):text(subject):up();
234         self:broadcast_message(msg, false);
235         return true;
236 end
237
238 local function build_unavailable_presence_from_error(stanza)
239         local type, condition, text = stanza:get_error();
240         local error_message = "Kicked: "..condition:gsub("%-", " ");
241         if text then
242                 error_message = error_message..": "..text;
243         end
244         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
245                 :tag('status'):text(error_message);
246 end
247
248 function room_mt:set_password(password)
249         if password == "" or type(password) ~= "string" then password = nil; end
250         if self._data.password ~= password then
251                 self._data.password = password;
252                 if self.save then self:save(true); end
253         end
254 end
255 function room_mt:get_password()
256         return self._data.password;
257 end
258 function room_mt:set_moderated(moderated)
259         moderated = moderated and true or nil;
260         if self._data.moderated ~= moderated then
261                 self._data.moderated = moderated;
262                 if self.save then self:save(true); end
263         end
264 end
265 function room_mt:is_moderated()
266         return self._data.moderated;
267 end
268 function room_mt:set_members_only(members_only)
269         members_only = members_only and true or nil;
270         if self._data.members_only ~= members_only then
271                 self._data.members_only = members_only;
272                 if self.save then self:save(true); end
273         end
274 end
275 function room_mt:is_members_only()
276         return self._data.members_only;
277 end
278 function room_mt:set_persistent(persistent)
279         persistent = persistent and true or nil;
280         if self._data.persistent ~= persistent then
281                 self._data.persistent = persistent;
282                 if self.save then self:save(true); end
283         end
284 end
285 function room_mt:is_persistent()
286         return self._data.persistent;
287 end
288 function room_mt:set_hidden(hidden)
289         hidden = hidden and true or nil;
290         if self._data.hidden ~= hidden then
291                 self._data.hidden = hidden;
292                 if self.save then self:save(true); end
293         end
294 end
295 function room_mt:is_hidden()
296         return self._data.hidden;
297 end
298
299 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
300         local from, to = stanza.attr.from, stanza.attr.to;
301         local room = jid_bare(to);
302         local current_nick = self._jid_nick[from];
303         local type = stanza.attr.type;
304         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
305         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
306         if stanza.name == "presence" then
307                 local pr = get_filtered_presence(stanza);
308                 pr.attr.from = current_nick;
309                 if type == "error" then -- error, kick em out!
310                         if current_nick then
311                                 log("debug", "kicking %s from %s", current_nick, room);
312                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
313                         end
314                 elseif type == "unavailable" then -- unavailable
315                         if current_nick then
316                                 log("debug", "%s leaving %s", current_nick, room);
317                                 local occupant = self._occupants[current_nick];
318                                 local new_jid = next(occupant.sessions);
319                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
320                                 if new_jid then
321                                         local jid = occupant.jid;
322                                         occupant.jid = new_jid;
323                                         occupant.sessions[from] = nil;
324                                         pr.attr.to = from;
325                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
326                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
327                                                 :tag("status", {code='110'});
328                                         self:_route_stanza(pr);
329                                         if jid ~= new_jid then
330                                                 pr = st.clone(occupant.sessions[new_jid])
331                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
332                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
333                                                 pr.attr.from = current_nick;
334                                                 self:broadcast_except_nick(pr, current_nick);
335                                         end
336                                 else
337                                         occupant.role = 'none';
338                                         self:broadcast_presence(pr, from);
339                                         self._occupants[current_nick] = nil;
340                                 end
341                                 self._jid_nick[from] = nil;
342                         end
343                 elseif not type then -- available
344                         if current_nick then
345                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
346                                         if current_nick == to then -- simple presence
347                                                 log("debug", "%s broadcasted presence", current_nick);
348                                                 self._occupants[current_nick].sessions[from] = pr;
349                                                 self:broadcast_presence(pr, from);
350                                         else -- change nick
351                                                 local occupant = self._occupants[current_nick];
352                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
353                                                 if self._occupants[to] or is_multisession then
354                                                         log("debug", "%s couldn't change nick", current_nick);
355                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
356                                                         reply.tags[1].attr.code = "409";
357                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
358                                                 else
359                                                         local data = self._occupants[current_nick];
360                                                         local to_nick = select(3, jid_split(to));
361                                                         if to_nick then
362                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
363                                                                 local p = st.presence({type='unavailable', from=current_nick});
364                                                                 self:broadcast_presence(p, from, '303', to_nick);
365                                                                 self._occupants[current_nick] = nil;
366                                                                 self._occupants[to] = data;
367                                                                 self._jid_nick[from] = to;
368                                                                 pr.attr.from = to;
369                                                                 self._occupants[to].sessions[from] = pr;
370                                                                 self:broadcast_presence(pr, from);
371                                                         else
372                                                                 --TODO malformed-jid
373                                                         end
374                                                 end
375                                         end
376                                 --else -- possible rejoin
377                                 --      log("debug", "%s had connection replaced", current_nick);
378                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
379                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
380                                 --      self:handle_to_occupant(origin, stanza); -- resend available
381                                 --end
382                         else -- enter room
383                                 local new_nick = to;
384                                 local is_merge;
385                                 if self._occupants[to] then
386                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
387                                                 new_nick = nil;
388                                         end
389                                         is_merge = true;
390                                 end
391                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
392                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
393                                 password = password and password[1] ~= "" and password[1];
394                                 if self:get_password() and self:get_password() ~= password then
395                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
396                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
397                                         reply.tags[1].attr.code = "401";
398                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
399                                 elseif not new_nick then
400                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
401                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
402                                         reply.tags[1].attr.code = "409";
403                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
404                                 else
405                                         log("debug", "%s joining as %s", from, to);
406                                         if not next(self._affiliations) then -- new room, no owners
407                                                 self._affiliations[jid_bare(from)] = "owner";
408                                         end
409                                         local affiliation = self:get_affiliation(from);
410                                         local role = self:get_default_role(affiliation)
411                                         if role then -- new occupant
412                                                 if not is_merge then
413                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
414                                                 else
415                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
416                                                 end
417                                                 self._jid_nick[from] = to;
418                                                 self:send_occupant_list(from);
419                                                 pr.attr.from = to;
420                                                 if not is_merge then
421                                                         self:broadcast_presence(pr, from);
422                                                 else
423                                                         pr.attr.to = from;
424                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
425                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
426                                                                 :tag("status", {code='110'}));
427                                                 end
428                                                 self:send_history(from, stanza);
429                                         else -- banned
430                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
431                                                 reply.tags[1].attr.code = "403";
432                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
433                                         end
434                                 end
435                         end
436                 elseif type ~= 'result' then -- bad type
437                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
438                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
439                         end
440                 end
441         elseif not current_nick then -- not in room
442                 if type == "error" or type == "result" then
443                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
444                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
445                         local occupant = self._occupants[stanza.attr.to];
446                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
447                                 local id, _to = stanza.attr.id;
448                                 for jid in pairs(occupant.sessions) do
449                                         if md5(jid) == _hash then
450                                                 _to = jid;
451                                                 break;
452                                         end
453                                 end
454                                 if _to then
455                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
456                                         self:_route_stanza(stanza);
457                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
458                                 end
459                         end
460                 else
461                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
462                 end
463         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
464                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
465         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
466                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
467                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
468         else -- private stanza
469                 local o_data = self._occupants[to];
470                 if o_data then
471                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
472                         local jid = o_data.jid;
473                         local bare = jid_bare(jid);
474                         stanza.attr.to, stanza.attr.from = jid, current_nick;
475                         local id = stanza.attr.id;
476                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
477                                 stanza.attr.to = bare;
478                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
479                         end
480                         self:_route_stanza(stanza);
481                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
482                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
483                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
484                 end
485         end
486 end
487
488 function room_mt:send_form(origin, stanza)
489         local title = "Configuration for "..self.jid;
490         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
491                 :tag("x", {xmlns='jabber:x:data', type='form'})
492                         :tag("title"):text(title):up()
493                         :tag("instructions"):text(title):up()
494                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
495                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
496                                 :tag("value"):text(self:is_persistent() and "1" or "0"):up()
497                         :up()
498                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
499                                 :tag("value"):text(self:is_hidden() and "0" or "1"):up()
500                         :up()
501                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
502                             :tag("value"):text(self._data.whois or 'moderators'):up()
503                             :tag("option", {label = 'Moderators Only'})
504                                 :tag("value"):text('moderators'):up()
505                                 :up()
506                             :tag("option", {label = 'Anyone'})
507                                 :tag("value"):text('anyone'):up()
508                                 :up()
509                         :up()
510                         :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
511                                 :tag("value"):text(self:get_password() or ""):up()
512                         :up()
513                         :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
514                                 :tag("value"):text(self:is_moderated() and "1" or "0"):up()
515                         :up()
516                         :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
517                                 :tag("value"):text(self:is_members_only() and "1" or "0"):up()
518                         :up()
519         );
520 end
521
522 local valid_whois = {
523     moderators = true,
524     anyone = true,
525 }
526
527 function room_mt:process_form(origin, stanza)
528         local query = stanza.tags[1];
529         local form;
530         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
531         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
532         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
533         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
534         local fields = {};
535         for _, field in pairs(form.tags) do
536                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
537                         fields[field.attr.var] = field.tags[1][1] or "";
538                 end
539         end
540         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
541
542         local dirty = false
543
544         local persistent = fields['muc#roomconfig_persistentroom'];
545         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
546         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
547         dirty = dirty or (self:is_persistent() ~= persistent)
548         module:log("debug", "persistent=%s", tostring(persistent));
549
550         local moderated = fields['muc#roomconfig_moderatedroom'];
551         if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
552         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
553         dirty = dirty or (self:is_moderated() ~= moderated)
554         module:log("debug", "moderated=%s", tostring(moderated));
555
556         local membersonly = fields['muc#roomconfig_membersonly'];
557         if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
558         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
559         dirty = dirty or (self:is_members_only() ~= membersonly)
560         module:log("debug", "membersonly=%s", tostring(membersonly));
561
562         local public = fields['muc#roomconfig_publicroom'];
563         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
564         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
565         dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
566
567         local whois = fields['muc#roomconfig_whois'];
568         if not valid_whois[whois] then
569             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
570             return;
571         end
572         local whois_changed = self._data.whois ~= whois
573         self._data.whois = whois
574         module:log('debug', 'whois=%s', tostring(whois))
575
576         local password = fields['muc#roomconfig_roomsecret'];
577         if password then
578                 self:set_password(password);
579         end
580         self:set_moderated(moderated);
581         self:set_members_only(membersonly);
582         self:set_persistent(persistent);
583         self:set_hidden(not public);
584
585         if self.save then self:save(true); end
586         origin.send(st.reply(stanza));
587
588         if dirty or whois_changed then
589             local msg = st.message({type='groupchat', from=self.jid})
590                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
591
592             if dirty then
593                 msg.tags[1]:tag('status', {code = '104'})
594             end
595             if whois_changed then
596                 local code = (whois == 'moderators') and 173 or 172
597                 msg.tags[1]:tag('status', {code = code})
598             end
599
600             self:broadcast_message(msg, false)
601         end
602 end
603
604 function room_mt:destroy(newjid, reason, password)
605         local pr = st.presence({type = "unavailable"})
606                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
607                         :tag("item", { affiliation='none', role='none' }):up()
608                         :tag("destroy", {jid=newjid})
609         if reason then pr:tag("reason"):text(reason):up(); end
610         if password then pr:tag("password"):text(password):up(); end
611         for nick, occupant in pairs(self._occupants) do
612                 pr.attr.from = nick;
613                 for jid in pairs(occupant.sessions) do
614                         pr.attr.to = jid;
615                         self:_route_stanza(pr);
616                         self._jid_nick[jid] = nil;
617                 end
618                 self._occupants[nick] = nil;
619         end
620         self:set_persistent(false);
621 end
622
623 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
624         local type = stanza.attr.type;
625         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
626         if stanza.name == "iq" then
627                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
628                         origin.send(self:get_disco_info(stanza));
629                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
630                         origin.send(self:get_disco_items(stanza));
631                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
632                         local actor = stanza.attr.from;
633                         local affiliation = self:get_affiliation(actor);
634                         local current_nick = self._jid_nick[actor];
635                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
636                         local item = stanza.tags[1].tags[1];
637                         if item and item.name == "item" then
638                                 if type == "set" then
639                                         local callback = function() origin.send(st.reply(stanza)); end
640                                         if item.attr.jid then -- Validate provided JID
641                                                 item.attr.jid = jid_prep(item.attr.jid);
642                                                 if not item.attr.jid then
643                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
644                                                         return;
645                                                 end
646                                         end
647                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
648                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
649                                                 if occupant then item.attr.jid = occupant.jid; end
650                                         elseif not item.attr.nick and item.attr.jid then
651                                                 local nick = self._jid_nick[item.attr.jid];
652                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
653                                         end
654                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
655                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
656                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
657                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
658                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
659                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
660                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
661                                         else
662                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
663                                         end
664                                 elseif type == "get" then
665                                         local _aff = item.attr.affiliation;
666                                         local _rol = item.attr.role;
667                                         if _aff and not _rol then
668                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
669                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
670                                                         for jid, affiliation in pairs(self._affiliations) do
671                                                                 if affiliation == _aff then
672                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
673                                                                 end
674                                                         end
675                                                         origin.send(reply);
676                                                 else
677                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
678                                                 end
679                                         elseif _rol and not _aff then
680                                                 if role == "moderator" then
681                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
682                                                         if _rol == "none" then _rol = nil; end
683                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
684                                                         for occupant_jid, occupant in pairs(self._occupants) do
685                                                                 if occupant.role == _rol then
686                                                                         reply:tag("item", {
687                                                                                 nick = select(3, jid_split(occupant_jid)),
688                                                                                 role = _rol or "none",
689                                                                                 affiliation = occupant.affiliation or "none",
690                                                                                 jid = occupant.jid
691                                                                                 }):up();
692                                                                 end
693                                                         end
694                                                         origin.send(reply);
695                                                 else
696                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
697                                                 end
698                                         else
699                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
700                                         end
701                                 end
702                         elseif type == "set" or type == "get" then
703                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
704                         end
705                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
706                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
707                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
708                         elseif stanza.attr.type == "get" then
709                                 self:send_form(origin, stanza);
710                         elseif stanza.attr.type == "set" then
711                                 local child = stanza.tags[1].tags[1];
712                                 if not child then
713                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
714                                 elseif child.name == "destroy" then
715                                         local newjid = child.attr.jid;
716                                         local reason, password;
717                                         for _,tag in ipairs(child.tags) do
718                                                 if tag.name == "reason" then
719                                                         reason = #tag.tags == 0 and tag[1];
720                                                 elseif tag.name == "password" then
721                                                         password = #tag.tags == 0 and tag[1];
722                                                 end
723                                         end
724                                         self:destroy(newjid, reason, password);
725                                         origin.send(st.reply(stanza));
726                                 else
727                                         self:process_form(origin, stanza);
728                                 end
729                         end
730                 elseif type == "set" or type == "get" then
731                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
732                 end
733         elseif stanza.name == "message" and type == "groupchat" then
734                 local from, to = stanza.attr.from, stanza.attr.to;
735                 local room = jid_bare(to);
736                 local current_nick = self._jid_nick[from];
737                 local occupant = self._occupants[current_nick];
738                 if not occupant then -- not in room
739                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
740                 elseif occupant.role == "visitor" then
741                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
742                 else
743                         local from = stanza.attr.from;
744                         stanza.attr.from = current_nick;
745                         local subject = getText(stanza, {"subject"});
746                         if subject then
747                                 if occupant.role == "moderator" then
748                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
749                                 else
750                                         stanza.attr.from = from;
751                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
752                                 end
753                         else
754                                 self:broadcast_message(stanza, true);
755                         end
756                         stanza.attr.from = from;
757                 end
758         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
759                 local current_nick = self._jid_nick[stanza.attr.from];
760                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
761                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
762         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
763                 local to = stanza.attr.to;
764                 local current_nick = self._jid_nick[stanza.attr.from];
765                 if current_nick then
766                         stanza.attr.to = current_nick;
767                         self:handle_to_occupant(origin, stanza);
768                         stanza.attr.to = to;
769                 elseif type ~= "error" and type ~= "result" then
770                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
771                 end
772         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
773                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
774                 local x = stanza.tags[1];
775                 local payload = (#x.tags == 1 and x.tags[1]);
776                 if payload and payload.name == "invite" and payload.attr.to then
777                         local _from, _to = stanza.attr.from, stanza.attr.to;
778                         local _invitee = jid_prep(payload.attr.to);
779                         if _invitee then
780                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
781                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
782                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
783                                                 :tag('invite', {from=_from})
784                                                         :tag('reason'):text(_reason or ""):up()
785                                                 :up();
786                                                 if self:get_password() then
787                                                         invite:tag("password"):text(self:get_password()):up();
788                                                 end
789                                         invite:up()
790                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
791                                                 :text(_reason or "")
792                                         :up()
793                                         :tag('body') -- Add a plain message for clients which don't support invites
794                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
795                                         :up();
796                                 self:_route_stanza(invite);
797                         else
798                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
799                         end
800                 else
801                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
802                 end
803         else
804                 if type == "error" or type == "result" then return; end
805                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
806         end
807 end
808
809 function room_mt:handle_stanza(origin, stanza)
810         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
811         if to_resource then
812                 self:handle_to_occupant(origin, stanza);
813         else
814                 self:handle_to_room(origin, stanza);
815         end
816 end
817
818 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
819
820 function room_mt:get_affiliation(jid)
821         local node, host, resource = jid_split(jid);
822         local bare = node and node.."@"..host or host;
823         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
824         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
825         return result;
826 end
827 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
828         jid = jid_bare(jid);
829         if affiliation == "none" then affiliation = nil; end
830         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
831                 return nil, "modify", "not-acceptable";
832         end
833         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
834         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
835         self._affiliations[jid] = affiliation;
836         local role = self:get_default_role(affiliation);
837         local p = st.presence()
838                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
839                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
840                                 :tag("reason"):text(reason or ""):up()
841                         :up();
842         local x = p.tags[1];
843         local item = x.tags[1];
844         if not role then -- getting kicked
845                 p.attr.type = "unavailable";
846                 if affiliation == "outcast" then
847                         x:tag("status", {code="301"}):up(); -- banned
848                 else
849                         x:tag("status", {code="321"}):up(); -- affiliation change
850                 end
851         end
852         local modified_nicks = {};
853         for nick, occupant in pairs(self._occupants) do
854                 if jid_bare(occupant.jid) == jid then
855                         if not role then -- getting kicked
856                                 self._occupants[nick] = nil;
857                         else
858                                 t_insert(modified_nicks, nick);
859                                 occupant.affiliation, occupant.role = affiliation, role;
860                         end
861                         p.attr.from = nick;
862                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
863                                 if not role then self._jid_nick[jid] = nil; end
864                                 p.attr.to = jid;
865                                 self:_route_stanza(p);
866                         end
867                 end
868         end
869         if self.save then self:save(); end
870         if callback then callback(); end
871         for _, nick in ipairs(modified_nicks) do
872                 p.attr.from = nick;
873                 self:broadcast_except_nick(p, nick);
874         end
875         return true;
876 end
877
878 function room_mt:get_role(nick)
879         local session = self._occupants[nick];
880         return session and session.role or nil;
881 end
882 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
883         if role == "none" then role = nil; end
884         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
885         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
886         local occupant = self._occupants[occupant_jid];
887         if not occupant then return nil, "modify", "not-acceptable"; end
888         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
889         local p = st.presence({from = occupant_jid})
890                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
891                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
892                                 :tag("reason"):text(reason or ""):up()
893                         :up();
894         if not role then -- kick
895                 p.attr.type = "unavailable";
896                 self._occupants[occupant_jid] = nil;
897                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
898                         self._jid_nick[jid] = nil;
899                 end
900                 p:tag("status", {code = "307"}):up();
901         else
902                 occupant.role = role;
903         end
904         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
905                 p.attr.to = jid;
906                 self:_route_stanza(p);
907         end
908         if callback then callback(); end
909         self:broadcast_except_nick(p, occupant_jid);
910         return true;
911 end
912
913 function room_mt:_route_stanza(stanza)
914         local muc_child;
915         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
916         local from_occupant = self._occupants[stanza.attr.from];
917         if stanza.name == "presence" then
918                 if to_occupant and from_occupant then
919                         if self._data.whois == 'anyone' then
920                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
921                         else
922                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
923                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
924                                 end
925                         end
926                 end
927         end
928         if muc_child then
929                 for _, item in pairs(muc_child.tags) do
930                         if item.name == "item" then
931                                 if from_occupant == to_occupant then
932                                         item.attr.jid = stanza.attr.to;
933                                 else
934                                         item.attr.jid = from_occupant.jid;
935                                 end
936                         end
937                 end
938                 if self._data.whois == 'anyone' then
939                     muc_child:tag('status', { code = '100' });
940                 end
941         end
942         self:route_stanza(stanza);
943         if muc_child then
944                 for _, item in pairs(muc_child.tags) do
945                         if item.name == "item" then
946                                 item.attr.jid = nil;
947                         end
948                 end
949         end
950 end
951
952 local _M = {}; -- module "muc"
953
954 function _M.new_room(jid)
955         return setmetatable({
956                 jid = jid;
957                 _jid_nick = {};
958                 _occupants = {};
959                 _data = {
960                     whois = 'moderators',
961                 };
962                 _affiliations = {};
963         }, room_mt);
964 end
965
966 return _M;