Skip to content
suit Documentation
Login

Documentation

#include "usage.h"

#include "platform.h"

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

// ---- the source -------------------------------------------------------------

void usage_source_fd(UsageSource *s, int fd)
{
    *s = (UsageSource){.fd = fd};
}

void usage_source_mem(UsageSource *s, const void *data, size_t len)
{
    *s = (UsageSource){.fd = -1, .mem = data, .memlen = len};
}

// The next chunk, when everything in the window is used. False at the end of
// the data or after a failed read (ERR set).
static bool src_refill(UsageSource *s)
{
    s->base += s->have;
    s->at = 0;
    s->have = 0;
    if (s->fd < 0) {
        uint64_t left = s->base < s->memlen ? s->memlen - s->base : 0;
        s->have = left < USAGE_CHUNK ? (size_t)left : USAGE_CHUNK;
        if (s->have > 0) memcpy(s->buf, s->mem + s->base, s->have);
        return s->have > 0;
    }
    ssize_t n = sys_read(s->fd, s->buf, USAGE_CHUNK);
    if (n < 0) {
        s->err = errno;
        return false;
    }
    s->have = (size_t)n;
    return n > 0;
}

static uint64_t src_pos(const UsageSource *s)
{
    return s->base + s->at;
}

// Move to offset OFF. Inside the window that is free; elsewhere the next read
// starts there.
static void src_seek(UsageSource *s, uint64_t off)
{
    if (off >= s->base && off <= s->base + s->have) {
        s->at = (size_t)(off - s->base);
        return;
    }
    s->base = off;
    s->at = 0;
    s->have = 0;
    if (s->fd >= 0 && sys_lseek(s->fd, (off_t)off, SEEK_SET) < 0) s->err = errno;
}

// ---- small helpers ----------------------------------------------------------

// The first place the VL bytes of VAL are in the N bytes at P, or null.
static const uint8_t *find_at(const uint8_t *p, size_t n, const char *val, size_t vl)
{
    while (n >= vl) {
        const uint8_t *q = memchr(p, (uint8_t)val[0], n - vl + 1);
        if (q == nullptr) return nullptr;
        if ((vl == 1 || q[1] == (uint8_t)val[1]) && memcmp(q, val, vl) == 0) return q;
        n -= (size_t)(q - p) + 1;
        p = q + 1;
    }
    return nullptr;
}

// 1 to MAX printable ASCII bytes, none of them < > or ".
static bool token_ok(const uint8_t *s, size_t n, size_t max)
{
    if (n == 0 || n > max) return false;
    for (size_t i = 0; i < n; i++)
        if (s[i] <= ' ' || s[i] >= 0x7f || s[i] == '<' || s[i] == '>' || s[i] == '"') return false;
    return true;
}

constexpr uint8_t DEAD = 255;
constexpr uint32_t PER_RULE = USAGE_PER_RULE;
constexpr uint32_t ROLE_IN = 0;
constexpr uint32_t ROLE_WHERE = 1;  // ... the next USAGE_WHERE_MAX
constexpr uint32_t ROLE_NAME_A = 1 + USAGE_WHERE_MAX;
constexpr uint32_t ROLE_NAME_B = 2 + USAGE_WHERE_MAX;
constexpr uint32_t ROLE_ID = 3 + USAGE_WHERE_MAX;
constexpr uint32_t T_TIME = 0;
constexpr uint32_t T_PROJECT = 1;
constexpr uint8_t ID_OK = 1;
constexpr uint8_t ID_BAD = 2;

static uint32_t base_of(uint32_t rule)
{
    return 2 + rule * PER_RULE;
}

// ---- setting up -------------------------------------------------------------

static void add_track(Usage *u, uint32_t t, const UsagePath *p)
{
    u->track[t] = (UsageTrack){p, p->n};
}

static uint32_t value_index(Usage *u, const char *val)
{
    size_t len = strlen(val);
    for (uint32_t i = 0; i < u->nv; i++)
        if (u->vlen[i] == len && memcmp(u->vals[i], val, len) == 0) return i;
    ensure(u->nv < USAGE_VALUES_MAX);
    u->vals[u->nv] = val;
    u->vlen[u->nv] = (uint8_t)len;
    if (len > u->vmax) u->vmax = len;
    return u->nv++;
}

