Skip to content
suit Documentation
Login

Documentation

#include "machine.h"

#include "conf.h"
#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

bool machine_name_ok(const char *s, size_t len)
{
    return len <= MACHINE_MAX && conf_name_ok(s, len, false);
}

int machine_read(const char *path, char *name)
{
    name[0] = '\0';
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0 && errno == ENOENT) return 0;
    if (fd < 0) {
        say(STDERR_FILENO, "suit: cannot open %s: %s\n", path, strerror(errno));
        return 1;
    }
    // Room for a longest name, its newline and one byte more: a file that
    // fills it is not a name.
    char buf[MACHINE_MAX + 2];
    size_t len = 0;
    ssize_t n = 1;
    while (len < sizeof buf && n > 0) {
        n = sys_read(fd, buf + len, sizeof buf - len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        len += n > 0 ? (size_t)n : 0;
    }
    int err = errno;
    (void)sys_close(fd);
    if (n < 0) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(err));
        return 1;
    }
    size_t name_len = len > 0 && buf[len - 1] == '\n' ? len - 1 : len;
    if (!machine_name_ok(buf, name_len)) {
        say(STDERR_FILENO, "suit: %s: not a machine name (one line of 1 to %zu letters, digits, - _ .)\n",
            path, MACHINE_MAX);
        return 1;
    }
    memcpy(name, buf, name_len);
    name[name_len] = '\0';
    return 0;
}

int machine_write(const char *path, const char *name)
{
    char line[MACHINE_MAX + 2];
    int len = snprintf(line, sizeof line, "%s\n", name);
    ensure(len > 1 && (size_t)len < sizeof line);
    int err = sys_write_atomic(path, line, (size_t)len);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}