2 * Copyright (c) 2022 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.
30 #include "telescope.h"
34 static struct timeval tv = { 5 * 60, 0 };
35 static unsigned int timeout;
37 static struct ohash h;
43 const struct parser *parser;
51 mcache_free_entry(const char *url)
53 struct mcache_entry *e;
56 slot = ohash_qlookup(&h, url);
57 if ((e = ohash_remove(&h, slot)) == NULL)
68 clean_old_entries(int fd, int ev, void *data)
70 struct mcache_entry *e;
74 /* delete pages older than an hour */
75 threshold = time(NULL) - 60 * 60;
77 for (e = ohash_first(&h, &i); e != NULL; e = ohash_next(&h, &i))
78 if (e->ts < threshold)
79 mcache_free_entry(e->url);
81 timeout = ev_timer(&tv, clean_old_entries, NULL);
87 struct ohash_info info = {
88 .key_offset = offsetof(struct mcache_entry, url),
89 .calloc = hash_calloc,
94 ohash_init(&h, 5, &info);
98 mcache_tab(struct tab *tab)
100 struct mcache_entry *e;
106 url = hist_cur(tab->hist);
108 len = sizeof(*e) + l + 1;
112 e->parser = tab->buffer.parser;
113 e->trust = tab->trust;
114 memcpy(e->url, url, l);
116 if ((fp = open_memstream(&e->buf, &e->buflen)) == NULL)
119 if (!parser_serialize(&tab->buffer, fp))
124 /* free any previously cached copies of this page */
125 mcache_free_entry(url);
127 slot = ohash_qlookup(&h, url);
128 ohash_insert(&h, slot, e);
133 if (!ev_timer_pending(timeout))
134 timeout = ev_timer(&tv, clean_old_entries, NULL);
148 mcache_lookup(const char *url, struct tab *tab)
150 struct mcache_entry *e;
153 slot = ohash_qlookup(&h, url);
154 if ((e = ohash_find(&h, slot)) == NULL)
157 parser_init(&tab->buffer, e->parser);
158 if (!parser_parse(&tab->buffer, e->buf, e->buflen))
160 if (!parser_free(tab))
163 tab->trust = e->trust;
168 erase_buffer(&tab->buffer);
173 mcache_info(size_t *r_npages, size_t *r_tot)