Class: Sandbox::Full

Inherits:
Object
  • Object
show all
Defined in:
lib/sandbox.rb

Instance Method Summary collapse

Instance Method Details

#eval(str, opts = {}) ⇒ Object

call-seq:

sandbox.eval(str, opts={})   => obj

Evaluates str as Ruby code inside the sandbox and returns the result. If an option hash opts is provided, any options specified in it take precedence over options specified when sandbox was created. (See Sandbox.new.)

Available options include:

:timeout

The maximum time in seconds which Sandbox#eval is allowed to run before it is forcibly terminated.

:safelevel

The $SAFE level to use during evaluation in the sandbox.

If evaluation times out, Sandbox#eval will raise a Sandbox::TimeoutError. If no timeout is specified, Sandbox#eval will be allowed to run indefinitely.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/sandbox.rb', line 44

def eval(str, opts = {})
  opts = @options.merge(opts)
  if opts[:timeout] or opts[:safelevel]
    th, exc, timed_out = nil, nil, false
    safelevel = opts[:safelevel]
    val = nil
    th = Thread.start(str) do
      $SAFE = safelevel if safelevel and safelevel > $SAFE
      begin
        val = _eval(str)
      rescue Exception => exc
      end
    end
    th.join(opts[:timeout])
    if th.alive?
      if th.respond_to? :kill!
        th.kill!
      else
        th.kill
      end
      timed_out = true
    end
    if timed_out
      raise TimeoutError, "#{self.class}#eval timed out"
    elsif exc
      raise exc
    else
      val
    end
  else
    _eval(str)
  end
end

#load(io, opts = {}) ⇒ Object

call-seq:

sandbox.load(portname, opts={})   => obj

Reads all available data from the given I/O port portname and then evaluates it as a string in sandbox. (See Sandbox#eval.)



85
86
87
# File 'lib/sandbox.rb', line 85

def load(io, opts = {})
  eval(IO.read(io), opts)
end