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
20 #define CACHE_BUFSIZE (1024 * 4)
30 const char *cache_name;
31 const char *lock_name;
36 char buf[CACHE_BUFSIZE];
39 /* Open an existing cache slot and fill the cache buffer with
40 * (part of) the content of the cache file. Return 0 on success
41 * and errno otherwise.
43 static int open_slot(struct cache_slot *slot)
48 slot->cache_fd = open(slot->cache_name, O_RDONLY);
49 if (slot->cache_fd == -1)
52 if (fstat(slot->cache_fd, &slot->cache_st))
55 slot->bufsize = xread(slot->cache_fd, slot->buf, sizeof(slot->buf));
56 if (slot->bufsize < 0)
59 bufz = memchr(slot->buf, 0, slot->bufsize);
61 bufkeylen = bufz - slot->buf;
63 slot->match = bufkeylen == slot->keylen &&
64 !memcmp(slot->key, slot->buf, bufkeylen + 1);
69 /* Close the active cache slot */
70 static int close_slot(struct cache_slot *slot)
73 if (slot->cache_fd > 0) {
74 if (close(slot->cache_fd))
82 /* Print the content of the active cache slot (but skip the key). */
83 static int print_slot(struct cache_slot *slot)
87 i = lseek(slot->cache_fd, slot->keylen + 1, SEEK_SET);
88 if (i != slot->keylen + 1)
92 i = j = xread(slot->cache_fd, slot->buf, sizeof(slot->buf));
94 j = xwrite(STDOUT_FILENO, slot->buf, i);
95 } while (i > 0 && j == i);
103 /* Check if the slot has expired */
104 static int is_expired(struct cache_slot *slot)
109 return slot->cache_st.st_mtime + slot->ttl * 60 < time(NULL);
112 /* Check if the slot has been modified since we opened it.
113 * NB: If stat() fails, we pretend the file is modified.
115 static int is_modified(struct cache_slot *slot)
119 if (stat(slot->cache_name, &st))
121 return (st.st_ino != slot->cache_st.st_ino ||
122 st.st_mtime != slot->cache_st.st_mtime ||
123 st.st_size != slot->cache_st.st_size);
126 /* Close an open lockfile */
127 static int close_lock(struct cache_slot *slot)
130 if (slot->lock_fd > 0) {
131 if (close(slot->lock_fd))
139 /* Create a lockfile used to store the generated content for a cache
140 * slot, and write the slot key + \0 into it.
141 * Returns 0 on success and errno otherwise.
143 static int lock_slot(struct cache_slot *slot)
145 slot->lock_fd = open(slot->lock_name, O_RDWR | O_CREAT | O_EXCL,
147 if (slot->lock_fd == -1)
149 if (xwrite(slot->lock_fd, slot->key, slot->keylen + 1) < 0)
154 /* Release the current lockfile. If `replace_old_slot` is set the
155 * lockfile replaces the old cache slot, otherwise the lockfile is
158 static int unlock_slot(struct cache_slot *slot, int replace_old_slot)
162 if (replace_old_slot)
163 err = rename(slot->lock_name, slot->cache_name);
165 err = unlink(slot->lock_name);
173 /* Generate the content for the current cache slot by redirecting
174 * stdout to the lock-fd and invoking the callback function
176 static int fill_slot(struct cache_slot *slot)
180 /* Preserve stdout */
181 tmp = dup(STDOUT_FILENO);
185 /* Redirect stdout to lockfile */
186 if (dup2(slot->lock_fd, STDOUT_FILENO) == -1)
189 /* Generate cache content */
190 slot->fn(slot->cbdata);
193 if (dup2(tmp, STDOUT_FILENO) == -1)
196 /* Close the temporary filedescriptor */
203 /* Crude implementation of 32-bit FNV-1 hash algorithm,
204 * see http://www.isthe.com/chongo/tech/comp/fnv/ for details
205 * about the magic numbers.
207 #define FNV_OFFSET 0x811c9dc5
208 #define FNV_PRIME 0x01000193
210 unsigned long hash_str(const char *str)
212 unsigned long h = FNV_OFFSET;
213 unsigned char *s = (unsigned char *)str;
225 static int process_slot(struct cache_slot *slot)
229 err = open_slot(slot);
230 if (!err && slot->match) {
231 if (is_expired(slot)) {
232 if (!lock_slot(slot)) {
233 /* If the cachefile has been replaced between
234 * `open_slot` and `lock_slot`, we'll just
235 * serve the stale content from the original
236 * cachefile. This way we avoid pruning the
237 * newly generated slot. The same code-path
238 * is chosen if fill_slot() fails for some
241 * TODO? check if the new slot contains the
242 * same key as the old one, since we would
243 * prefer to serve the newest content.
244 * This will require us to open yet another
245 * file-descriptor and read and compare the
246 * key from the new file, so for now we're
247 * lazy and just ignore the new file.
249 if (is_modified(slot) || fill_slot(slot)) {
250 unlock_slot(slot, 0);
254 unlock_slot(slot, 1);
255 slot->cache_fd = slot->lock_fd;
259 if ((err = print_slot(slot)) != 0) {
260 cache_log("[cgit] error printing cache %s: %s (%d)\n",
269 /* If the cache slot does not exist (or its key doesn't match the
270 * current key), lets try to create a new cache slot for this
271 * request. If this fails (for whatever reason), lets just generate
272 * the content without caching it and fool the caller to belive
273 * everything worked out (but print a warning on stdout).
277 if ((err = lock_slot(slot)) != 0) {
278 cache_log("[cgit] Unable to lock slot %s: %s (%d)\n",
279 slot->lock_name, strerror(err), err);
280 slot->fn(slot->cbdata);
284 if ((err = fill_slot(slot)) != 0) {
285 cache_log("[cgit] Unable to fill slot %s: %s (%d)\n",
286 slot->lock_name, strerror(err), err);
287 unlock_slot(slot, 0);
289 slot->fn(slot->cbdata);
292 // We've got a valid cache slot in the lock file, which
293 // is about to replace the old cache slot. But if we
294 // release the lockfile and then try to open the new cache
295 // slot, we might get a race condition with a concurrent
296 // writer for the same cache slot (with a different key).
297 // Lets avoid such a race by just printing the content of
299 slot->cache_fd = slot->lock_fd;
300 unlock_slot(slot, 1);
301 if ((err = print_slot(slot)) != 0) {
302 cache_log("[cgit] error printing cache %s: %s (%d)\n",
311 /* Print cached content to stdout, generate the content if necessary. */
312 int cache_process(int size, const char *path, const char *key, int ttl,
313 cache_fill_fn fn, void *cbdata)
317 struct strbuf filename = STRBUF_INIT;
318 struct strbuf lockname = STRBUF_INIT;
319 struct cache_slot slot;
322 /* If the cache is disabled, just generate the content */
328 /* Verify input, calculate filenames */
330 cache_log("[cgit] Cache path not specified, caching is disabled\n");
336 hash = hash_str(key) % size;
337 strbuf_addstr(&filename, path);
338 strbuf_ensure_end(&filename, '/');
339 for (i = 0; i < 8; i++) {
340 strbuf_addf(&filename, "%x", (unsigned char)(hash & 0xf));
343 strbuf_addbuf(&lockname, &filename);
344 strbuf_addstr(&lockname, ".lock");
346 slot.cbdata = cbdata;
348 slot.cache_name = filename.buf;
349 slot.lock_name = lockname.buf;
351 slot.keylen = strlen(key);
352 result = process_slot(&slot);
354 strbuf_release(&filename);
355 strbuf_release(&lockname);
359 /* Return a strftime formatted date/time
360 * NB: the result from this function is to shared memory
362 static char *sprintftime(const char *format, time_t time)
370 strftime(buf, sizeof(buf)-1, format, tm);
374 int cache_ls(const char *path)
379 struct cache_slot slot;
380 struct strbuf fullname = STRBUF_INIT;
384 cache_log("[cgit] cache path not specified\n");
390 cache_log("[cgit] unable to open path %s: %s (%d)\n",
391 path, strerror(err), err);
394 strbuf_addstr(&fullname, path);
395 strbuf_ensure_end(&fullname, '/');
396 prefixlen = fullname.len;
397 while ((ent = readdir(dir)) != NULL) {
398 if (strlen(ent->d_name) != 8)
400 strbuf_setlen(&fullname, prefixlen);
401 strbuf_addstr(&fullname, ent->d_name);
402 slot.cache_name = fullname.buf;
403 if ((err = open_slot(&slot)) != 0) {
404 cache_log("[cgit] unable to open path %s: %s (%d)\n",
405 fullname.buf, strerror(err), err);
408 htmlf("%s %s %10"PRIuMAX" %s\n",
410 sprintftime("%Y-%m-%d %H:%M:%S",
411 slot.cache_st.st_mtime),
412 (uintmax_t)slot.cache_st.st_size,
417 strbuf_release(&fullname);
421 /* Print a message to stdout */
422 void cache_log(const char *format, ...)
425 va_start(args, format);
426 vfprintf(stderr, format, args);