Debian Codegraph @

src/sysupdate/sysupdate-cache.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "alloc-util.h"
4 #include "hashmap.h"
5 #include "memory-util.h"
6 #include "sysupdate-cache.h"
7
8 #define WEB_CACHE_ENTRIES_MAX 64U
9 #define WEB_CACHE_ITEM_SIZE_MAX (64U*1024U*1024U)
10
11 static WebCacheItem* web_cache_item_free(WebCacheItem *i) {
12 if (!i)
13 return NULL;
14
15 free(i->url);
16 return mfree(i);
17 }
18
19 DEFINE_TRIVIAL_CLEANUP_FUNC(WebCacheItem*, web_cache_item_free);
20
21 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(web_cache_hash_ops, char, string_hash_func, string_compare_func, WebCacheItem, web_cache_item_free);
22
23 int web_cache_add_item(
24 Hashmap **web_cache,
25 const char *url,
26 bool verified,
27 const void *data,
28 size_t size) {
29
30 _cleanup_(web_cache_item_freep) WebCacheItem *item = NULL;
31 _cleanup_free_ char *u = NULL;
32 int r;
33
34 assert(web_cache);
35 assert(url);
36 assert(data || size == 0);
37
38 if (size > WEB_CACHE_ITEM_SIZE_MAX)
39 return -E2BIG;
40
41 item = web_cache_get_item(*web_cache, url, verified);
42 if (item && memcmp_nn(item->data, item->size, data, size) == 0)
43 return 0;
44
45 if (hashmap_size(*web_cache) >= (size_t) (WEB_CACHE_ENTRIES_MAX + hashmap_contains(*web_cache, url)))
46 return -ENOSPC;
47
48 r = hashmap_ensure_allocated(web_cache, &web_cache_hash_ops);
49 if (r < 0)
50 return r;
51
52 u = strdup(url);
53 if (!u)
54 return -ENOMEM;
55
56 item = malloc(offsetof(WebCacheItem, data) + size + 1);
57 if (!item)
58 return -ENOMEM;
59
60 *item = (WebCacheItem) {
61 .url = TAKE_PTR(u),
62 .size = size,
63 .verified = verified,
64 };
65
66 /* Just to be extra paranoid, let's NUL terminate the downloaded buffer */
67 *mempcpy_typesafe(item->data, data, size) = 0;
68
69 web_cache_item_free(hashmap_remove(*web_cache, url));
70
71 r = hashmap_put(*web_cache, item->url, item);
72 if (r < 0)
73 return r;
74
75 TAKE_PTR(item);
76 return 1;
77 }
78
79 WebCacheItem* web_cache_get_item(Hashmap *web_cache, const char *url, bool verified) {
80 WebCacheItem *i;
81
82 i = hashmap_get(web_cache, url);
83 if (!i)
84 return NULL;
85
86 if (i->verified != verified)
87 return NULL;
88
89 return i;
90 }