"""Provisional Linux namespace worker; launched only inside the prepared root."""
import ctypes
import errno
import json
import resource
import sys
import traceback

request = json.loads(sys.stdin.readline())
memory = int(request['mem_limit'])
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32))
lib = ctypes.CDLL('libseccomp.so.2', use_errno=True)
lib.seccomp_init.argtypes = [ctypes.c_uint32]; lib.seccomp_init.restype = ctypes.c_void_p
lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]; lib.seccomp_syscall_resolve_name.restype = ctypes.c_int
lib.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint]
lib.seccomp_load.argtypes = [ctypes.c_void_p]; lib.seccomp_release.argtypes = [ctypes.c_void_p]
ctx = lib.seccomp_init(0x7fff0000)
if not ctx:
    raise RuntimeError('seccomp_init failed')
for name in ('clone','clone3','fork','vfork','execve','execveat','socket','socketpair','mount','umount2','pivot_root','chroot','unshare','setns','ptrace','bpf','perf_event_open','keyctl','add_key','request_key','io_uring_setup','open_by_handle_at'):
    number = lib.seccomp_syscall_resolve_name(name.encode())
    if number >= 0 and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0:
        raise RuntimeError('seccomp rule failed: '+name)
if lib.seccomp_load(ctx) != 0:
    raise RuntimeError('seccomp_load failed')
lib.seccomp_release(ctx)

class Bounded:
    def __init__(self, limit=4096): self.limit, self.text, self.truncated = limit, '', False
    def write(self, s):
        s = str(s); room = max(0, self.limit-len(self.text))
        self.text += s[:room]; self.truncated |= len(s) > room
        return len(s)
    def flush(self): pass

out = Bounded(); sys.stdout = sys.stderr = out
scope = {'__name__': '__main__'}
results = []
for code in request['actions']:
    out.text = ''; out.truncated = False
    try:
        exec(compile(code, '<action>', 'exec'), scope, scope)
        status = 'ok'
    except BaseException:
        status = 'error'; traceback.print_exc(limit=5)
    results.append({'status': status, 'output': out.text, 'truncated': out.truncated})
sys.__stdout__.write(json.dumps({'actions': results})+'\n'); sys.__stdout__.flush()
