summaryrefslogtreecommitdiff
path: root/locker.c
blob: 37daac5ab4b5f9142e7b026487332a8a326420bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
 * pkg - Package locker
 * https://rawnix.org
 *
 * Copyright (c) 2025 zorz@gmx.com
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "locker.h"
#include "paths.h"
#include <fcntl.h>
#include <unistd.h>

struct locker {
    char       *path;
    strarray_t  pkgs;
};

locker_t *locker_open(const char *root)
{
    locker_t *l;
    FILE     *fp;
    char      line[256];

    l = xmalloc(sizeof(locker_t));
    strarray_init(&l->pkgs);
    l->path = build_root_path(root, LOCK_FILE);

    fp = fopen(l->path, "r");
    if (!fp)
        return l;

    while (fgets(line, sizeof(line), fp)) {
        line[strcspn(line, "\n")] = '\0';
        if (line[0] && line[0] != '#')
            strarray_add(&l->pkgs, line);
    }

    fclose(fp);
    return l;
}

void locker_close(locker_t *l)
{
    if (!l)
        return;
    strarray_free(&l->pkgs);
    free(l->path);
    free(l);
}

static int locker_save(locker_t *l)
{
    char  tmp[4096];
    int   fd;
    FILE *fp;
    size_t i;

    ensure_parent_dir(l->path);

    snprintf(tmp, sizeof(tmp), "%s.tmp", l->path);

    fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0)
        return -1;

    fp = fdopen(fd, "w");
    if (!fp) {
        close(fd);
        unlink(tmp);
        return -1;
    }

    fprintf(fp, "# Locked packages (excluded from sysup)\n");
    for (i = 0; i < l->pkgs.size; i++)
        fprintf(fp, "%s\n", l->pkgs.data[i]);

    if (file_close_checked(fp) != 0) {
        unlink(tmp);
        return -1;
    }

    if (rename(tmp, l->path) != 0) {
        unlink(tmp);
        return -1;
    }

    return 0;
}

bool locker_is_locked(locker_t *l, const char *pkg)
{
    return strarray_contains(&l->pkgs, pkg);
}

bool locker_lock(locker_t *l, const char *pkg)
{
    if (locker_is_locked(l, pkg))
        return true;
    strarray_add(&l->pkgs, pkg);
    return locker_save(l) == 0;
}

bool locker_unlock(locker_t *l, const char *pkg)
{
    size_t i;

    for (i = 0; i < l->pkgs.size; i++) {
        if (strcmp(l->pkgs.data[i], pkg) == 0) {
            free(l->pkgs.data[i]);
            l->pkgs.data[i] = l->pkgs.data[--l->pkgs.size];
            return locker_save(l) == 0;
        }
    }
    return false;
}

strarray_t *locker_list(locker_t *l)
{
    strarray_t *arr;
    size_t      i;

    arr = xmalloc(sizeof(strarray_t));
    strarray_init(arr);

    for (i = 0; i < l->pkgs.size; i++)
        strarray_add(arr, l->pkgs.data[i]);

    return arr;
}