]> git.cameronkatri.com Git - cgit.git/blob - cache.c
Make branches, tags and log play better together in the summary view
[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 #include "cache.h"
11
12 const int NOLOCK = -1;
13
14 char *cache_safe_filename(const char *unsafe)
15 {
16 static char buf[4][PATH_MAX];
17 static int bufidx;
18 char *s;
19 char c;
20
21 bufidx++;
22 bufidx &= 3;
23 s = buf[bufidx];
24
25 while(unsafe && (c = *unsafe++) != 0) {
26 if (c == '/' || c == ' ' || c == '&' || c == '|' ||
27 c == '>' || c == '<' || c == '.')
28 c = '_';
29 *s++ = c;
30 }
31 *s = '\0';
32 return buf[bufidx];
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", ctx.cfg.cache_root);
49 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
50 return 0;
51
52 if (!ctx.repo)
53 return 0;
54
55 path = fmt("%s/%s", ctx.cfg.cache_root,
56 cache_safe_filename(ctx.repo->url));
57
58 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
59 return 0;
60
61 if (ctx.qry.page) {
62 path = fmt("%s/%s/%s", ctx.cfg.cache_root,
63 cache_safe_filename(ctx.repo->url),
64 ctx.qry.page);
65 if (mkdir(path, S_IRWXU) && errno!=EEXIST)
66 return 0;
67 }
68 return 1;
69 }
70
71 int cache_refill_overdue(const char *lockfile)
72 {
73 struct stat st;
74
75 if (stat(lockfile, &st))
76 return 0;
77 else
78 return (time(NULL) - st.st_mtime > ctx.cfg.cache_max_create_time);
79 }
80
81 int cache_lock(struct cacheitem *item)
82 {
83 int i = 0;
84 char *lockfile = xstrdup(fmt("%s.lock", item->name));
85
86 top:
87 if (++i > ctx.cfg.max_lock_attempts)
88 die("cache_lock: unable to lock %s: %s",
89 item->name, strerror(errno));
90
91 item->fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
92
93 if (item->fd == NOLOCK && errno == ENOENT && cache_create_dirs())
94 goto top;
95
96 if (item->fd == NOLOCK && errno == EEXIST &&
97 cache_refill_overdue(lockfile) && !unlink(lockfile))
98 goto top;
99
100 free(lockfile);
101 return (item->fd > 0);
102 }
103
104 int cache_unlock(struct cacheitem *item)
105 {
106 close(item->fd);
107 return (rename(fmt("%s.lock", item->name), item->name) == 0);
108 }
109
110 int cache_cancel_lock(struct cacheitem *item)
111 {
112 return (unlink(fmt("%s.lock", item->name)) == 0);
113 }
114
115 int cache_expired(struct cacheitem *item)
116 {
117 if (item->ttl < 0)
118 return 0;
119 return item->st.st_mtime + item->ttl * 60 < time(NULL);
120 }