xref: /lighttpd1.4/src/mod_vhostdb.c (revision 463c60ce)
1 /*
2  * mod_vhostdb - virtual hosts mapping from backend database
3  *
4  * Copyright(c) 2017 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
5  * License: BSD 3-clause (same as lighttpd)
6  */
7 #include "first.h"
8 
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include "mod_vhostdb_api.h"
13 #include "base.h"
14 #include "plugin.h"
15 #include "plugin_config.h"
16 #include "log.h"
17 #include "stat_cache.h"
18 #include "algo_splaytree.h"
19 
20 /**
21  * vhostdb framework
22  */
23 
24 typedef struct {
25     splay_tree *sptree; /* data in nodes of tree are (vhostdb_cache_entry *) */
26     time_t max_age;
27 } vhostdb_cache;
28 
29 typedef struct {
30     const http_vhostdb_backend_t *vhostdb_backend;
31     vhostdb_cache *vhostdb_cache;
32 } plugin_config;
33 
34 typedef struct {
35     PLUGIN_DATA;
36     plugin_config defaults;
37     plugin_config conf;
38 } plugin_data;
39 
40 typedef struct {
41     char *server_name;
42     char *document_root;
43     uint32_t slen;
44     uint32_t dlen;
45     unix_time64_t ctime;
46 } vhostdb_cache_entry;
47 
48 static vhostdb_cache_entry *
49 vhostdb_cache_entry_init (const buffer * const server_name, const buffer * const docroot)
50 {
51     const uint32_t slen = buffer_clen(server_name);
52     const uint32_t dlen = buffer_clen(docroot);
53     vhostdb_cache_entry * const ve =
54       malloc(sizeof(vhostdb_cache_entry) + slen + dlen);
55     force_assert(ve);
56     ve->ctime = log_monotonic_secs;
57     ve->slen = slen;
58     ve->dlen = dlen;
59     ve->server_name   = (char *)(ve + 1);
60     ve->document_root = ve->server_name + slen;
61     memcpy(ve->server_name,   server_name->ptr, slen);
62     memcpy(ve->document_root, docroot->ptr,     dlen);
63     return ve;
64 }
65 
66 static void
67 vhostdb_cache_entry_free (vhostdb_cache_entry *ve)
68 {
69     free(ve);
70 }
71 
72 static void
73 vhostdb_cache_free (vhostdb_cache *vc)
74 {
75     splay_tree *sptree = vc->sptree;
76     while (sptree) {
77         vhostdb_cache_entry_free(sptree->data);
78         sptree = splaytree_delete(sptree, sptree->key);
79     }
80     free(vc);
81 }
82 
83 static vhostdb_cache *
84 vhostdb_cache_init (const array *opts)
85 {
86     vhostdb_cache *vc = malloc(sizeof(vhostdb_cache));
87     force_assert(vc);
88     vc->sptree = NULL;
89     vc->max_age = 600; /* 10 mins */
90     for (uint32_t i = 0, used = opts->used; i < used; ++i) {
91         data_unset *du = opts->data[i];
92         if (buffer_is_equal_string(&du->key, CONST_STR_LEN("max-age")))
93             vc->max_age = (time_t)
94               config_plugin_value_to_int32(du, (int32_t)vc->max_age);
95     }
96     return vc;
97 }
98 
99 static vhostdb_cache_entry *
100 mod_vhostdb_cache_query (request_st * const r, plugin_data * const p)
101 {
102     const int ndx = splaytree_djbhash(BUF_PTR_LEN(&r->uri.authority));
103     splay_tree ** const sptree = &p->conf.vhostdb_cache->sptree;
104     *sptree = splaytree_splay(*sptree, ndx);
105     vhostdb_cache_entry * const ve =
106       (*sptree && (*sptree)->key == ndx) ? (*sptree)->data : NULL;
107 
108     return ve
109         && buffer_is_equal_string(&r->uri.authority, ve->server_name, ve->slen)
110       ? ve
111       : NULL;
112 }
113 
114 static void
115 mod_vhostdb_cache_insert (request_st * const r, plugin_data * const p, vhostdb_cache_entry * const ve)
116 {
117     const int ndx = splaytree_djbhash(BUF_PTR_LEN(&r->uri.authority));
118     splay_tree ** const sptree = &p->conf.vhostdb_cache->sptree;
119     /*(not necessary to re-splay (with current usage) since single-threaded
120      * and splaytree has not been modified since mod_vhostdb_cache_query())*/
121     /* *sptree = splaytree_splay(*sptree, ndx); */
122     if (NULL == *sptree || (*sptree)->key != ndx)
123         *sptree = splaytree_insert(*sptree, ndx, ve);
124     else { /* collision; replace old entry */
125         vhostdb_cache_entry_free((*sptree)->data);
126         (*sptree)->data = ve;
127     }
128 }
129 
130 INIT_FUNC(mod_vhostdb_init) {
131     return calloc(1, sizeof(plugin_data));
132 }
133 
134 FREE_FUNC(mod_vhostdb_free) {
135     plugin_data *p = p_d;
136 
137     if (NULL == p->cvlist) return;
138     /* (init i to 0 if global context; to 1 to skip empty global context) */
139     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
140         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
141         for (; -1 != cpv->k_id; ++cpv) {
142             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
143             switch (cpv->k_id) {
144               case 1: /* vhostdb.cache */
145                 vhostdb_cache_free(cpv->v.v);
146                 break;
147               default:
148                 break;
149             }
150         }
151     }
152 
153     http_vhostdb_dumbdata_reset();
154 }
155 
156 static void mod_vhostdb_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
157     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
158       case 0: /* vhostdb.backend */
159         if (cpv->vtype == T_CONFIG_LOCAL)
160             pconf->vhostdb_backend = cpv->v.v;
161         break;
162       case 1: /* vhostdb.cache */
163         if (cpv->vtype == T_CONFIG_LOCAL)
164             pconf->vhostdb_cache = cpv->v.v;
165         break;
166       default:/* should not happen */
167         return;
168     }
169 }
170 
171 static void mod_vhostdb_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
172     do {
173         mod_vhostdb_merge_config_cpv(pconf, cpv);
174     } while ((++cpv)->k_id != -1);
175 }
176 
177 static void mod_vhostdb_patch_config(request_st * const r, plugin_data * const p) {
178     memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
179     for (int i = 1, used = p->nconfig; i < used; ++i) {
180         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
181             mod_vhostdb_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
182     }
183 }
184 
185 SETDEFAULTS_FUNC(mod_vhostdb_set_defaults) {
186     static const config_plugin_keys_t cpk[] = {
187       { CONST_STR_LEN("vhostdb.backend"),
188         T_CONFIG_STRING,
189         T_CONFIG_SCOPE_CONNECTION }
190      ,{ CONST_STR_LEN("vhostdb.cache"),
191         T_CONFIG_ARRAY,
192         T_CONFIG_SCOPE_CONNECTION }
193      ,{ NULL, 0,
194         T_CONFIG_UNSET,
195         T_CONFIG_SCOPE_UNSET }
196     };
197 
198     plugin_data * const p = p_d;
199     if (!config_plugin_values_init(srv, p, cpk, "mod_vhostdb"))
200         return HANDLER_ERROR;
201 
202     /* process and validate config directives
203      * (init i to 0 if global context; to 1 to skip empty global context) */
204     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
205         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
206         for (; -1 != cpv->k_id; ++cpv) {
207             switch (cpv->k_id) {
208               case 0: /* vhostdb.backend */
209                 if (!buffer_is_blank(cpv->v.b)) {
210                     const buffer * const b = cpv->v.b;
211                     *(const void **)&cpv->v.v = http_vhostdb_backend_get(b);
212                     if (NULL == cpv->v.v) {
213                         log_error(srv->errh, __FILE__, __LINE__,
214                           "vhostdb.backend not supported: %s", b->ptr);
215                         return HANDLER_ERROR;
216                     }
217                     cpv->vtype = T_CONFIG_LOCAL;
218                 }
219                 break;
220               case 1: /* vhostdb.cache */
221                 cpv->v.v = vhostdb_cache_init(cpv->v.a);
222                 cpv->vtype = T_CONFIG_LOCAL;
223                 break;
224               default:/* should not happen */
225                 break;
226             }
227         }
228     }
229 
230     /* initialize p->defaults from global config context */
231     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
232         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
233         if (-1 != cpv->k_id)
234             mod_vhostdb_merge_config(&p->defaults, cpv);
235     }
236 
237     return HANDLER_GO_ON;
238 }
239 
240 REQUEST_FUNC(mod_vhostdb_handle_request_reset) {
241     plugin_data *p = p_d;
242     vhostdb_cache_entry *ve;
243 
244     if ((ve = r->plugin_ctx[p->id])) {
245         r->plugin_ctx[p->id] = NULL;
246         vhostdb_cache_entry_free(ve);
247     }
248 
249     return HANDLER_GO_ON;
250 }
251 
252 __attribute_cold__
253 static handler_t mod_vhostdb_error_500 (request_st * const r)
254 {
255     r->http_status = 500; /* Internal Server Error */
256     r->handler_module = NULL;
257     return HANDLER_FINISHED;
258 }
259 
260 static handler_t mod_vhostdb_found (request_st * const r, vhostdb_cache_entry * const ve)
261 {
262     /* fix virtual server and docroot */
263     if (ve->slen) {
264         r->server_name = &r->server_name_buf;
265         buffer_copy_string_len(&r->server_name_buf, ve->server_name, ve->slen);
266     }
267     buffer_copy_string_len(&r->physical.doc_root, ve->document_root, ve->dlen);
268     return HANDLER_GO_ON;
269 }
270 
271 REQUEST_FUNC(mod_vhostdb_handle_docroot) {
272     plugin_data *p = p_d;
273     vhostdb_cache_entry *ve;
274 
275     /* no host specified? */
276     if (buffer_is_blank(&r->uri.authority)) return HANDLER_GO_ON;
277 
278     /* check if cached this connection */
279     ve = r->plugin_ctx[p->id];
280     if (ve
281         && buffer_is_equal_string(&r->uri.authority, ve->server_name, ve->slen))
282         return mod_vhostdb_found(r, ve); /* HANDLER_GO_ON */
283 
284     mod_vhostdb_patch_config(r, p);
285     if (!p->conf.vhostdb_backend) return HANDLER_GO_ON;
286 
287     if (p->conf.vhostdb_cache && (ve = mod_vhostdb_cache_query(r, p)))
288         return mod_vhostdb_found(r, ve); /* HANDLER_GO_ON */
289 
290     buffer * const b = r->tmp_buf; /*(cleared before use in backend->query())*/
291     const http_vhostdb_backend_t * const backend = p->conf.vhostdb_backend;
292     if (0 != backend->query(r, backend->p_d, b)) {
293         return mod_vhostdb_error_500(r); /* HANDLER_FINISHED */
294     }
295 
296     if (buffer_is_blank(b)) {
297         /* no such virtual host */
298         return HANDLER_GO_ON;
299     }
300 
301     /* sanity check that really is a directory */
302     buffer_append_slash(b);
303     if (!stat_cache_path_isdir(b)) {
304         log_perror(r->conf.errh, __FILE__, __LINE__, "%s", b->ptr);
305         return mod_vhostdb_error_500(r); /* HANDLER_FINISHED */
306     }
307 
308     if (ve && !p->conf.vhostdb_cache)
309         vhostdb_cache_entry_free(ve);
310 
311     ve = vhostdb_cache_entry_init(&r->uri.authority, b);
312 
313     if (!p->conf.vhostdb_cache)
314         r->plugin_ctx[p->id] = ve;
315     else
316         mod_vhostdb_cache_insert(r, p, ve);
317 
318     return mod_vhostdb_found(r, ve); /* HANDLER_GO_ON */
319 }
320 
321 /* walk though cache, collect expired ids, and remove them in a second loop */
322 static void
323 mod_vhostdb_tag_old_entries (splay_tree * const t, int * const keys, int * const ndx, const time_t max_age, const unix_time64_t cur_ts)
324 {
325     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
326     if (t->left)
327         mod_vhostdb_tag_old_entries(t->left, keys, ndx, max_age, cur_ts);
328     if (t->right)
329         mod_vhostdb_tag_old_entries(t->right, keys, ndx, max_age, cur_ts);
330     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
331 
332     const vhostdb_cache_entry * const ve = t->data;
333     if (cur_ts - ve->ctime > max_age)
334         keys[(*ndx)++] = t->key;
335 }
336 
337 __attribute_noinline__
338 static void
339 mod_vhostdb_periodic_cleanup(splay_tree **sptree_ptr, const time_t max_age, const unix_time64_t cur_ts)
340 {
341     splay_tree *sptree = *sptree_ptr;
342     int max_ndx, i;
343     int keys[8192]; /* 32k size on stack */
344     do {
345         if (!sptree) break;
346         max_ndx = 0;
347         mod_vhostdb_tag_old_entries(sptree, keys, &max_ndx, max_age, cur_ts);
348         for (i = 0; i < max_ndx; ++i) {
349             int ndx = keys[i];
350             sptree = splaytree_splay(sptree, ndx);
351             if (sptree && sptree->key == ndx) {
352                 vhostdb_cache_entry_free(sptree->data);
353                 sptree = splaytree_delete(sptree, ndx);
354             }
355         }
356     } while (max_ndx == sizeof(keys)/sizeof(int));
357     *sptree_ptr = sptree;
358 }
359 
360 TRIGGER_FUNC(mod_vhostdb_periodic)
361 {
362     const plugin_data * const p = p_d;
363     const unix_time64_t cur_ts = log_monotonic_secs;
364     if (cur_ts & 0x7) return HANDLER_GO_ON; /*(continue once each 8 sec)*/
365     UNUSED(srv);
366 
367     /* future: might construct array of (vhostdb_cache *) at startup
368      *         to avoid the need to search for them here */
369     /* (init i to 0 if global context; to 1 to skip empty global context) */
370     if (NULL == p->cvlist) return HANDLER_GO_ON;
371     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
372         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
373         for (; cpv->k_id != -1; ++cpv) {
374             if (cpv->k_id != 1) continue; /* k_id == 1 for vhostdb.cache */
375             if (cpv->vtype != T_CONFIG_LOCAL) continue;
376             vhostdb_cache *vc = cpv->v.v;
377             mod_vhostdb_periodic_cleanup(&vc->sptree, vc->max_age, cur_ts);
378         }
379     }
380 
381     return HANDLER_GO_ON;
382 }
383 
384 
385 __attribute_cold__
386 int mod_vhostdb_plugin_init(plugin *p);
387 int mod_vhostdb_plugin_init(plugin *p) {
388     p->version          = LIGHTTPD_VERSION_ID;
389     p->name             = "vhostdb";
390     p->init             = mod_vhostdb_init;
391     p->cleanup          = mod_vhostdb_free;
392     p->set_defaults     = mod_vhostdb_set_defaults;
393     p->handle_trigger   = mod_vhostdb_periodic;
394     p->handle_docroot   = mod_vhostdb_handle_docroot;
395     p->handle_request_reset = mod_vhostdb_handle_request_reset;
396 
397     return 0;
398 }
399