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_free_entry(const char *url)
46 struct mcache_entry *e;
49 slot = ohash_qlookup(&h, url);
50 if ((e = ohash_remove(&h, slot)) == NULL)
54 tot -= EVBUFFER_LENGTH(e->evb);
56 evbuffer_free(e->evb);
61 clean_old_entries(int fd, short ev, void *data)
63 struct mcache_entry *e;
67 /* delete pages older than an hour */
68 treshold = time(NULL) - 60 * 60;
70 for (e = ohash_first(&h, &i); e != NULL; e = ohash_next(&h, &i))
72 mcache_free_entry(e->url);
74 evtimer_add(&timerev, &tv);
80 struct ohash_info info = {
81 .key_offset = offsetof(struct mcache_entry, url),
82 .calloc = hash_calloc,
87 ohash_init(&h, 5, &info);
89 evtimer_set(&timerev, clean_old_entries, NULL);
93 mcache_tab(struct tab *tab)
95 struct mcache_entry *e;
100 url = tab->hist_cur->h;
102 len = sizeof(*e) + l + 1;
104 if ((e = calloc(1, len)) == NULL)
107 e->parser = tab->buffer.page.init;
108 e->trust = tab->trust;
109 memcpy(e->url, url, l);
111 if ((e->evb = evbuffer_new()) == NULL)
114 if (!parser_serialize(tab, e->evb))
117 /* free any previously cached copies of this page */
118 mcache_free_entry(url);
120 slot = ohash_qlookup(&h, url);
121 ohash_insert(&h, slot, e);
124 tot += EVBUFFER_LENGTH(e->evb);
126 if (!evtimer_pending(&timerev, NULL))
127 evtimer_add(&timerev, &tv);
133 evbuffer_free(e->evb);
139 mcache_lookup(const char *url, struct tab *tab)
141 struct mcache_entry *e;
144 slot = ohash_qlookup(&h, url);
145 if ((e = ohash_find(&h, slot)) == NULL)
148 parser_init(tab, e->parser);
149 if (!parser_parse(tab, EVBUFFER_DATA(e->evb), EVBUFFER_LENGTH(e->evb)))
151 if (!parser_free(tab))
154 tab->trust = e->trust;
159 erase_buffer(&tab->buffer);
164 mcache_info(size_t *r_npages, size_t *r_tot)