void usage_init(Usage *u, const UsageRule *rules, uint32_t n, const UsagePath *time, const UsagePath *project)
{
    ensure(n <= CONF_USE_MAX);
    memset(u, 0, sizeof *u);
    u->rules = rules;
    u->nrules = n;
    u->ntrack = 2 + n * PER_RULE;
    u->vmax = 1;
    if (time != nullptr) add_track(u, T_TIME, time);
    if (project != nullptr) add_track(u, T_PROJECT, project);
    for (uint32_t r = 0; r < n; r++) {
        const UsageRule *rule = &rules[r];
        uint32_t b = base_of(r);
        add_track(u, b + ROLE_IN, &rule->in);
        for (uint32_t i = 0; i < rule->nwhere; i++) {
            add_track(u, b + ROLE_WHERE + i, &rule->where_path[i]);
            u->rmask[r] |= 1ull << value_index(u, rule->where_value[i]);
        }
        add_track(u, b + ROLE_NAME_A, &rule->name);
        add_track(u, b + ROLE_NAME_B, &rule->name_list);
        if (rule->has_id) add_track(u, b + ROLE_ID, &rule->id);
        u->always |= rule->nwhere == 0;
    }
}

// ---- reading bytes of a line -------------------------------------------------

// The next byte of the line, or -1 at its end: a newline, or the end of the data.
static int peek(Usage *u)
{
    UsageSource *s = u->src;
    if (s->at == s->have && !src_refill(s)) return -1;
    uint8_t c = s->buf[s->at];
    return c == '\n' ? -1 : c;
}

static void adv(Usage *u)
{
    u->src->at++;
}

static int skipws(Usage *u)
{
    int c = peek(u);
    while (c == ' ' || c == '\t' || c == '\r') {
        adv(u);
        c = peek(u);
    }
    return c;
}

static int hexval(int c)
{
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    return -1;
}

// Add the bytes P to OUT while there is room, counting all of them in *TOTAL.
static void put(char *out, size_t cap, uint64_t *total, const uint8_t *p, size_t n)
{
    for (size_t i = 0; i < n && *total + i < cap; i++) out[*total + i] = (char)p[i];
    *total += n;
}

// The four hex digits of \uXXXX as UTF-8 into OUT. A surrogate is written as
// U+FFFD, so it is never ASCII and never equals what a rule asks for.
static bool escape_u(Usage *u, char *out, size_t cap, uint64_t *total)
{
    unsigned cp = 0;
    for (int i = 0; i < 4; i++) {
        int c = peek(u);
        int h = hexval(c);
        if (h < 0) return false;
        adv(u);
        cp = cp * 16 + (unsigned)h;
    }
    if (cp >= 0xD800 && cp <= 0xDFFF) cp = 0xFFFD;
    uint8_t b[3];
    size_t n;
    if (cp < 0x80) {
        b[0] = (uint8_t)cp;
        n = 1;
    } else if (cp < 0x800) {
        b[0] = (uint8_t)(0xC0 | (cp >> 6));
        b[1] = (uint8_t)(0x80 | (cp & 0x3F));
        n = 2;
    } else {
        b[0] = (uint8_t)(0xE0 | (cp >> 12));
        b[1] = (uint8_t)(0x80 | ((cp >> 6) & 0x3F));
        b[2] = (uint8_t)(0x80 | (cp & 0x3F));
        n = 3;
    }
    put(out, cap, total, b, n);
    return true;
}

// After the opening quote: read to the closing one, decoding escapes. The
// first CAP bytes of the result go to OUT; *TOTAL counts them all. False if
// the line is not valid there.
static bool scan_string(Usage *u, char *out, size_t cap, uint64_t *total)
{
    UsageSource *s = u->src;
    *total = 0;
    for (;;) {
        if (s->at == s->have && !src_refill(s)) return false;
        const uint8_t *p = s->buf + s->at;
        const uint8_t *e = s->buf + s->have;
        const uint8_t *q = p;
        while (q < e && *q != '"' && *q != '\\' && *q >= ' ') q++;
        put(out, cap, total, p, (size_t)(q - p));
        s->at += (size_t)(q - p);
        if (q == e) continue;
        s->at++;
        if (*q == '"') return true;
        if (*q != '\\') return false;  // a control byte, or the end of the line
        int c = peek(u);
        if (c == 'u') {
            adv(u);
            if (!escape_u(u, out, cap, total)) return false;
            continue;
        }
        // The letters of the short escapes, and what each stands for.
        static const char from[] = "\"\\/bfnrt";
        static const uint8_t to[] = {'"', '\\', '/', '\b', '\f', '\n', '\r', '\t'};
        const char *at = memchr(from, c, sizeof from - 1);
        if (at == nullptr) return false;
        adv(u);
        put(out, cap, total, &to[at - from], 1);
    }
}

