【问题标题】:Execution time limit for a Lua script called from the C API从 C API 调用的 Lua 脚本的执行时间限制
【发布时间】:2011-03-24 23:19:08
【问题描述】:
luaL_loadfile(mState, path.c_str());
lua_pcall(mState, 0, 0, 0);

有没有办法为这两个加载然后执行 lua 文件的 C++ 语句设置执行时间限制(比如 10-20 秒)?

由于 Lua 文件不受信任,我不希望恶意用户在 Lua 代码中无限循环地挂起程序。

标记 C 因为 Lua API 是 C,标记 C++ 因为我使用 C++

【问题讨论】:

    标签: c++ c lua lua-api


    【解决方案1】:

    有 lua_sethook 可用于告诉解释器在执行每个“计数”指令后调用一个钩子。这样您就可以监控用户脚本并在它耗尽其配额时终止它:

     int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
    

    这也可以在 Lua 中使用:

    debug.sethook(function() print("That's enough for today"); os.exit(0); end, "", 10000)
    for i=1,10000 do end
    

    如果您使用来自http://lua-users.org/wiki/SandBoxes 的技术,那么您可以使用完全来自 Lua 的sethook() 和朋友设置一个安全的执行环境,然后在执行用户脚本时切换到沙盒模式。我在这里试过了,只是为了让你开始:

    -- set an execution quota 
    local function set_quota(secs)
     local st=os.clock()
     function check() 
      if os.clock()-st > secs then 
        debug.sethook() -- disable hooks
        error("quota exceeded")
      end
     end
     debug.sethook(check,"",100000);
    end
    
    -- these are the global objects, the user can use:
    local env = {print=print}
    
    -- The user code is allowed to run for 5 seconds.
    set_quota(5)
    
    -- run code under environment:
    local function run(untrusted_code)
      local untrusted_function, message = loadstring(untrusted_code)
      if not untrusted_function then return nil, message end
      setfenv(untrusted_function, env)
      return pcall(untrusted_function)
    end
    
    -- here is the user code:
    local userscript=[[
    function fib(n) 
     if n<2 then return n
     else return fib(n-2)+fib(n-1)
     end
    end
    for n=1,42 do print(n,fib(n)) end
    ]]
    -- call it:
    local r,m=run(userscript)
    print(r,m)
    

    这应该打印 fib() 的值 5 秒,然后显示错误。

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 2012-08-25
      • 2013-06-24
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多