/* Tiny process service: fake ttys for the browser's curl helpers. */ #include #include #include #include #include #include #include #include #include #include #include "host.h" #include "fs.h" #include "proc.h" #define HOST_TTY_MAX 8 struct host_tty { int used; int rfd; int wfd; }; static struct host_tty ttys[HOST_TTY_MAX]; int host_tty_create(void) { int i; int fds[2]; for (i = 0; i < HOST_TTY_MAX; i++) { if (ttys[i].used) continue; if (pipe2(fds, O_NONBLOCK | O_CLOEXEC) != 0) return -1; ttys[i].used = 1; ttys[i].rfd = fds[0]; ttys[i].wfd = fds[1]; return i + 1; } return -1; } int host_tty_read(int id, char *buf, unsigned int max) { ssize_t n; if (id <= 0 || id > HOST_TTY_MAX) return -1; id--; if (!ttys[id].used) return -1; n = read(ttys[id].rfd, buf, max); if (n < 0) return (errno == EAGAIN || errno == EWOULDBLOCK) ? 0 : -1; return (int)n; } static const char *exec_path(const char *path, char *buf, size_t cap) { if (!path || !path[0]) return 0; if (!strcmp(path, "/ramfs/bin/curl") && host_curl_bin[0]) return host_curl_bin; if (path[0] == '/') { if (host_guest_to_host(path, buf, cap) != 0) return 0; if (access(buf, X_OK) == 0) return buf; } if (access(path, X_OK) == 0) return path; return 0; } int host_spawn(const char *path, const char *arg, int tty, const char *cwd) { char exe_buf[HOST_PATH_MAX]; char cwd_buf[HOST_PATH_MAX]; const char *exe; const char *cwd_host = 0; pid_t pid; exe = exec_path(path, exe_buf, sizeof(exe_buf)); if (!exe) { fprintf(stderr, "browser-host: cannot find helper %s\n", path); return -1; } if (cwd && cwd[0] && host_guest_to_host(cwd, cwd_buf, sizeof(cwd_buf)) == 0) cwd_host = cwd_buf; pid = fork(); if (pid < 0) return -1; if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL); if (tty > 0 && tty <= HOST_TTY_MAX && ttys[tty - 1].used) { int wfd = ttys[tty - 1].wfd; dup2(wfd, STDOUT_FILENO); dup2(wfd, STDERR_FILENO); close(ttys[tty - 1].rfd); if (wfd > STDERR_FILENO) close(wfd); } if (cwd_host) chdir(cwd_host); if (arg && arg[0]) { char *const argv[] = { (char *)exe, (char *)arg, 0 }; execv(exe, argv); } else { char *const argv[] = { (char *)exe, 0 }; execv(exe, argv); } _exit(127); } return (int)pid; } int host_alive(unsigned int pid) { int status; if (pid == 0) return 0; for (;;) { pid_t r = waitpid((pid_t)pid, &status, WNOHANG); if (r == 0) return 1; if (r == (pid_t)pid) return 0; if (errno == EINTR) continue; return 0; } } int host_kill(unsigned int pid) { if (pid == 0) return -1; return kill((pid_t)pid, SIGKILL) == 0 ? 0 : -1; }