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 "telescope.h"
19 #include <stdlib.h>
20 #include <string.h>
22 static void *hash_alloc(size_t, void*);
23 static void *hash_calloc(size_t, size_t, void*);
24 static void hash_free(void*, void*);
26 static void *
27 hash_alloc(size_t len, void *d)
28 {
29 if ((d = malloc(len)) == NULL)
30 abort();
31 return d;
32 }
34 static void *
35 hash_calloc(size_t nmemb, size_t size, void *d)
36 {
37 if ((d = calloc(nmemb, size)) == NULL)
38 abort();
39 return d;
40 }
42 static void
43 hash_free(void *ptr, void *d)
44 {
45 free(ptr);
46 }
48 void
49 tofu_init(struct ohash *h, unsigned int sz, ptrdiff_t ko)
50 {
51 struct ohash_info info = {
52 .key_offset = ko,
53 .calloc = hash_calloc,
54 .free = hash_free,
55 .alloc = hash_alloc,
56 };
58 ohash_init(h, sz, &info);
59 }
61 struct tofu_entry *
62 tofu_lookup(struct ohash *h, const char *domain, const char *port)
63 {
64 char buf[GEMINI_URL_LEN];
65 unsigned int slot;
67 strlcpy(buf, domain, sizeof(buf));
68 if (port != NULL && *port != '\0' && strcmp(port, "1965")) {
69 strlcat(buf, ":", sizeof(buf));
70 strlcat(buf, port, sizeof(buf));
71 }
73 slot = ohash_qlookup(h, buf);
74 return ohash_find(h, slot);
75 }
77 void
78 tofu_add(struct ohash *h, struct tofu_entry *e)
79 {
80 unsigned int slot;
82 slot = ohash_qlookup(h, e->domain);
83 ohash_insert(h, slot, e);
84 }
86 void
87 tofu_update(struct ohash *h, struct tofu_entry *e)
88 {
89 struct tofu_entry *t;
91 if ((t = tofu_lookup(h, e->domain, NULL)) == NULL)
92 tofu_add(h, e);
93 else {
94 strlcpy(t->hash, e->hash, sizeof(t->hash));
95 t->verified = e->verified;
96 free(e);
97 }
98 }
100 void
101 tofu_temp_trust(struct ohash *h, const char *host, const char *port,
102 const char *hash)
104 struct tofu_entry *e;
106 if ((e = calloc(1, sizeof(*e))) == NULL)
107 abort();
109 strlcpy(e->domain, host, sizeof(e->domain));
110 if (*port != '\0' && strcmp(port, "1965")) {
111 strlcat(e->domain, ":", sizeof(e->domain));
112 strlcat(e->domain, port, sizeof(e->domain));
114 strlcpy(e->hash, hash, sizeof(e->hash));
115 e->verified = -1;
117 tofu_update(h, e);