Debian Codegraph @

tests/test_cache.c

raw symbols SCIP
1 #include "../src/cache.h"
2 #include "../src/config.h"
3 #include "../src/link.h"
4 #include "../src/util.h"
5
6 #include <errno.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/param.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unity.h>
13 #include <unistd.h>
14
15 void setUp(void)
16 {
17 Config_init();
18 }
19
20 void tearDown(void)
21 {
22 // clean stuff up here
23 }
24
25 void test_CacheSystem_get_cache_dir(void)
26 {
27 char *dir;
28
29 // 1. Test when CONFIG.cache_dir is explicitly set
30 CONFIG.cache_dir = "/tmp/explicit_cache";
31 dir = CacheSystem_get_cache_dir();
32 TEST_ASSERT_NOT_NULL(dir);
33 TEST_ASSERT_EQUAL_STRING("/tmp/explicit_cache", dir);
34 // Not dynamically allocated in cache.c when CONFIG.cache_dir is used
35 CONFIG.cache_dir = NULL;
36
37 // 2. Test fallback to XDG_CACHE_HOME
38 setenv("XDG_CACHE_HOME", "/tmp/xdg_cache", 1);
39 dir = CacheSystem_get_cache_dir();
40 TEST_ASSERT_NOT_NULL(dir);
41 TEST_ASSERT_EQUAL_STRING("/tmp/xdg_cache", dir);
42 FREE(dir);
43 unsetenv("XDG_CACHE_HOME");
44
45 // 3. Test fallback to HOME/.cache
46 setenv("HOME", "/tmp/my_home", 1);
47 dir = CacheSystem_get_cache_dir();
48 TEST_ASSERT_NOT_NULL(dir);
49 TEST_ASSERT_EQUAL_STRING("/tmp/my_home/.cache", dir);
50 FREE(dir);
51 unsetenv("HOME");
52
53 // 4. Test fallback when neither is set
54 dir = CacheSystem_get_cache_dir();
55 TEST_ASSERT_NOT_NULL(dir);
56 char *expected_cur_dir = REALPATH("./", NULL);
57 TEST_ASSERT_NOT_NULL(expected_cur_dir);
58 char *expected_dir = path_append(expected_cur_dir, ".cache");
59 TEST_ASSERT_NOT_NULL(expected_dir);
60 TEST_ASSERT_EQUAL_STRING(expected_dir, dir);
61 FREE(expected_cur_dir);
62 FREE(expected_dir);
63 FREE(dir);
64 }
65
66 void test_ActiveDownload_find(void)
67 {
68 Cache cf = {0};
69
70 // 1. Search in an empty list must return NULL
71 TEST_ASSERT_NULL(ActiveDownload_find(&cf, 1024));
72
73 // 2. Construct a mock active downloads linked list
74 ActiveDownload ad1 = {.offset = 1024, .ts = NULL, .next = NULL};
75 ActiveDownload ad2 = {.offset = 2048, .ts = NULL, .next = &ad1};
76 cf.active_dls = &ad2;
77
78 // 3. Verify that matching offsets are correctly resolved
79 TEST_ASSERT_EQUAL_PTR(&ad2, ActiveDownload_find(&cf, 2048));
80 TEST_ASSERT_EQUAL_PTR(&ad1, ActiveDownload_find(&cf, 1024));
81
82 // 4. Verify that non-existent offsets correctly return NULL
83 TEST_ASSERT_NULL(ActiveDownload_find(&cf, 4096));
84 }
85
86 void test_Cache_read_zero_length(void)
87 {
88 Cache cf = {0};
89 Link link = {0};
90 link.content_length = 0;
91 cf.link = &link;
92 cf.blksz = 4096;
93
94 char buf[10];
95 long res = Cache_read(&cf, buf, sizeof(buf), 0);
96 TEST_ASSERT_EQUAL_INT(0, res);
97 }
98
99 void test_Cache_read_past_eof(void)
100 {
101 Cache cf = {0};
102 Link link = {0};
103 link.content_length = 100;
104 cf.link = &link;
105 cf.blksz = 4096;
106
107 char buf[10];
108 long res = Cache_read(&cf, buf, sizeof(buf), 100);
109 TEST_ASSERT_EQUAL_INT(0, res);
110
111 res = Cache_read(&cf, buf, sizeof(buf), 150);
112 TEST_ASSERT_EQUAL_INT(0, res);
113 }
114
115 void test_Cache_read_negative_len(void)
116 {
117 /* The new len < 0 guard must reject negative lengths with -EINVAL
118 * rather than wrapping the value to a huge size_t. */
119 Cache cf = {0};
120 Link link = {0};
121 link.content_length = 1024;
122 cf.link = &link;
123 cf.blksz = 4096;
124
125 char buf[64];
126 long res = Cache_read(&cf, buf, (off_t)-1, 0);
127 TEST_ASSERT_EQUAL_INT(-EINVAL, res);
128
129 res = Cache_read(&cf, buf, (off_t)-1024, 0);
130 TEST_ASSERT_EQUAL_INT(-EINVAL, res);
131 }
132
133 void test_Cache_read_null_cf(void)
134 {
135 /* Cache_read must return -EINVAL when passed a NULL cf pointer. */
136 char buf[16];
137 long res = Cache_read(NULL, buf, sizeof(buf), 0);
138 TEST_ASSERT_EQUAL_INT(-EINVAL, res);
139 }
140
141 void test_Cache_read_null_link(void)
142 {
143 /* Cache_read must return -EINVAL when cf->link is NULL. */
144 Cache cf = {0};
145 cf.link = NULL;
146
147 char buf[16];
148 long res = Cache_read(&cf, buf, sizeof(buf), 0);
149 TEST_ASSERT_EQUAL_INT(-EINVAL, res);
150 }
151
152 static void cleanup_temp_dir(const char *tmp_cache_dir)
153 {
154 char filepath[512];
155
156 // Remove files
157 snprintf(filepath, sizeof(filepath), "%s/meta/file.bin", tmp_cache_dir);
158 (void)unlink(filepath);
159
160 snprintf(filepath, sizeof(filepath), "%s/data/file.bin", tmp_cache_dir);
161 (void)unlink(filepath);
162
163 snprintf(filepath, sizeof(filepath), "%s/meta/dummy.bin", tmp_cache_dir);
164 (void)unlink(filepath);
165
166 snprintf(filepath, sizeof(filepath), "%s/data/dummy.bin", tmp_cache_dir);
167 (void)unlink(filepath);
168
169 // Remove directories
170 snprintf(filepath, sizeof(filepath), "%s/meta", tmp_cache_dir);
171 (void)rmdir(filepath);
172
173 snprintf(filepath, sizeof(filepath), "%s/data", tmp_cache_dir);
174 (void)rmdir(filepath);
175
176 (void)rmdir(tmp_cache_dir);
177 }
178
179 static LinkTable *setup_mock_link_table(const char *link_name)
180 {
181 LinkTable *table = LinkTable_alloc("https://example.com/");
182 Link *link = CALLOC(1, sizeof(Link));
183 link->type = LINK_FILE;
184 link->content_length = 100;
185 link->parent_table = table;
186 strncpy(link->linkname, link_name, NAME_MAX);
187 snprintf(link->f_url, PATH_MAX, "https://example.com/%s", link_name);
188 LinkTable_add(table, link);
189 return table;
190 }
191
192 static void setup_temp_cache_dir(const char *tmp_cache_dir)
193 {
194 char meta_dir[256];
195 char data_dir[256];
196 snprintf(meta_dir, sizeof(meta_dir), "%s/meta", tmp_cache_dir);
197 snprintf(data_dir, sizeof(data_dir), "%s/data", tmp_cache_dir);
198
199 cleanup_temp_dir(tmp_cache_dir);
200 TEST_ASSERT_EQUAL_INT(0, mkdir(tmp_cache_dir, S_IRWXU));
201 TEST_ASSERT_EQUAL_INT(0, mkdir(meta_dir, S_IRWXU));
202 TEST_ASSERT_EQUAL_INT(0, mkdir(data_dir, S_IRWXU));
203 }
204
205 void test_Cache_invalid_zero_length_disk_files(void)
206 {
207 const char *tmp_cache_dir = "./test_cache_invalidation_dir";
208 setup_temp_cache_dir(tmp_cache_dir);
209
210 char *old_cache_dir = CONFIG.cache_dir;
211 CONFIG.cache_dir = (char *)tmp_cache_dir;
212
213 LinkTable *table = setup_mock_link_table("file.bin");
214
215 LinkTable *old_root_link_tbl = ROOT_LINK_TBL;
216 ROOT_LINK_TBL = table;
217 int old_root_link_offset = ROOT_LINK_OFFSET;
218 ROOT_LINK_OFFSET = 20;
219
220 CacheSystem_init(tmp_cache_dir, 0);
221
222 // Scenario 1: Metadata file exists but is 0 bytes (empty)
223 char meta_filepath[512];
224 char data_filepath[512];
225 snprintf(meta_filepath, sizeof(meta_filepath), "%s/meta/file.bin",
226 tmp_cache_dir);
227 snprintf(data_filepath, sizeof(data_filepath), "%s/data/file.bin",
228 tmp_cache_dir);
229
230 // Touch both files to make them exist, meta is 0 bytes
231 FILE *f_meta = fopen(meta_filepath, "w");
232 TEST_ASSERT_NOT_NULL(f_meta);
233 fclose(f_meta);
234
235 FILE *f_data = fopen(data_filepath, "w");
236 TEST_ASSERT_NOT_NULL(f_data);
237 fclose(f_data);
238
239 // Now, call Cache_open. Since meta is empty, it is invalid.
240 // Cache_open should detect this invalid/corrupted cache, delete it,
241 // and recreate a fresh cache which should succeed and have a correct
242 // non-zero size.
243 Cache *cf = Cache_open("file.bin");
244 TEST_ASSERT_NOT_NULL(cf);
245 TEST_ASSERT_NOT_NULL(cf->mfp);
246 TEST_ASSERT_NOT_NULL(cf->dfp);
247
248 // Verify that the recreated meta file is now not empty (it has valid
249 // metadata written)
250 struct stat st;
251 TEST_ASSERT_EQUAL_INT(0, fstat(fileno(cf->mfp), &st));
252 TEST_ASSERT_TRUE(st.st_size > 0);
253
254 // Close the cache
255 Cache_close(cf);
256
257 // Scenario 2: Metadata file contains invalid zero-length/negative size
258 // Create invalid metadata file with disk_content_length = 0
259 f_meta = fopen(meta_filepath, "w");
260 TEST_ASSERT_NOT_NULL(f_meta);
261 long bad_time = 0;
262 off_t bad_len = 0;
263 int bad_blksz = 4096;
264 long bad_segbc = 0;
265 fwrite(&bad_time, sizeof(long), 1, f_meta);
266 fwrite(&bad_len, sizeof(off_t), 1, f_meta);
267 fwrite(&bad_blksz, sizeof(int), 1, f_meta);
268 fwrite(&bad_segbc, sizeof(long), 1, f_meta);
269 fclose(f_meta);
270
271 // Re-open
272 cf = Cache_open("file.bin");
273 TEST_ASSERT_NOT_NULL(cf);
274 TEST_ASSERT_NOT_NULL(cf->mfp);
275 TEST_ASSERT_NOT_NULL(cf->dfp);
276
277 // Verify it was again invalidated, recreated, and now has a valid non-zero
278 // content_length
279 TEST_ASSERT_EQUAL_INT(0, fstat(fileno(cf->mfp), &st));
280 TEST_ASSERT_TRUE(st.st_size > 0);
281
282 Cache_close(cf);
283
284 // Cleanup
285 ROOT_LINK_TBL = old_root_link_tbl;
286 ROOT_LINK_OFFSET = old_root_link_offset;
287 LinkTable_free(table);
288 CacheSystem_cleanup();
289 CONFIG.cache_dir = old_cache_dir;
290 cleanup_temp_dir(tmp_cache_dir);
291 }
292
293 void test_Cache_alloc_num_bg_workers(void)
294 {
295 // Mock the external global CONFIG
296 int old_max_conns = CONFIG.max_conns;
297
298 const char *tmp_cache_dir = "./test_cache_bg_workers_dir";
299 setup_temp_cache_dir(tmp_cache_dir);
300
301 char *old_cache_dir = CONFIG.cache_dir;
302 CONFIG.cache_dir = (char *)tmp_cache_dir;
303
304 LinkTable *table = setup_mock_link_table("dummy.bin");
305
306 LinkTable *old_root_link_tbl = ROOT_LINK_TBL;
307 ROOT_LINK_TBL = table;
308 int old_root_link_offset = ROOT_LINK_OFFSET;
309 ROOT_LINK_OFFSET = 20;
310
311 CacheSystem_init(tmp_cache_dir, 0);
312
313 int test_conns[] = {10, 4, 1};
314 for (int i = 0; i < 3; i++) {
315 CONFIG.max_conns = test_conns[i];
316 Cache *cf = Cache_open("dummy.bin");
317 TEST_ASSERT_NOT_NULL(cf);
318 int expected = MIN(CONFIG.max_conns, DEFAULT_NETWORK_MAX_CONNS) / 2;
319 if (expected <= 0) {
320 expected = 1;
321 }
322 TEST_ASSERT_EQUAL_INT(expected, cf->num_bg_workers);
323 Cache_close(cf);
324 }
325
326 // Cleanup
327 ROOT_LINK_TBL = old_root_link_tbl;
328 ROOT_LINK_OFFSET = old_root_link_offset;
329 LinkTable_free(table);
330 CacheSystem_cleanup();
331 CONFIG.cache_dir = old_cache_dir;
332 cleanup_temp_dir(tmp_cache_dir);
333 CONFIG.max_conns = old_max_conns;
334 }
335
336 void test_Cache_free_active_downloads(void)
337 {
338 const char *tmp_cache_dir = "./test_cache_free_ad_dir";
339 setup_temp_cache_dir(tmp_cache_dir);
340
341 char *old_cache_dir = CONFIG.cache_dir;
342 CONFIG.cache_dir = (char *)tmp_cache_dir;
343
344 LinkTable *table = setup_mock_link_table("dummy.bin");
345
346 LinkTable *old_root_link_tbl = ROOT_LINK_TBL;
347 ROOT_LINK_TBL = table;
348 int old_root_link_offset = ROOT_LINK_OFFSET;
349 ROOT_LINK_OFFSET = 20;
350
351 CacheSystem_init(tmp_cache_dir, 0);
352
353 Cache *cf = Cache_open("dummy.bin");
354 TEST_ASSERT_NOT_NULL(cf);
355
356 // Under the dl_lock, manually add mock ActiveDownload nodes to test
357 // Cache_free's teardown path
358 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
359
360 ActiveDownload *ad1 = CALLOC(1, sizeof(ActiveDownload));
361 ad1->offset = 1024;
362 ad1->refcount = 1;
363 PTHREAD_COND_INIT(&ad1->cond, NULL);
364
365 ActiveDownload *ad2 = CALLOC(1, sizeof(ActiveDownload));
366 ad2->offset = 2048;
367 ad2->refcount = 2; // Extra reference to trigger the warning/no-free path
368 PTHREAD_COND_INIT(&ad2->cond, NULL);
369
370 ad2->next = ad1;
371 cf->active_dls = ad2;
372
373 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
374
375 // Call Cache_close to trigger Cache_free
376 Cache_close(cf);
377
378 // Since ad2 had a refcount of 2, Cache_free only decremented its refcount
379 // to 1 and did not free it. It is therefore safe and valid to inspect ad2
380 // here without risking use-after-free.
381 TEST_ASSERT_EQUAL_INT(1, ad2->refcount);
382
383 // Clean up ad2 manually to prevent leak warnings
384 PTHREAD_COND_DESTROY(&ad2->cond);
385 FREE(ad2);
386
387 // Cleanup
388 ROOT_LINK_TBL = old_root_link_tbl;
389 ROOT_LINK_OFFSET = old_root_link_offset;
390 LinkTable_free(table);
391 CacheSystem_cleanup();
392 CONFIG.cache_dir = old_cache_dir;
393 cleanup_temp_dir(tmp_cache_dir);
394 }
395
396 struct WaiterThreadArgs {
397 Cache *cf;
398 char *buf;
399 off_t len;
400 off_t offset;
401 long expected_res;
402 };
403
404 static void *waiter_thread_func(void *arg)
405 {
406 struct WaiterThreadArgs *args = (struct WaiterThreadArgs *)arg;
407 long res = Cache_read(args->cf, args->buf, args->len, args->offset);
408 args->expected_res = res;
409 return NULL;
410 }
411
412 void test_Cache_free_active_downloads_with_waiters(void)
413 {
414 const char *tmp_cache_dir = "./test_cache_free_ad_wait_dir";
415 setup_temp_cache_dir(tmp_cache_dir);
416
417 char *old_cache_dir = CONFIG.cache_dir;
418 CONFIG.cache_dir = (char *)tmp_cache_dir;
419
420 LinkTable *table = setup_mock_link_table("dummy.bin");
421
422 LinkTable *old_root_link_tbl = ROOT_LINK_TBL;
423 ROOT_LINK_TBL = table;
424 int old_root_link_offset = ROOT_LINK_OFFSET;
425 ROOT_LINK_OFFSET = 20;
426
427 CacheSystem_init(tmp_cache_dir, 0);
428
429 Cache *cf = Cache_open("dummy.bin");
430 TEST_ASSERT_NOT_NULL(cf);
431
432 // Manually inject an active download so any reader will block
433 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
434 ActiveDownload *ad = CALLOC(1, sizeof(ActiveDownload));
435 ad->offset = 0;
436 ad->refcount = 1;
437 PTHREAD_COND_INIT(&ad->cond, NULL);
438 cf->active_dls = ad;
439 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
440
441 // Spawn waiter thread
442 pthread_t thread;
443 char buf[64];
444 struct WaiterThreadArgs args = {.cf = cf,
445 .buf = buf,
446 .len = sizeof(buf),
447 .offset = 0,
448 .expected_res = 0};
449
450 TEST_ASSERT_EQUAL_INT(
451 0, pthread_create(&thread, NULL, waiter_thread_func, &args));
452
453 // Wait until the reader thread registers as a waiter
454 struct timespec start_time;
455 struct timespec current_time;
456 clock_gettime(CLOCK_MONOTONIC, &start_time);
457 while (1) {
458 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
459 int has_waiter = (cf->waiters == 1);
460 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
461 if (has_waiter) {
462 break;
463 }
464 clock_gettime(CLOCK_MONOTONIC, &current_time);
465 double elapsed
466 = (double)(current_time.tv_sec - start_time.tv_sec)
467 + ((double)(current_time.tv_nsec - start_time.tv_nsec) / 1e9);
468 if (elapsed >= 5.0) {
469 TEST_FAIL_MESSAGE(
470 "Timed out waiting for reader to register as waiter");
471 }
472 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000000};
473 nanosleep(&delay, NULL);
474 }
475
476 // Call Cache_close which triggers Cache_free, setting shutting_down to 1,
477 // waking all waiters and joining them before tearing down
478 Cache_close(cf);
479
480 // Join the helper thread
481 TEST_ASSERT_EQUAL_INT(0, pthread_join(thread, NULL));
482
483 // The read must have been aborted with -EIO due to shutdown
484 TEST_ASSERT_EQUAL_INT(-EIO, args.expected_res);
485
486 // Cleanup
487 ROOT_LINK_TBL = old_root_link_tbl;
488 ROOT_LINK_OFFSET = old_root_link_offset;
489 LinkTable_free(table);
490 CacheSystem_cleanup();
491 CONFIG.cache_dir = old_cache_dir;
492 cleanup_temp_dir(tmp_cache_dir);
493 }
494
495 int main(void)
496 {
497 UNITY_BEGIN();
498 RUN_TEST(test_CacheSystem_get_cache_dir);
499 RUN_TEST(test_ActiveDownload_find);
500 RUN_TEST(test_Cache_read_zero_length);
501 RUN_TEST(test_Cache_read_past_eof);
502 RUN_TEST(test_Cache_read_negative_len);
503 RUN_TEST(test_Cache_read_null_cf);
504 RUN_TEST(test_Cache_read_null_link);
505 RUN_TEST(test_Cache_invalid_zero_length_disk_files);
506 RUN_TEST(test_Cache_alloc_num_bg_workers);
507 RUN_TEST(test_Cache_free_active_downloads);
508 RUN_TEST(test_Cache_free_active_downloads_with_waiters);
509 return UNITY_END();
510 }