static size_t digits(Usage *u)
{
    size_t n = 0;
    int c = peek(u);
    while (c >= '0' && c <= '9') {
        adv(u);
        n++;
        c = peek(u);
    }
    return n;
}

static bool number(Usage *u)
{
    if (peek(u) == '-') adv(u);
    int c = peek(u);
    if (c == '0') adv(u);
    else if (c < '1' || c > '9') return false;
    else (void)digits(u);
    if (peek(u) == '.') {
        adv(u);
        if (digits(u) == 0) return false;
    }
    c = peek(u);
    if (c == 'e' || c == 'E') {
        adv(u);
        c = peek(u);
        if (c == '+' || c == '-') adv(u);
        if (digits(u) == 0) return false;
    }
    return true;
}

static bool literal(Usage *u, int first)
{
    const char *word = first == 't' ? "true" : first == 'f' ? "false" : first == 'n' ? "null" : nullptr;
    if (word == nullptr) return false;
    for (const char *w = word; *w != '\0'; w++) {
        if (peek(u) != *w) return false;
        adv(u);
    }
    return true;
}

// ---- following the paths ------------------------------------------------------

// The state of tracker T for a child of a value in state S: a member named
// KEY (IS_KEY) or an element of an array.
static uint8_t step_to(const UsageTrack *t, uint8_t s, bool is_key, const char *key, uint64_t klen)
{
    if (s >= t->n) return DEAD;
    const UsagePath *p = t->path;
    if (p->each[s]) return is_key ? DEAD : (uint8_t)(s + 1);
    bool same = is_key && klen == p->len[s] && memcmp(p->key[s], key, klen) == 0;
    return same ? (uint8_t)(s + 1) : DEAD;
}

// A rule's thing has been reached at level L: start following what it
// takes from it.
static void arrive(Usage *u, UsageLevel *l, uint32_t r)
{
    uint32_t b = base_of(r);
    for (uint32_t j = 1; j < PER_RULE; j++) l->st[b + j] = u->track[b + j].path != nullptr ? 0 : DEAD;
    l->arrived = (uint16_t)(l->arrived | (1u << r));
    u->cap[r] = (UsageCap){};
}

static void settle(Usage *u, UsageLevel *l)
{
    l->arrived = 0;
    for (uint32_t r = 0; r < u->nrules; r++) {
        uint32_t b = base_of(r);
        if (l->st[b] == u->track[b].n) arrive(u, l, r);
    }
}

static void root_init(Usage *u)
{
    UsageLevel *l = &u->lv[0];
    for (uint32_t t = 0; t < u->ntrack; t++) l->st[t] = DEAD;
    for (uint32_t t = 0; t < 2; t++) l->st[t] = u->track[t].path != nullptr ? 0 : DEAD;
    for (uint32_t r = 0; r < u->nrules; r++) l->st[base_of(r) + ROLE_IN] = 0;
    settle(u, l);
}

// The states for the child at slot PARENT + 1.
static void descend(Usage *u, size_t parent, bool is_key, const char *key, uint64_t klen)
{
    const UsageLevel *par = &u->lv[parent];
    UsageLevel *ch = &u->lv[parent + 1];
    for (uint32_t t = 0; t < u->ntrack; t++)
        ch->st[t] = par->st[t] == DEAD ? DEAD : step_to(&u->track[t], par->st[t], is_key, key, klen);
    settle(u, ch);
}

// ---- what a string completes ---------------------------------------------------

static void add_cand(Usage *u, uint32_t r, uint64_t total)
{
    UsageCap *cap = &u->cap[r];
    if (cap->ncand == USAGE_CAND_MAX) return;
    const UsageRule *rule = &u->rules[r];
    size_t stored = total < USAGE_STR_KEEP ? (size_t)total : USAGE_STR_KEEP;
    const uint8_t *s = (const uint8_t *)u->str;
    size_t n = stored;
    bool found = true;
    if (rule->between) {
        size_t alen = strlen(rule->a);
        const uint8_t *a = find_at(s, stored, rule->a, alen);
        if (a == nullptr) return;  // not a record of this kind
        s = a + alen;
        n = stored - (size_t)(s - (const uint8_t *)u->str);
        const uint8_t *b = find_at(s, n, rule->b, strlen(rule->b));
        found = b != nullptr;
        n = found ? (size_t)(b - s) : 0;
    }
    UsageCand *c = &cap->cand[cap->ncand++];
    // Without between the name is the whole string, and a string longer than was kept is too long.
    bool fits = rule->between || total <= USAGE_NAME_MAX;
    c->ok = found && fits && token_ok(s, n, USAGE_NAME_MAX);
    if (c->ok) {
        memcpy(c->name, s, n);
        c->name[n] = '\0';
    }
}

