]> git.cameronkatri.com Git - cgit.git/blob - cache.c
Handle '+' in querystring
[cgit.git] / cache.c
1 /* cache.c: cache management
2 *
3 * Copyright (C) 2006 Lars Hjemli
4 *
5 * Licensed under GNU General Public License v2
6 * (see COPYING for full license text)
7 */
8
9 #include "cgit.h"
10
11 const int NOLOCK = -1;
12
13 void cache_prepare(struct cacheitem *item)
14 {
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,
20 cgit_query_repo));
21 item->ttl = cgit_cache_repo_ttl;
22 } else {
23 item->name = xstrdup(fmt("%s/%s/%s/%s.html", cgit_cache_root,
24 cgit_query_repo, cgit_query_page,
25 cgit_querystring));
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;
30 else
31 item->ttl = cgit_cache_repo_ttl;
32 }
33 }
34
35 int cache_exist(struct cacheitem *item)
36 {
37 if (stat(item->name, &item->st)) {
38 item->st.st_mtime = 0;
39 return 0;
40 }
41 return 1;
42 }
43
44 int cache_create_dirs()
45 {
46 char *path;
47
48 path = fmt("%s", cgit_cache_root);
49 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
50 return 0;
51
52 if (!cgit_query_repo)
53 return 0;
54
55 path = fmt("%s/%s", cgit_cache_root, cgit_query_repo);
56 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
57 return 0;
58
59 if (cgit_query_page) {
60 path = fmt("%s/%s/%s", cgit_cache_root, cgit_query_repo,
61 cgit_query_page);
62 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
63 return 0;
64 }
65 return 1;
66 }
67
68 int cache_refill_overdue(const char *lockfile)
69 {
70 struct stat st;
71
72 if (stat(lockfile, &st))
73 return 0;
74 else
75 return (time(NULL) - st.st_mtime > cgit_cache_max_create_time);
76 }
77
78 int cache_lock(struct cacheitem *item)
79 {
80 int i = 0;
81 char *lockfile = xstrdup(fmt("%s.lock", item->name));
82
83 top:
84 if (++i > cgit_max_lock_attempts)
85 die("cache_lock: unable to lock %s: %s",
86 item->name, strerror(errno));
87
88 item->fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
89
90 if (item->fd == NOLOCK && errno == ENOENT && cache_create_dirs())
91 goto top;
92
93 if (item->fd == NOLOCK && errno == EEXIST &&
94 cache_refill_overdue(lockfile) && !unlink(lockfile))
95 goto top;
96
97 free(lockfile);
98 return (item->fd > 0);
99 }
100
101 int cache_unlock(struct cacheitem *item)
102 {
103 close(item->fd);
104 return (rename(fmt("%s.lock", item->name), item->name) == 0);
105 }
106
107 int cache_cancel_lock(struct cacheitem *item)
108 {
109 return (unlink(fmt("%s.lock", item->name)) == 0);
110 }
111
112 int cache_expired(struct cacheitem *item)
113 {
114 if (item->ttl < 0)
115 return 0;
116 return item->st.st_mtime + item->ttl * 60 < time(NULL);
117 }