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.
32 static struct timeval tv = { 5 * 60, 0 };
33 static unsigned int timeout;
35 static struct ohash h;
49 mcache_free_entry(const char *url)
51 struct mcache_entry *e;
54 slot = ohash_qlookup(&h, url);
55 if ((e = ohash_remove(&h, slot)) == NULL)
66 clean_old_entries(int fd, int ev, void *data)
68 struct mcache_entry *e;
72 /* delete pages older than an hour */
73 treshold = time(NULL) - 60 * 60;
75 for (e = ohash_first(&h, &i); e != NULL; e = ohash_next(&h, &i))
77 mcache_free_entry(e->url);
79 timeout = ev_timer(&tv, clean_old_entries, NULL);
85 struct ohash_info info = {
86 .key_offset = offsetof(struct mcache_entry, url),
87 .calloc = hash_calloc,
92 ohash_init(&h, 5, &info);
96 mcache_tab(struct tab *tab)
98 struct mcache_entry *e;
104 url = hist_cur(tab->hist);
106 len = sizeof(*e) + l + 1;
108 if ((e = calloc(1, len)) == NULL)
111 e->parser = tab->buffer.page.init;
112 e->trust = tab->trust;
113 memcpy(e->url, url, l);
115 if ((fp = open_memstream(&e->buf, &e->buflen)) == NULL)
118 if (!parser_serialize(tab, fp))
123 /* free any previously cached copies of this page */
124 mcache_free_entry(url);
126 slot = ohash_qlookup(&h, url);
127 ohash_insert(&h, slot, e);
132 if (!ev_timer_pending(timeout))
133 timeout = ev_timer(&tv, clean_old_entries, NULL);
147 mcache_lookup(const char *url, struct tab *tab)
149 struct mcache_entry *e;
152 slot = ohash_qlookup(&h, url);
153 if ((e = ohash_find(&h, slot)) == NULL)
156 parser_init(tab, e->parser);
157 if (!parser_parse(tab, e->buf, e->buflen))
159 if (!parser_free(tab))
162 tab->trust = e->trust;
167 erase_buffer(&tab->buffer);
172 mcache_info(size_t *r_npages, size_t *r_tot)