Class: Secure::ChildProcess

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

Instance Method Summary collapse

Constructor Details

#initialize(opts, read_file, write_file) ⇒ ChildProcess

Returns a new instance of ChildProcess.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/secure/child_process.rb', line 5

def initialize(opts, read_file, write_file)
  read_file.close
  @pipe = write_file
  @timeout = opts[:timeout]
  @limit_memory = opts[:limit_memory]
  @limit_cpu = opts[:limit_cpu]
  @limit_files = opts[:limit_files]
  @limit_procs = opts[:limit_procs]
  @pipe_stdout = opts[:pipe_stdout]
  @pipe_stderr = opts[:pipe_stderr]
  @pipe_stdin = opts[:pipe_stdin]
  @run_before = opts[:run_before]
  @safe_value = opts[:safe] || 3
end

Instance Method Details

#decorate_with_guard_threads(thread) ⇒ Object



66
67
68
# File 'lib/secure/child_process.rb', line 66

def decorate_with_guard_threads(thread)
  GuardThread.kill_thread_on_timeout(@timeout, thread) if @timeout
end

#executeObject



70
71
72
73
# File 'lib/secure/child_process.rb', line 70

def execute
  ret = safely_run_block { yield }
  @pipe.write(Base64.encode64(Marshal.dump(ret)))
end

#guard_threadsObject



20
21
22
# File 'lib/secure/child_process.rb', line 20

def guard_threads
  @guard_threads || []
end

#redirect_filesObject



31
32
33
34
35
# File 'lib/secure/child_process.rb', line 31

def redirect_files
  $stdout.reopen(@pipe_stdout) if @pipe_stdout
  $stderr.reopen(@pipe_stderr) if @pipe_stderr
  $stdin.reopen(@pipe_stdin) if @pipe_stdin
end

#run_before_methodsObject



37
38
39
40
41
42
43
44
# File 'lib/secure/child_process.rb', line 37

def run_before_methods
  return unless @run_before
  if @run_before.is_a? Array
    @run_before.each &:call
  else
    @run_before.call
  end
end

#safely_run_blockObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/secure/child_process.rb', line 52

def safely_run_block
  redirect_files
  thread = Thread.start do
    sleep
    secure_process
    yield
  end
  decorate_with_guard_threads(thread)
  thread.wakeup
  Response.success(thread.value)
rescue Exception => e
  Response.error(e)
end

#secure_processObject



46
47
48
49
50
# File 'lib/secure/child_process.rb', line 46

def secure_process
  run_before_methods
  set_resource_limits
  $SAFE = @safe_value
end

#set_resource_limitsObject



24
25
26
27
28
29
# File 'lib/secure/child_process.rb', line 24

def set_resource_limits
  Process::setrlimit(Process::RLIMIT_AS, @limit_memory) if @limit_memory
  Process::setrlimit(Process::RLIMIT_CPU, @limit_cpu, 1 + @limit_cpu) if @limit_cpu
  Process::setrlimit(Process::RLIMIT_NOFILE, @limit_files, @limit_files) if @limit_files
  Process::setrlimit(Process::RLIMIT_NPROC, @limit_procs, @limit_procs) if @limit_procs
end