#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#define REQUIRE(x) do { if (!(x)) { fprintf(stderr, "failed: %s\n", #x); exit(1); } } while (0)
static const char payload[] = "HESELA42";

static uintmax_t number(const char *s) {
    char *end;
    errno = 0;
    uintmax_t value = strtoumax(s, &end, 10);
    REQUIRE(*s && *s != '-' && !*end && !errno);
    return value;
}

static int descriptor(const char *s) {
    uintmax_t value = number(s);
    REQUIRE(value <= INT_MAX);
    return (int)value;
}

static void same_file(int fd, uintmax_t dev, uintmax_t ino) {
    struct stat info;
    REQUIRE(fstat(fd, &info) == 0);
    REQUIRE((uintmax_t)info.st_dev == dev && (uintmax_t)info.st_ino == ino);
    REQUIRE(S_ISREG(info.st_mode));
}

static void flags(int source, int target, int alias) {
    REQUIRE(fcntl(source, F_GETFD) == FD_CLOEXEC);
    REQUIRE(fcntl(target, F_GETFD) == FD_CLOEXEC);
    REQUIRE(fcntl(alias, F_GETFD) == 0);
}

static void closed(int fd) {
    errno = 0;
    REQUIRE(fcntl(fd, F_GETFD) == -1 && errno == EBADF);
}

int main(int argc, char **argv) {
    if (argc == 7 && strcmp(argv[1], "--child") == 0) {
        int source = descriptor(argv[2]), target = descriptor(argv[3]);
        int alias = descriptor(argv[4]);
        uintmax_t dev = number(argv[5]), ino = number(argv[6]);
        closed(source);
        closed(target);
        REQUIRE(fcntl(alias, F_GETFD) == 0);
        same_file(alias, dev, ino);
        char bytes[sizeof(payload)];
        REQUIRE(read(alias, bytes, sizeof(payload) - 1) == sizeof(payload) - 1);
        REQUIRE(memcmp(bytes, payload, sizeof(payload) - 1) == 0);
        return 0;
    }
    int fail_exec = argc == 2 && strcmp(argv[1], "--fail-exec") == 0;
    if (argc != 1 && !fail_exec) return 64;

    char directory[] = "./hesela-cloexec-XXXXXX", path[128], missing[128];
    REQUIRE(mkdtemp(directory) != NULL);
    REQUIRE(snprintf(path, sizeof(path), "%s/data", directory) < (int)sizeof(path));
    REQUIRE(snprintf(missing, sizeof(missing), "%s/absent", directory) < (int)sizeof(missing));
    int original = open(path, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, 0600);
    REQUIRE(original >= 0 && fcntl(original, F_GETFD) == FD_CLOEXEC);
    /* High, owned descriptors keep startup activity away from closure sentinels. */
    int source = fcntl(original, F_DUPFD_CLOEXEC, 100);
    REQUIRE(source >= 100);
    REQUIRE(close(original) == 0);
    int alias = dup(source);
    REQUIRE(alias >= 0 && fcntl(alias, F_GETFD) == 0);
    int target = fcntl(source, F_DUPFD_CLOEXEC, 100);
    REQUIRE(target >= 100 && target != source);
    REQUIRE(fcntl(target, F_SETFD, 0) == 0 && fcntl(target, F_GETFD) == 0);
    REQUIRE(dup3(source, target, O_CLOEXEC) == target);
    flags(source, target, alias);
    REQUIRE(write(source, payload, sizeof(payload) - 1) == sizeof(payload) - 1);
    REQUIRE(lseek(source, 0, SEEK_SET) == 0);
    struct stat info;
    REQUIRE(fstat(source, &info) == 0);
    char a[32], b[32], c[32], dev[32], ino[32];
    snprintf(a, sizeof(a), "%d", source);
    snprintf(b, sizeof(b), "%d", target);
    snprintf(c, sizeof(c), "%d", alias);
    snprintf(dev, sizeof(dev), "%ju", (uintmax_t)info.st_dev);
    snprintf(ino, sizeof(ino), "%ju", (uintmax_t)info.st_ino);
    char *args[] = {"cloexec-probe", "--child", a, b, c, dev, ino, NULL};
    char *env[] = {NULL};
    pid_t child = fork();
    REQUIRE(child >= 0);
    if (child == 0) {
        flags(source, target, alias);
        same_file(source, info.st_dev, info.st_ino);
        same_file(target, info.st_dev, info.st_ino);
        same_file(alias, info.st_dev, info.st_ino);
        execve(missing, args, env);
        REQUIRE(errno == ENOENT);
        flags(source, target, alias);
        same_file(source, info.st_dev, info.st_ino);
        same_file(target, info.st_dev, info.st_ino);
        same_file(alias, info.st_dev, info.st_ino);
        execve(fail_exec ? missing : "/proc/self/exe", args, env);
        perror("successful-exec control failed");
        _exit(1);
    }
    int status;
    REQUIRE(waitpid(child, &status, 0) == child);
    flags(source, target, alias);
    same_file(source, info.st_dev, info.st_ino);
    off_t offset = lseek(source, 0, SEEK_CUR);
    REQUIRE(close(source) == 0 && close(target) == 0 && close(alias) == 0);
    REQUIRE(unlink(path) == 0 && rmdir(directory) == 0);
    REQUIRE(WIFEXITED(status) && WEXITSTATUS(status) == 0);
    REQUIRE(offset == sizeof(payload) - 1);
    puts("{\"open_cloexec\":true,\"dup_clears_flag\":true,\"dup3_sets_flag\":true,"
         "\"fork_retains_all\":true,\"failed_exec_retains_all\":true,"
         "\"successful_exec_closes_flagged\":true,\"survivor_identity_and_bytes\":true,"
         "\"parent_retains_flagged\":true,\"shared_offset\":8}");
    return 0;
}
