Merge 0.9->0.10
authorMatthew Wild <mwild1@gmail.com>
Wed, 2 Apr 2014 16:41:38 +0000 (17:41 +0100)
committerMatthew Wild <mwild1@gmail.com>
Wed, 2 Apr 2014 16:41:38 +0000 (17:41 +0100)
1  2 
core/portmanager.lua
net/server_event.lua
net/server_select.lua
plugins/mod_compression.lua
plugins/muc/muc.lib.lua
util/dependencies.lua
util/xmppstream.lua

diff --combined core/portmanager.lua
index 95900c08483156f8f54f8fe2412e450c56e6b63b,421d7fc60f4c27c40ab0b98f3a8db15cb02d55c7..4cbf3eb3619315d0e48728f31640f7e91481eaaa
@@@ -29,6 -29,8 +29,8 @@@ if socket.tcp6 and config.get("*", "use
        table.insert(default_local_interfaces, "::1");
  end
  
+ local default_mode = config.get("*", "network_default_read_size") or 4096;
  --- Private state
  
  -- service_name -> { service_info, ... }
@@@ -87,7 -89,7 +89,7 @@@ function activate(service_name
        if not service_info then
                return nil, "Unknown service: "..service_name;
        end
 -      
 +
        local listener = service_info.listener;
  
        local config_prefix = (service_info.config_prefix or service_name).."_";
                or listener.default_interface -- COMPAT w/pre0.9
                or default_interfaces
        bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces);
 -      
 +
        local bind_ports = config.get("*", config_prefix.."ports")
                or service_info.default_ports
                or {service_info.default_port
                   }
        bind_ports = set.new(type(bind_ports) ~= "table" and { bind_ports } or bind_ports );
  
-       local mode, ssl = listener.default_mode or "*a";
+       local mode, ssl = listener.default_mode or default_mode;
        local hooked_ports = {};
 -      
 +
        for interface in bind_interfaces do
                for port in bind_ports do
                        local port_number = tonumber(port);
@@@ -188,7 -190,7 +190,7 @@@ function register_service(service_name
                        log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error");
                end
        end
 -      
 +
        fire_event("service-added", { name = service_name, service = service_info });
        return true;
  end
diff --combined net/server_event.lua
index 59217a0cf33d449ed0002423105900649bc6bc09,257996401ca4ecfd57726eba66e53adcfa692032..5333099776674de86a591e58b582052d77dc6b03
@@@ -115,10 -115,10 +115,10 @@@ end )( 
  local interface_mt
  do
        interface_mt = {}; interface_mt.__index = interface_mt;
 -      
 +
        local addevent = base.addevent
        local coroutine_wrap, coroutine_yield = coroutine.wrap,coroutine.yield
 -      
 +
        -- Private methods
        function interface_mt:_position(new_position)
                        self.position = new_position or self.position
        function interface_mt:_close()
                return self:_destroy();
        end
 -      
 +
        function interface_mt:_start_connection(plainssl) -- should be called from addclient
                        local callback = function( event )
                                if EV_TIMEOUT == event then  -- timeout during connection
                        interfacelist( "delete", self )
                        return true
        end
 -      
 +
        function interface_mt:_lock(nointerface, noreading, nowriting)  -- lock or unlock this interface or events
                        self.nointerface, self.noreading, self.nowriting = nointerface, noreading, nowriting
                        return nointerface, noreading, nowriting
        end
 -      
 +
        --TODO: Deprecate
        function interface_mt:lock_read(switch)
                if switch then
                end
                return self._connections
        end
 -      
 +
        -- Public methods
        function interface_mt:write(data)
                if self.nowriting then return nil, "locked" end
                        return true
                end
        end
 -      
 +
        function interface_mt:socket()
                return self.conn
        end
 -      
 +
        function interface_mt:server()
                return self._server or self;
        end
 -      
 +
        function interface_mt:port()
                return self._port
        end
 -      
 +
        function interface_mt:serverport()
                return self._serverport
        end
 -      
 +
        function interface_mt:ip()
                return self._ip
        end
 -      
 +
        function interface_mt:ssl()
                return self._usingssl
        end
+       interface_mt.clientport = interface_mt.port -- COMPAT server_select
  
        function interface_mt:type()
                return self._type or "client"
        end
 -      
 +
        function interface_mt:connections()
                return self._connections
        end
 -      
 +
        function interface_mt:address()
                return self.addr
        end
 -      
 +
        function interface_mt:set_sslctx(sslctx)
                self._sslctx = sslctx;
                if sslctx then
                end
                return self._pattern;
        end
 -      
 +
        function interface_mt:set_send(new_send)
                -- No-op, we always use the underlying connection's send
        end
 -      
 +
        function interface_mt:starttls(sslctx, call_onconnect)
                debug( "try to start ssl at client id:", self.id )
                local err
                self.starttls = false;
                return true
        end
 -      
 +
        function interface_mt:setoption(option, value)
                if self.conn.setoption then
                        return self.conn:setoption(option, value);
                end
                return false, "setoption not implemented";
        end
 -      
 +
        function interface_mt:setlistener(listener)
 -              self.onconnect, self.ondisconnect, self.onincoming, self.ontimeout, self.onstatus
 -                      = listener.onconnect, listener.ondisconnect, listener.onincoming, listener.ontimeout, listener.onstatus;
 +              self.onconnect, self.ondisconnect, self.onincoming, self.ontimeout, self.onreadtimeout, self.onstatus
 +                      = listener.onconnect, listener.ondisconnect, listener.onincoming,
 +                        listener.ontimeout, listener.onreadtimeout, listener.onstatus;
        end
 -      
 +
        -- Stub handlers
        function interface_mt:onconnect()
        end
        end
        function interface_mt:ontimeout()
        end
 +      function interface_mt:onreadtimeout()
 +              self.fatalerror = "timeout during receiving"
 +              debug( "connection failed:", self.fatalerror )
 +              self:_close()
 +              self.eventread = nil
 +      end
        function interface_mt:ondrain()
        end
        function interface_mt:onstatus()
@@@ -484,7 -478,6 +485,7 @@@ d
                        ondisconnect = listener.ondisconnect;  -- will be called when client disconnects
                        onincoming = listener.onincoming;  -- will be called when client sends data
                        ontimeout = listener.ontimeout; -- called when fatal socket timeout occurs
 +                      onreadtimeout = listener.onreadtimeout; -- called when socket inactivity timeout occurs
                        ondrain = listener.ondrain; -- called when writebuffer is empty
                        onstatus = listener.onstatus; -- called for status changes (e.g. of SSL/TLS)
                        eventread = false, eventwrite = false, eventclose = false,
                        noreading = false, nowriting = false;  -- locks of the read/writecallback
                        startsslcallback = false;  -- starting handshake callback
                        position = false;  -- position of client in interfacelist
 -                      
 +
                        -- Properties
                        _ip = ip, _port = port, _server = server, _pattern = pattern,
                        _serverport = (server and server:port() or nil),
                                end
                        end
                end
 -              
 +
                interface.readcallback = function( event )  -- called on read events
                        --vdebug( "new client read event, id/ip/port:", tostring(interface.id), tostring(ip), tostring(port) )
                        if interface.noreading or interface.fatalerror then  -- leave this event
                                interface.eventread = nil
                                return -1
                        end
 -                      if EV_TIMEOUT == event then  -- took too long to get some data from client -> disconnect
 -                              interface.fatalerror = "timeout during receiving"
 -                              debug( "connection failed:", interface.fatalerror )
 +                      if EV_TIMEOUT == event and interface:onreadtimeout() ~= true then
 +                              return -1 -- took too long to get some data from client -> disconnect
 +                      end
 +                      if interface._usingssl then  -- handle luasec
 +                              if interface.eventwritetimeout then  -- ok, in the past writecallback was regged
 +                                      local ret = interface.writecallback( )  -- call it
 +                                      --vdebug( "tried to write in readcallback, result:", tostring(ret) )
 +                              end
 +                              if interface.eventreadtimeout then
 +                                      interface.eventreadtimeout:close( )
 +                                      interface.eventreadtimeout = nil
 +                              end
 +                      end
 +                      local buffer, err, part = interface.conn:receive( interface._pattern )  -- receive buffer with "pattern"
 +                      --vdebug( "read data:", tostring(buffer), "error:", tostring(err), "part:", tostring(part) )
 +                      buffer = buffer or part
 +                      if buffer and #buffer > cfg.MAX_READ_LENGTH then  -- check buffer length
 +                              interface.fatalerror = "receive buffer exceeded"
 +                              debug( "fatal error:", interface.fatalerror )
                                interface:_close()
                                interface.eventread = nil
                                return -1
 -                      else -- can read
 -                              if interface._usingssl then  -- handle luasec
 -                                      if interface.eventwritetimeout then  -- ok, in the past writecallback was regged
 -                                              local ret = interface.writecallback( )  -- call it
 -                                              --vdebug( "tried to write in readcallback, result:", tostring(ret) )
 -                                      end
 -                                      if interface.eventreadtimeout then
 -                                              interface.eventreadtimeout:close( )
 -                                              interface.eventreadtimeout = nil
 +                      end
 +                      if err and ( err ~= "timeout" and err ~= "wantread" ) then
 +                              if "wantwrite" == err then -- need to read on write event
 +                                      if not interface.eventwrite then  -- register new write event if needed
 +                                              interface.eventwrite = addevent( base, interface.conn, EV_WRITE, interface.writecallback, cfg.WRITE_TIMEOUT )
                                        end
 -                              end
 -                              local buffer, err, part = interface.conn:receive( interface._pattern )  -- receive buffer with "pattern"
 -                              --vdebug( "read data:", tostring(buffer), "error:", tostring(err), "part:", tostring(part) )
 -                              buffer = buffer or part
 -                              if buffer and #buffer > cfg.MAX_READ_LENGTH then  -- check buffer length
 -                                      interface.fatalerror = "receive buffer exceeded"
 -                                      debug( "fatal error:", interface.fatalerror )
 +                                      interface.eventreadtimeout = addevent( base, nil, EV_TIMEOUT,
 +                                              function( )
 +                                                      interface:_close()
 +                                              end, cfg.READ_TIMEOUT
 +                                      )
 +                                      debug( "wantwrite during read attempt, reg it in writecallback but dont know what really happens next..." )
 +                                      -- to be honest i dont know what happens next, if it is allowed to first read, the write etc...
 +                              else  -- connection was closed or fatal error
 +                                      interface.fatalerror = err
 +                                      debug( "connection failed in read event:", interface.fatalerror )
                                        interface:_close()
                                        interface.eventread = nil
                                        return -1
                                end
 -                              if err and ( err ~= "timeout" and err ~= "wantread" ) then
 -                                      if "wantwrite" == err then -- need to read on write event
 -                                              if not interface.eventwrite then  -- register new write event if needed
 -                                                      interface.eventwrite = addevent( base, interface.conn, EV_WRITE, interface.writecallback, cfg.WRITE_TIMEOUT )
 -                                              end
 -                                              interface.eventreadtimeout = addevent( base, nil, EV_TIMEOUT,
 -                                                      function( )
 -                                                              interface:_close()
 -                                                      end, cfg.READ_TIMEOUT
 -                                              )
 -                                              debug( "wantwrite during read attempt, reg it in writecallback but dont know what really happens next..." )
 -                                              -- to be honest i dont know what happens next, if it is allowed to first read, the write etc...
 -                                      else  -- connection was closed or fatal error
 -                                              interface.fatalerror = err
 -                                              debug( "connection failed in read event:", interface.fatalerror )
 -                                              interface:_close()
 -                                              interface.eventread = nil
 -                                              return -1
 -                                      end
 -                              else
 -                                      interface.onincoming( interface, buffer, err )  -- send new data to listener
 -                              end
 -                              if interface.noreading then
 -                                      interface.eventread = nil;
 -                                      return -1;
 -                              end
 -                              return EV_READ, cfg.READ_TIMEOUT
 +                      else
 +                              interface.onincoming( interface, buffer, err )  -- send new data to listener
                        end
 +                      if interface.noreading then
 +                              interface.eventread = nil;
 +                              return -1;
 +                      end
 +                      return EV_READ, cfg.READ_TIMEOUT
                end
  
                client:settimeout( 0 )  -- set non blocking
@@@ -648,7 -646,7 +649,7 @@@ d
                debug "creating server interface..."
                local interface = {
                        _connections = 0;
 -                      
 +
                        conn = server;
                        onconnect = listener.onconnect;  -- will be called when new client connected
                        eventread = false;  -- read event handler
                        readcallback = false; -- read event callback
                        fatalerror = false; -- error message
                        nointerface = true;  -- lock/unlock parameter
 -                      
 +
                        _ip = addr, _port = port, _pattern = pattern,
                        _sslctx = sslctx;
                }
                                        clientinterface:_start_session( true )
                                end
                                debug( "accepted incoming client connection from:", client_ip or "<unknown IP>", client_port or "<unknown port>", "to", port or "<unknown port>");
 -                              
 +
                                client, err = server:accept()    -- try to accept again
                        end
                        return EV_READ
                end
 -              
 +
                server:settimeout( 0 )
                setmetatable(interface, interface_mt)
                interfacelist( "add", interface )
@@@ -743,7 -741,7 +744,7 @@@ d
                return interface, client
                --function handleclient( client, ip, port, server, pattern, listener, _, sslctx )  -- creates an client interface
        end
 -      
 +
        function addclient( addr, serverport, listener, pattern, localaddr, localport, sslcfg, startssl )
                local client, err = socket.tcp()  -- creating new socket
                if not client then
@@@ -834,14 -832,14 +835,14 @@@ en
  
  local function link(sender, receiver, buffersize)
        local sender_locked;
 -      
 +
        function receiver:ondrain()
                if sender_locked then
                        sender:resume();
                        sender_locked = nil;
                end
        end
 -      
 +
        function sender:onincoming(data)
                receiver:write(data);
                if receiver.writebufferlen >= buffersize then
diff --combined net/server_select.lua
index c5e0772f8a7ff1bc32e255487d817e8f27d7ede2,4bda3ef048ff9e27c4ba2e20cb7bf9509206b282..daad0f50fb7fd05abcf7f0dd25bb2d985ba643a2
@@@ -1,7 -1,7 +1,7 @@@
 --- 
 +--
  -- server.lua by blastbeat of the luadch project
  -- Re-used here under the MIT/X Consortium License
 --- 
 +--
  -- Modifications (C) 2008-2010 Matthew Wild, Waqas Hussain
  --
  
@@@ -145,7 -145,7 +145,7 @@@ _tcpbacklog = 128 -- some kind of hint 
  _maxsendlen = 51000 * 1024 -- max len of send buffer
  _maxreadlen = 25000 * 1024 -- max len of read buffer
  
 -_checkinterval = 1200000 -- interval in secs to check idle clients
 +_checkinterval = 30 -- interval in secs to check idle clients
  _sendtimeout = 60000 -- allowed send idle time in secs
  _readtimeout = 6 * 60 * 60 -- allowed read idle time in secs
  
@@@ -284,7 -284,6 +284,7 @@@ wrapconnection = function( server, list
        local status = listeners.onstatus
        local disconnect = listeners.ondisconnect
        local drain = listeners.ondrain
 +      local onreadtimeout = listeners.onreadtimeout;
  
        local bufferqueue = { } -- buffer array
        local bufferqueuelen = 0        -- end of buffer array
        handler.disconnect = function( )
                return disconnect
        end
 +      handler.onreadtimeout = onreadtimeout;
 +
        handler.setlistener = function( self, listeners )
                dispatch = listeners.onincoming
                disconnect = listeners.ondisconnect
                status = listeners.onstatus
                drain = listeners.ondrain
 +              handler.onreadtimeout = listeners.onreadtimeout
        end
        handler.getstats = function( )
                return readtraffic, sendtraffic
        handler.clientport = function( )
                return clientport
        end
+       handler.port = handler.clientport -- COMPAT server_event
        local write = function( self, data )
                bufferlen = bufferlen + #data
                if bufferlen > maxsendlen then
                        shutdown = id
                        _socketlist[ socket ] = handler
                        _readlistlen = addsocket(_readlist, socket, _readlistlen)
 -                      
 +
                        -- remove traces of the old socket
                        _readlistlen = removesocket( _readlist, oldsocket, _readlistlen )
                        _sendlistlen = removesocket( _sendlist, oldsocket, _sendlistlen )
@@@ -699,7 -696,7 +700,7 @@@ local function link(sender, receiver, b
                        sender_locked = nil;
                end
        end
 -      
 +
        local _readbuffer = sender.readbuffer;
        function sender.readbuffer()
                _readbuffer();
@@@ -867,16 -864,16 +868,16 @@@ loop = function(once) -- this is the ma
                        _starttime = _currenttime
                        for handler, timestamp in pairs( _writetimes ) do
                                if os_difftime( _currenttime - timestamp ) > _sendtimeout then
 -                                      --_writetimes[ handler ] = nil
                                        handler.disconnect( )( handler, "send timeout" )
                                        handler:force_close()    -- forced disconnect
                                end
                        end
                        for handler, timestamp in pairs( _readtimes ) do
                                if os_difftime( _currenttime - timestamp ) > _readtimeout then
 -                                      --_readtimes[ handler ] = nil
 -                                      handler.disconnect( )( handler, "read timeout" )
 -                                      handler:close( )        -- forced disconnect?
 +                                      if not(handler.onreadtimeout) or handler:onreadtimeout() ~= true then
 +                                              handler.disconnect( )( handler, "read timeout" )
 +                                              handler:close( )        -- forced disconnect?
 +                                      end
                                end
                        end
                end
@@@ -937,9 -934,9 +938,9 @@@ local addclient = function( address, po
        client:settimeout( 0 )
        _, err = client:connect( address, port )
        if err then -- try again
 -              local handler = wrapclient( client, address, port, listeners )
 +              return wrapclient( client, address, port, listeners, pattern, sslctx )
        else
 -              wrapconnection( nil, listeners, client, address, port, "clientport", pattern, sslctx )
 +              return wrapconnection( nil, listeners, client, address, port, "clientport", pattern, sslctx )
        end
  end
  
@@@ -969,7 -966,7 +970,7 @@@ return 
  
        addclient = addclient,
        wrapclient = wrapclient,
 -      
 +
        loop = loop,
        link = link,
        step = step,
index f44e8a6d6ac80257f5a8d5e2cb696f0831eb9cd8,531ea8ea52cc5db7d3bfcabc6a0cc1b62fc5eb24..9da5254e5877a2f05b5caa7860671ddfd84f6ca3
@@@ -1,6 -1,6 +1,6 @@@
  -- Prosody IM
  -- Copyright (C) 2009-2012 Tobias Markmann
 --- 
 +--
  -- This project is MIT/X11 licensed. Please see the
  -- COPYING file in the source package for more information.
  --
@@@ -103,7 -103,7 +103,7 @@@ local function setup_compression(sessio
                        return;
                end
                return compressed;
 -      end);   
 +      end);
  end
  
  -- setup decompression for a stream
@@@ -125,19 -125,19 +125,19 @@@ en
  
  module:hook("stanza/http://jabber.org/protocol/compress:compressed", function(event)
        local session = event.origin;
-       if session.type == "s2sout_unauthed" or session.type == "s2sout" then
+       
+       if session.type == "s2sout" then
                session.log("debug", "Activating compression...")
                -- create deflate and inflate streams
                local deflate_stream = get_deflate_stream(session);
                if not deflate_stream then return true; end
 -              
 +
                local inflate_stream = get_inflate_stream(session);
                if not inflate_stream then return true; end
 -              
 +
                -- setup compression for session.w
                setup_compression(session, deflate_stream);
 -                      
 +
                -- setup decompression for session.data
                setup_decompression(session, inflate_stream);
                session:reset_stream();
@@@ -150,7 -150,7 +150,7 @@@ end)
  module:hook("stanza/http://jabber.org/protocol/compress:compress", function(event)
        local session, stanza = event.origin, event.stanza;
  
-       if session.type == "c2s" or session.type == "s2sin" or session.type == "c2s_unauthed" or session.type == "s2sin_unauthed" then
+       if session.type == "c2s" or session.type == "s2sin" then
                -- fail if we are already compressed
                if session.compressed then
                        local error_st = st.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("setup-failed");
                        session.log("debug", "Client tried to establish another compression layer.");
                        return true;
                end
 -              
 +
                -- checking if the compression method is supported
                local method = stanza:child_with_name("method");
                method = method and (method[1] or "");
                if method == "zlib" then
                        session.log("debug", "zlib compression enabled.");
 -                      
 +
                        -- create deflate and inflate streams
                        local deflate_stream = get_deflate_stream(session);
                        if not deflate_stream then return true; end
 -                      
 +
                        local inflate_stream = get_inflate_stream(session);
                        if not inflate_stream then return true; end
 -                      
 +
                        (session.sends2s or session.send)(st.stanza("compressed", {xmlns=xmlns_compression_protocol}));
                        session:reset_stream();
 -                      
 +
                        -- setup compression for session.w
                        setup_compression(session, deflate_stream);
 -                              
 +
                        -- setup decompression for session.data
                        setup_decompression(session, inflate_stream);
 -                      
 +
                        session.compressed = true;
                elseif method then
                        session.log("debug", "%s compression selected, but we don't support it.", tostring(method));
diff --combined plugins/muc/muc.lib.lua
index d09c768e51f60049b354e6e013fb7591096d8121,8028f5aee0e5cc9dc352930a27797cc3b2f6e246..8cf8d882e5895962a2a3e779267a52e9d6cc4e46
@@@ -1,7 -1,7 +1,7 @@@
  -- Prosody IM
  -- Copyright (C) 2008-2010 Matthew Wild
  -- Copyright (C) 2008-2010 Waqas Hussain
 --- 
 +--
  -- This project is MIT/X11 licensed. Please see the
  -- COPYING file in the source package for more information.
  --
@@@ -27,16 -27,28 +27,16 @@@ local muc_domain = nil; --module:get_ho
  local default_history_length, max_history_length = 20, math.huge;
  
  ------------
 -local function filter_xmlns_from_array(array, filters)
 -      local count = 0;
 -      for i=#array,1,-1 do
 -              local attr = array[i].attr;
 -              if filters[attr and attr.xmlns] then
 -                      t_remove(array, i);
 -                      count = count + 1;
 -              end
 -      end
 -      return count;
 -end
 -local function filter_xmlns_from_stanza(stanza, filters)
 -      if filters then
 -              if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
 -                      return stanza, filter_xmlns_from_array(stanza, filters);
 -              end
 +local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
 +local function presence_filter(tag)
 +      if presence_filters[tag.attr.xmlns] then
 +              return nil;
        end
 -      return stanza, 0;
 +      return tag;
  end
 -local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
 +
  local function get_filtered_presence(stanza)
 -      return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
 +      return st.clone(stanza):maptags(presence_filter);
  end
  local kickable_error_conditions = {
        ["gone"] = true;
@@@ -60,6 -72,17 +60,6 @@@ local function is_kickable_error(stanza
        local cond = get_error_condition(stanza);
        return kickable_error_conditions[cond] and cond;
  end
 -local function getUsingPath(stanza, path, getText)
 -      local tag = stanza;
 -      for _, name in ipairs(path) do
 -              if type(tag) ~= 'table' then return; end
 -              tag = tag:child_with_name(name);
 -      end
 -      if tag and getText then tag = table.concat(tag); end
 -      return tag;
 -end
 -local function getTag(stanza, path) return getUsingPath(stanza, path); end
 -local function getText(stanza, path) return getUsingPath(stanza, path, true); end
  -----------
  
  local room_mt = {};
@@@ -75,8 -98,8 +75,8 @@@ function room_mt:get_default_role(affil
        elseif affiliation == "member" then
                return "participant";
        elseif not affiliation then
 -              if not self:is_members_only() then
 -                      return self:is_moderated() and "visitor" or "participant";
 +              if not self:get_members_only() then
 +                      return self:get_moderated() and "visitor" or "participant";
                end
        end
  end
@@@ -107,21 -130,18 +107,21 @@@ function room_mt:broadcast_message(stan
        end
        stanza.attr.to = to;
        if historic then -- add to history
 -              local history = self._data['history'];
 -              if not history then history = {}; self._data['history'] = history; end
 -              stanza = st.clone(stanza);
 -              stanza.attr.to = "";
 -              local stamp = datetime.datetime();
 -              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 };
 -              t_insert(history, entry);
 -              while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
 +              return self:save_to_history(stanza)
        end
  end
 +function room_mt:save_to_history(stanza)
 +      local history = self._data['history'];
 +      if not history then history = {}; self._data['history'] = history; end
 +      stanza = st.clone(stanza);
 +      stanza.attr.to = "";
 +      local stamp = datetime.datetime();
 +      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 };
 +      t_insert(history, entry);
 +      while #history > (self._data.history_length or default_history_length) do t_remove(history, 1) end
 +end
  function room_mt:broadcast_except_nick(stanza, nick)
        for rnick, occupant in pairs(self._occupants) do
                if rnick ~= nick then
@@@ -150,10 -170,10 +150,10 @@@ function room_mt:send_history(to, stanz
        if history then
                local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
                local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
 -              
 +
                local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
                if maxchars then maxchars = math.floor(maxchars); end
 -              
 +
                local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
                if not history_tag then maxstanzas = 20; end
  
  
                local n = 0;
                local charcount = 0;
 -              
 +
                for i=#history,1,-1 do
                        local entry = history[i];
                        if maxchars then
                        self:_route_stanza(msg);
                end
        end
 +end
 +function room_mt:send_subject(to)
        if self._data['subject'] then
                self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
        end
@@@ -200,10 -218,10 +200,10 @@@ function room_mt:get_disco_info(stanza
                :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
                :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
                :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
 -              :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
 -              :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
 -              :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:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
 +              :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
 +              :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
 +              :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
                :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
                :add_child(dataform.new({
                        { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
@@@ -220,6 -238,7 +220,6 @@@ function room_mt:get_disco_items(stanza
        return reply;
  end
  function room_mt:set_subject(current_nick, subject)
 -      -- TODO check nick's authority
        if subject == "" then subject = nil; end
        self._data['subject'] = subject;
        self._data['subject_from'] = current_nick;
@@@ -277,7 -296,7 +277,7 @@@ function room_mt:set_moderated(moderate
                if self.save then self:save(true); end
        end
  end
 -function room_mt:is_moderated()
 +function room_mt:get_moderated()
        return self._data.moderated;
  end
  function room_mt:set_members_only(members_only)
                if self.save then self:save(true); end
        end
  end
 -function room_mt:is_members_only()
 +function room_mt:get_members_only()
        return self._data.members_only;
  end
  function room_mt:set_persistent(persistent)
                if self.save then self:save(true); end
        end
  end
 -function room_mt:is_persistent()
 +function room_mt:get_persistent()
        return self._data.persistent;
  end
  function room_mt:set_hidden(hidden)
                if self.save then self:save(true); end
        end
  end
 -function room_mt:is_hidden()
 +function room_mt:get_hidden()
        return self._data.hidden;
  end
 +function room_mt:get_public()
 +      return not self:get_hidden();
 +end
 +function room_mt:set_public(public)
 +      return self:set_hidden(not public);
 +end
  function room_mt:set_changesubject(changesubject)
        changesubject = changesubject and true or nil;
        if self._data.changesubject ~= changesubject then
@@@ -338,25 -351,12 +338,25 @@@ function room_mt:set_historylength(leng
  end
  
  
 +local valid_whois = { moderators = true, anyone = true };
 +
 +function room_mt:set_whois(whois)
 +      if valid_whois[whois] and self._data.whois ~= whois then
 +              self._data.whois = whois;
 +              if self.save then self:save(true); end
 +      end
 +end
 +
 +function room_mt:get_whois()
 +      return self._data.whois;
 +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)
@@@ -485,12 -485,6 +485,12 @@@ function room_mt:handle_to_occupant(ori
                                        log("debug", "%s joining as %s", from, to);
                                        if not next(self._affiliations) then -- new room, no owners
                                                self._affiliations[jid_bare(from)] = "owner";
 +                                              if self.locked and not stanza:get_child("x", "http://jabber.org/protocol/muc") then
 +                                                      self.locked = nil; -- Older groupchat protocol doesn't lock
 +                                              end
 +                                      elseif self.locked then -- Deny entry
 +                                              origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
 +                                              return;
                                        end
                                        local affiliation = self:get_affiliation(from);
                                        local role = self:get_default_role(affiliation)
                                                if self._data.whois == 'anyone' then
                                                        pr:tag("status", {code='100'}):up();
                                                end
 +                                              if self.locked then
 +                                                      pr:tag("status", {code='201'}):up();
 +                                              end
                                                pr.attr.to = from;
                                                self:_route_stanza(pr);
                                                self:send_history(from, stanza);
 +                                              self:send_subject(from);
                                        elseif not affiliation then -- registration required for entering members-only room
                                                local reply = st.error_reply(stanza, "auth", "registration-required"):up();
                                                reply.tags[1].attr.code = "407";
                                end
                                stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
                        else -- message
 +                              stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
                                stanza.attr.from = current_nick;
                                for jid in pairs(o_data.sessions) do
                                        stanza.attr.to = jid;
@@@ -586,11 -575,11 +586,11 @@@ en
  
  function room_mt:send_form(origin, stanza)
        origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
 -              :add_child(self:get_form_layout():form())
 +              :add_child(self:get_form_layout(stanza.attr.from):form())
        );
  end
  
 -function room_mt:get_form_layout()
 +function room_mt:get_form_layout(actor)
        local form = dataform.new({
                title = "Configuration for "..self.jid,
                instructions = "Complete and submit this form to configure the room.",
                        name = 'muc#roomconfig_persistentroom',
                        type = 'boolean',
                        label = 'Make Room Persistent?',
 -                      value = self:is_persistent()
 +                      value = self:get_persistent()
                },
                {
                        name = 'muc#roomconfig_publicroom',
                        type = 'boolean',
                        label = 'Make Room Publicly Searchable?',
 -                      value = not self:is_hidden()
 +                      value = not self:get_hidden()
                },
                {
                        name = 'muc#roomconfig_changesubject',
                        name = 'muc#roomconfig_moderatedroom',
                        type = 'boolean',
                        label = 'Make Room Moderated?',
 -                      value = self:is_moderated()
 +                      value = self:get_moderated()
                },
                {
                        name = 'muc#roomconfig_membersonly',
                        type = 'boolean',
                        label = 'Make Room Members-Only?',
 -                      value = self:is_members_only()
 +                      value = self:get_members_only()
                },
                {
                        name = 'muc#roomconfig_historylength',
                        value = tostring(self:get_historylength())
                }
        });
 -      return module:fire_event("muc-config-form", { room = self, form = form }) or form;
 +      return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
  end
  
 -local valid_whois = {
 -      moderators = true,
 -      anyone = true,
 -}
 -
  function room_mt:process_form(origin, stanza)
        local query = stanza.tags[1];
        local form;
        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", "Not a submitted form")); return; end
  
 -      local fields = self:get_form_layout():data(form);
 +      local fields = self:get_form_layout(stanza.attr.from):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 event = { room = self, fields = fields, changed = dirty };
 -      module:fire_event("muc-config-submitted", event);
 -      dirty = event.changed or dirty;
 -
 -      local name = fields['muc#roomconfig_roomname'];
 -      if name ~= self:get_name() then
 -              self:set_name(name);
 -      end
 +      local changed = {};
  
 -      local description = fields['muc#roomconfig_roomdesc'];
 -      if description ~= self:get_description() then
 -              self:set_description(description);
 +      local function handle_option(name, field, allowed)
 +              local new = fields[field];
 +              if new == nil then return; end
 +              if allowed and not allowed[new] then return; end
 +              if new == self["get_"..name](self) then return; end
 +              changed[name] = true;
 +              self["set_"..name](self, new);
        end
  
 -      local persistent = fields['muc#roomconfig_persistentroom'];
 -      dirty = dirty or (self:is_persistent() ~= persistent)
 -      module:log("debug", "persistent=%s", tostring(persistent));
 -
 -      local moderated = fields['muc#roomconfig_moderatedroom'];
 -      dirty = dirty or (self:is_moderated() ~= moderated)
 -      module:log("debug", "moderated=%s", tostring(moderated));
 -
 -      local membersonly = fields['muc#roomconfig_membersonly'];
 -      dirty = dirty or (self:is_members_only() ~= membersonly)
 -      module:log("debug", "membersonly=%s", tostring(membersonly));
 -
 -      local public = fields['muc#roomconfig_publicroom'];
 -      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 event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
 +      module:fire_event("muc-config-submitted", event);
  
 -      local whois = fields['muc#roomconfig_whois'];
 -      if not valid_whois[whois] then
 -          origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
 -          return;
 -      end
 -      local whois_changed = self._data.whois ~= whois
 -      self._data.whois = whois
 -      module:log('debug', 'whois=%s', whois)
 -
 -      local password = fields['muc#roomconfig_roomsecret'];
 -      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);
 +      handle_option("name", "muc#roomconfig_roomname");
 +      handle_option("description", "muc#roomconfig_roomdesc");
 +      handle_option("persistent", "muc#roomconfig_persistentroom");
 +      handle_option("moderated", "muc#roomconfig_moderatedroom");
 +      handle_option("members_only", "muc#roomconfig_membersonly");
 +      handle_option("public", "muc#roomconfig_publicroom");
 +      handle_option("changesubject", "muc#roomconfig_changesubject");
 +      handle_option("historylength", "muc#roomconfig_historylength");
 +      handle_option("whois", "muc#roomconfig_whois", valid_whois);
 +      handle_option("password", "muc#roomconfig_roomsecret");
  
        if self.save then self:save(true); end
 +      if self.locked then
 +              module:fire_event("muc-room-unlocked", { room = self });
 +              self.locked = nil;
 +      end
        origin.send(st.reply(stanza));
  
 -      if dirty or whois_changed then
 +      if next(changed) then
                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'}):up();
 -              end
 -              if whois_changed then
 -                      local code = (whois == 'moderators') and "173" or "172";
 +                              :tag('status', {code = '104'}):up();
 +              if changed.whois then
 +                      local code = (self:get_whois() == 'moderators') and "173" or "172";
                        msg.tags[1]:tag('status', {code = code}):up();
                end
 -
                self:broadcast_message(msg, false)
        end
  end
@@@ -853,7 -881,7 +853,7 @@@ function room_mt:handle_to_room(origin
                        origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
                end
        elseif stanza.name == "message" and type == "groupchat" then
 -              local from, to = stanza.attr.from, stanza.attr.to;
 +              local from = stanza.attr.from;
                local current_nick = self._jid_nick[from];
                local occupant = self._occupants[current_nick];
                if not occupant then -- not in room
                else
                        local from = stanza.attr.from;
                        stanza.attr.from = current_nick;
 -                      local subject = getText(stanza, {"subject"});
 +                      local subject = stanza:get_child_text("subject");
                        if subject 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
 +                                      self:set_subject(current_nick, subject);
                                else
                                        stanza.attr.from = from;
                                        origin.send(st.error_reply(stanza, "auth", "forbidden"));
                                        :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
 +                              if self:get_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
@@@ -1032,7 -1060,7 +1032,7 @@@ function room_mt:can_set_role(actor_jid
        if actor_jid == true then return true; end
  
        local actor = self._occupants[self._jid_nick[actor_jid]];
-       if actor.role == "moderator" then
+       if actor and actor.role == "moderator" then
                if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
                        if actor.affiliation == "owner" or actor.affiliation == "admin" then
                                return true;
diff --combined util/dependencies.lua
index 109a3332e9180c50dcc0915cd4d3af0d53340584,e55b240596a2b563b8216091f20f305e81fe3fd0..9d80d241ad38370c985e662d3b44e26743e070c4
@@@ -1,7 -1,7 +1,7 @@@
  -- Prosody IM
  -- Copyright (C) 2008-2010 Matthew Wild
  -- Copyright (C) 2008-2010 Waqas Hussain
 --- 
 +--
  -- This project is MIT/X11 licensed. Please see the
  -- COPYING file in the source package for more information.
  --
@@@ -35,7 -35,7 +35,7 @@@ function missingdep(name, sources, msg
        print("");
  end
  
 --- COMPAT w/pre-0.8 Debian: The Debian config file used to use 
 +-- COMPAT w/pre-0.8 Debian: The Debian config file used to use
  -- util.ztact, which has been removed from Prosody in 0.8. This
  -- is to log an error for people who still use it, so they can
  -- update their configs.
@@@ -50,9 -50,9 +50,9 @@@ end
  
  function check_dependencies()
        local fatal;
 -      
 +
        local lxp = softreq "lxp"
 -      
 +
        if not lxp then
                missingdep("luaexpat", {
                                ["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-expat0";
@@@ -61,9 -61,9 +61,9 @@@
                        });
                fatal = true;
        end
 -      
 +
        local socket = softreq "socket"
 -      
 +
        if not socket then
                missingdep("luasocket", {
                                ["Debian/Ubuntu"] = "sudo apt-get install liblua5.1-socket2";
@@@ -72,7 -72,7 +72,7 @@@
                        });
                fatal = true;
        end
 -      
 +
        local lfs, err = softreq "lfs"
        if not lfs then
                missingdep("luafilesystem", {
@@@ -82,9 -82,9 +82,9 @@@
                        });
                fatal = true;
        end
 -      
 +
        local ssl = softreq "ssl"
 -      
 +
        if not ssl then
                missingdep("LuaSec", {
                                ["Debian/Ubuntu"] = "http://prosody.im/download/start#debian_and_ubuntu";
@@@ -92,7 -92,7 +92,7 @@@
                                ["Source"] = "http://www.inf.puc-rio.br/~brunoos/luasec/";
                        }, "SSL/TLS support will not be available");
        end
 -      
 +
        local encodings, err = softreq "util.encodings"
        if not encodings then
                if err:match("not found") then
@@@ -140,7 -140,15 +140,15 @@@ function log_warnings(
                if not pcall(lxp.new, { StartDoctypeDecl = false }) then
                        log("error", "The version of LuaExpat on your system leaves Prosody "
                                .."vulnerable to denial-of-service attacks. You should upgrade to "
-                               .."LuaExpat 1.1.1 or higher as soon as possible. See "
+                               .."LuaExpat 1.3.0 or higher as soon as possible. See "
+                               .."http://prosody.im/doc/depends#luaexpat for more information.");
+               end
+               if not lxp.new({}).getcurrentbytecount then
+                       log("error", "The version of LuaExpat on your system does not support "
+                               .."stanza size limits, which may leave servers on untrusted "
+                               .."networks (e.g. the internet) vulnerable to denial-of-service "
+                               .."attacks. You should upgrade to LuaExpat 1.3.0 or higher as "
+                               .."soon as possible. See "
                                .."http://prosody.im/doc/depends#luaexpat for more information.");
                end
        end
diff --combined util/xmppstream.lua
index 550170c94c75d96118cf023be0fe9bcfaeaf093c,73f5e314177f8269a0e50e9a21b7536da1438de9..586ad5f94a4cdaede7ae18b3fcbea3f99a700e69
@@@ -1,12 -1,11 +1,11 @@@
  -- Prosody IM
  -- Copyright (C) 2008-2010 Matthew Wild
  -- Copyright (C) 2008-2010 Waqas Hussain
 --- 
 +--
  -- This project is MIT/X11 licensed. Please see the
  -- COPYING file in the source package for more information.
  --
  
  local lxp = require "lxp";
  local st = require "util.stanza";
  local stanza_mt = st.stanza_mt;
@@@ -20,6 -19,10 +19,10 @@@ local setmetatable = setmetatable
  
  -- COMPAT: w/LuaExpat 1.1.0
  local lxp_supports_doctype = pcall(lxp.new, { StartDoctypeDecl = false });
+ local lxp_supports_xmldecl = pcall(lxp.new, { XmlDecl = false });
+ local lxp_supports_bytecount = not not lxp.new({}).getcurrentbytecount;
+ local default_stanza_size_limit = 1024*1024*10; -- 10MB
  
  module "xmppstream"
  
@@@ -40,25 -43,29 +43,29 @@@ local ns_pattern = "^([^"..ns_separator
  _M.ns_separator = ns_separator;
  _M.ns_pattern = ns_pattern;
  
- function new_sax_handlers(session, stream_callbacks)
+ local function dummy_cb() end
+ function new_sax_handlers(session, stream_callbacks, cb_handleprogress)
        local xml_handlers = {};
 -      
 +
        local cb_streamopened = stream_callbacks.streamopened;
        local cb_streamclosed = stream_callbacks.streamclosed;
        local cb_error = stream_callbacks.error or function(session, e, stanza) error("XML stream error: "..tostring(e)..(stanza and ": "..tostring(stanza) or ""),2); end;
        local cb_handlestanza = stream_callbacks.handlestanza;
 -      
+       cb_handleprogress = cb_handleprogress or dummy_cb;
 +
        local stream_ns = stream_callbacks.stream_ns or xmlns_streams;
        local stream_tag = stream_callbacks.stream_tag or "stream";
        if stream_ns ~= "" then
                stream_tag = stream_ns..ns_separator..stream_tag;
        end
        local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error");
 -      
 +
        local stream_default_ns = stream_callbacks.default_ns;
 -      
 +
        local stack = {};
        local chardata, stanza = {};
+       local stanza_size = 0;
        local non_streamns_depth = 0;
        function xml_handlers:StartElement(tagname, attr)
                if stanza and #chardata > 0 then
@@@ -75,7 -82,7 +82,7 @@@
                        attr.xmlns = curr_ns;
                        non_streamns_depth = non_streamns_depth + 1;
                end
 -              
 +
                for i=1,#attr do
                        local k = attr[i];
                        attr[i] = nil;
                                attr[k] = nil;
                        end
                end
 -              
 +
                if not stanza then --if we are not currently inside a stanza
+                       if lxp_supports_bytecount then
+                               stanza_size = self:getcurrentbytecount();
+                       end
                        if session.notopen then
                                if tagname == stream_tag then
                                        non_streamns_depth = 0;
                                        if cb_streamopened then
+                                               if lxp_supports_bytecount then
+                                                       cb_handleprogress(stanza_size);
+                                                       stanza_size = 0;
+                                               end
                                                cb_streamopened(session, attr);
                                        end
                                else
                        if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then
                                cb_error(session, "invalid-top-level-element");
                        end
 -                      
 +
                        stanza = setmetatable({ name = name, attr = attr, tags = {} }, stanza_mt);
                else -- we are inside a stanza, so add a tag
+                       if lxp_supports_bytecount then
+                               stanza_size = stanza_size + self:getcurrentbytecount();
+                       end
                        t_insert(stack, stanza);
                        local oldstanza = stanza;
                        stanza = setmetatable({ name = name, attr = attr, tags = {} }, stanza_mt);
                        t_insert(oldstanza.tags, stanza);
                end
        end
+       if lxp_supports_xmldecl then
+               function xml_handlers:XmlDecl(version, encoding, standalone)
+                       if lxp_supports_bytecount then
+                               cb_handleprogress(self:getcurrentbytecount());
+                       end
+               end
+       end
+       function xml_handlers:StartCdataSection()
+               if lxp_supports_bytecount then
+                       if stanza then
+                               stanza_size = stanza_size + self:getcurrentbytecount();
+                       else
+                               cb_handleprogress(self:getcurrentbytecount());
+                       end
+               end
+       end
+       function xml_handlers:EndCdataSection()
+               if lxp_supports_bytecount then
+                       if stanza then
+                               stanza_size = stanza_size + self:getcurrentbytecount();
+                       else
+                               cb_handleprogress(self:getcurrentbytecount());
+                       end
+               end
+       end
        function xml_handlers:CharacterData(data)
                if stanza then
+                       if lxp_supports_bytecount then
+                               stanza_size = stanza_size + self:getcurrentbytecount();
+                       end
                        t_insert(chardata, data);
+               elseif lxp_supports_bytecount then
+                       cb_handleprogress(self:getcurrentbytecount());
                end
        end
        function xml_handlers:EndElement(tagname)
+               if lxp_supports_bytecount then
+                       stanza_size = stanza_size + self:getcurrentbytecount()
+               end
                if non_streamns_depth > 0 then
                        non_streamns_depth = non_streamns_depth - 1;
                end
                        end
                        -- Complete stanza
                        if #stack == 0 then
+                               if lxp_supports_bytecount then
+                                       cb_handleprogress(stanza_size);
+                               end
+                               stanza_size = 0;
                                if tagname ~= stream_error_tag then
                                        cb_handlestanza(session, stanza);
                                else
                        error("Failed to abort parsing");
                end
        end
 -      
 +
        if lxp_supports_doctype then
                xml_handlers.StartDoctypeDecl = restricted_handler;
        end
        xml_handlers.Comment = restricted_handler;
        xml_handlers.ProcessingInstruction = restricted_handler;
 -      
 +
        local function reset()
-               stanza, chardata = nil, {};
+               stanza, chardata, stanza_size = nil, {}, 0;
                stack = {};
        end
 -      
 +
        local function set_session(stream, new_session)
                session = new_session;
        end
 -      
 +
        return xml_handlers, { reset = reset, set_session = set_session };
  end
  
- function new(session, stream_callbacks)
-       local handlers, meta = new_sax_handlers(session, stream_callbacks);
-       local parser = new_parser(handlers, ns_separator);
+ function new(session, stream_callbacks, stanza_size_limit)
+       -- Used to track parser progress (e.g. to enforce size limits)
+       local n_outstanding_bytes = 0;
+       local handle_progress;
+       if lxp_supports_bytecount then
+               function handle_progress(n_parsed_bytes)
+                       n_outstanding_bytes = n_outstanding_bytes - n_parsed_bytes;
+               end
+               stanza_size_limit = stanza_size_limit or default_stanza_size_limit;
+       elseif stanza_size_limit then
+               error("Stanza size limits are not supported on this version of LuaExpat")
+       end
+       local handlers, meta = new_sax_handlers(session, stream_callbacks, handle_progress);
+       local parser = new_parser(handlers, ns_separator, false);
        local parse = parser.parse;
  
        return {
                reset = function ()
-                       parser = new_parser(handlers, ns_separator);
+                       parser = new_parser(handlers, ns_separator, false);
                        parse = parser.parse;
+                       n_outstanding_bytes = 0;
                        meta.reset();
                end,
                feed = function (self, data)
-                       return parse(parser, data);
+                       if lxp_supports_bytecount then
+                               n_outstanding_bytes = n_outstanding_bytes + #data;
+                       end
+                       local ok, err = parse(parser, data);
+                       if lxp_supports_bytecount and n_outstanding_bytes > stanza_size_limit then
+                               return nil, "stanza-too-large";
+                       end
+                       return ok, err;
                end,
                set_session = meta.set_session;
        };