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 void cache_prepare(struct cacheitem *item)
15 if (!cgit_query_repo) {
16 item->name = xstrdup(fmt("%s/index.html", cgit_cache_root));
17 item->ttl = cgit_cache_root_ttl;
18 } else if (!cgit_query_page) {
19 item->name = xstrdup(fmt("%s/%s/index.html", cgit_cache_root,
21 item->ttl = cgit_cache_repo_ttl;
23 item->name = xstrdup(fmt("%s/%s/%s/%s.html", cgit_cache_root,
24 cgit_query_repo, cgit_query_page,
26 if (cgit_query_has_symref)
27 item->ttl = cgit_cache_dynamic_ttl;
28 else if (cgit_query_has_sha1)
29 item->ttl = cgit_cache_static_ttl;
31 item->ttl = cgit_cache_repo_ttl;
35 int cache_exist(struct cacheitem *item)
37 if (stat(item->name, &item->st)) {
38 item->st.st_mtime = 0;
44 int cache_create_dirs()
51 path = fmt("%s/%s", cgit_cache_root, cgit_query_repo);
52 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
55 if (cgit_query_page) {
56 path = fmt("%s/%s/%s", cgit_cache_root, cgit_query_repo,
58 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
64 int cache_lock(struct cacheitem *item)
67 char *lockfile = fmt("%s.lock", item->name);
70 item->fd = open(lockfile, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR|S_IWUSR);
71 if (item->fd == NOLOCK && errno == ENOENT && cache_create_dirs())
73 if (item->fd == NOLOCK && errno == EEXIST) {
76 if (stat(lockfile, &st))
79 if (t-st.st_mtime > cgit_cache_max_create_time &&
84 return (item->fd > 0);
87 int cache_unlock(struct cacheitem *item)
90 return (rename(fmt("%s.lock", item->name), item->name) == 0);
93 int cache_expired(struct cacheitem *item)
97 return item->st.st_mtime + item->ttl * 60 < time(NULL);