Debian Codegraph @

src/cache.c

raw symbols SCIP
1 /*
2 * HTTPDirFS - HTTP Directory Filesystem
3 *
4 * Copyright (C) 2020-2026 Fufu Fang <[email protected]>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * In addition, as a special exception, the copyright holders give
20 * permission to link the code of portions of this program with the OpenSSL
21 * library.
22 */
23
24 /**
25 * \file cache.c
26 * \brief Permanent cache system implementation
27 */
28
29 #include "cache.h"
30
31 #include "config.h"
32 #include "link.h"
33 #include "log.h"
34 #include "memcache.h"
35 #include "util.h"
36 #include <curl/curl.h>
37
38 #include <sys/param.h>
39 #include <sys/stat.h>
40
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <ftw.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48
49 /*
50 * ---------------- External variables -----------------------
51 */
52 int CACHE_SYSTEM_INIT = 0;
53 char *META_DIR;
54
55 /*
56 * ----------------- Static variables -----------------------
57 */
58
59 /**
60 * \brief Cache file locking
61 * \details Ensure cache opening and cache closing is an atomic operation
62 */
63 static pthread_mutex_t cf_lock;
64
65 /**
66 * \brief The data directory
67 */
68 static char *DATA_DIR;
69
70
71 char *CacheSystem_get_cache_dir(void)
72 {
73 if (CONFIG.cache_dir) {
74 return CONFIG.cache_dir;
75 }
76
77 const char *default_cache_subdir = "/.cache";
78 char *cache_dir = NULL;
79
80 const char *xdg_cache_home = getenv("XDG_CACHE_HOME");
81 if (xdg_cache_home) {
82 cache_dir = STRNDUP(xdg_cache_home, PATH_MAX);
83 } else {
84 const char *user_home = getenv("HOME");
85 if (user_home) {
86 cache_dir = path_append(user_home, default_cache_subdir);
87 } else {
88 lprintf(warning, "$HOME is unset\n");
89 /*
90 * XDG_CACHE_HOME and HOME already are full paths. Not relying
91 * on environment PWD since it too may be undefined.
92 */
93 char *cur_dir = REALPATH("./", NULL);
94 if (cur_dir) {
95 cache_dir = path_append(cur_dir, default_cache_subdir);
96 FREE(cur_dir);
97 } else {
98 lprintf(fatal, "Could not create cache directory\n");
99 }
100 }
101 }
102 return cache_dir;
103 }
104
105 /**
106 * \brief Calculate cache system directory path
107 */
108 static char *CacheSystem_calc_dir(const char *url)
109 {
110 char *cache_home = CacheSystem_get_cache_dir();
111
112 if (mkdir(cache_home, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
113 && (errno != EEXIST)) {
114 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
115 }
116 char *cache_dir_root = path_append(cache_home, "/httpdirfs/");
117 if (mkdir(cache_dir_root, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
118 && (errno != EEXIST)) {
119 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
120 }
121
122 char *fn = path_append(cache_dir_root, "/CACHEDIR.TAG");
123 FILE *fp = fopen(fn, "w");
124 if (fp) {
125 fprintf(fp, "Signature: 8a477f597d28d172789f06886806bc55\n\
126 # This file is a cache directory tag created by httpdirfs.\n\
127 # For information about cache directory tags, see:\n\
128 # http://www.brynosaurus.com/cachedir/\n");
129 } else {
130 lprintf(fatal, "fopen(%s): %s", fn, strerror(errno));
131 }
132 if (ferror(fp)) {
133 lprintf(fatal, "fwrite(): encountered error!\n");
134 }
135 if (fclose(fp)) {
136 lprintf(fatal, "fclose(%s): %s\n", fn, strerror(errno));
137 }
138 CURL *c = curl_easy_init();
139 char *escaped_url = curl_easy_escape(c, url, 0);
140 char *full_path = path_append(cache_dir_root, escaped_url);
141 if (mkdir(full_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
142 && (errno != EEXIST)) {
143 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
144 }
145 FREE(fn);
146 FREE(cache_home);
147 FREE(cache_dir_root);
148 curl_free(escaped_url);
149 curl_easy_cleanup(c);
150 return full_path;
151 }
152
153 void CacheSystem_init(const char *path, int url_supplied)
154 {
155 lprintf(cache_lock_debug, "thread %lx: initialise cf_lock;\n",
156 (unsigned long)pthread_self());
157 PTHREAD_MUTEX_INIT(&cf_lock, NULL);
158
159 if (url_supplied) {
160 path = CacheSystem_calc_dir(path);
161 }
162
163 META_DIR = path_append(path, "meta/");
164 DATA_DIR = path_append(path, "data/");
165 /*
166 * Check if directories exist, if not, create them
167 */
168 if (mkdir(META_DIR, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
169 && (errno != EEXIST)) {
170 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
171 }
172
173 if (mkdir(DATA_DIR, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
174 && (errno != EEXIST)) {
175 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
176 }
177
178 if (CONFIG.mode == SONIC) {
179 char *sonic_path;
180 /*
181 * Create "rest" sub-directory for META_DIR
182 */
183 sonic_path = path_append(META_DIR, "rest/");
184 if (mkdir(sonic_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
185 && (errno != EEXIST)) {
186 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
187 }
188 FREE(sonic_path);
189
190 /*
191 * Create "rest" sub-directory for DATA_DIR
192 */
193 sonic_path = path_append(DATA_DIR, "rest/");
194 if (mkdir(sonic_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
195 && (errno != EEXIST)) {
196 lprintf(fatal, "mkdir(): %s\n", strerror(errno));
197 }
198 FREE(sonic_path);
199 }
200
201 CACHE_SYSTEM_INIT = 1;
202 }
203
204 void CacheSystem_cleanup(void)
205 {
206 if (CACHE_SYSTEM_INIT) {
207 FREE(META_DIR);
208 FREE(DATA_DIR);
209 PTHREAD_MUTEX_DESTROY(&cf_lock);
210 CACHE_SYSTEM_INIT = 0;
211 }
212 }
213
214 static int ntfw_cb(const char *fpath, const struct stat *sb, int typeflag,
215 struct FTW *ftwbuf)
216 {
217 (void)sb;
218 (void)typeflag;
219 (void)ftwbuf;
220 return remove(fpath);
221 }
222
223 void CacheSystem_clear(void)
224 {
225 char *cache_home = CacheSystem_get_cache_dir();
226 const char *cache_del;
227 if (CONFIG.cache_dir) {
228 cache_del = cache_home;
229 } else {
230 cache_del = path_append(cache_home, "/httpdirfs/");
231 }
232 nftw(cache_del, ntfw_cb, 64, FTW_DEPTH | FTW_PHYS | FTW_MOUNT);
233 FREE(cache_home);
234 exit(EXIT_SUCCESS);
235 }
236
237 /**
238 * \brief read a metadata file
239 * \return 0 on success, errno on error.
240 */
241 static int Meta_read(Cache *cf)
242 {
243 FILE *fp = cf->mfp;
244
245 if (!fp) {
246 /*
247 * The metadata file does not exist
248 */
249 lprintf(error, "fopen(): %s\n", strerror(errno));
250 return EIO;
251 }
252
253 if (fseek(fp, 0, SEEK_SET) != 0) {
254 lprintf(error, "fseek(): %s\n", strerror(errno));
255 return EIO;
256 }
257
258 if (!cf->link) {
259 lprintf(error, "cf->link is NULL in Meta_read\n");
260 return EINVAL;
261 }
262
263 long disk_time;
264 off_t disk_content_length;
265
266 if (1 != fread(&disk_time, sizeof(long), 1, fp)
267 || 1 != fread(&disk_content_length, sizeof(off_t), 1, fp)
268 || 1 != fread(&cf->blksz, sizeof(int), 1, fp)
269 || 1 != fread(&cf->segbc, sizeof(long), 1, fp) || ferror(fp)) {
270 lprintf(error, "error reading core metadata %s!\n", cf->path);
271 return EIO;
272 }
273
274 /*
275 * We do not support zero-byte files in the on-disk cache files.
276 * Both disk_content_length and cf->segbc must be strictly positive.
277 */
278 if (disk_content_length <= 0 || cf->blksz <= 0 || cf->segbc <= 0) {
279 lprintf(error,
280 "corruption: content_length: %jd, blksz: %d, segbc: %jd\n",
281 (intmax_t)disk_content_length, cf->blksz, (intmax_t)cf->segbc);
282 return EBADMSG;
283 }
284
285 if (cf->blksz != CONFIG.data_blksz) {
286 lprintf(warning, "Warning: cf->blksz != CONFIG.data_blksz\n");
287 }
288
289 if (disk_content_length > INT64_MAX - cf->blksz) {
290 lprintf(error, "Error: segbc upper bound overflow\n");
291 return EBADMSG;
292 }
293
294 /* Verify cached metadata matches the live Link metadata */
295 if (disk_time != cf->link->time) {
296 lprintf(warning, "outdated cache file: %s (disk: %ld, link: %ld)\n",
297 cf->path, disk_time, cf->link->time);
298 return EBADMSG;
299 }
300
301 if ((uintmax_t)disk_content_length != (uintmax_t)cf->link->content_length) {
302 lprintf(warning, "cache size mismatch: %s (disk: %jd, link: %zu)\n",
303 cf->path, (intmax_t)disk_content_length,
304 cf->link->content_length);
305 return EBADMSG;
306 }
307
308 off_t max_segbc = disk_content_length / cf->blksz;
309
310 if (max_segbc >= INT_MAX) {
311 max_segbc = INT_MAX;
312 } else if ((disk_content_length % cf->blksz) != 0) {
313 max_segbc += 1;
314 }
315
316 if (cf->segbc != max_segbc) {
317 lprintf(error, "Error: invalid segbc size: %ld (expected: %ld)\n",
318 cf->segbc, (long)max_segbc);
319 return EBADMSG;
320 }
321
322 /*
323 * Allocate memory for all segments, and read them in
324 */
325 cf->seg = CALLOC(cf->segbc, sizeof(Seg));
326 long nmemb = fread(cf->seg, sizeof(Seg), cf->segbc, fp);
327
328 /*
329 * We shouldn't have gone past the end of the file
330 */
331 if (feof(fp)) {
332 /*
333 * reached EOF
334 */
335 lprintf(error, "attempted to read past the end of the file!\n");
336 return EBADMSG;
337 }
338
339 /*
340 * Error checking for fread
341 */
342 if (ferror(fp)) {
343 lprintf(error, "error reading bitmap!\n");
344 return EIO;
345 }
346
347 /*
348 * Check for inconsistent metadata file
349 */
350 if (nmemb != cf->segbc) {
351 lprintf(error, "corrupted metadata!\n");
352 return EBADMSG;
353 }
354
355 return 0;
356 }
357
358 /**
359 * \brief write a metadata file
360 * \return
361 * - -1 on error,
362 * - 0 on success
363 */
364 static int Meta_write(Cache *cf)
365 {
366 FILE *fp = cf->mfp;
367
368 if (!fp) {
369 /*
370 * Cannot create the metadata file
371 */
372 lprintf(error, "fopen(): %s\n", strerror(errno));
373 return -1;
374 }
375
376 if (fseek(fp, 0, SEEK_SET) != 0) {
377 lprintf(error, "fseek(): %s\n", strerror(errno));
378 return -1;
379 }
380
381 if (!cf->link) {
382 lprintf(error, "cf->link is NULL in Meta_write\n");
383 return -1;
384 }
385
386 /*
387 * We do not support zero-byte files. Both write_content_length and
388 * cf->segbc must be strictly positive.
389 */
390 off_t write_content_length = (off_t)cf->link->content_length;
391 off_t expected_segbc = 0;
392 if (cf->blksz > 0 && write_content_length > 0) {
393 expected_segbc = write_content_length / cf->blksz;
394 if (expected_segbc >= INT_MAX) {
395 expected_segbc = INT_MAX;
396 } else if (write_content_length % cf->blksz != 0) {
397 expected_segbc += 1;
398 }
399 }
400 if (write_content_length <= 0
401 || (size_t)write_content_length != cf->link->content_length
402 || cf->blksz <= 0 || cf->segbc != expected_segbc || cf->segbc <= 0) {
403 lprintf(error,
404 "invalid metadata for write: content_length: %jd, blksz: %d, "
405 "segbc: %ld (expected: %ld)\n",
406 (intmax_t)write_content_length, cf->blksz, cf->segbc,
407 expected_segbc);
408 return -1;
409 }
410
411 fwrite(&cf->link->time, sizeof(long), 1, fp);
412 fwrite(&write_content_length, sizeof(off_t), 1, fp);
413 fwrite(&cf->blksz, sizeof(int), 1, fp);
414 fwrite(&cf->segbc, sizeof(long), 1, fp);
415 fwrite(cf->seg, sizeof(Seg), cf->segbc, fp);
416
417 /*
418 * Error checking for fwrite
419 */
420 if (ferror(fp)) {
421 lprintf(error, "fwrite(): encountered error!\n");
422 return -1;
423 }
424
425 return 0;
426 }
427
428 /**
429 * \brief create a data file
430 * \details We use sparse creation here
431 * \return exit on failure
432 */
433 static void Data_create(Cache *cf)
434 {
435 int fd;
436 int mode;
437
438 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
439 char *datafn = path_append(DATA_DIR, cf->path);
440 fd = open(datafn, O_WRONLY | O_CREAT, mode);
441 FREE(datafn);
442 if (fd == -1) {
443 lprintf(fatal, "open(): %s\n", strerror(errno));
444 }
445 if (!cf->link) {
446 lprintf(fatal, "cf->link is NULL in Data_create\n");
447 }
448 off_t truncate_size = (off_t)cf->link->content_length;
449 if (truncate_size < 0
450 || (size_t)truncate_size != cf->link->content_length) {
451 lprintf(fatal, "File size too large for system off_t: %zu\n",
452 cf->link->content_length);
453 }
454 if (ftruncate(fd, truncate_size)) {
455 lprintf(warning, "ftruncate(): %s\n", strerror(errno));
456 }
457 if (close(fd)) {
458 lprintf(fatal, "close:(): %s\n", strerror(errno));
459 }
460 }
461
462 /**
463 * \brief obtain the data file size
464 * \return file size on success, -1 on error
465 */
466 static off_t Data_size(const char *fn)
467 {
468 char *datafn = path_append(DATA_DIR, fn);
469 struct stat st;
470 int s = stat(datafn, &st);
471 FREE(datafn);
472 if (!s) {
473 return st.st_size;
474 }
475 lprintf(error, "stat(): %s\n", strerror(errno));
476 return -1;
477 }
478
479 /**
480 * \brief read a data file
481 * \param[in] cf the pointer to the cache in-memory data structure
482 * \param[out] buf the output buffer
483 * \param[in] len the length of the segment
484 * \param[in] offset the offset of the segment
485 * \return
486 * - negative values on error,
487 * - otherwise, the number of bytes read.
488 */
489 static long Data_read(Cache *cf, uint8_t *buf, off_t len, off_t offset)
490 {
491 if (!cf->link) {
492 lprintf(error, "cf->link is NULL in Data_read\n");
493 return -EINVAL;
494 }
495
496 off_t total_len = (off_t)cf->link->content_length;
497 if (total_len < 0 || (size_t)total_len != cf->link->content_length) {
498 lprintf(error, "content_length overflow in Data_read\n");
499 return -EINVAL;
500 }
501
502 if (len < 0) {
503 lprintf(error, "requested to read negative bytes: %jd\n",
504 (intmax_t)len);
505 return -EINVAL;
506 }
507
508 if (len == 0) {
509 lprintf(error, "requested to read 0 byte!\n");
510 return -EINVAL;
511 }
512
513 lprintf(cache_lock_debug, "thread %lx: locking seek_lock;\n",
514 (unsigned long)pthread_self());
515 PTHREAD_MUTEX_LOCK(&cf->seek_lock);
516
517 long byte_read = 0;
518
519 if (offset < 0 || offset >= total_len) {
520 goto end;
521 } else if (len > total_len - offset) {
522 len = total_len - offset;
523 }
524
525 /*
526 * Seek to the right location
527 */
528 if (fseeko(cf->dfp, offset, SEEK_SET)) {
529 /*
530 * fseeko failed
531 */
532 lprintf(error, "fseeko(): %s\n", strerror(errno));
533 byte_read = -EIO;
534 goto end;
535 }
536
537 byte_read = fread(buf, sizeof(uint8_t), len, cf->dfp);
538 if (byte_read != len) {
539 if (feof(cf->dfp)) {
540 /*
541 * reached EOF
542 */
543 lprintf(error, "fread(): reached the end of the file!\n");
544 }
545 if (ferror(cf->dfp)) {
546 /*
547 * filesystem error
548 */
549 lprintf(error, "fread(): encountered error!\n");
550 }
551 }
552
553 end:
554
555 lprintf(cache_lock_debug, "thread %lx: unlocking seek_lock;\n",
556 (unsigned long)pthread_self());
557 PTHREAD_MUTEX_UNLOCK(&cf->seek_lock);
558 return byte_read;
559 }
560
561 /**
562 * \brief write to a data file
563 * \param[in] cf the pointer to the cache in-memory data structure
564 * \param[in] buf the input buffer
565 * \param[in] len the length of the segment
566 * \param[in] offset the offset of the segment
567 * \return
568 * - -1 when the data file does not exist
569 * - otherwise, the number of bytes written.
570 */
571 static long Data_write(Cache *cf, const uint8_t *buf, off_t len, off_t offset)
572 {
573 if (len <= 0) {
574 lprintf(error, "requested to write 0 or negative bytes: %jd\n",
575 (intmax_t)len);
576 return -EINVAL;
577 }
578
579 lprintf(cache_lock_debug, "thread %lx: locking seek_lock;\n",
580 (unsigned long)pthread_self());
581 PTHREAD_MUTEX_LOCK(&cf->seek_lock);
582
583 long byte_written = 0;
584
585 if (fseeko(cf->dfp, offset, SEEK_SET)) {
586 /*
587 * fseeko failed
588 */
589 lprintf(error, "fseeko(): %s\n", strerror(errno));
590 byte_written = -EIO;
591 goto end;
592 }
593
594 byte_written = fwrite(buf, sizeof(uint8_t), len, cf->dfp);
595
596 if (byte_written != len) {
597 lprintf(error, "fwrite(): requested %ld, returned %ld!\n", len,
598 byte_written);
599 }
600
601 if (ferror(cf->dfp)) {
602 /*
603 * filesystem error
604 */
605 lprintf(error, "fwrite(): encountered error!\n");
606 }
607
608 end:
609 lprintf(cache_lock_debug, "thread %lx: unlocking seek_lock;\n",
610 (unsigned long)pthread_self());
611 PTHREAD_MUTEX_UNLOCK(&cf->seek_lock);
612 return byte_written;
613 }
614
615 int CacheDir_create(const char *dirn)
616 {
617 char *metadirn = path_append(META_DIR, dirn);
618 char *datadirn = path_append(DATA_DIR, dirn);
619 int res = 0;
620
621 if (mkdir(metadirn, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0
622 && errno != EEXIST) {
623 lprintf(fatal, "mkdir(%s): %s\n", metadirn, strerror(errno));
624 res |= 1;
625 }
626
627 if (mkdir(datadirn, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0
628 && errno != EEXIST) {
629 lprintf(fatal, "mkdir(%s): %s\n", datadirn, strerror(errno));
630 res |= 2;
631 }
632 FREE(datadirn);
633 FREE(metadirn);
634 return res;
635 }
636 ActiveDownload *ActiveDownload_find(Cache *cf, off_t offset)
637 {
638 ActiveDownload *ad = cf->active_dls;
639 while (ad) {
640 if (ad->offset == offset) {
641 return ad;
642 }
643 ad = ad->next;
644 }
645 return NULL;
646 }
647
648 /**
649 * \brief Allocates and prepends a new ActiveDownload tracker to the list.
650 * \param[in] cf The cache instance.
651 * \param[in] offset The offset to track.
652 * \note Must be called while holding cf->dl_lock.
653 */
654 static void ActiveDownload_add(Cache *cf, off_t offset)
655 {
656 ActiveDownload *ad = CALLOC(1, sizeof(ActiveDownload));
657 ad->offset = offset;
658 ad->ts = NULL;
659 PTHREAD_COND_INIT(&ad->cond, NULL);
660 ad->refcount = 1;
661 ad->next = cf->active_dls;
662 cf->active_dls = ad;
663 }
664
665 void ActiveDownload_unref(ActiveDownload *ad)
666 {
667 if (ad == NULL) {
668 return;
669 }
670 ad->refcount--;
671 if (ad->refcount == 0) {
672 PTHREAD_COND_DESTROY(&ad->cond);
673 FREE(ad);
674 }
675 }
676
677 /**
678 * \brief Removes and frees the ActiveDownload tracker for the given offset.
679 * \param[in] cf The cache instance.
680 * \param[in] offset The offset to untrack.
681 * \note Must be called while holding cf->dl_lock.
682 */
683 static void ActiveDownload_remove(Cache *cf, off_t offset)
684 {
685 ActiveDownload **curr = &cf->active_dls;
686 while (*curr) {
687 if ((*curr)->offset == offset) {
688 ActiveDownload *temp = *curr;
689 *curr = (*curr)->next;
690 temp->unlinked = 1;
691 PTHREAD_COND_BROADCAST(&temp->cond);
692 ActiveDownload_unref(temp);
693 return;
694 }
695 curr = &(*curr)->next;
696 }
697 }
698
699 /**
700 * \brief Decrement the waiter/active thread count under dl_lock and broadcast
701 * if shutting down and no waiters remain.
702 * \param[in] cf The cache instance.
703 */
704 static void Cache_waiter_decrement(Cache *cf)
705 {
706 cf->waiters--;
707 if (cf->shutting_down && cf->waiters == 0) {
708 PTHREAD_COND_BROADCAST(&cf->shutdown_cond);
709 }
710 }
711
712 /**
713 * \brief Allocate a new cache data structure
714 */
715 static Cache *Cache_alloc(void)
716 {
717 Cache *cf = CALLOC(1, sizeof(Cache));
718 PTHREAD_MUTEX_INIT(&cf->seek_lock, NULL);
719 PTHREAD_MUTEX_INIT(&cf->w_lock, NULL);
720 PTHREAD_MUTEX_INIT(&cf->dl_lock, NULL);
721 cf->active_dls = NULL;
722 cf->cache_opened = 1;
723 cf->waiters = 0;
724 PTHREAD_COND_INIT(&cf->shutdown_cond, NULL);
725 cf->shutting_down = 0;
726
727 cf->num_bg_workers = MIN(CONFIG.max_conns, DEFAULT_NETWORK_MAX_CONNS) / 2;
728 if (cf->num_bg_workers <= 0) {
729 cf->num_bg_workers = 1;
730 }
731
732 SEM_INIT(&cf->bgt_sem, 0, cf->num_bg_workers);
733 return cf;
734 }
735
736 /**
737 * \brief free a cache data structure
738 */
739 static void Cache_free(Cache *cf)
740 {
741 if (cf->path) {
742 FREE(cf->path);
743 }
744
745 if (cf->seg) {
746 FREE(cf->seg);
747 }
748
749 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
750 cf->shutting_down = 1;
751 ActiveDownload *ad = cf->active_dls;
752 cf->active_dls = NULL;
753 while (ad) {
754 ActiveDownload *next = ad->next;
755 if (ad->refcount > 1) {
756 lprintf(warning,
757 "Cache_free: ActiveDownload at offset %jd has refcount %d "
758 "(transfer or waiters still active)\n",
759 (intmax_t)ad->offset, ad->refcount);
760 }
761 ad->next = NULL;
762 ad->unlinked = 1;
763 PTHREAD_COND_BROADCAST(&ad->cond);
764 ActiveDownload_unref(ad);
765 ad = next;
766 }
767 while (cf->waiters > 0) {
768 PTHREAD_COND_WAIT(&cf->shutdown_cond, &cf->dl_lock);
769 }
770 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
771
772 PTHREAD_MUTEX_DESTROY(&cf->seek_lock);
773 PTHREAD_MUTEX_DESTROY(&cf->w_lock);
774 PTHREAD_MUTEX_DESTROY(&cf->dl_lock);
775 PTHREAD_COND_DESTROY(&cf->shutdown_cond);
776 SEM_DESTROY(&cf->bgt_sem);
777
778 FREE(cf);
779 }
780
781 /**
782 * \brief Check if both metadata and data file exist, otherwise perform cleanup.
783 * \details
784 * This function checks if both metadata file and the data file exist. If that
785 * is not the case, clean up is performed - the existing unpaired metadata file
786 * or data file is deleted.
787 * \return
788 * - 0, if both metadata and cache file exist
789 * - -1, otherwise
790 */
791 static int Cache_exist(const char *fn)
792 {
793 char *metafn = path_append(META_DIR, fn);
794 char *datafn = path_append(DATA_DIR, fn);
795
796 struct stat metast;
797 struct stat datast;
798 int no_meta = stat(metafn, &metast);
799 int no_data = stat(datafn, &datast);
800
801 if (no_meta == 0 && metast.st_size == 0) {
802 no_meta = -1;
803 }
804 if (no_data == 0 && datast.st_size == 0) {
805 no_data = -1;
806 }
807
808 if ((no_meta == 0) != (no_data == 0)) {
809 lprintf(warning,
810 "Cache file partially missing or invalid (zero-length).\n");
811 if (no_meta != 0) {
812 if (unlink(datafn) && errno != ENOENT) {
813 lprintf(fatal, "unlink(): %s\n", strerror(errno));
814 }
815 }
816 if (no_data != 0) {
817 if (unlink(metafn) && errno != ENOENT) {
818 lprintf(fatal, "unlink(): %s\n", strerror(errno));
819 }
820 }
821 }
822
823 FREE(metafn);
824 FREE(datafn);
825
826 return (no_meta != 0) || (no_data != 0);
827 }
828
829 /**
830 * \brief delete a cache file set
831 */
832 void Cache_delete(const char *fn)
833 {
834 Link *link = path_to_Link(fn);
835 char *cache_key = NULL;
836 if (CONFIG.mode == SONIC) {
837 if (!link) {
838 return;
839 }
840 fn = link->sonic.id;
841 } else if (CONFIG.mode == NORMAL) {
842 if (!link) {
843 return;
844 }
845 cache_key = url_to_cache_path(link->f_url);
846 if (!cache_key) {
847 lprintf(error, "Failed to derive cache key from URL: %s\n",
848 link->f_url);
849 LinkTable_unref(link->parent_table);
850 return;
851 }
852 fn = cache_key;
853 }
854
855 char *metafn = path_append(META_DIR, fn);
856 char *datafn = path_append(DATA_DIR, fn);
857 if (unlink(metafn) && errno != ENOENT) {
858 lprintf(error, "unlink(): %s\n", strerror(errno));
859 }
860
861 if (unlink(datafn) && errno != ENOENT) {
862 lprintf(error, "unlink(): %s\n", strerror(errno));
863 }
864 FREE(metafn);
865 FREE(datafn);
866 if (cache_key) {
867 FREE(cache_key);
868 }
869 if (link) {
870 LinkTable_unref(link->parent_table);
871 }
872 }
873
874 /**
875 * \brief Open the data file of a cache data set
876 * \return
877 * - 0 on success
878 * - -1 on failure, with appropriate errno set.
879 */
880 static int Data_open(Cache *cf)
881 {
882 char *datafn = path_append(DATA_DIR, cf->path);
883 cf->dfp = fopen(datafn, "r+");
884 if (!cf->dfp) {
885 /*
886 * Failed to open the data file
887 */
888 lprintf(error, "fopen(%s): %s\n", datafn, strerror(errno));
889 FREE(datafn);
890 return -1;
891 }
892 FREE(datafn);
893 return 0;
894 }
895
896 /**
897 * \brief Open a metafile
898 * \return
899 * - 0 on success
900 * - -1 on failure, with appropriate errno set.
901 */
902 static int Meta_open(Cache *cf)
903 {
904 char *metafn = path_append(META_DIR, cf->path);
905 cf->mfp = fopen(metafn, "r+");
906 if (!cf->mfp) {
907 /*
908 * Failed to open the data file
909 */
910 lprintf(error, "fopen(%s): %s\n", metafn, strerror(errno));
911 FREE(metafn);
912 return -1;
913 }
914 FREE(metafn);
915 return 0;
916 }
917
918 /**
919 * \brief Create a metafile
920 * \return exit on error
921 */
922 static void Meta_create(Cache *cf)
923 {
924 char *metafn = path_append(META_DIR, cf->path);
925 cf->mfp = fopen(metafn, "w");
926 if (!cf->mfp) {
927 /*
928 * Failed to open the data file
929 */
930 lprintf(fatal, "fopen(%s): %s\n", metafn, strerror(errno));
931 }
932 if (fclose(cf->mfp)) {
933 lprintf(error, "cannot close metadata after creation: %s.\n",
934 strerror(errno));
935 }
936 FREE(metafn);
937 }
938
939 int Cache_create(const char *path)
940 {
941 Link *this_link = path_to_Link(path);
942 if (!this_link) {
943 return 1;
944 }
945
946 if (this_link->content_length <= 0) {
947 lprintf(error, "Zero-length files are not supported in cache system\n");
948 LinkTable_unref(this_link->parent_table);
949 return 1;
950 }
951
952 char *fn = NULL;
953 char *fn_alloc = NULL;
954
955 if (CONFIG.mode == NORMAL) {
956 fn_alloc = url_to_cache_path(this_link->f_url);
957 fn = fn_alloc;
958 } else if (CONFIG.mode == SINGLE) {
959 fn = curl_easy_unescape(NULL, this_link->linkname, 0, NULL);
960 } else if (CONFIG.mode == SONIC) {
961 fn = this_link->sonic.id;
962 } else {
963 lprintf(fatal, "Invalid CONFIG.mode\n");
964 }
965
966 if (!fn) {
967 lprintf(error,
968 "Failed to derive cache key/name from URL or linkname\n");
969 if (fn_alloc) {
970 FREE(fn_alloc);
971 }
972 LinkTable_unref(this_link->parent_table);
973 return 1;
974 }
975 Cache *cf = Cache_alloc();
976 cf->path = STRNDUP(fn, PATH_MAX);
977 cf->link = this_link;
978 cf->blksz = CONFIG.data_blksz;
979 size_t calculated_segbc = this_link->content_length / cf->blksz;
980 if (calculated_segbc >= INT_MAX) {
981 cf->segbc = INT_MAX;
982 } else {
983 cf->segbc = (long)calculated_segbc;
984 if (this_link->content_length % cf->blksz != 0) {
985 cf->segbc += 1;
986 }
987 }
988 cf->seg = CALLOC(cf->segbc, sizeof(Seg));
989
990 Meta_create(cf);
991
992 if (Meta_open(cf)) {
993 lprintf(error, "cannot open metadata file, %s.\n", fn);
994 Cache_free(cf);
995 }
996
997 if (Meta_write(cf)) {
998 lprintf(error, "Meta_write() failed!\n");
999 }
1000
1001 if (fclose(cf->mfp)) {
1002 lprintf(error, "cannot close metadata after write, %s.\n",
1003 strerror(errno));
1004 }
1005
1006 Data_create(cf);
1007
1008 lprintf(cache_lock_debug, "Flushing cache file for %s after creating.\n",
1009 fn);
1010 Cache_free(cf);
1011
1012 int res = Cache_exist(fn);
1013
1014 if (res) {
1015 lprintf(fatal, "Cache file creation failed for %s\n", path);
1016 }
1017
1018 if (CONFIG.mode == NORMAL) {
1019 FREE(fn_alloc);
1020 } else if (CONFIG.mode == SINGLE) {
1021 curl_free(fn);
1022 }
1023
1024 if (this_link) {
1025 LinkTable_unref(this_link->parent_table);
1026 }
1027
1028 return res;
1029 }
1030
1031 Cache *Cache_open(const char *fn)
1032 {
1033 /*
1034 * Obtain the link structure memory pointer
1035 */
1036 Link *link = path_to_Link(fn);
1037 if (!link) {
1038 /*
1039 * There is no associated link to the path
1040 */
1041 return NULL;
1042 }
1043
1044 lprintf(cache_lock_debug, "thread %lx: locking cf_lock;\n",
1045 (unsigned long)pthread_self());
1046 PTHREAD_MUTEX_LOCK(&cf_lock);
1047
1048 if (link->cache_ptr) {
1049 link->cache_ptr->cache_opened++;
1050 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1051 (unsigned long)pthread_self());
1052 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1053 LinkTable_unref(link->parent_table);
1054 return link->cache_ptr;
1055 }
1056
1057 char *actual_fn_alloc = NULL;
1058 const char *actual_fn = fn;
1059 if (CONFIG.mode == SONIC) {
1060 actual_fn = link->sonic.id;
1061 } else if (CONFIG.mode == NORMAL) {
1062 actual_fn_alloc = url_to_cache_path(link->f_url);
1063 if (!actual_fn_alloc) {
1064 lprintf(error, "Failed to derive cache path from URL: %s\n",
1065 link->f_url);
1066 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1067 (unsigned long)pthread_self());
1068 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1069 LinkTable_unref(link->parent_table);
1070 return NULL;
1071 }
1072 actual_fn = actual_fn_alloc;
1073 }
1074
1075 if (link->content_length <= 0) {
1076 lprintf(error, "Zero-length files are not supported in cache system\n");
1077 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1078 (unsigned long)pthread_self());
1079 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1080 LinkTable_unref(link->parent_table);
1081 if (actual_fn_alloc) {
1082 FREE(actual_fn_alloc);
1083 }
1084 return NULL;
1085 }
1086
1087 // Try up to 2 times. If opening fails on the first attempt (outdated,
1088 // corrupt, etc.), we delete the cache and try creating and opening a fresh
1089 // one.
1090 for (int attempt = 0; attempt < 2; attempt++) {
1091 if (Cache_exist(actual_fn) != 0) {
1092 Cache_delete(fn);
1093 if (Cache_create(fn) != 0) {
1094 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1095 (unsigned long)pthread_self());
1096 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1097 LinkTable_unref(link->parent_table);
1098 if (actual_fn_alloc) {
1099 FREE(actual_fn_alloc);
1100 }
1101 return NULL;
1102 }
1103 }
1104
1105 /*
1106 * Create the cache in-memory data structure
1107 */
1108 Cache *cf = Cache_alloc();
1109
1110 cf->path = STRNDUP(actual_fn, PATH_MAX);
1111
1112 /*
1113 * Associate the cache structure with a link
1114 */
1115 cf->link = link;
1116
1117 int ok = 1;
1118 if (Meta_open(cf)) {
1119 lprintf(error, "cannot open metadata file %s.\n", actual_fn);
1120 ok = 0;
1121 } else if (Meta_read(cf)) {
1122 lprintf(error, "metadata error: %s.\n", actual_fn);
1123 ok = 0;
1124 } else {
1125 off_t d_size = Data_size(actual_fn);
1126 if (d_size < 0) {
1127 lprintf(error, "cannot stat data file %s.\n", actual_fn);
1128 ok = 0;
1129 } else if ((uintmax_t)cf->link->content_length
1130 > (uintmax_t)d_size) {
1131 lprintf(error,
1132 "metadata inconsistency %s, "
1133 "cf->link->content_length: %jd, Data_size(fn): %jd.\n",
1134 actual_fn, (intmax_t)cf->link->content_length,
1135 (intmax_t)d_size);
1136 ok = 0;
1137 } else if (Data_open(cf)) {
1138 lprintf(error, "cannot open data file %s.\n", actual_fn);
1139 ok = 0;
1140 }
1141 }
1142
1143 if (ok) {
1144 /*
1145 * Yup, we just created a circular loop. ;)
1146 */
1147 cf->link->cache_ptr = cf;
1148
1149 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1150 (unsigned long)pthread_self());
1151 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1152 if (actual_fn_alloc) {
1153 FREE(actual_fn_alloc);
1154 }
1155 return cf;
1156 }
1157
1158 // Clean up opened resources before retry
1159 if (cf->mfp) {
1160 fclose(cf->mfp);
1161 cf->mfp = NULL;
1162 }
1163 if (cf->dfp) {
1164 fclose(cf->dfp);
1165 cf->dfp = NULL;
1166 }
1167 Cache_free(cf);
1168 Cache_delete(fn);
1169 }
1170
1171 lprintf(cache_lock_debug, "thread %lx: unlocking cf_lock;\n",
1172 (unsigned long)pthread_self());
1173 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1174 LinkTable_unref(link->parent_table);
1175 if (actual_fn_alloc) {
1176 FREE(actual_fn_alloc);
1177 }
1178 return NULL;
1179 }
1180
1181 void Cache_close(Cache *cf)
1182 {
1183 lprintf(cache_lock_debug, "thread %lx: locking cf_lock: %s\n",
1184 (unsigned long)pthread_self(), cf->path);
1185 PTHREAD_MUTEX_LOCK(&cf_lock);
1186
1187 cf->cache_opened--;
1188
1189 if (cf->cache_opened > 0) {
1190 lprintf(cache_lock_debug,
1191 "thread %lx: unlocking cf_lock: %s, cache_opened: %d\n",
1192 (unsigned long)pthread_self(), cf->path, cf->cache_opened);
1193 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1194 return;
1195 }
1196
1197 /*
1198 * Wait for any background download to finish before closing. If we don't
1199 * wait, Cache_free() might be called while Cache_bgdl() is still
1200 * running. This will cause a use-after-free error.
1201 */
1202 lprintf(cache_lock_debug,
1203 "thread %lx: waiting for background download to finish for %s\n",
1204 (unsigned long)pthread_self(), cf->path);
1205 for (int i = 0; i < cf->num_bg_workers; i++) {
1206 SEM_WAIT(&cf->bgt_sem);
1207 }
1208
1209 if (cf->mfp && Meta_write(cf)) {
1210 lprintf(error, "Meta_write() error.");
1211 }
1212
1213 if (cf->mfp && fclose(cf->mfp)) {
1214 lprintf(error, "cannot close metadata: %s.\n", strerror(errno));
1215 }
1216
1217 if (cf->dfp && fclose(cf->dfp)) {
1218 lprintf(error, "cannot close data file %s.\n", strerror(errno));
1219 }
1220
1221 Link *link = cf->link;
1222 link->cache_ptr = NULL;
1223
1224 lprintf(cache_lock_debug,
1225 "thread %lx: unlocking cf_lock, cache closed: %s\n",
1226 (unsigned long)pthread_self(), cf->path);
1227 Cache_free(cf);
1228 LinkTable_unref(link->parent_table);
1229 PTHREAD_MUTEX_UNLOCK(&cf_lock);
1230 }
1231
1232 /**
1233 * \brief Check if a segment exists.
1234 * \return 1 if the segment exists
1235 */
1236 static int Seg_exist(Cache *cf, off_t offset)
1237 {
1238 if (cf->segbc <= 0 || cf->blksz <= 0) {
1239 return 0;
1240 }
1241 off_t byte = offset / cf->blksz;
1242 if (byte < 0 || byte >= cf->segbc) {
1243 return 0;
1244 }
1245 return cf->seg[byte];
1246 }
1247
1248 /**
1249 * \brief Set the existence of a segment
1250 * \param[in] cf the cache in-memory data structure
1251 * \param[in] offset the starting position of the segment.
1252 * \param[in] i 1 for exist, 0 for doesn't exist
1253 * \note Call this after downloading a segment.
1254 */
1255 static void Seg_set(Cache *cf, off_t offset, int i)
1256 {
1257 if (cf->segbc <= 0 || cf->blksz <= 0) {
1258 return;
1259 }
1260 off_t byte = offset / cf->blksz;
1261 if (byte < 0 || byte >= cf->segbc) {
1262 return;
1263 }
1264 cf->seg[byte] = i;
1265 }
1266
1267 /**
1268 * \brief Arguments passed to the background download thread.
1269 */
1270 typedef struct BgdlArg {
1271 Cache *cf; /**< The cache instance. */
1272 off_t dl_offset; /**< The segment offset to download. */
1273 } BgdlArg;
1274
1275 /**
1276 * \brief Background download function
1277 * \details If we are requesting the data from the second half of the current
1278 * segment, we can spawn a pthread using this function to download the next
1279 * segment.
1280 * \param[in] arg A pointer to a BgdlArg structure.
1281 */
1282 static void *Cache_bgdl(void *arg)
1283 {
1284 BgdlArg *bg_arg = (BgdlArg *)arg;
1285 Cache *cf = bg_arg->cf;
1286 off_t dl_offset = bg_arg->dl_offset;
1287 FREE(bg_arg);
1288
1289 uint8_t *recv_buf = CALLOC(cf->blksz, sizeof(uint8_t));
1290 long recv
1291 = Link_download(cf->link, (char *)recv_buf, cf->blksz, dl_offset, cf);
1292 if (recv < 0) {
1293 lprintf(error,
1294 "thread %lx received %ld bytes, "
1295 "which doesn't make sense\n",
1296 (unsigned long)pthread_self(), recv);
1297 FREE(recv_buf);
1298 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1299 ActiveDownload_remove(cf, dl_offset);
1300 Cache_waiter_decrement(cf);
1301 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1302 SEM_POST(&cf->bgt_sem);
1303 pthread_exit(NULL);
1304 }
1305
1306 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1307 if ((recv == cf->blksz)
1308 || ((uintmax_t)dl_offset
1309 == (cf->link->content_length / (size_t)cf->blksz
1310 * (size_t)cf->blksz))) {
1311 if (Data_write(cf, recv_buf, recv, dl_offset) == recv) {
1312 Seg_set(cf, dl_offset, 1);
1313 }
1314 } else {
1315 lprintf(error,
1316 "received %ld rather than %d, possible network "
1317 "error.\n",
1318 recv, cf->blksz);
1319 }
1320 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1321
1322 FREE(recv_buf);
1323
1324 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1325 ActiveDownload_remove(cf, dl_offset);
1326 Cache_waiter_decrement(cf);
1327 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1328
1329 SEM_POST(&cf->bgt_sem);
1330
1331 pthread_exit(NULL);
1332 }
1333
1334 /**
1335 * \brief Spawns a background thread to download the next segment.
1336 * \param[in] cf The cache instance.
1337 * \param[in] dl_offset The offset of the segment to download.
1338 */
1339 static void Cache_bgdl_launcher(Cache *cf, off_t dl_offset)
1340 {
1341 pthread_t thread;
1342 pthread_attr_t attr;
1343
1344 if (pthread_attr_init(&attr)) {
1345 lprintf(fatal, "pthread_attr_init():%d, %s\n", errno, strerror(errno));
1346 }
1347
1348 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1349 lprintf(fatal, "pthread_attr_setdetachstate():%d, %s\n", errno,
1350 strerror(errno));
1351 }
1352
1353 BgdlArg *arg = CALLOC(1, sizeof(BgdlArg));
1354 arg->cf = cf;
1355 arg->dl_offset = dl_offset;
1356
1357 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1358 cf->waiters++;
1359 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1360
1361 if (pthread_create(&thread, &attr, Cache_bgdl, arg)) {
1362 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1363 Cache_waiter_decrement(cf);
1364 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1365 FREE(arg);
1366 lprintf(fatal, "pthread_create(): %d, %s\n", errno, strerror(errno));
1367 }
1368
1369 if (pthread_attr_destroy(&attr)) {
1370 lprintf(fatal, "pthread_attr_destroy(): %d, %s\n", errno,
1371 strerror(errno));
1372 }
1373 }
1374
1375 /**
1376 * \brief Reads a segment of size 'len' starting at 'offset_start'.
1377 * \param[in] cf The cache instance.
1378 * \param[out] output_buf Output buffer to read data into.
1379 * \param[in] len Length of the data to read.
1380 * \param[in] offset_start The offset to start reading from.
1381 * \return The number of bytes read, or negative on error.
1382 *
1383 * \details Concurrency Architecture & State Machine:
1384 * ----------------------------------------
1385 * This function supports multiple concurrent segment downloads to allow
1386 * parallel FUSE reading. To prevent race conditions, memory leaks, and
1387 * duplicate downloads:
1388 *
1389 * 1. Mutual Exclusion & Locking:
1390 * - `w_lock` guards writing to the cache files (`dfp`/`mfp`) and checking
1391 * segment existence.
1392 * - `dl_lock` guards access to `active_dls`, which tracks currently active
1393 * downloads.
1394 * - Ordering: ALWAYS lock `w_lock` before `dl_lock` to avoid deadlocks.
1395 *
1396 * 2. Active Download Tracking (`active_dls`):
1397 * - A linked list of `ActiveDownload` nodes tracks the offsets currently
1398 * being downloaded.
1399 * - If a segment is not cached but is already being downloaded by another
1400 * thread, subsequent FUSE threads will detect the node and wait via
1401 * `PTHREAD_COND_WAIT` on `ad->cond`.
1402 *
1403 * 3. Early-Return Copy:
1404 * - While waiting, threads can perform early returns by copying data
1405 * directly from the in-progress `TransferStruct`'s memory buffer (`ts->data`)
1406 * once enough bytes have been received.
1407 *
1408 * 4. Double-Checked Locking:
1409 * - Because locks must be released when launching threads or checking
1410 * semaphores, other threads could concurrently insert download trackers. We use
1411 * double-checked locking inside the background thread launcher and `sync_dl`
1412 * fallback path to verify that the download is still not tracked before
1413 * allocating a new node.
1414 */
1415 static long Cache_read_segment(Cache *cf, char *const output_buf,
1416 const off_t len, const off_t offset_start)
1417 {
1418 if (!cf->link) {
1419 lprintf(error, "cf->link is NULL in Cache_read_segment\n");
1420 return -EINVAL;
1421 }
1422
1423 if (cf->link->content_length <= 0 || offset_start < 0
1424 || (size_t)offset_start >= cf->link->content_length) {
1425 return 0;
1426 }
1427
1428 long send;
1429 off_t dl_offset = offset_start / cf->blksz * cf->blksz;
1430 int ret;
1431
1432 retry:
1433 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1434 if (Seg_exist(cf, dl_offset)) {
1435 send = Data_read(cf, (uint8_t *)output_buf, len, offset_start);
1436 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1437 goto bgdl;
1438 }
1439
1440 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1441 ActiveDownload *ad = ActiveDownload_find(cf, dl_offset);
1442 if (ad != NULL) {
1443 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1444 ad->refcount++;
1445 ActiveDownload *orig_ad = ad;
1446
1447 cf->waiters++;
1448
1449 while (!cf->shutting_down && !orig_ad->unlinked) {
1450 if (orig_ad->ts && orig_ad->ts->data
1451 && orig_ad->ts->curr_size
1452 >= (size_t)(offset_start - dl_offset + len)) {
1453 memcpy(output_buf,
1454 orig_ad->ts->data + (offset_start - dl_offset), len);
1455
1456 Cache_waiter_decrement(cf);
1457
1458 ActiveDownload_unref(orig_ad);
1459 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1460 send = len;
1461 goto bgdl;
1462 }
1463 PTHREAD_COND_WAIT(&orig_ad->cond, &cf->dl_lock);
1464 }
1465
1466 int was_shutdown = cf->shutting_down;
1467 Cache_waiter_decrement(cf);
1468
1469 ActiveDownload_unref(orig_ad);
1470 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1471
1472 if (was_shutdown) {
1473 return -EIO;
1474 }
1475
1476 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1477 if (Seg_exist(cf, dl_offset)) {
1478 send = Data_read(cf, (uint8_t *)output_buf, len, offset_start);
1479 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1480 goto bgdl;
1481 }
1482 goto sync_dl;
1483 }
1484 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1485
1486 /*
1487 * Attempt to launch a background download thread if the background thread
1488 * slot is available (bgt_sem > 0). This acts as a throttle on concurrent
1489 * background prefetches.
1490 */
1491 ret = SEM_TRYWAIT(&cf->bgt_sem);
1492 if (ret == 0) {
1493 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1494 /*
1495 * Double-checked locking: Re-verify that another thread hasn't already
1496 * added this offset to the active downloads list while we were
1497 * unlocked.
1498 */
1499 ActiveDownload *bg_ad = ActiveDownload_find(cf, dl_offset);
1500 if (bg_ad == NULL) {
1501 ActiveDownload_add(cf, dl_offset);
1502 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1503 Cache_bgdl_launcher(cf, dl_offset);
1504 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1505 goto retry;
1506 }
1507 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1508 SEM_POST(&cf->bgt_sem); /* Back off and release the slot */
1509 }
1510
1511 sync_dl:
1512 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1513 /*
1514 * Double-checked locking: Verify that another thread hasn't concurrently
1515 * started a download for this offset. If it has, back off, release the
1516 * locks, and retry to join the wait loop.
1517 */
1518 ActiveDownload *sync_ad = ActiveDownload_find(cf, dl_offset);
1519 if (sync_ad != NULL) {
1520 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1521 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1522 goto retry;
1523 }
1524 ActiveDownload_add(cf, dl_offset);
1525 cf->waiters++;
1526 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1527
1528 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1529
1530 uint8_t *recv_buf = CALLOC(cf->blksz, sizeof(uint8_t));
1531 long recv
1532 = Link_download(cf->link, (char *)recv_buf, cf->blksz, dl_offset, cf);
1533
1534 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1535
1536 if (recv < 0) {
1537 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1538 ActiveDownload_remove(cf, dl_offset);
1539 Cache_waiter_decrement(cf);
1540 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1541 FREE(recv_buf);
1542 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1543 return recv;
1544 }
1545 if ((recv == cf->blksz)
1546 || ((uintmax_t)dl_offset
1547 == (cf->link->content_length / (size_t)cf->blksz
1548 * (size_t)cf->blksz))) {
1549 if (recv < (offset_start - dl_offset) + len) {
1550 lprintf(error,
1551 "received %ld bytes, but required at least %ld bytes\n",
1552 recv, (long)((offset_start - dl_offset) + len));
1553 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1554 ActiveDownload_remove(cf, dl_offset);
1555 Cache_waiter_decrement(cf);
1556 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1557 FREE(recv_buf);
1558 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1559 return -EIO;
1560 }
1561 if (Data_write(cf, recv_buf, recv, dl_offset) == recv) {
1562 Seg_set(cf, dl_offset, 1);
1563 }
1564 } else {
1565 lprintf(error,
1566 "received %ld rather than %d, possible network "
1567 "error.\n",
1568 recv, cf->blksz);
1569 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1570 ActiveDownload_remove(cf, dl_offset);
1571 Cache_waiter_decrement(cf);
1572 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1573 FREE(recv_buf);
1574 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1575 return -EIO;
1576 }
1577
1578 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1579 ActiveDownload_remove(cf, dl_offset);
1580 Cache_waiter_decrement(cf);
1581 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1582 send = len;
1583 if (offset_start < dl_offset
1584 || (size_t)(offset_start - dl_offset) + (size_t)send
1585 > (size_t)cf->blksz) {
1586 lprintf(error, "invalid offset or length for memcpy, aborting copy\n");
1587 send = 0;
1588 } else {
1589 memcpy(output_buf, recv_buf + (offset_start - dl_offset), send);
1590 }
1591 FREE(recv_buf);
1592 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1593
1594 bgdl: {
1595 }
1596 off_t next_dl_offset = dl_offset + cf->blksz;
1597 int next_seg_missing = 0;
1598 if ((uintmax_t)next_dl_offset < (uintmax_t)cf->link->content_length) {
1599 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1600 next_seg_missing = !Seg_exist(cf, next_dl_offset);
1601 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1602 }
1603 if (next_seg_missing) {
1604 ret = SEM_TRYWAIT(&cf->bgt_sem);
1605 if (!ret) {
1606 PTHREAD_MUTEX_LOCK(&cf->w_lock);
1607 next_seg_missing = !Seg_exist(cf, next_dl_offset);
1608 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1609 const ActiveDownload *next_ad
1610 = ActiveDownload_find(cf, next_dl_offset);
1611 if (next_seg_missing && next_ad == NULL) {
1612 ActiveDownload_add(cf, next_dl_offset);
1613 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1614 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1615 Cache_bgdl_launcher(cf, next_dl_offset);
1616 } else {
1617 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1618 PTHREAD_MUTEX_UNLOCK(&cf->w_lock);
1619 SEM_POST(&cf->bgt_sem);
1620 }
1621 }
1622 }
1623
1624 return send;
1625 }
1626
1627 long Cache_read(Cache *cf, char *const output_buf, off_t len,
1628 const off_t offset_start)
1629 {
1630 if (!cf || !cf->link) {
1631 lprintf(error, "Invalid cache or link in Cache_read\n");
1632 return -EINVAL;
1633 }
1634
1635 if (len < 0) {
1636 lprintf(error, "requested to read negative bytes: %jd\n",
1637 (intmax_t)len);
1638 return -EINVAL;
1639 }
1640
1641 if (offset_start < 0 || (size_t)offset_start >= cf->link->content_length) {
1642 return 0;
1643 }
1644
1645 size_t remaining = cf->link->content_length - (size_t)offset_start;
1646 if ((size_t)len > remaining) {
1647 len = (off_t)remaining;
1648 }
1649
1650 if (len <= 0) {
1651 return 0;
1652 }
1653
1654 off_t send = 0;
1655 for (off_t start = offset_start, end; len > 0;
1656 len -= end - start, start = end) {
1657 end = start / cf->blksz * cf->blksz + cf->blksz;
1658 if (end > start + len) {
1659 end = start + len;
1660 }
1661 long seg_send = Cache_read_segment(
1662 cf, output_buf + (start - offset_start), end - start, start);
1663 if (seg_send < 0) {
1664 return seg_send;
1665 }
1666 send += seg_send;
1667 if (seg_send < end - start) {
1668 break;
1669 }
1670 }
1671 return send;
1672 }