MUC: Always return <service-unavailable/> when a node is present in service discovery...
[prosody.git] / plugins / muc / muc.lib.lua
index 1359d21ddf11ea32401ddea77eaff23469d4553c..91b4792d9d30fb72539ea69fc1a4272debd0b5f1 100644 (file)
@@ -9,22 +9,22 @@
 local select = select;
 local pairs, ipairs = pairs, ipairs;
 
-local datamanager = require "util.datamanager";
 local datetime = require "util.datetime";
 
+local dataform = require "util.dataforms";
+
 local jid_split = require "util.jid".split;
 local jid_bare = require "util.jid".bare;
 local jid_prep = require "util.jid".prep;
 local st = require "util.stanza";
 local log = require "util.logger".init("mod_muc");
-local multitable_new = require "util.multitable".new;
 local t_insert, t_remove = table.insert, table.remove;
 local setmetatable = setmetatable;
 local base64 = require "util.encodings".base64;
 local md5 = require "util.hashes".md5;
 
 local muc_domain = nil; --module:get_host();
-local default_history_length = 20;
+local default_history_length, max_history_length = 20, math.huge;
 
 ------------
 local function filter_xmlns_from_array(array, filters)
@@ -111,7 +111,7 @@ function room_mt:broadcast_presence(stanza, sid, code, nick)
        self:broadcast_except_nick(stanza, stanza.attr.from);
        local me = self._occupants[stanza.attr.from];
        if me then
-               stanza:tag("status", {code='110'});
+               stanza:tag("status", {code='110'}):up();
                stanza.attr.to = sid;
                self:_route_stanza(stanza);
        end
@@ -131,7 +131,6 @@ function room_mt:broadcast_message(stanza, historic)
                stanza = st.clone(stanza);
                stanza.attr.to = "";
                local stamp = datetime.datetime();
-               local chars = #tostring(stanza);
                stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
                stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
                local entry = { stanza = stanza, stamp = stamp };
@@ -178,12 +177,11 @@ function room_mt:send_history(to, stanza)
                if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
 
                local since = history_tag and history_tag.attr.since;
-               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
+               if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
                if seconds and (not since or since < seconds) then since = seconds; end
 
                local n = 0;
                local charcount = 0;
-               local stanzacount = 0;
                
                for i=#history,1,-1 do
                        local entry = history[i];
@@ -211,6 +209,7 @@ function room_mt:send_history(to, stanza)
 end
 
 function room_mt:get_disco_info(stanza)
+       local count = 0; for _ in pairs(self._occupants) do count = count + 1; end
        return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
                :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
                :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
@@ -220,14 +219,11 @@ function room_mt:get_disco_info(stanza)
                :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
                :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
                :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
