#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "moonbit.h" static void bytes_to_cstr(moonbit_bytes_t b, char *out, size_t cap) { int32_t len = Moonbit_array_length(b); size_t n = (size_t)len < cap - 1 ? (size_t)len : cap - 1; memcpy(out, b, n); out[n] = '\0'; } static int set_nonblock_cloexec(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags >= 0) { fcntl(fd, F_SETFL, flags | O_NONBLOCK); } int fdflags = fcntl(fd, F_GETFD, 0); if (fdflags >= 0) { fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC); } return 0; } MOONBIT_FFI_EXPORT int32_t mp_unix_listen(moonbit_bytes_t path_bytes) { char path[108]; bytes_to_cstr(path_bytes, path, sizeof(path)); unlink(path); int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return -1; set_nonblock_cloexec(fd); struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { close(fd); return -1; } if (listen(fd, 16) < 0) { close(fd); return -1; } return fd; } MOONBIT_FFI_EXPORT int32_t mp_unix_accept(int32_t listen_fd) { int fd = accept(listen_fd, NULL, NULL); if (fd < 0) { return -1; } set_nonblock_cloexec(fd); return fd; } MOONBIT_FFI_EXPORT int32_t mp_unix_connect(moonbit_bytes_t path_bytes) { char path[108]; bytes_to_cstr(path_bytes, path, sizeof(path)); int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return -1; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { close(fd); return -1; } return fd; } MOONBIT_FFI_EXPORT int32_t mp_close_fd(int32_t fd) { if (fd < 0) return 0; return close(fd); } MOONBIT_FFI_EXPORT int32_t mp_unlink(moonbit_bytes_t path_bytes) { char path[512]; bytes_to_cstr(path_bytes, path, sizeof(path)); return unlink(path); } MOONBIT_FFI_EXPORT int32_t mp_poll_read(int32_t fd, int32_t timeout_ms) { struct pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; pfd.revents = 0; int r = poll(&pfd, 1, timeout_ms); if (r < 0) return -1; if (r == 0) return 0; return (pfd.revents & (POLLIN | POLLHUP | POLLERR)) ? 1 : 0; } /* Block until one of fds[0..n) is readable or timeout_ms passes; poll(2)'s result. */ MOONBIT_FFI_EXPORT int32_t mp_wait_readable(int32_t *fds, int32_t n, int32_t timeout_ms) { struct pollfd pfd[64]; int k = 0; for (int i = 0; i < n && k < 64; i++) { if (fds[i] < 0) continue; pfd[k].fd = fds[i]; pfd[k].events = POLLIN; pfd[k].revents = 0; k++; } return poll(pfd, (nfds_t)k, timeout_ms); } MOONBIT_FFI_EXPORT int32_t mp_recvmsg_fd(int32_t fd, moonbit_bytes_t buf, int32_t max_len, int32_t *out_fd) { /* out_fd[0] = number of fds received, out_fd[1..] the fds. A client flushes up to 28 fds (libwayland's limit) with one sendmsg, e.g. a Vulkan swapchain making a wl_shm_pool per image: every one of them is needed, in order. */ int32_t out_cap = Moonbit_array_length(out_fd) - 1; out_fd[0] = 0; int32_t cap = Moonbit_array_length(buf); int32_t n = max_len < cap ? max_len : cap; if (n <= 0) return 0; struct iovec iov; iov.iov_base = buf; iov.iov_len = (size_t)n; char cmsg_buf[CMSG_SPACE(sizeof(int) * 32)]; memset(cmsg_buf, 0, sizeof(cmsg_buf)); struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cmsg_buf; msg.msg_controllen = sizeof(cmsg_buf); ssize_t recvd = recvmsg(fd, &msg, MSG_CMSG_CLOEXEC); if (recvd < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) return -1; return -2; } for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { int *fds = (int *)CMSG_DATA(cmsg); size_t num_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int); for (size_t i = 0; i < num_fds; i++) { if (out_fd[0] < out_cap) { out_fd[1 + out_fd[0]] = fds[i]; out_fd[0]++; } else { close(fds[i]); } } } } return (int32_t)recvd; } MOONBIT_FFI_EXPORT int32_t mp_sendmsg_fds(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t *fds, int32_t n_fds) { int32_t cap = Moonbit_array_length(buf); int32_t n = len < cap ? len : cap; if (n <= 0 || n_fds < 0 || n_fds > 28) return -1; struct iovec iov = { .iov_base = buf, .iov_len = (size_t)n }; char cmsg_buf[CMSG_SPACE(sizeof(int) * 28)]; memset(cmsg_buf, 0, sizeof(cmsg_buf)); struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; if (n_fds > 0) { msg.msg_control = cmsg_buf; msg.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds); struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int) * n_fds); memcpy(CMSG_DATA(cmsg), fds, sizeof(int) * n_fds); } return (int32_t)sendmsg(fd, &msg, MSG_NOSIGNAL); } MOONBIT_FFI_EXPORT int32_t mp_sendmsg_fd(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t send_fd) { int32_t cap = Moonbit_array_length(buf); int32_t n = len < cap ? len : cap; if (n <= 0) return 0; struct iovec iov; iov.iov_base = buf; iov.iov_len = (size_t)n; char cmsg_buf[CMSG_SPACE(sizeof(int))]; memset(cmsg_buf, 0, sizeof(cmsg_buf)); struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; if (send_fd >= 0) { msg.msg_control = cmsg_buf; msg.msg_controllen = sizeof(cmsg_buf); struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); memcpy(CMSG_DATA(cmsg), &send_fd, sizeof(int)); } size_t total = 0; while (total < (size_t)n) { iov.iov_base = buf + total; iov.iov_len = (size_t)n - total; ssize_t sent = sendmsg(fd, &msg, MSG_NOSIGNAL); if (sent < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 }; poll(&pfd, 1, 50); continue; } return -1; } total += (size_t)sent; // Only send ancillary data on the first sendmsg call msg.msg_control = NULL; msg.msg_controllen = 0; } return (int32_t)total; } MOONBIT_FFI_EXPORT int32_t mp_memfd_create(moonbit_bytes_t name_bytes, int32_t size) { char name[64]; bytes_to_cstr(name_bytes, name, sizeof(name)); int fd = memfd_create(name, MFD_CLOEXEC); if (fd < 0) return -1; if (size > 0 && ftruncate(fd, (off_t)size) < 0) { close(fd); return -1; } return fd; } MOONBIT_FFI_EXPORT int32_t mp_pwrite_bytes(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t offset) { int32_t cap = Moonbit_array_length(buf); int32_t n = len < cap ? len : cap; if (offset < 0) { /* A pipe or socket (clipboard paste, screen recording): write what fits now. 0 when it is * full, -1 on error. A reader that went away must not kill us with SIGPIPE. */ signal(SIGPIPE, SIG_IGN); int fl = fcntl(fd, F_GETFL); if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK); ssize_t w = write(fd, buf, (size_t)n); if (w < 0) return (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ? 0 : -1; return (int32_t)w; } ssize_t w = pwrite(fd, buf, (size_t)n, (off_t)offset); return w < 0 ? -1 : (int32_t)w; } MOONBIT_FFI_EXPORT moonbit_bytes_t mp_mmap_read(int32_t fd, int32_t size) { if (fd < 0 || size <= 0) { return moonbit_make_bytes_raw(0); } struct stat st; if (fstat(fd, &st) < 0 || st.st_size < (off_t)size) { return moonbit_make_bytes_raw(0); } void *ptr = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED, fd, 0); if (ptr == MAP_FAILED) { return moonbit_make_bytes_raw(0); } moonbit_bytes_t out = moonbit_make_bytes_raw(size); memcpy(out, ptr, (size_t)size); munmap(ptr, (size_t)size); return out; } MOONBIT_FFI_EXPORT moonbit_bytes_t mp_read_file(moonbit_bytes_t path_bytes) { char path[512]; bytes_to_cstr(path_bytes, path, sizeof(path)); FILE *f = fopen(path, "rb"); if (!f) return moonbit_make_bytes_raw(0); fseek(f, 0, SEEK_END); long sz = ftell(f); if (sz <= 0) { fclose(f); return moonbit_make_bytes_raw(0); } fseek(f, 0, SEEK_SET); moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)sz); size_t rd = fread(out, 1, (size_t)sz, f); fclose(f); if (rd != (size_t)sz) { return moonbit_make_bytes_raw(0); } return out; } MOONBIT_FFI_EXPORT int32_t mp_write_file(moonbit_bytes_t path_bytes, moonbit_bytes_t buf, int32_t len) { char path[512]; bytes_to_cstr(path_bytes, path, sizeof(path)); int32_t cap = Moonbit_array_length(buf); int32_t n = len < cap ? len : cap; FILE *f = fopen(path, "wb"); if (!f) return -1; size_t wr = fwrite(buf, 1, (size_t)n, f); fclose(f); return wr == (size_t)n ? 0 : -1; } MOONBIT_FFI_EXPORT void mp_sleep_ms(int32_t ms) { if (ms > 0) { usleep((useconds_t)ms * 1000); } } /* SIGUSR1: reload the panel modules (compositor/host/control.mbt). The handler only sets a * flag; it is installed without SA_RESTART, so a blocked poll() returns EINTR and the main loop * runs a pass. */ static volatile sig_atomic_t mp_sigusr1_seen = 0; static int mp_sigusr1_installed = 0; static void mp_on_sigusr1(int sig) { (void)sig; mp_sigusr1_seen = 1; } MOONBIT_FFI_EXPORT int32_t mp_take_sigusr1(void) { if (!mp_sigusr1_installed) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = mp_on_sigusr1; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL); mp_sigusr1_installed = 1; } if (mp_sigusr1_seen) { mp_sigusr1_seen = 0; return 1; } return 0; } MOONBIT_FFI_EXPORT int32_t mp_getpid(void) { return (int32_t)getpid(); } /* Local wall-clock field: 0 year, 1 month(1-12), 2 day, 3 hour, 4 minute, 5 second, 6 weekday(0=Sun). */ MOONBIT_FFI_EXPORT int32_t mp_wall_time_field(int32_t which) { time_t t = time(NULL); struct tm tmv; localtime_r(&t, &tmv); switch (which) { case 0: return tmv.tm_year + 1900; case 1: return tmv.tm_mon + 1; case 2: return tmv.tm_mday; case 3: return tmv.tm_hour; case 4: return tmv.tm_min; case 5: return tmv.tm_sec; case 6: return tmv.tm_wday; default: return 0; } } /* True when `name` resolves to an executable via PATH (or is an executable path). */ MOONBIT_FFI_EXPORT int32_t mp_has_exe(moonbit_bytes_t name_bytes) { char name[256]; bytes_to_cstr(name_bytes, name, sizeof(name)); if (strchr(name, '/')) return access(name, X_OK) == 0; const char *path = getenv("PATH"); if (!path) return 0; char *copy = strdup(path); char *save = NULL; int found = 0; for (char *dir = strtok_r(copy, ":", &save); dir && !found; dir = strtok_r(NULL, ":", &save)) { char full[1024]; snprintf(full, sizeof(full), "%s/%s", dir, name); if (access(full, X_OK) == 0) found = 1; } free(copy); return found; } /* Private session bus for launched apps, so single-instance apps (Firefox, Kate, * Dolphin...) don't forward the launch to an instance on the host session. * Started lazily; dies with the compositor. * * Only when nested inside another graphical session (WAYLAND_DISPLAY or DISPLAY set). * As a login session (--drm) the session bus is ours, and it is where the PAM-unlocked * gnome-keyring (org.freedesktop.secrets), portals and notifications live: a private bus * would hide them, so apps would D-Bus-activate a fresh, locked keyring on it. * * An xdg-document-portal activated on the private bus must not see our XDG_RUNTIME_DIR: every * instance mounts $XDG_RUNTIME_DIR/doc, whatever bus it is on, so a second one takes over the * host session's mount and removes it when this bus exits. The host's portal keeps running * without it, and `flatpak run` fails ("Can't find source path .../doc/by-app/APP") until it is * restarted. So the bus gets its own config, whose first service directory starts that service * with a runtime directory of this compositor's own. (Not starting it at all is no way out: * xdg-desktop-portal then exports nothing.) Without that config there is no private bus. */ static char private_bus[256]; static int private_bus_tried = 0; static int env_set(const char *name) { const char *v = getenv(name); return v && v[0]; } /* Replace `path` with `text`, atomically. */ static int write_text_file(const char *path, const char *text) { char tmp[PATH_MAX]; if (snprintf(tmp, sizeof(tmp), "%s.%d", path, (int)getpid()) >= (int)sizeof(tmp)) return -1; FILE *f = fopen(tmp, "w"); if (!f) return -1; int ok = fputs(text, f) >= 0; ok = fclose(f) == 0 && ok; if (ok && rename(tmp, path) == 0) return 0; unlink(tmp); return -1; } /* mkdir that accepts a directory already there. */ static int make_dir(const char *path) { return mkdir(path, 0700) == 0 || errno == EEXIST ? 0 : -1; } /* Write the private bus's config and its document portal service file, and put the config's * path in `conf`. Both stay in place: dbus-daemon rereads its service directories as it runs. */ static int write_private_bus_config(char *conf, size_t cap) { /* One directory per compositor: two nested ones would take over each other's mounts too. */ char dir[PATH_MAX - 128]; const char *rt = getenv("XDG_RUNTIME_DIR"); if (rt && rt[0] == '/') { if (snprintf(dir, sizeof(dir), "%s/chandra", rt) >= (int)sizeof(dir)) return -1; if (make_dir(dir) != 0) return -1; if (snprintf(dir, sizeof(dir), "%s/chandra/private-bus-%d", rt, (int)getpid()) >= (int)sizeof(dir)) return -1; if (make_dir(dir) != 0) return -1; } else { strcpy(dir, "/tmp/chandra-bus-XXXXXX"); if (!mkdtemp(dir)) return -1; } /* The path goes into XML and into an Exec= command line as it is. */ if (strpbrk(dir, "<>& \t\n\"'\\")) return -1; char runtime[PATH_MAX]; snprintf(runtime, sizeof(runtime), "%s/runtime", dir); if (make_dir(runtime) != 0) return -1; const char *portal = NULL; if (access("/usr/lib/xdg-document-portal", X_OK) == 0) portal = "/usr/lib/xdg-document-portal"; else if (access("/usr/libexec/xdg-document-portal", X_OK) == 0) portal = "/usr/libexec/xdg-document-portal"; /* Not where we know to look: don't start it at all, rather than with the shared directory. */ char exec[2 * PATH_MAX]; if (portal) snprintf(exec, sizeof(exec), "/usr/bin/env XDG_RUNTIME_DIR=%s %s", runtime, portal); else strcpy(exec, "/bin/false"); char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/org.freedesktop.portal.Documents.service", dir); char service[2 * PATH_MAX + 128]; snprintf(service, sizeof(service), "[D-BUS Service]\n" "Name=org.freedesktop.portal.Documents\n" "Exec=%s\n", exec); if (write_text_file(path, service) != 0) return -1; /* Of two service files for one name, the one in the earlier directory wins. */ char xml[PATH_MAX + 256]; snprintf(xml, sizeof(xml), "\n" " %s\n" " /usr/share/dbus-1/session.conf\n" "\n", dir); if (snprintf(conf, cap, "%s/bus.conf", dir) >= (int)cap) return -1; return write_text_file(conf, xml); } static void start_private_bus(void) { if (private_bus_tried) return; private_bus_tried = 1; if (!env_set("WAYLAND_DISPLAY") && !env_set("DISPLAY")) return; char conf[PATH_MAX]; if (write_private_bus_config(conf, sizeof(conf)) != 0) return; int fds[2]; if (pipe(fds) != 0) return; pid_t pid = fork(); if (pid < 0) { close(fds[0]); close(fds[1]); return; } if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGTERM); close(fds[0]); char arg[64]; snprintf(arg, sizeof(arg), "--print-address=%d", fds[1]); char conf_arg[PATH_MAX + 16]; snprintf(conf_arg, sizeof(conf_arg), "--config-file=%s", conf); execlp("dbus-daemon", "dbus-daemon", conf_arg, "--nofork", arg, (char *)NULL); _exit(127); } close(fds[1]); ssize_t n = read(fds[0], private_bus, sizeof(private_bus) - 1); close(fds[0]); if (n > 0) { private_bus[n] = 0; char *nl = strchr(private_bus, '\n'); if (nl) *nl = 0; } else { private_bus[0] = 0; } } /* The environment of a launched app (in the forked child): our Wayland socket, and the * private bus when nested (see start_private_bus). */ static void app_env(const char *cmd, const char *display) { /* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */ signal(SIGCHLD, SIG_DFL); signal(SIGPIPE, SIG_DFL); /* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak * on the real session bus, so they keep it; the sandbox isolates their instances anyway. */ if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1); setenv("WAYLAND_DISPLAY", display, 1); unsetenv("DISPLAY"); /* Make toolkits pick our Wayland socket, not X11 or the host session. */ setenv("XDG_SESSION_TYPE", "wayland", 1); setenv("QT_QPA_PLATFORM", "wayland", 1); setenv("GDK_BACKEND", "wayland", 1); setenv("SDL_VIDEODRIVER", "wayland", 1); setenv("MOZ_ENABLE_WAYLAND", "1", 1); setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1); setenv("CLUTTER_BACKEND", "wayland", 1); } /* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */ MOONBIT_FFI_EXPORT int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { char cmd[2048]; char display[512]; bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd)); bytes_to_cstr(display_bytes, display, sizeof(display)); signal(SIGCHLD, SIG_IGN); /* no zombies */ start_private_bus(); pid_t pid = fork(); if (pid < 0) return -1; if (pid == 0) { setsid(); app_env(cmd, display); execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); _exit(127); } return 0; } static uint64_t mono_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void write_all(int fd, const char *p, size_t n) { while (n > 0) { ssize_t w = write(fd, p, n); if (w < 0 && errno == EINTR) continue; if (w <= 0) return; p += w; n -= (size_t)w; } } /* Keep the last LAUNCH_TAIL bytes an app wrote. */ #define LAUNCH_TAIL 2048 struct tail { char buf[LAUNCH_TAIL]; size_t len; }; static void tail_add(struct tail *t, const char *p, size_t n) { if (n >= LAUNCH_TAIL) { memcpy(t->buf, p + n - LAUNCH_TAIL, LAUNCH_TAIL); t->len = LAUNCH_TAIL; return; } if (t->len + n > LAUNCH_TAIL) { size_t drop = t->len + n - LAUNCH_TAIL; memmove(t->buf, t->buf + drop, t->len - drop); t->len -= drop; } memcpy(t->buf + t->len, p, n); t->len += n; } /* Copy what is readable on `from` to our stderr (the session log) and into `t`. 0 at EOF. */ static int pump(int from, struct tail *t) { char buf[4096]; for (;;) { ssize_t n = read(from, buf, sizeof(buf)); if (n > 0) { write_all(2, buf, (size_t)n); tail_add(t, buf, (size_t)n); continue; } if (n < 0 && errno == EINTR) continue; if (n < 0 && errno == EAGAIN) return 1; return 0; } } /* ---- the launch monitor ---- * A watched launch runs this binary again, as MONITOR_ARG0 (monitor_entry takes over before * anything else in the new process starts). It must not be a plain fork of the compositor: that * child lives as long as the app does and keeps a snapshot of the compositor's whole heap, which * stays allocated (and went to swap) as the compositor's own copy changes. */ #define MONITOR_ARG0 "chandra-launch-monitor" #define MONITOR_FD 3 /* its end of the report socket */ /* Start `cmd` with its stdout and stderr on a pipe, copy that output to our stderr (the session * log) and keep its last 2 KiB; report on `report` when it exits (see mp_spawn_watch). `bus` is * the compositor's private session bus, "" when there is none. */ static void launch_monitor(const char *cmd, const char *display, const char *bus, int report) { prctl(PR_SET_NAME, "chandra-launch"); signal(SIGCHLD, SIG_DFL); signal(SIGPIPE, SIG_IGN); /* the compositor may stop listening; keep copying output */ /* Hold nothing of the compositor's (DRM, seat, client sockets) for the app's lifetime. */ for (int fd = 3; fd < 1024; fd++) if (fd != report) close(fd); fcntl(report, F_SETFD, FD_CLOEXEC); snprintf(private_bus, sizeof(private_bus), "%s", bus); int out[2]; uint64_t t0 = mono_ms(); pid_t app = pipe2(out, O_CLOEXEC) == 0 ? fork() : -1; if (app < 0) { char msg[128]; int n = snprintf(msg, sizeof(msg), "exit 127 0\nfork failed: %s\n", strerror(errno)); write_all(report, msg, (size_t)n); _exit(1); } if (app == 0) { /* The command's stdout and stderr go to the monitor; none of our other fds leak into it. */ dup2(out[1], 1); dup2(out[1], 2); for (int fd = 3; fd < 1024; fd++) close(fd); app_env(cmd, display); execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); _exit(127); } close(out[1]); fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL, 0) | O_NONBLOCK); struct tail t = { .len = 0 }; int open_out = 1, reported = 0; while (open_out || !reported) { if (open_out) { struct pollfd p = { .fd = out[0], .events = POLLIN }; poll(&p, 1, reported ? -1 : 100); open_out = pump(out[0], &t); } if (!reported) { int st = 0; pid_t r = waitpid(app, &st, open_out ? WNOHANG : 0); if (r == app) { if (open_out) open_out = pump(out[0], &t); /* what it wrote just before exiting */ char head[64]; int n = WIFSIGNALED(st) ? snprintf(head, sizeof(head), "signal %d %llu\n", WTERMSIG(st), (unsigned long long)(mono_ms() - t0)) : snprintf(head, sizeof(head), "exit %d %llu\n", WEXITSTATUS(st), (unsigned long long)(mono_ms() - t0)); write_all(report, head, (size_t)n); fprintf(stderr, "chandra-launch: `%s` %s", cmd, head); /* "... exit 1 230\n" in the session log */ write_all(report, t.buf, t.len); close(report); reported = 1; } } } _exit(0); } /* glibc passes constructors main's arguments. */ __attribute__((constructor)) static void monitor_entry(int argc, char **argv) { if (argc == 4 && argv && strcmp(argv[0], MONITOR_ARG0) == 0) launch_monitor(argv[1], argv[2], argv[3], MONITOR_FD); } /* Launch `cmd` like mp_spawn, watched: a small monitor process (above) starts it with its stdout * and stderr on a pipe, copies that output to our stderr (the session log, as before) and keeps its * last 2 KiB. When `sh -c cmd` exits the monitor reports on the returned socket (non-blocking): * "exit CODE MS\n" or "signal NUM MS\n" (MS = how long it ran), then the output tail. * The socket closes after that. The monitor keeps copying output from anything the command left * running, until nothing holds the pipe open. Returns our end, or -1 when nothing could start. */ MOONBIT_FFI_EXPORT int32_t mp_spawn_watch(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { char cmd[2048]; char display[512]; bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd)); bytes_to_cstr(display_bytes, display, sizeof(display)); signal(SIGCHLD, SIG_IGN); /* the monitor is never our zombie */ start_private_bus(); int rep[2]; /* A socket, not a pipe: the compositor reads every fd it watches with recvmsg. */ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, rep) != 0) return -1; posix_spawn_file_actions_t actions; posix_spawnattr_t attr; posix_spawn_file_actions_init(&actions); posix_spawnattr_init(&attr); /* (Onto itself, when it already is MONITOR_FD, this clears close-on-exec.) */ posix_spawn_file_actions_adddup2(&actions, rep[1], MONITOR_FD); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSID); char *argv[] = { MONITOR_ARG0, cmd, display, private_bus, NULL }; pid_t mon; /* /proc/self/exe: this very build, even after an update replaced the file. */ int err = posix_spawn(&mon, "/proc/self/exe", &actions, &attr, argv, environ); posix_spawn_file_actions_destroy(&actions); posix_spawnattr_destroy(&attr); close(rep[1]); if (err != 0) { close(rep[0]); return -1; } set_nonblock_cloexec(rep[0]); return rep[0]; } /* Names of "*.desktop" files in `dir`, newline-separated. */ MOONBIT_FFI_EXPORT moonbit_bytes_t mp_list_desktop(moonbit_bytes_t dir_bytes) { char dir[512]; bytes_to_cstr(dir_bytes, dir, sizeof(dir)); DIR *d = opendir(dir); if (!d) return moonbit_make_bytes_raw(0); size_t cap = 4096, len = 0; char *buf = malloc(cap); struct dirent *e; while ((e = readdir(d)) != NULL) { size_t n = strlen(e->d_name); if (n < 9 || strcmp(e->d_name + n - 8, ".desktop") != 0) continue; if (len + n + 2 > cap) { cap = (len + n + 2) * 2; buf = realloc(buf, cap); } memcpy(buf + len, e->d_name, n); len += n; buf[len++] = '\n'; } closedir(d); moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len); memcpy(out, buf, len); free(buf); return out; } MOONBIT_FFI_EXPORT moonbit_bytes_t mp_getenv(moonbit_bytes_t name_bytes) { char name[128]; bytes_to_cstr(name_bytes, name, sizeof(name)); const char *v = getenv(name); if (!v) return moonbit_make_bytes_raw(0); size_t n = strlen(v); moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n); memcpy(out, v, n); return out; } /* mkdir -p; returns 0 when the directory exists afterwards. */ MOONBIT_FFI_EXPORT int32_t mp_mkdir_p(moonbit_bytes_t path_bytes) { char path[512]; bytes_to_cstr(path_bytes, path, sizeof(path)); for (char *p = path + 1; *p; p++) { if (*p == '/') { *p = 0; mkdir(path, 0755); *p = '/'; } } if (mkdir(path, 0755) != 0 && errno != EEXIST) return -1; return 0; } /* Read a small /proc or /sys file (they report size 0, so read until EOF; capped at 64 KiB). */ MOONBIT_FFI_EXPORT moonbit_bytes_t mp_read_proc(moonbit_bytes_t path_bytes) { char path[512]; bytes_to_cstr(path_bytes, path, sizeof(path)); FILE *f = fopen(path, "rb"); if (!f) return moonbit_make_bytes_raw(0); static char buf[65536]; size_t n = fread(buf, 1, sizeof(buf), f); fclose(f); moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n); memcpy(out, buf, n); return out; } /* Run a program with its stdin and stdout on one end of a socket pair and return the other end * (-1 on failure). `argv_bytes` holds the arguments separated by '\n'. stderr is inherited (the * session log). The child is not waited for: SIGCHLD is ignored (see mp_spawn) or it is reaped * by the double fork below. Used for polkit's setuid authentication helper. */ MOONBIT_FFI_EXPORT int32_t mp_spawn_socket(moonbit_bytes_t argv_bytes) { size_t n = Moonbit_array_length(argv_bytes); char *buf = malloc(n + 1); if (!buf) return -1; memcpy(buf, argv_bytes, n); buf[n] = 0; char *argv[16]; int argc = 0; char *save = NULL; for (char *a = strtok_r(buf, "\n", &save); a && argc < 15; a = strtok_r(NULL, "\n", &save)) argv[argc++] = a; argv[argc] = NULL; if (argc == 0) { free(buf); return -1; } int sv[2]; if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) { free(buf); return -1; } pid_t pid = fork(); if (pid < 0) { close(sv[0]); close(sv[1]); free(buf); return -1; } if (pid == 0) { /* Double fork so the helper is never our zombie. */ pid_t inner = fork(); if (inner != 0) _exit(inner < 0 ? 1 : 0); signal(SIGCHLD, SIG_DFL); signal(SIGPIPE, SIG_DFL); dup2(sv[1], 0); dup2(sv[1], 1); for (int fd = 3; fd < 1024; fd++) close(fd); execv(argv[0], argv); _exit(127); } close(sv[1]); free(buf); int status; waitpid(pid, &status, 0); return sv[0]; }