global: replace hard coded hash length
[cgit.git] / cache.c
blob2c70be784d6187cb63d20475e8c6df203b6bb31f
1 /* cache.c: cache management
3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
5 * Licensed under GNU General Public License v2
6 * (see COPYING for full license text)
9 * The cache is just a directory structure where each file is a cache slot,
10 * and each filename is based on the hash of some key (e.g. the cgit url).
11 * Each file contains the full key followed by the cached content for that
12 * key.
16 #include "cgit.h"
17 #include "cache.h"
18 #include "html.h"
19 #ifdef HAVE_LINUX_SENDFILE
20 #include <sys/sendfile.h>
21 #endif
23 #define CACHE_BUFSIZE (1024 * 4)
25 struct cache_slot {
26 const char *key;
27 size_t keylen;
28 int ttl;
29 cache_fill_fn fn;
30 int cache_fd;
31 int lock_fd;
32 int stdout_fd;
33 const char *cache_name;
34 const char *lock_name;
35 int match;
36 struct stat cache_st;
37 int bufsize;
38 char buf[CACHE_BUFSIZE];
41 /* Open an existing cache slot and fill the cache buffer with
42 * (part of) the content of the cache file. Return 0 on success
43 * and errno otherwise.
45 static int open_slot(struct cache_slot *slot)
47 char *bufz;
48 ssize_t bufkeylen = -1;
50 slot->cache_fd = open(slot->cache_name, O_RDONLY);
51 if (slot->cache_fd == -1)
52 return errno;
54 if (fstat(slot->cache_fd, &slot->cache_st))
55 return errno;
57 slot->bufsize = xread(slot->cache_fd, slot->buf, sizeof(slot->buf));
58 if (slot->bufsize < 0)
59 return errno;
61 bufz = memchr(slot->buf, 0, slot->bufsize);
62 if (bufz)
63 bufkeylen = bufz - slot->buf;
65 if (slot->key)
66 slot->match = bufkeylen == slot->keylen &&
67 !memcmp(slot->key, slot->buf, bufkeylen + 1);
69 return 0;
72 /* Close the active cache slot */
73 static int close_slot(struct cache_slot *slot)
75 int err = 0;
76 if (slot->cache_fd > 0) {
77 if (close(slot->cache_fd))
78 err = errno;
79 else
80 slot->cache_fd = -1;
82 return err;
85 /* Print the content of the active cache slot (but skip the key). */
86 static int print_slot(struct cache_slot *slot)
88 #ifdef HAVE_LINUX_SENDFILE
89 off_t start_off;
90 int ret;
92 start_off = slot->keylen + 1;
94 do {
95 ret = sendfile(STDOUT_FILENO, slot->cache_fd, &start_off,
96 slot->cache_st.st_size - start_off);
97 if (ret < 0) {
98 if (errno == EAGAIN || errno == EINTR)
99 continue;
100 return errno;
102 return 0;
103 } while (1);
104 #else
105 ssize_t i, j;
107 i = lseek(slot->cache_fd, slot->keylen + 1, SEEK_SET);
108 if (i != slot->keylen + 1)
109 return errno;
111 do {
112 i = j = xread(slot->cache_fd, slot->buf, sizeof(slot->buf));
113 if (i > 0)
114 j = xwrite(STDOUT_FILENO, slot->buf, i);
115 } while (i > 0 && j == i);
117 if (i < 0 || j != i)
118 return errno;
119 else
120 return 0;
121 #endif
124 /* Check if the slot has expired */
125 static int is_expired(struct cache_slot *slot)
127 if (slot->ttl < 0)
128 return 0;
129 else
130 return slot->cache_st.st_mtime + slot->ttl * 60 < time(NULL);
133 /* Check if the slot has been modified since we opened it.
134 * NB: If stat() fails, we pretend the file is modified.
136 static int is_modified(struct cache_slot *slot)
138 struct stat st;
140 if (stat(slot->cache_name, &st))
141 return 1;
142 return (st.st_ino != slot->cache_st.st_ino ||
143 st.st_mtime != slot->cache_st.st_mtime ||
144 st.st_size != slot->cache_st.st_size);
147 /* Close an open lockfile */
148 static int close_lock(struct cache_slot *slot)
150 int err = 0;
151 if (slot->lock_fd > 0) {
152 if (close(slot->lock_fd))
153 err = errno;
154 else
155 slot->lock_fd = -1;
157 return err;
160 /* Create a lockfile used to store the generated content for a cache
161 * slot, and write the slot key + \0 into it.
162 * Returns 0 on success and errno otherwise.
164 static int lock_slot(struct cache_slot *slot)
166 struct flock lock = {
167 .l_type = F_WRLCK,
168 .l_whence = SEEK_SET,
169 .l_start = 0,
170 .l_len = 0,
173 slot->lock_fd = open(slot->lock_name, O_RDWR | O_CREAT,
174 S_IRUSR | S_IWUSR);
175 if (slot->lock_fd == -1)
176 return errno;
177 if (fcntl(slot->lock_fd, F_SETLK, &lock) < 0) {
178 int saved_errno = errno;
179 close(slot->lock_fd);
180 slot->lock_fd = -1;
181 return saved_errno;
183 if (xwrite(slot->lock_fd, slot->key, slot->keylen + 1) < 0)
184 return errno;
185 return 0;
188 /* Release the current lockfile. If `replace_old_slot` is set the
189 * lockfile replaces the old cache slot, otherwise the lockfile is
190 * just deleted.
192 static int unlock_slot(struct cache_slot *slot, int replace_old_slot)
194 int err;
196 if (replace_old_slot)
197 err = rename(slot->lock_name, slot->cache_name);
198 else
199 err = unlink(slot->lock_name);
201 /* Restore stdout and close the temporary FD. */
202 if (slot->stdout_fd >= 0) {
203 dup2(slot->stdout_fd, STDOUT_FILENO);
204 close(slot->stdout_fd);
205 slot->stdout_fd = -1;
208 if (err)
209 return errno;
211 return 0;
214 /* Generate the content for the current cache slot by redirecting
215 * stdout to the lock-fd and invoking the callback function
217 static int fill_slot(struct cache_slot *slot)
219 /* Preserve stdout */
220 slot->stdout_fd = dup(STDOUT_FILENO);
221 if (slot->stdout_fd == -1)
222 return errno;
224 /* Redirect stdout to lockfile */
225 if (dup2(slot->lock_fd, STDOUT_FILENO) == -1)
226 return errno;
228 /* Generate cache content */
229 slot->fn();
231 /* Make sure any buffered data is flushed to the file */
232 if (fflush(stdout))
233 return errno;
235 /* update stat info */
236 if (fstat(slot->lock_fd, &slot->cache_st))
237 return errno;
239 return 0;
242 /* Crude implementation of 32-bit FNV-1 hash algorithm,
243 * see http://www.isthe.com/chongo/tech/comp/fnv/ for details
244 * about the magic numbers.
246 #define FNV_OFFSET 0x811c9dc5
247 #define FNV_PRIME 0x01000193
249 unsigned long hash_str(const char *str)
251 unsigned long h = FNV_OFFSET;
252 unsigned char *s = (unsigned char *)str;
254 if (!s)
255 return h;
257 while (*s) {
258 h *= FNV_PRIME;
259 h ^= *s++;
261 return h;
264 static int process_slot(struct cache_slot *slot)
266 int err;
268 err = open_slot(slot);
269 if (!err && slot->match) {
270 if (is_expired(slot)) {
271 if (!lock_slot(slot)) {
272 /* If the cachefile has been replaced between
273 * `open_slot` and `lock_slot`, we'll just
274 * serve the stale content from the original
275 * cachefile. This way we avoid pruning the
276 * newly generated slot. The same code-path
277 * is chosen if fill_slot() fails for some
278 * reason.
280 * TODO? check if the new slot contains the
281 * same key as the old one, since we would
282 * prefer to serve the newest content.
283 * This will require us to open yet another
284 * file-descriptor and read and compare the
285 * key from the new file, so for now we're
286 * lazy and just ignore the new file.
288 if (is_modified(slot) || fill_slot(slot)) {
289 unlock_slot(slot, 0);
290 close_lock(slot);
291 } else {
292 close_slot(slot);
293 unlock_slot(slot, 1);
294 slot->cache_fd = slot->lock_fd;
298 if ((err = print_slot(slot)) != 0) {
299 cache_log("[cgit] error printing cache %s: %s (%d)\n",
300 slot->cache_name,
301 strerror(err),
302 err);
304 close_slot(slot);
305 return err;
308 /* If the cache slot does not exist (or its key doesn't match the
309 * current key), lets try to create a new cache slot for this
310 * request. If this fails (for whatever reason), lets just generate
311 * the content without caching it and fool the caller to believe
312 * everything worked out (but print a warning on stdout).
315 close_slot(slot);
316 if ((err = lock_slot(slot)) != 0) {
317 cache_log("[cgit] Unable to lock slot %s: %s (%d)\n",
318 slot->lock_name, strerror(err), err);
319 slot->fn();
320 return 0;
323 if ((err = fill_slot(slot)) != 0) {
324 cache_log("[cgit] Unable to fill slot %s: %s (%d)\n",
325 slot->lock_name, strerror(err), err);
326 unlock_slot(slot, 0);
327 close_lock(slot);
328 slot->fn();
329 return 0;
331 // We've got a valid cache slot in the lock file, which
332 // is about to replace the old cache slot. But if we
333 // release the lockfile and then try to open the new cache
334 // slot, we might get a race condition with a concurrent
335 // writer for the same cache slot (with a different key).
336 // Lets avoid such a race by just printing the content of
337 // the lock file.
338 slot->cache_fd = slot->lock_fd;
339 unlock_slot(slot, 1);
340 if ((err = print_slot(slot)) != 0) {
341 cache_log("[cgit] error printing cache %s: %s (%d)\n",
342 slot->cache_name,
343 strerror(err),
344 err);
346 close_slot(slot);
347 return err;
350 /* Print cached content to stdout, generate the content if necessary. */
351 int cache_process(int size, const char *path, const char *key, int ttl,
352 cache_fill_fn fn)
354 unsigned long hash;
355 int i;
356 struct strbuf filename = STRBUF_INIT;
357 struct strbuf lockname = STRBUF_INIT;
358 struct cache_slot slot;
359 int result;
361 /* If the cache is disabled, just generate the content */
362 if (size <= 0 || ttl == 0) {
363 fn();
364 return 0;
367 /* Verify input, calculate filenames */
368 if (!path) {
369 cache_log("[cgit] Cache path not specified, caching is disabled\n");
370 fn();
371 return 0;
373 if (!key)
374 key = "";
375 hash = hash_str(key) % size;
376 strbuf_addstr(&filename, path);
377 strbuf_ensure_end(&filename, '/');
378 for (i = 0; i < 8; i++) {
379 strbuf_addf(&filename, "%x", (unsigned char)(hash & 0xf));
380 hash >>= 4;
382 strbuf_addbuf(&lockname, &filename);
383 strbuf_addstr(&lockname, ".lock");
384 slot.fn = fn;
385 slot.ttl = ttl;
386 slot.stdout_fd = -1;
387 slot.cache_name = filename.buf;
388 slot.lock_name = lockname.buf;
389 slot.key = key;
390 slot.keylen = strlen(key);
391 result = process_slot(&slot);
393 strbuf_release(&filename);
394 strbuf_release(&lockname);
395 return result;
398 /* Return a strftime formatted date/time
399 * NB: the result from this function is to shared memory
401 static char *sprintftime(const char *format, time_t time)
403 static char buf[64];
404 struct tm *tm;
406 if (!time)
407 return NULL;
408 tm = gmtime(&time);
409 strftime(buf, sizeof(buf)-1, format, tm);
410 return buf;
413 int cache_ls(const char *path)
415 DIR *dir;
416 struct dirent *ent;
417 int err = 0;
418 struct cache_slot slot = { NULL };
419 struct strbuf fullname = STRBUF_INIT;
420 size_t prefixlen;
422 if (!path) {
423 cache_log("[cgit] cache path not specified\n");
424 return -1;
426 dir = opendir(path);
427 if (!dir) {
428 err = errno;
429 cache_log("[cgit] unable to open path %s: %s (%d)\n",
430 path, strerror(err), err);
431 return err;
433 strbuf_addstr(&fullname, path);
434 strbuf_ensure_end(&fullname, '/');
435 prefixlen = fullname.len;
436 while ((ent = readdir(dir)) != NULL) {
437 if (strlen(ent->d_name) != 8)
438 continue;
439 strbuf_setlen(&fullname, prefixlen);
440 strbuf_addstr(&fullname, ent->d_name);
441 slot.cache_name = fullname.buf;
442 if ((err = open_slot(&slot)) != 0) {
443 cache_log("[cgit] unable to open path %s: %s (%d)\n",
444 fullname.buf, strerror(err), err);
445 continue;
447 htmlf("%s %s %10"PRIuMAX" %s\n",
448 fullname.buf,
449 sprintftime("%Y-%m-%d %H:%M:%S",
450 slot.cache_st.st_mtime),
451 (uintmax_t)slot.cache_st.st_size,
452 slot.buf);
453 close_slot(&slot);
455 closedir(dir);
456 strbuf_release(&fullname);
457 return 0;
460 /* Print a message to stdout */
461 void cache_log(const char *format, ...)
463 va_list args;
464 va_start(args, format);
465 vfprintf(stderr, format, args);
466 va_end(args);