Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/types.h>
18 #include <sys/queue.h>
19 #include <sys/uio.h>
21 #include <event.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <imsg.h>
27 #include "log.h"
28 #include "utils.h"
29 #include "kamid.h"
31 #include "table.h"
33 int
34 table_open(struct kd_conf *conf, const char *name, const char *type,
35 const char *path)
36 {
37 struct table *t;
38 struct kd_tables_conf *entry;
39 struct table_backend *backends[] = {
40 &table_static,
41 NULL,
42 }, *b;
43 size_t i;
45 for (i = 0; backends[i] != NULL; ++i) {
46 b = backends[i];
47 if (!strcmp(type, b->name))
48 goto found;
49 }
50 log_warn("unknown table type %s", type);
51 return -1;
53 found:
54 if (b->open == NULL) {
55 log_warn("can't open table %s (type %s)",
56 name, b->name);
57 return -1;
58 }
60 t = xcalloc(1, sizeof(*t));
61 strlcpy(t->t_name, name, sizeof(t->t_name));
62 if (path != NULL)
63 strlcpy(t->t_path, path, sizeof(t->t_path));
64 t->t_backend = b;
66 if (t->t_backend->open(t) == -1)
67 fatal("can't open table %s (type %s)",
68 name, path);
70 entry = xcalloc(1, sizeof(*entry));
71 entry->table = t;
72 STAILQ_INSERT_HEAD(&conf->table_head, entry, entry);
73 return 0;
74 }
76 int
77 table_add(struct table *t, const char *key, const char *val)
78 {
79 if (t->t_backend->add == NULL) {
80 log_warn("can't add to table %s (type %s)",
81 t->t_name, t->t_backend->name);
82 return -1;
83 }
85 return t->t_backend->add(t, key, val);
86 }
88 int
89 table_lookup(struct table *t, const char *key, char **ret_val)
90 {
91 if (t->t_backend->lookup == NULL) {
92 log_warn("can't lookup table %s (type %s)",
93 t->t_name, t->t_backend->name);
94 return -1;
95 }
97 return t->t_backend->lookup(t, key, ret_val);
98 }
100 void
101 table_close(struct table *t)
103 if (t->t_backend->close != NULL)
104 t->t_backend->close(t);