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.
23 #include "telescope.h"
28 static struct timeval tv = { 5 * 60, 0 };
29 static struct event timerev;
31 static struct ohash h;
44 mcache_printf(void *d, const char *fmt, ...)
46 struct evbuffer *evb = d;
51 r = evbuffer_add_vprintf(evb, fmt, ap);
58 mcache_free_entry(const char *url)
60 struct mcache_entry *e;
63 slot = ohash_qlookup(&h, url);
64 if ((e = ohash_remove(&h, slot)) == NULL)
68 tot -= EVBUFFER_LENGTH(e->evb);
70 evbuffer_free(e->evb);
75 clean_old_entries(int fd, short ev, void *data)
77 struct mcache_entry *e;
81 /* delete pages older than an hour */
82 treshold = time(NULL) - 60 * 60;
84 for (e = ohash_first(&h, &i); e != NULL; e = ohash_next(&h, &i))
86 mcache_free_entry(e->url);
88 evtimer_add(&timerev, &tv);
94 struct ohash_info info = {
95 .key_offset = offsetof(struct mcache_entry, url),
96 .calloc = hash_calloc,
101 ohash_init(&h, 5, &info);
103 evtimer_set(&timerev, clean_old_entries, NULL);
107 mcache_tab(struct tab *tab)
109 struct mcache_entry *e;
114 url = tab->hist_cur->h;
116 len = sizeof(*e) + l + 1;
118 if ((e = calloc(1, len)) == NULL)
121 e->parser = tab->buffer.page.init;
122 e->trust = tab->trust;
123 memcpy(e->url, url, l);
125 if ((e->evb = evbuffer_new()) == NULL)
128 if (!parser_serialize(tab, mcache_printf, e->evb))
131 /* free any previously cached copies of this page */
132 mcache_free_entry(url);
134 slot = ohash_qlookup(&h, url);
135 ohash_insert(&h, slot, e);
138 tot += EVBUFFER_LENGTH(e->evb);
140 if (!evtimer_pending(&timerev, NULL))
141 evtimer_add(&timerev, &tv);
147 evbuffer_free(e->evb);
153 mcache_lookup(const char *url, struct tab *tab)
155 struct mcache_entry *e;
158 slot = ohash_qlookup(&h, url);
159 if ((e = ohash_find(&h, slot)) == NULL)
162 parser_init(tab, e->parser);
163 if (!parser_parse(tab, EVBUFFER_DATA(e->evb), EVBUFFER_LENGTH(e->evb)))
165 if (!parser_free(tab))
168 tab->trust = e->trust;
173 erase_buffer(&tab->buffer);
178 mcache_info(size_t *r_npages, size_t *r_tot)