static void on_string(Usage *u, const UsageLevel *l, uint64_t total)
{
    size_t stored = total < USAGE_STR_KEEP ? (size_t)total : USAGE_STR_KEEP;
    for (uint32_t t = 0; t < u->ntrack; t++) {
        if (l->st[t] != u->track[t].n) continue;
        if (t == T_TIME || t == T_PROJECT) {
            char *dest = t == T_TIME ? u->time : u->project;
            size_t max = t == T_TIME ? USAGE_TIME_MAX : USAGE_PROJECT_MAX;
            dest[0] = '\0';
            if (total <= max) {
                memcpy(dest, u->str, stored);
                dest[stored] = '\0';
            }
            continue;
        }
        uint32_t r = (t - 2) / PER_RULE;
        uint32_t role = (t - 2) % PER_RULE;
        UsageCap *cap = &u->cap[r];
        if (role == ROLE_IN) {
            continue;  // the thing examined is a string: there is nothing in it to look at
        } else if (role == ROLE_NAME_A || role == ROLE_NAME_B) {
            add_cand(u, r, total);
        } else if (role == ROLE_ID) {
            bool ok = total <= USAGE_ID_MAX && token_ok((const uint8_t *)u->str, stored, USAGE_ID_MAX);
            cap->id_state = ok ? ID_OK : ID_BAD;
            if (ok) {
                memcpy(cap->id, u->str, stored);
                cap->id[stored] = '\0';
            }
        } else {
            const UsageRule *rule = &u->rules[r];
            size_t i = role - ROLE_WHERE;
            size_t vl = strlen(rule->where_value[i]);
            if (total == vl && memcmp(u->str, rule->where_value[i], vl) == 0) cap->where_ok |= 1u << i;
        }
    }
}

// The thing a rule examined has ended: what it found becomes hits.
static void finalize(Usage *u, uint32_t r)
{
    UsageCap *cap = &u->cap[r];
    uint32_t need = (1u << u->rules[r].nwhere) - 1;
    if ((cap->where_ok & need) != need) return;
    for (uint32_t i = 0; i < cap->ncand; i++) {
        if (!cap->cand[i].ok || cap->id_state == ID_BAD || u->nhits == USAGE_LINE_HITS_MAX) {
            u->line_skipped++;
            continue;
        }
        UsageHit *h = &u->hits[u->nhits++];
        h->kind = u->rules[r].kind;
        memcpy(h->name, cap->cand[i].name, sizeof h->name);
        memcpy(h->id, cap->id, sizeof h->id);
    }
}

static void close_slot(Usage *u, size_t slot)
{
    for (uint32_t r = 0; r < u->nrules; r++)
        if (((uint32_t)u->lv[slot].arrived >> r) & 1u) finalize(u, r);
}

// ---- walking a line --------------------------------------------------------------

static bool member(Usage *u, size_t depth)
{
    if (skipws(u) != '"') return false;
    adv(u);
    uint64_t klen;
    if (!scan_string(u, u->key, sizeof u->key, &klen)) return false;
    if (skipws(u) != ':') return false;
    adv(u);
    descend(u, depth - 1, true, u->key, klen);
    return true;
}

typedef enum { AFTER_MORE, AFTER_DONE, AFTER_BAD } After;

// A value has ended at slot DEPTH: close the containers that end here and go
// on to the next member or element.
static After after_value(Usage *u, size_t *depth)
{
    for (;;) {
        int c = skipws(u);
        if (*depth == 0) return c < 0 ? AFTER_DONE : AFTER_BAD;
        bool obj = u->is_obj[*depth - 1];
        if (c == ',') {
            adv(u);
            if (obj) return member(u, *depth) ? AFTER_MORE : AFTER_BAD;
            descend(u, *depth - 1, false, nullptr, 0);
            return AFTER_MORE;
        }
        if (c != (obj ? '}' : ']')) return AFTER_BAD;
        adv(u);
        (*depth)--;
        close_slot(u, *depth);
    }
}

