#include "starter.h" uint64_t time_start; // get time in milliseconds uint64_t getmstime() { struct timeval tm; gettimeofday(&tm, NULL); return (uint64_t) tm.tv_sec * 1000 + (uint64_t) tm.tv_usec / 1000; } // time limit realisation static int killafter(void *arg) { // die when parent dies if (prctl(PR_SET_PDEATHSIG, SIGKILL)) die("cannot PR_SET_PDEATHSIG for child process: %m\n"); struct killparams* params = (struct killparams*) arg; struct timespec tw = {params -> time / 1000, ((params->time) % 1000+5) * 1000000}; struct timespec tr; nanosleep(&tw, &tr); kill(params->pid, SIGKILL); return 0; } #define STACK_SIZE 1000000 static char nmstack[STACK_SIZE]; static char killstack[STACK_SIZE]; // setup user namespace static void prepare_userns(int pid) { char path[100]; char line[100]; int uid = 0;// root int gid = 0;// root int unprivileged_uid = 66534;// nobody int unprivileged_gid = 65534;// nogroup sprintf(path, "/proc/%d/uid_map", pid); sprintf(line, "0 %d 1\n1 %d 1000\n", uid, unprivileged_uid);// map root to uid 0,nobody to unprivileged uid write_file(path, line); sprintf(path, "/proc/%d/setgroups", pid); sprintf(line, "deny"); write_file(path, line); sprintf(path, "/proc/%d/gid_map", pid); sprintf(line, "0 %d 1\n1 %d 1000\n", gid, unprivileged_gid);// map root to gid 0,nogroup to unprivileged gid write_file(path, line); } int starter(char* working_path, struct limits limits, struct params params) { if(setuid(0)) die("must be run as root"); if(setgid(0)) die("must be run as root"); // get binary path char* real_path=working_path; //get_real_path(real_path, argv[0]); if(chdir(real_path)) die("unable to chdir to binary path: %m"); // set random seed srand(time(NULL)); // setup parameters prepare_cgroup(&limits); if (pipe(params.fd) < 0) die("can't open pipe: %m");// a pipe to report readiness int clone_flags = SIGCHLD | CLONE_NEWUTS | CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWIPC | CLONE_NEWCGROUP; int nsrun_pid = clone(nsrun, nmstack + STACK_SIZE, clone_flags, ¶ms);// make new namespace prepare_userns(nsrun_pid); if (nsrun_pid < 0) die("faled to clone"); add_to_cgroup(nsrun_pid); if (write(params.fd[1], "OK", 2) != 2) die("Failed to write to pipe: %m");// report readiness struct killparams killparams; killparams.time = limits.time; killparams.pid = nsrun_pid; int kill_pid = clone(killafter, killstack + STACK_SIZE, SIGCHLD, &killparams); time_start = getmstime(); if (waitpid(nsrun_pid, NULL, 0) == -1) die("Failed to wait pid %d: %m\n", nsrun_pid); kill(kill_pid, SIGKILL);// kill killer int time = getmstime() - time_start; if(chdir(params.shared_folder)) die("Failed to chdir to shared folder:%m"); if(time >= limits.time) { write_file("time", "-1"); } else { char* timestr = NULL; asprintf(×tr, "%d", time); write_file("time", timestr); free(timestr); } int memory = check_mem(); char* memstr = NULL; asprintf(&memstr, "%d", memory); write_file("memory", memstr); free(memstr); remove_cgroup(); return 0; }