summaryrefslogtreecommitdiffstats
path: root/src/util.c
diff options
context:
space:
mode:
authordev <dev@example>2026-11-14 17:46:44 +0000
committerdev <dev@example>2026-11-14 17:46:44 +0000
commit11c976ec713b975568594cf57d9118f58ba8c511 (patch)
tree840912cd000f50fbd4c045a3bceaa2b55261f3fe /src/util.c
parent12dcb09794c48a333bb850d353540c688c503b76 (diff)
downloadaccess-control-11c976ec713b975568594cf57d9118f58ba8c511.tar.gz
access-control-11c976ec713b975568594cf57d9118f58ba8c511.zip
One reader for every file, one voice for every finding
Seven places opened a file, ran a getline loop, freed the line buffer and closed the handle, and five of them also rewrote the same skip-the-blank- and-comment preamble. authz_read_lines() does it once, and keeps the distinction policy_load needed: a file that would not give an answer is not an empty file. lines_t moves to util.c with it, so edit.c's private copy goes too. verr, vwarn and vok were one function with three tags. cmd_authorize now frees what it read on one path instead of four.
Diffstat (limited to 'src/util.c')
-rw-r--r--src/util.c69
1 files changed, 69 insertions, 0 deletions
diff --git a/src/util.c b/src/util.c
index 92f17f8..f0991fe 100644
--- a/src/util.c
+++ b/src/util.c
@@ -7,6 +7,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/types.h>
const char *progname = "git-authz";
@@ -135,3 +136,71 @@ void authz_opt_reset(void)
opterr = 0;
}
+// ----------------------------------------------------------------- lines
+
+void lines_init(lines_t *l)
+{
+ l->v = NULL;
+ l->n = 0;
+ l->cap = 0;
+}
+
+void lines_push(lines_t *l, char *s) // takes ownership
+{
+ if (l->n == l->cap) {
+ l->cap = l->cap != 0 ? l->cap * 2 : 64;
+ l->v = xrealloc(l->v, l->cap * sizeof(*l->v));
+ }
+ l->v[l->n++] = s;
+}
+
+void lines_free(lines_t *l)
+{
+ size_t i;
+
+ for (i = 0; i < l->n; i++)
+ free(l->v[i]);
+ free(l->v);
+ lines_init(l);
+}
+
+// Every reader in this program used to write this loop, its teardown and its
+// "skip the blank and comment lines" preamble again by hand, and a reader that
+// forgot one of the three leaked quietly.
+
+int authz_read_lines(const char *path, lines_t *l)
+{
+ FILE *f;
+ char *line = NULL;
+ size_t cap = 0;
+ ssize_t len;
+
+ lines_init(l);
+ f = fopen(path, "r");
+ if (f == NULL)
+ return -1;
+ while ((len = getline(&line, &cap, f)) != -1) {
+ size_t n = strlen(line);
+
+ if (n == 0 || line[n - 1] == '\n') {
+ lines_push(l, xstrdup(line));
+ continue;
+ }
+ { // a last line without its newline
+ char *own = xmalloc(n + 2);
+
+ memcpy(own, line, n);
+ own[n] = '\n';
+ own[n + 1] = '\0';
+ lines_push(l, own);
+ }
+ }
+ free(line);
+ if (ferror(f)) {
+ fclose(f);
+ return -2;
+ }
+ fclose(f);
+ return 0;
+}
+