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 "compat.h"
19 #include <stdlib.h>
20 #include <string.h>
22 #include "log.h"
23 #include "table.h"
24 #include "utils.h"
26 int
27 table_open(struct kd_conf *conf, const char *name, const char *type,
28 const char *path)
29 {
30 struct table *t;
31 struct kd_tables_conf *entry;
32 struct table_backend *backends[] = {
33 &table_static,
34 NULL,
35 }, *b;
36 size_t i;
38 for (i = 0; backends[i] != NULL; ++i) {
39 b = backends[i];
40 if (!strcmp(type, b->name))
41 goto found;
42 }
43 log_warn("unknown table type %s", type);
44 return -1;
46 found:
47 if (b->open == NULL) {
48 log_warn("can't open table %s (type %s)",
49 name, b->name);
50 return -1;
51 }
53 t = xcalloc(1, sizeof(*t));
54 strlcpy(t->t_name, name, sizeof(t->t_name));
55 if (path != NULL)
56 strlcpy(t->t_path, path, sizeof(t->t_path));
57 t->t_backend = b;
59 if (t->t_backend->open(t) == -1)
60 fatal("can't open table %s (type %s)",
61 name, path);
63 entry = xcalloc(1, sizeof(*entry));
64 entry->table = t;
65 STAILQ_INSERT_HEAD(&conf->table_head, entry, entry);
66 return 0;
67 }
69 int
70 table_add(struct table *t, const char *key, const char *val)
71 {
72 if (t->t_backend->add == NULL) {
73 log_warn("can't add to table %s (type %s)",
74 t->t_name, t->t_backend->name);
75 return -1;
76 }
78 return t->t_backend->add(t, key, val);
79 }
81 int
82 table_lookup(struct table *t, const char *key, char **ret_val)
83 {
84 if (t->t_backend->lookup == NULL) {
85 log_warn("can't lookup table %s (type %s)",
86 t->t_name, t->t_backend->name);
87 return -1;
88 }
90 return t->t_backend->lookup(t, key, ret_val);
91 }
93 void
94 table_close(struct table *t)
95 {
96 if (t->t_backend->close != NULL)
97 t->t_backend->close(t);
98 }