// Is the line one valid JSON value? Collects hits as it goes.
static bool walk(Usage *u)
{
    size_t depth = 0;
    root_init(u);
    for (;;) {
        int c = skipws(u);
        if (c == '{' || c == '[') {
            if (depth == USAGE_DEPTH_MAX) return false;
            adv(u);
            u->is_obj[depth++] = c == '{';
            int d = skipws(u);
            if (d == (c == '{' ? '}' : ']')) {
                adv(u);
                close_slot(u, --depth);
            } else if (c == '{') {
                if (!member(u, depth)) return false;
                continue;
            } else {
                descend(u, depth - 1, false, nullptr, 0);
                continue;
            }
        } else if (c == '"') {
            adv(u);
            uint64_t total;
            if (!scan_string(u, u->str, sizeof u->str, &total)) return false;
            on_string(u, &u->lv[depth], total);
        } else if (c == '-' || (c >= '0' && c <= '9')) {
            if (!number(u)) return false;
        } else {
            if (c < 0 || !literal(u, c)) return false;
        }
        After a = after_value(u, &depth);
        if (a != AFTER_MORE) return a == AFTER_DONE;
    }
}

// ---- lines -----------------------------------------------------------------------

static void scan_values(Usage *u, const uint8_t *p, size_t n)
{
    for (uint32_t v = 0; v < u->nv; v++) {
        if ((u->seen >> v) & 1u) continue;
        size_t vl = u->vlen[v];
        bool hit = find_at(p, n, u->vals[v], vl) != nullptr;
        if (!hit && u->ntail > 0) {  // a value cut by the end of the last chunk
            uint8_t join[2 * USAGE_VALUE_MAX];
            size_t head = n < vl - 1 ? n : vl - 1;
            memcpy(join, u->tail, u->ntail);
            memcpy(join + u->ntail, p, head);
            hit = find_at(join, u->ntail + head, u->vals[v], vl) != nullptr;
        }
        if (hit) u->seen |= 1ull << v;
    }
    size_t keep = u->vmax - 1;
    size_t take = n < keep ? n : keep;
    uint8_t tmp[2 * USAGE_VALUE_MAX];
    memcpy(tmp, u->tail, u->ntail);
    memcpy(tmp + u->ntail, p + n - take, take);
    size_t total = u->ntail + take;
    size_t off = total > keep ? total - keep : 0;
    memcpy(u->tail, tmp + off, total - off);
    u->ntail = total - off;
}

// Read to the end of the line the source is at, noting which where VALUEs it
// holds. True, with the source just past the newline and *NL the newline's
// offset, if the line has one; false at the end of the data, or after a failed read.
static bool find_line(Usage *u, uint64_t *nl)
{
    UsageSource *s = u->src;
    u->seen = 0;
    u->ntail = 0;
    for (;;) {
        if (s->at == s->have && !src_refill(s)) return false;
        const uint8_t *p = s->buf + s->at;
        size_t n = s->have - s->at;
        const uint8_t *e = memchr(p, '\n', n);
        size_t seg = e != nullptr ? (size_t)(e - p) : n;
        if (!u->always) scan_values(u, p, seg);
        if (e != nullptr) {
            *nl = src_pos(s) + seg;
            s->at += seg + 1;
            return true;
        }
        s->at = s->have;
    }
}

// The pre-test: only a filter. The walk decides.
static bool passes(const Usage *u)
{
    bool pass = u->always;
    for (uint32_t r = 0; r < u->nrules; r++) pass |= (u->rmask[r] & ~u->seen) == 0;
    return pass;
}

static void walk_line(Usage *u, UsageSink sink, void *state)
{
    u->nhits = 0;
    u->line_skipped = 0;
    u->time[0] = '\0';
    u->project[0] = '\0';
    u->lines++;
    if (!walk(u)) {
        u->skipped++;
        return;
    }
    u->skipped += u->line_skipped;
    for (uint32_t i = 0; i < u->nhits; i++) {
        UsageEvent ev;
        ev.kind = u->hits[i].kind;
        memcpy(ev.name, u->hits[i].name, sizeof ev.name);
        memcpy(ev.id, u->hits[i].id, sizeof ev.id);
        memcpy(ev.time, u->time, sizeof ev.time);
        memcpy(ev.project, u->project, sizeof ev.project);
        sink(state, &ev);
    }
}

bool usage_read(Usage *u, UsageSource *s, uint64_t start, uint64_t *end, UsageSink sink, void *state)
{
    u->src = s;
    s->err = 0;
    src_seek(s, start);
    uint64_t pos = start;
    while (s->err == 0) {
        uint64_t nl;
        if (!find_line(u, &nl)) break;
        u->pass = passes(u);
        if (u->pass) {
            src_seek(s, pos);
            walk_line(u, sink, state);
            src_seek(s, nl + 1);
        }
        pos = nl + 1;
    }
    *end = pos;
    return s->err == 0;
}