1 /* cache.c: cache management
3 * Copyright (C) 2006 Lars Hjemli
5 * Licensed under GNU General Public License v2
6 * (see COPYING for full license text)
11 const int NOLOCK = -1;
13 int cache_exist(struct cacheitem *item)
15 if (stat(item->name, &item->st)) {
16 item->st.st_mtime = 0;
22 int cache_create_dirs()
26 path = fmt("%s", cgit_cache_root);
27 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
33 path = fmt("%s/%s", cgit_cache_root, cgit_query_repo);
34 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
37 if (cgit_query_page) {
38 path = fmt("%s/%s/%s", cgit_cache_root, cgit_query_repo,
40 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
46 int cache_refill_overdue(const char *lockfile)
50 if (stat(lockfile, &st))
53 return (time(NULL) - st.st_mtime > cgit_cache_max_create_time);
56 int cache_lock(struct cacheitem *item)
59 char *lockfile = xstrdup(fmt("%s.lock", item->name));
62 if (++i > cgit_max_lock_attempts)
63 die("cache_lock: unable to lock %s: %s",
64 item->name, strerror(errno));
66 item->fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
68 if (item->fd == NOLOCK && errno == ENOENT && cache_create_dirs())
71 if (item->fd == NOLOCK && errno == EEXIST &&
72 cache_refill_overdue(lockfile) && !unlink(lockfile))
76 return (item->fd > 0);
79 int cache_unlock(struct cacheitem *item)
82 return (rename(fmt("%s.lock", item->name), item->name) == 0);
85 int cache_cancel_lock(struct cacheitem *item)
87 return (unlink(fmt("%s.lock", item->name)) == 0);
90 int cache_expired(struct cacheitem *item)
94 return item->st.st_mtime + item->ttl * 60 < time(NULL);