2 * Copyright (c) 2021, 2022, 2024 Omar Polo <op@omarpolo.com>
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.
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.
31 tofu_init(struct ohash *h, unsigned int sz, ptrdiff_t ko)
33 struct ohash_info info = {
35 .calloc = hash_calloc,
40 ohash_init(h, sz, &info);
44 tofu_lookup(struct ohash *h, const char *domain, const char *port)
46 char buf[TOFU_URL_MAX_LEN];
49 strlcpy(buf, domain, sizeof(buf));
50 if (port != NULL && *port != '\0' && strcmp(port, "1965")) {
51 strlcat(buf, ":", sizeof(buf));
52 strlcat(buf, port, sizeof(buf));
55 slot = ohash_qlookup(h, buf);
56 return ohash_find(h, slot);
60 tofu_add(struct ohash *h, struct tofu_entry *e)
64 slot = ohash_qlookup(h, e->domain);
65 ohash_insert(h, slot, e);
69 tofu_save(struct ohash *h, struct tofu_entry *e)
75 if ((fp = fopen(known_hosts_file, "a")) == NULL)
77 fprintf(fp, "%s %s %d\n", e->domain, e->hash, e->verified);
83 tofu_update(struct ohash *h, struct tofu_entry *e)
87 if ((t = tofu_lookup(h, e->domain, NULL)) == NULL)
90 strlcpy(t->hash, e->hash, sizeof(t->hash));
91 t->verified = e->verified;
97 tofu_update_persist(struct ohash *h, struct tofu_entry *e)
100 char sfn[PATH_MAX], *line = NULL;
101 size_t l, linesize = 0;
107 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
108 if ((fd = mkstemp(sfn)) == -1 ||
109 (tmp = fdopen(fd, "w")) == NULL) {
117 if ((fp = fopen(known_hosts_file, "r")) == NULL) {
123 l = strlen(e->domain);
124 while ((linelen = getline(&line, &linesize, fp)) != -1) {
125 if (!strncmp(line, e->domain, l))
127 if (linesize > 0 && line[linesize-1] == '\n')
128 line[linesize-1] = '\0';
129 fprintf(tmp, "%s\n", line);
131 fprintf(tmp, "%s %s %d\n", e->domain, e->hash, e->verified);
143 if (rename(sfn, known_hosts_file) == -1)
149 tofu_temp_trust(struct ohash *h, const char *host, const char *port,
152 struct tofu_entry *e;
154 e = xcalloc(1, sizeof(*e));
156 strlcpy(e->domain, host, sizeof(e->domain));
157 if (*port != '\0' && strcmp(port, "1965")) {
158 strlcat(e->domain, ":", sizeof(e->domain));
159 strlcat(e->domain, port, sizeof(e->domain));
161 strlcpy(e->hash, hash, sizeof(e->hash));