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 }, *b;
35 size_t i;
37 for (i = 0; i < sizeof(backends)/sizeof(backends[0]); ++i) {
38 b = &backends[i];
39 if (!strcmp(type, b->name))
40 goto found;
41 }
42 log_warn("unknown table type %s", type);
43 return -1;
45 found:
46 if (b->open == NULL) {
47 log_warn("can't open table %s (type %s)",
48 name, b->name);
49 return -1;
50 }
52 t = xcalloc(1, sizeof(*t));
53 strlcpy(t->t_name, name, sizeof(t->t_name));
54 if (path != NULL)
55 strlcpy(t->t_path, path, sizeof(t->t_path));
56 t->t_backend = b;
58 if (t->t_backend->open(t) == -1)
59 fatal("can't open table %s (type %s)",
60 name, path);
62 entry = xcalloc(1, sizeof(*entry));
63 entry->table = t;
64 SIMPLEQ_INSERT_HEAD(&conf->table_head, entry, entry);
65 return 0;
66 }
68 int
69 table_add(struct table *t, const char *key, const char *val)
70 {
71 if (t->t_backend->add == NULL) {
72 log_warn("can't add to table %s (type %s)",
73 t->t_name, t->t_backend->name);
74 return -1;
75 }
77 return t->t_backend->add(t, key, val);
78 }
80 int
81 table_lookup(struct table *t, const char *key, char **ret_val)
82 {
83 if (t->t_backend->lookup == NULL) {
84 log_warn("can't lookup table %s (type %s)",
85 t->t_name, t->t_backend->name);
86 return -1;
87 }
89 return t->t_backend->lookup(t, key, ret_val);
90 }
92 void
93 table_close(struct table *t)
94 {
95 if (t->t_backend->close != NULL)
96 t->t_backend->close(t);
97 }