[autobuild] rm module stub code for missing deps
[lighttpd.git] / src / mod_magnet_cache.c
blob11c41a9d25599fb7af7caa11e6a1dfef2263170c
1 #include "first.h"
3 #include "mod_magnet_cache.h"
4 #include "stat_cache.h"
6 #include <stdlib.h>
7 #include <time.h>
8 #include <assert.h>
10 #include <lualib.h>
11 #include <lauxlib.h>
13 static script *script_init() {
14 script *sc;
16 sc = calloc(1, sizeof(*sc));
17 sc->name = buffer_init();
18 sc->etag = buffer_init();
20 return sc;
23 static void script_free(script *sc) {
24 if (!sc) return;
26 lua_pop(sc->L, 1); /* the function copy */
28 buffer_free(sc->name);
29 buffer_free(sc->etag);
31 lua_close(sc->L);
33 free(sc);
36 script_cache *script_cache_init() {
37 script_cache *p;
39 p = calloc(1, sizeof(*p));
41 return p;
44 void script_cache_free(script_cache *p) {
45 size_t i;
47 if (!p) return;
49 for (i = 0; i < p->used; i++) {
50 script_free(p->ptr[i]);
53 free(p->ptr);
55 free(p);
58 lua_State *script_cache_get_script(server *srv, connection *con, script_cache *cache, buffer *name) {
59 size_t i;
60 script *sc = NULL;
61 stat_cache_entry *sce;
63 for (i = 0; i < cache->used; i++) {
64 sc = cache->ptr[i];
66 if (buffer_is_equal(name, sc->name)) {
67 sc->last_used = time(NULL);
69 /* oops, the script failed last time */
71 if (lua_gettop(sc->L) == 0) break;
72 force_assert(lua_gettop(sc->L) == 1);
74 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, sc->name, &sce)) {
75 lua_pop(sc->L, 1); /* pop the old function */
76 break;
79 if (!buffer_is_equal(sce->etag, sc->etag)) {
80 /* the etag is outdated, reload the function */
81 lua_pop(sc->L, 1);
82 break;
85 force_assert(lua_isfunction(sc->L, -1));
87 return sc->L;
90 sc = NULL;
93 /* if the script was script already loaded but either got changed or
94 * failed to load last time */
95 if (sc == NULL) {
96 sc = script_init();
98 if (cache->size == 0) {
99 cache->size = 16;
100 cache->ptr = malloc(cache->size * sizeof(*(cache->ptr)));
101 } else if (cache->used == cache->size) {
102 cache->size += 16;
103 cache->ptr = realloc(cache->ptr, cache->size * sizeof(*(cache->ptr)));
106 cache->ptr[cache->used++] = sc;
108 buffer_copy_buffer(sc->name, name);
110 sc->L = luaL_newstate();
111 luaL_openlibs(sc->L);
114 sc->last_used = time(NULL);
116 if (0 != luaL_loadfile(sc->L, name->ptr)) {
117 /* oops, an error, return it */
118 return sc->L;
121 if (HANDLER_GO_ON == stat_cache_get_entry(srv, con, sc->name, &sce)) {
122 buffer_copy_buffer(sc->etag, sce->etag);
125 force_assert(lua_isfunction(sc->L, -1));
127 return sc->L;