[core] avoid spurious trace and error abort
[lighttpd.git] / src / mod_magnet_cache.c
blobbefc19cb826b9673921caeac24795bbb4cad4ac3
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 #ifdef HAVE_LUA_H
11 #include <lualib.h>
12 #include <lauxlib.h>
14 static script *script_init() {
15 script *sc;
17 sc = calloc(1, sizeof(*sc));
18 sc->name = buffer_init();
19 sc->etag = buffer_init();
21 return sc;
24 static void script_free(script *sc) {
25 if (!sc) return;
27 lua_pop(sc->L, 1); /* the function copy */
29 buffer_free(sc->name);
30 buffer_free(sc->etag);
32 lua_close(sc->L);
34 free(sc);
37 script_cache *script_cache_init() {
38 script_cache *p;
40 p = calloc(1, sizeof(*p));
42 return p;
45 void script_cache_free(script_cache *p) {
46 size_t i;
48 if (!p) return;
50 for (i = 0; i < p->used; i++) {
51 script_free(p->ptr[i]);
54 free(p->ptr);
56 free(p);
59 lua_State *script_cache_get_script(server *srv, connection *con, script_cache *cache, buffer *name) {
60 size_t i;
61 script *sc = NULL;
62 stat_cache_entry *sce;
64 for (i = 0; i < cache->used; i++) {
65 sc = cache->ptr[i];
67 if (buffer_is_equal(name, sc->name)) {
68 sc->last_used = time(NULL);
70 /* oops, the script failed last time */
72 if (lua_gettop(sc->L) == 0) break;
73 force_assert(lua_gettop(sc->L) == 1);
75 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, sc->name, &sce)) {
76 lua_pop(sc->L, 1); /* pop the old function */
77 break;
80 if (!buffer_is_equal(sce->etag, sc->etag)) {
81 /* the etag is outdated, reload the function */
82 lua_pop(sc->L, 1);
83 break;
86 force_assert(lua_isfunction(sc->L, -1));
88 return sc->L;
91 sc = NULL;
94 /* if the script was script already loaded but either got changed or
95 * failed to load last time */
96 if (sc == NULL) {
97 sc = script_init();
99 if (cache->size == 0) {
100 cache->size = 16;
101 cache->ptr = malloc(cache->size * sizeof(*(cache->ptr)));
102 } else if (cache->used == cache->size) {
103 cache->size += 16;
104 cache->ptr = realloc(cache->ptr, cache->size * sizeof(*(cache->ptr)));
107 cache->ptr[cache->used++] = sc;
109 buffer_copy_buffer(sc->name, name);
111 sc->L = luaL_newstate();
112 luaL_openlibs(sc->L);
115 sc->last_used = time(NULL);
117 if (0 != luaL_loadfile(sc->L, name->ptr)) {
118 /* oops, an error, return it */
119 return sc->L;
122 if (HANDLER_GO_ON == stat_cache_get_entry(srv, con, sc->name, &sce)) {
123 buffer_copy_buffer(sc->etag, sce->etag);
126 force_assert(lua_isfunction(sc->L, -1));
128 return sc->L;
131 #endif