-               :tag("x", {xmlns="jabber:x:data", type="result"})
-                       :tag("field", {var="FORM_TYPE", type="hidden"})
-                               :tag("value"):text("http://jabber.org/protocol/muc#roominfo"):up()
-                       :up()
-                       :tag("field", {var="muc#roominfo_description", label="Description"})
-                               :tag("value"):text(self:get_description()):up()
-                       :up()
-               :up()   
+               :add_child(dataform.new({
+                       { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
+                       { name = "muc#roominfo_description", label = "Description"},
+                       { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
+               }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
        ;
 end
 function room_mt:get_disco_items(stanza)
@@ -251,7 +247,7 @@ end
 
 local function build_unavailable_presence_from_error(stanza)
        local type, condition, text = stanza:get_error();
-       local error_message = "Kicked: "..condition:gsub("%-", " ");
+       local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
        if text then
                error_message = error_message..": "..text;
        end
@@ -260,14 +256,14 @@ local function build_unavailable_presence_from_error(stanza)
 end
 
 function room_mt:set_name(name)
-       if name == "" or type(name) ~= "string" then name = nil; end
+       if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
        if self._data.name ~= name then
                self._data.name = name;
                if self.save then self:save(true); end
        end
 end
 function room_mt:get_name()
-       return self._data.name;
+       return self._data.name or jid_split(self.jid);
 end
 function room_mt:set_description(description)
        if description == "" or type(description) ~= "string" then description = nil; end
@@ -329,6 +325,52 @@ end
 function room_mt:is_hidden()
        return self._data.hidden;
 end
+function room_mt:set_changesubject(changesubject)
+       changesubject = changesubject and true or nil;
+       if self._data.changesubject ~= changesubject then
+               self._data.changesubject = changesubject;
+               if self.save then self:save(true); end
+       end
+end
+function room_mt:get_changesubject()
+       return self._data.changesubject;
+end
+function room_mt:get_historylength()
+       return self._data.history_length or default_history_length;
+end
+function room_mt:set_historylength(length)
+       length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
+       if length == default_history_length then
+               length = nil;
+       end
+       self._data.history_length = length;
+end
+
+
+local function construct_stanza_id(room, stanza)
+       local from_jid, to_nick = stanza.attr.from, stanza.attr.to;
+       local from_nick = room._jid_nick[from_jid];
+       local occupant = room._occupants[to_nick];
+       local to_jid = occupant.jid;
+       
+       return from_nick, to_jid, base64.encode(to_jid.."\0"..stanza.attr.id.."\0"..md5(from_jid));
+end
+local function deconstruct_stanza_id(room, stanza)
+       local from_jid_possiblybare, to_nick = stanza.attr.from, stanza.attr.to;
+       local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
+       local from_nick = room._jid_nick[from_jid];
+
+       if not(from_nick) then return; end
+       if not(from_jid_possiblybare == from_jid or from_jid_possiblybare == jid_bare(from_jid)) then return; end
+
+       local occupant = room._occupants[to_nick];
+       for to_jid in pairs(occupant and occupant.sessions or {}) do
+               if md5(to_jid) == to_jid_hash then
+                       return from_nick, to_jid, id;
+               end
+       end
+end
+
 
 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
        local from, to = stanza.attr.from, stanza.attr.to;
@@ -348,6 +390,7 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                elseif type == "unavailable" then -- unavailable
                        if current_nick then
                                log("debug", "%s leaving %s", current_nick, room);
+                               self._jid_nick[from] = nil;
                                local occupant = self._occupants[current_nick];
                                local new_jid = next(occupant.sessions);
                                if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
@@ -358,7 +401,7 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                                        pr.attr.to = from;
                                        pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
                                                :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
-                                               :tag("status", {code='110'});
+                                               :tag("status", {code='110'}):up();
                                        self:_route_stanza(pr);
                                        if jid ~= new_jid then
                                                pr = st.clone(occupant.sessions[new_jid])
@@ -372,7 +415,6 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                                        self:broadcast_presence(pr, from);
                                        self._occupants[current_nick] = nil;
                                end
-                               self._jid_nick[from] = nil;
                        end
                elseif not type then -- available
                        if current_nick then
@@ -451,14 +493,17 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                                                self._jid_nick[from] = to;
                                                self:send_occupant_list(from);
                                                pr.attr.from = to;
+                                               pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
+                                                       :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
                                                if not is_merge then
-                                                       self:broadcast_presence(pr, from);
-                                               else
-                                                       pr.attr.to = from;
-                                                       self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
-                                                               :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
-                                                               :tag("status", {code='110'}));
+                                                       self:broadcast_except_nick(pr, to);
                                                end
+                                               pr:tag("status", {code='110'}):up();
+                                               if self._data.whois == 'anyone' then
+                                                       pr:tag("status", {code='100'}):up();
+                                               end
+                                               pr.attr.to = from;
+                                               self:_route_stanza(pr);
                                                self:send_history(from, stanza);
                                        elseif not affiliation then -- registration required for entering members-only room
                                                local reply = st.error_reply(stanza, "auth", "registration-required"):up();
@@ -477,25 +522,14 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                        end
                end
        elseif not current_nick then -- not in room
-               if type == "error" or type == "result" then
-                       local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
-                       local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
-                       local occupant = self._occupants[stanza.attr.to];
-                       if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
-                               local id, _to = stanza.attr.id;
-                               for jid in pairs(occupant.sessions) do
-                                       if md5(jid) == _hash then
-                                               _to = jid;
-                                               break;
-                                       end
-                               end
-                               if _to then
-                                       stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
-                                       self:_route_stanza(stanza);
-                                       stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
-                               end
+               if (type == "error" or type == "result") and stanza.name == "iq" then
+                       local id = stanza.attr.id;
+                       stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
+                       if stanza.attr.id then
+                               self:_route_stanza(stanza);
                        end
-               else
+                       stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
+               elseif type ~= "error" then
                        origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
                end
        elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
@@ -507,16 +541,28 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
                local o_data = self._occupants[to];
                if o_data then
                        log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
-                       local jid = o_data.jid;
-                       local bare = jid_bare(jid);
-                       stanza.attr.to, stanza.attr.from = jid, current_nick;
-                       local id = stanza.attr.id;
-                       if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
-                               stanza.attr.to = bare;
-                               stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
+                       if stanza.name == "iq" then
+                               local id = stanza.attr.id;
+                               if stanza.attr.type == "get" or stanza.attr.type == "set" then
+                                       stanza.attr.from, stanza.attr.to, stanza.attr.id = construct_stanza_id(self, stanza);
+                               else
+                                       stanza.attr.from, stanza.attr.to, stanza.attr.id = deconstruct_stanza_id(self, stanza);
+                               end
+                               if type == 'get' and stanza.tags[1].attr.xmlns == 'vcard-temp' then
+                                       stanza.attr.to = jid_bare(stanza.attr.to);
+                               end
+                               if stanza.attr.id then
+                                       self:_route_stanza(stanza);
+                               end
+                               stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
+                       else -- message
+                               stanza.attr.from = current_nick;
+                               for jid in pairs(o_data.sessions) do
+                                       stanza.attr.to = jid;
+                                       self:_route_stanza(stanza);
+                               end
+                               stanza.attr.from, stanza.attr.to = from, to;
                        end
-                       self:_route_stanza(stanza);
-                       stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
                elseif type ~= "error" and type ~= "result" then -- recipient not in room
                        origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
                end
@@ -524,48 +570,90 @@ function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
 end
 
 function room_mt:send_form(origin, stanza)
-       local title = "Configuration for "..self.jid;
        origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
-               :tag("x", {xmlns='jabber:x:data', type='form'})
-                       :tag("title"):text(title):up()
-                       :tag("instructions"):text(title):up()
-                       :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
-                       :tag("field", {type='text-single', label='Name', var='muc#roomconfig_roomname'})
-                               :tag("value"):text(self:get_name() or ""):up()
-                       :up()
-                       :tag("field", {type='text-single', label='Description', var='muc#roomconfig_roomdesc'})
-                               :tag("value"):text(self:get_description() or ""):up()
-                       :up()
-                       :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
-                               :tag("value"):text(self:is_persistent() and "1" or "0"):up()
-                       :up()
-                       :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
-                               :tag("value"):text(self:is_hidden() and "0" or "1"):up()
-                       :up()
-                       :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
-                           :tag("value"):text(self._data.whois or 'moderators'):up()
-                           :tag("option", {label = 'Moderators Only'})
-                               :tag("value"):text('moderators'):up()
-                               :up()
-                           :tag("option", {label = 'Anyone'})
-                               :tag("value"):text('anyone'):up()
-                               :up()
-                       :up()
-                       :tag("field", {type='text-private', label='Password', var='muc#roomconfig_roomsecret'})
-                               :tag("value"):text(self:get_password() or ""):up()
-                       :up()
-                       :tag("field", {type='boolean', label='Make Room Moderated?', var='muc#roomconfig_moderatedroom'})
-                               :tag("value"):text(self:is_moderated() and "1" or "0"):up()
-                       :up()
-                       :tag("field", {type='boolean', label='Make Room Members-Only?', var='muc#roomconfig_membersonly'})
-                               :tag("value"):text(self:is_members_only() and "1" or "0"):up()
-                       :up()
+               :add_child(self:get_form_layout():form())
        );
 end
 
+function room_mt:get_form_layout()
+       local title = "Configuration for "..self.jid;
+       return dataform.new({
+               title = title,
+               instructions = title,
+               {
+                       name = 'FORM_TYPE',
+                       type = 'hidden',
+                       value = 'http://jabber.org/protocol/muc#roomconfig'
+               },
+               {
+                       name = 'muc#roomconfig_roomname',
+                       type = 'text-single',
+                       label = 'Name',
+                       value = self:get_name() or "",
+               },
+               {
+                       name = 'muc#roomconfig_roomdesc',
+                       type = 'text-single',
+                       label = 'Description',
+                       value = self:get_description() or "",
+               },
+               {
+                       name = 'muc#roomconfig_persistentroom',
+                       type = 'boolean',
+                       label = 'Make Room Persistent?',
+                       value = self:is_persistent()
+               },
+               {
+                       name = 'muc#roomconfig_publicroom',
+                       type = 'boolean',
+                       label = 'Make Room Publicly Searchable?',
+                       value = not self:is_hidden()
+               },
+               {
+                       name = 'muc#roomconfig_changesubject',
+                       type = 'boolean',
+                       label = 'Allow Occupants to Change Subject?',
+                       value = self:get_changesubject()
+               },
+               {
+                       name = 'muc#roomconfig_whois',
+                       type = 'list-single',
+                       label = 'Who May Discover Real JIDs?',
+                       value = {
+                               { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
+                               { value = 'anyone',     label = 'Anyone',          default = self._data.whois == 'anyone' }
+                       }
+               },
+               {
+                       name = 'muc#roomconfig_roomsecret',
+                       type = 'text-private',
+                       label = 'Password',
+                       value = self:get_password() or "",
+               },
+               {
+                       name = 'muc#roomconfig_moderatedroom',
+                       type = 'boolean',
+                       label = 'Make Room Moderated?',
+                       value = self:is_moderated()
+               },
+               {
+                       name = 'muc#roomconfig_membersonly',
+                       type = 'boolean',
+                       label = 'Make Room Members-Only?',
+                       value = self:is_members_only()
+               },
+               {
+                       name = 'muc#roomconfig_historylength',
+                       type = 'text-single',
+                       label = 'Maximum Number of History Messages Returned by Room',
+                       value = tostring(self:get_historylength())
+               }
+       });
+end
+
 local valid_whois = {
-    moderators = true,
-    anyone = true,
+       moderators = true,
+       anyone = true,
 }
 
 function room_mt:process_form(origin, stanza)
@@ -574,53 +662,50 @@ function room_mt:process_form(origin, stanza)
        for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
        if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
        if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
-       if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
-       local fields = {};
-       for _, field in pairs(form.tags) do
-               if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
-                       fields[field.attr.var] = field.tags[1][1] or "";
-               end
-       end
-       if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
+       if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
+
+       local fields = self:get_form_layout():data(form);
+       if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
 
        local dirty = false
 
        local name = fields['muc#roomconfig_roomname'];
-       if name then
+       if name ~= self:get_name() then
                self:set_name(name);
        end
 
        local description = fields['muc#roomconfig_roomdesc'];
-       if description then
+       if description ~= self:get_description() then
                self:set_description(description);
        end
 
        local persistent = fields['muc#roomconfig_persistentroom'];
-       if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
-       else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
        dirty = dirty or (self:is_persistent() ~= persistent)
        module:log("debug", "persistent=%s", tostring(persistent));
 
        local moderated = fields['muc#roomconfig_moderatedroom'];
-       if moderated == "0" or moderated == "false" then moderated = nil; elseif moderated == "1" or moderated == "true" then moderated = true;
-       else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
        dirty = dirty or (self:is_moderated() ~= moderated)
        module:log("debug", "moderated=%s", tostring(moderated));
 
        local membersonly = fields['muc#roomconfig_membersonly'];
-       if membersonly == "0" or membersonly == "false" then membersonly = nil; elseif membersonly == "1" or membersonly == "true" then membersonly = true;
-       else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
        dirty = dirty or (self:is_members_only() ~= membersonly)
        module:log("debug", "membersonly=%s", tostring(membersonly));
 
        local public = fields['muc#roomconfig_publicroom'];
-       if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
-       else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
        dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
 
+       local changesubject = fields['muc#roomconfig_changesubject'];
+       dirty = dirty or (self:get_changesubject() ~= (not changesubject and true or nil))
+       module:log('debug', 'changesubject=%s', changesubject and "true" or "false")
+
+       local historylength = tonumber(fields['muc#roomconfig_historylength']);
+       dirty = dirty or (historylength and (self:get_historylength() ~= historylength));
+       module:log('debug', 'historylength=%s', historylength)
+
+
        local whois = fields['muc#roomconfig_whois'];
        if not valid_whois[whois] then
-           origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
+           origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
            return;
        end
        local whois_changed = self._data.whois ~= whois
@@ -628,30 +713,32 @@ function room_mt:process_form(origin, stanza)
        module:log('debug', 'whois=%s', whois)
 
        local password = fields['muc#roomconfig_roomsecret'];
-       if password then
+       if self:get_password() ~= password then
                self:set_password(password);
        end
        self:set_moderated(moderated);
        self:set_members_only(membersonly);
        self:set_persistent(persistent);
        self:set_hidden(not public);
+       self:set_changesubject(changesubject);
+       self:set_historylength(historylength);
 
        if self.save then self:save(true); end
        origin.send(st.reply(stanza));
 
        if dirty or whois_changed then
-           local msg = st.message({type='groupchat', from=self.jid})
-                   :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
+               local msg = st.message({type='groupchat', from=self.jid})
+                       :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
 
-           if dirty then
-               msg.tags[1]:tag('status', {code = '104'})
-           end
-           if whois_changed then
-               local code = (whois == 'moderators') and 173 or 172
-               msg.tags[1]:tag('status', {code = code})
-           end
+               if dirty then
+                       msg.tags[1]:tag('status', {code = '104'}):up();
+               end
+               if whois_changed then
+                       local code = (whois == 'moderators') and "173" or "172";
+                       msg.tags[1]:tag('status', {code = code}):up();
+               end
 
-           self:broadcast_message(msg, false)
+               self:broadcast_message(msg, false)
        end
 end
 
@@ -678,9 +765,9 @@ function room_mt:handle_to_room(origin, stanza) -- presence changes and groupcha
        local type = stanza.attr.type;
        local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
        if stanza.name == "iq" then
-               if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
+               if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" and not stanza.tags[1].attr.node then
                        origin.send(self:get_disco_info(stanza));
-               elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
+               elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" and not stanza.tags[1].attr.node then
                        origin.send(self:get_disco_items(stanza));
                elseif xmlns == "http://jabber.org/protocol/muc#admin" then
                        local actor = stanza.attr.from;
@@ -758,13 +845,13 @@ function room_mt:handle_to_room(origin, stanza) -- presence changes and groupcha
                        end
                elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
                        if self:get_affiliation(stanza.attr.from) ~= "owner" then
-                               origin.send(st.error_reply(stanza, "auth", "forbidden"));
+                               origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
                        elseif stanza.attr.type == "get" then
                                self:send_form(origin, stanza);
                        elseif stanza.attr.type == "set" then
                                local child = stanza.tags[1].tags[1];
                                if not child then
-                                       origin.send(st.error_reply(stanza, "auth", "bad-request"));
+                                       origin.send(st.error_reply(stanza, "modify", "bad-request"));
                                elseif child.name == "destroy" then
                                        local newjid = child.attr.jid;
                                        local reason, password;
@@ -786,26 +873,26 @@ function room_mt:handle_to_room(origin, stanza) -- presence changes and groupcha
                end
        elseif stanza.name == "message" and type == "groupchat" then
                local from, to = stanza.attr.from, stanza.attr.to;
-               local room = jid_bare(to);
                local current_nick = self._jid_nick[from];
                local occupant = self._occupants[current_nick];
                if not occupant then -- not in room
                        origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
                elseif occupant.role == "visitor" then
-                       origin.send(st.error_reply(stanza, "cancel", "forbidden"));
+                       origin.send(st.error_reply(stanza, "auth", "forbidden"));
                else
                        local from = stanza.attr.from;
                        stanza.attr.from = current_nick;
                        local subject = getText(stanza, {"subject"});
                        if subject then
-                               if occupant.role == "moderator" then
+                               if occupant.role == "moderator" or
+                                       ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
                                        self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
                                else
                                        stanza.attr.from = from;
-                                       origin.send(st.error_reply(stanza, "cancel", "forbidden"));
+                                       origin.send(st.error_reply(stanza, "auth", "forbidden"));
                                end
                        else
-                               self:broadcast_message(stanza, true);
+                               self:broadcast_message(stanza, self:get_historylength() > 0);
                        end
                        stanza.attr.from = from;
                end
@@ -823,8 +910,8 @@ function room_mt:handle_to_room(origin, stanza) -- presence changes and groupcha
                elseif type ~= "error" and type ~= "result" then
                        origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
                end
-       elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
-               and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
+       elseif stanza.name == "message" and not(type == "chat" or type == "error" or type == "groupchat" or type == "headline") and #stanza.tags == 1
+               and self._jid_nick[stanza.attr.from] and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
                local x = stanza.tags[1];
                local payload = (#x.tags == 1 and x.tags[1]);
                if payload and payload.name == "invite" and payload.attr.to then
@@ -847,6 +934,10 @@ function room_mt:handle_to_room(origin, stanza) -- presence changes and groupcha
                                        :tag('body') -- Add a plain message for clients which don't support invites
                                                :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
                                        :up();
+                               if self:is_members_only() and not self:get_affiliation(_invitee) then
+                                       log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
+                                       self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
+                               end
                                self:_route_stanza(invite);
                        else
                                origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
@@ -884,19 +975,34 @@ function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
        if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
                return nil, "modify", "not-acceptable";
        end
-       if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
-       if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
+       if actor ~= true then
+               local actor_affiliation = self:get_affiliation(actor);
+               local target_affiliation = self:get_affiliation(jid);
+               if target_affiliation == affiliation then -- no change, shortcut
+                       if callback then callback(); end
+                       return true;
+               end
+               if actor_affiliation ~= "owner" then
+                       if affiliation == "owner" or affiliation == "admin" or actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
+                               return nil, "cancel", "not-allowed";
+                       end
+               elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
+                       local is_last = true;
+                       for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
+                       if is_last then
+                               return nil, "cancel", "conflict";
+                       end
+               end
+       end
        self._affiliations[jid] = affiliation;
        local role = self:get_default_role(affiliation);
-       local p = st.presence()
-               :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
+       local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
                        :tag("item", {affiliation=affiliation or "none", role=role or "none"})
                                :tag("reason"):text(reason or ""):up()
                        :up();
-       local x = p.tags[1];
-       local item = x.tags[1];
+       local presence_type = nil;
        if not role then -- getting kicked
-               p.attr.type = "unavailable";
+               presence_type = "unavailable";
                if affiliation == "outcast" then
                        x:tag("status", {code="301"}):up(); -- banned
                else
@@ -906,23 +1012,28 @@ function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
        local modified_nicks = {};
        for nick, occupant in pairs(self._occupants) do
                if jid_bare(occupant.jid) == jid then
-                       t_insert(modified_nicks, nick);
                        if not role then -- getting kicked
                                self._occupants[nick] = nil;
                        else
                                occupant.affiliation, occupant.role = affiliation, role;
                        end
-                       p.attr.from = nick;
-                       for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
+                       for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
                                if not role then self._jid_nick[jid] = nil; end
+                               local p = st.clone(pres);
+                               p.attr.from = nick;
+                               p.attr.type = presence_type;
                                p.attr.to = jid;
+                               p:add_child(x);
                                self:_route_stanza(p);
+                               if occupant.jid == jid then
+                                       modified_nicks[nick] = p;
+                               end
                        end
                end
        end
        if self.save then self:save(); end
        if callback then callback(); end
-       for _, nick in ipairs(modified_nicks) do
+       for nick,p in pairs(modified_nicks) do
                p.attr.from = nick;
                self:broadcast_except_nick(p, nick);
        end
@@ -956,27 +1067,37 @@ function room_mt:set_role(actor, occupant_jid, role, callback, reason)
        local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
        if not allowed then return allowed, err_type, err_condition; end
        local occupant = self._occupants[occupant_jid];
-       local p = st.presence({from = occupant_jid})
-               :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
+       local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
                        :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
                                :tag("reason"):text(reason or ""):up()
                        :up();
+       local presence_type = nil;
        if not role then -- kick
-               p.attr.type = "unavailable";
+               presence_type = "unavailable";
                self._occupants[occupant_jid] = nil;
                for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
                        self._jid_nick[jid] = nil;
                end
-               p:tag("status", {code = "307"}):up();
+               x:tag("status", {code = "307"}):up();
        else
                occupant.role = role;
        end
-       for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
+       local bp;
+       for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
+               local p = st.clone(pres);
+               p.attr.from = occupant_jid;
+               p.attr.type = presence_type;
                p.attr.to = jid;
+               p:add_child(x);
                self:_route_stanza(p);
+               if occupant.jid == jid then
+                       bp = p;
+               end
        end
        if callback then callback(); end
-       self:broadcast_except_nick(p, occupant_jid);
+       if bp then
+               self:broadcast_except_nick(bp, occupant_jid);
+       end
        return true;
 end
 
@@ -1005,9 +1126,6 @@ function room_mt:_route_stanza(stanza)
                                end
                        end
                end
-               if self._data.whois == 'anyone' then
-                   muc_child:tag('status', { code = '100' });
-               end
        end
        self:route_stanza(stanza);
        if muc_child then
@@ -1028,10 +1146,17 @@ function _M.new_room(jid, config)
                _occupants = {};
                _data = {
                    whois = 'moderators';
-                   history_length = (config and config.history_length);
+                   history_length = math.min((config and config.history_length)
+                       or default_history_length, max_history_length);
                };
                _affiliations = {};
        }, room_mt);
 end
 
+function _M.set_max_history_length(_max_history_length)
+       max_history_length = _max_history_length or math.huge;
+end
+
+_M.room_mt = room_mt;
+
 return _M;