netif_utils: correctly close fd on read error
[project/ustp.git] / config.c
1 /*
2 * ustp - OpenWrt STP/RSTP/MSTP daemon
3 * Copyright (C) 2021 Felix Fietkau <nbd@nbd.name>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14 #include <string.h>
15
16 #include <libubox/avl-cmp.h>
17 #include <libubox/utils.h>
18
19 #include "config.h"
20
21 AVL_TREE(bridge_config, avl_strcmp, false, NULL);
22
23 static uint32_t bridge_config_timestamp(void)
24 {
25 struct timespec ts;
26
27 clock_gettime(CLOCK_MONOTONIC, &ts);
28
29 return ts.tv_sec;
30 }
31
32 struct bridge_config *
33 bridge_config_get(const char *name, bool create)
34 {
35 struct bridge_config *cfg;
36 char *name_buf;
37
38 cfg = avl_find_element(&bridge_config, name, cfg, node);
39 if (cfg)
40 goto out;
41
42 if (!create)
43 return NULL;
44
45 cfg = calloc_a(sizeof(*cfg), &name_buf, strlen(name) + 1);
46 cfg->node.key = strcpy(name_buf, name);
47 avl_insert(&bridge_config, &cfg->node);
48
49 out:
50 cfg->timestamp = bridge_config_timestamp();
51
52 return cfg;
53 }
54
55 void bridge_config_expire(void)
56 {
57 struct bridge_config *cfg, *tmp;
58 uint32_t ts;
59
60 ts = bridge_config_timestamp();
61 avl_for_each_element_safe(&bridge_config, cfg, node, tmp) {
62 if (ts - cfg->timestamp < 60)
63 continue;
64
65 avl_delete(&bridge_config, &cfg->node);
66 free(cfg);
67 }
68 }