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_lookup(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;
33 if (stat(item->name, &item->st)) {
34 item->st.st_mtime = 0;
40 int cache_create_dirs()
47 path = fmt("%s/%s", cgit_cache_root, cgit_query_repo);
48 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
51 if (cgit_query_page) {
52 path = fmt("%s/%s/%s", cgit_cache_root, cgit_query_repo,
54 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
60 int cache_lock(struct cacheitem *item)
63 char *lockfile = fmt("%s.lock", item->name);
66 item->fd = open(lockfile, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR|S_IWUSR);
67 if (item->fd == NOLOCK && errno == ENOENT && cache_create_dirs())
69 if (item->fd == NOLOCK && errno == EEXIST) {
72 if (stat(lockfile, &st))
75 if (t-st.st_mtime > cgit_cache_max_create_time &&
80 return (item->fd > 0);
83 int cache_unlock(struct cacheitem *item)
86 return (rename(fmt("%s.lock", item->name), item->name) == 0);
89 int cache_expired(struct cacheitem *item)
93 return item->st.st_mtime + item->ttl * 60 < time(NULL);