Blob


1 /*
2 * Copyright (c) 2021, 2022 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 <limits.h>
20 #include <stdlib.h>
21 #include <string.h>
23 #include "fs.h"
24 #include "telescope.h"
25 #include "utils.h"
27 void
28 tofu_init(struct ohash *h, unsigned int sz, ptrdiff_t ko)
29 {
30 struct ohash_info info = {
31 .key_offset = ko,
32 .calloc = hash_calloc,
33 .free = hash_free,
34 .alloc = hash_alloc,
35 };
37 ohash_init(h, sz, &info);
38 }
40 struct tofu_entry *
41 tofu_lookup(struct ohash *h, const char *domain, const char *port)
42 {
43 char buf[GEMINI_URL_LEN];
44 unsigned int slot;
46 strlcpy(buf, domain, sizeof(buf));
47 if (port != NULL && *port != '\0' && strcmp(port, "1965")) {
48 strlcat(buf, ":", sizeof(buf));
49 strlcat(buf, port, sizeof(buf));
50 }
52 slot = ohash_qlookup(h, buf);
53 return ohash_find(h, slot);
54 }
56 void
57 tofu_add(struct ohash *h, struct tofu_entry *e)
58 {
59 unsigned int slot;
61 slot = ohash_qlookup(h, e->domain);
62 ohash_insert(h, slot, e);
63 }
65 int
66 tofu_save(struct ohash *h, struct tofu_entry *e)
67 {
68 FILE *fp;
70 tofu_add(h, e);
72 if ((fp = fopen(known_hosts_file, "a")) == NULL)
73 return -1;
74 fprintf(fp, "%s %s %d\n", e->domain, e->hash, e->verified);
75 fclose(fp);
76 return 0;
77 }
79 void
80 tofu_update(struct ohash *h, struct tofu_entry *e)
81 {
82 struct tofu_entry *t;
84 if ((t = tofu_lookup(h, e->domain, NULL)) == NULL)
85 tofu_add(h, e);
86 else {
87 strlcpy(t->hash, e->hash, sizeof(t->hash));
88 t->verified = e->verified;
89 free(e);
90 }
91 }
93 void
94 tofu_temp_trust(struct ohash *h, const char *host, const char *port,
95 const char *hash)
96 {
97 struct tofu_entry *e;
99 if ((e = calloc(1, sizeof(*e))) == NULL)
100 abort();
102 strlcpy(e->domain, host, sizeof(e->domain));
103 if (*port != '\0' && strcmp(port, "1965")) {
104 strlcat(e->domain, ":", sizeof(e->domain));
105 strlcat(e->domain, port, sizeof(e->domain));
107 strlcpy(e->hash, hash, sizeof(e->hash));
108 e->verified = -1;
110 tofu_update(h, e);