aboutsummaryrefslogtreecommitdiffstats
path: root/src/lua/lua_mempool.c
blob: 00c2c24e0ea57746bb0e409011b9824c872c7120 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*-
 * Copyright 2016 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "lua_common.h"
#include "mem_pool.h"

/***
 * @module rspamd_mempool
 * Rspamd memory pool is used to allocate memory attached to specific objects,
 * namely it was initially used for memory allocation for rspamd_task.
 *
 * All memory allocated by the pool is destroyed when the associated object is
 * destroyed. This allows a sort of controlled garbage collection for memory
 * allocated from the pool. Memory pools are extensively used by rspamd internal
 * components and provide some powerful features, such as destructors or
 * persistent variables.
 * @example
local mempool = require "rspamd_mempool"
local pool = mempool.create()

pool:set_variable('a', 'bcd', 1, 1.01, false)
local v1, v2, v3, v4 = pool:get_variable('a', 'string,double,double,bool')
pool:destroy()
 */

/* Lua bindings */
/***
 * @function mempool.create([size])
 * Creates a memory pool of a specified `size` or platform dependent optimal size (normally, a page size)
 * @param {number} size size of a page inside pool
 * @return {rspamd_mempool} new pool object (that should be removed by explicit call to `pool:destroy()`)
 */
LUA_FUNCTION_DEF (mempool, create);
/***
 * @method mempool:add_destructor(func)
 * Adds new destructor function to the pool
 * @param {function} func function to be called when the pool is destroyed
 */
LUA_FUNCTION_DEF (mempool, add_destructor);
/***
 * @method mempool:destroy()
 * Destroys memory pool cleaning all variables and calling all destructors registered (both C and Lua ones)
 */
LUA_FUNCTION_DEF (mempool, delete);
LUA_FUNCTION_DEF (mempool, stat);
LUA_FUNCTION_DEF (mempool, suggest_size);
/***
 * @method mempool:set_variable(name, [value1[, value2 ...]])
 * Sets a variable that's valid during memory pool lifetime. This function allows
 * to pack multiple values inside a single variable. Currently supported types are:
 *
 * - `string`: packed as null terminated C string (so no `\0` are allowed)
 * - `number`: packed as C double
 * - `boolean`: packed as bool
 * @param {string} name variable's name to set
 */
LUA_FUNCTION_DEF (mempool, set_variable);
/***
 * @method mempool:get_variable(name[, type])
 * Unpacks mempool variable to lua If `type` is not specified, then a variable is
 * assumed to be zero-terminated C string. Otherwise, `type` is a comma separated (spaces are ignored)
 * list of types that should be unpacked from a variable's content. The following types
 * are supported:
 *
 * - `string`: null terminated C string (so no `\0` are allowed)
 * - `double`: returned as lua number
 * - `int`: unpack a single integer
 * - `int64`: unpack 64-bits integer
 * - `boolean`: unpack boolean
 * @param {string} name variable's name to get
 * @param {string} type list of types to be extracted
 * @return {variable list} list of variables extracted (but **not** a table)
 */
LUA_FUNCTION_DEF (mempool, get_variable);
/***
 * @method mempool:has_variable(name)
 * Checks if the specified variable `name` exists in the memory pool
 * @param {string} name variable's name to get
 * @return {boolean} `true` if variable exists and `false` otherwise
 */
LUA_FUNCTION_DEF (mempool, has_variable);

/***
 * @method mempool:delete_variable(name)
 * Removes the specified variable `name` from the memory pool
 * @param {string} name variable's name to remove
 * @return {boolean} `true` if variable exists and has been removed
 */
LUA_FUNCTION_DEF (mempool, delete_variable);

static const struct luaL_reg mempoollib_m[] = {
	LUA_INTERFACE_DEF (mempool, add_destructor),
	LUA_INTERFACE_DEF (mempool, stat),
	LUA_INTERFACE_DEF (mempool, suggest_size),
	LUA_INTERFACE_DEF (mempool, set_variable),
	LUA_INTERFACE_DEF (mempool, get_variable),
	LUA_INTERFACE_DEF (mempool, has_variable),
	LUA_INTERFACE_DEF (mempool, delete_variable),
	LUA_INTERFACE_DEF (mempool, delete),
	{"destroy", lua_mempool_delete},
	{"__tostring", rspamd_lua_class_tostring},
	{NULL, NULL}
};

static const struct luaL_reg mempoollib_f[] = {
	LUA_INTERFACE_DEF (mempool, create),
	{NULL, NULL}
};

/*
 * Struct for lua destructor
 */

struct lua_mempool_udata {
	lua_State *L;
	gint cbref;
	rspamd_mempool_t *mempool;
};

struct memory_pool_s *
rspamd_lua_check_mempool (lua_State * L, gint pos)
{
	void *ud = luaL_checkudata (L, pos, "rspamd{mempool}");
	luaL_argcheck (L, ud != NULL, pos, "'mempool' expected");
	return ud ? *((struct memory_pool_s **)ud) : NULL;
}


static int
lua_mempool_create (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_mempool_new (rspamd_mempool_suggest_size (), NULL), **pmempool;

	if (mempool) {
		pmempool = lua_newuserdata (L, sizeof (struct memory_pool_s *));
		rspamd_lua_setclass (L, "rspamd{mempool}", -1);
		*pmempool = mempool;
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static void
lua_mempool_destructor_func (gpointer p)
{
	struct lua_mempool_udata *ud = p;

	lua_rawgeti (ud->L, LUA_REGISTRYINDEX, ud->cbref);
	if (lua_pcall (ud->L, 0, 0, 0) != 0) {
		msg_info ("call to destructor failed: %s", lua_tostring (ud->L, -1));
		lua_pop (ud->L, 1);
	}
	luaL_unref (ud->L, LUA_REGISTRYINDEX, ud->cbref);
}

static int
lua_mempool_add_destructor (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);
	struct lua_mempool_udata *ud;

	if (mempool) {
		if (lua_isfunction (L, 2)) {
			ud = rspamd_mempool_alloc (mempool,
					sizeof (struct lua_mempool_udata));
			lua_pushvalue (L, 2);
			/* Get a reference */
			ud->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
			ud->L = L;
			ud->mempool = mempool;
			rspamd_mempool_add_destructor (mempool,
				lua_mempool_destructor_func,
				ud);
		}
		else {
			msg_err ("trying to add destructor without function");
		}
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static int
lua_mempool_delete (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);

	if (mempool) {
		rspamd_mempool_delete (mempool);
		return 0;
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static int
lua_mempool_stat (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);

	if (mempool) {

	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static int
lua_mempool_suggest_size (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);

	if (mempool) {
		lua_pushinteger (L, rspamd_mempool_suggest_size ());
		return 0;
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static int
lua_mempool_set_variable (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);
	const gchar *var = luaL_checkstring (L, 2);
	gpointer value;
	gchar *vp;
	union {
		gdouble d;
		const gchar *s;
		gboolean b;
	} val;
	gsize slen;
	gint i, len = 0, type;

	if (mempool && var) {

		for (i = 3; i <= lua_gettop (L); i ++) {
			type = lua_type (L, i);

			if (type == LUA_TNUMBER) {
				/* We have some ambiguity here between integer and double */
				len += sizeof (gdouble);
			}
			else if (type == LUA_TBOOLEAN) {
				len += sizeof (gboolean);
			}
			else if (type == LUA_TSTRING) {
				(void)lua_tolstring (L, i, &slen);
				len += slen + 1;
			}
			else {
				msg_err ("cannot handle lua type %s", lua_typename (L, type));
			}
		}

		if (len == 0) {
			msg_err ("no values specified");
		}
		else {
			value = rspamd_mempool_alloc (mempool, len);
			vp = value;

			for (i = 3; i <= lua_gettop (L); i ++) {
				type = lua_type (L, i);

				if (type == LUA_TNUMBER) {
					val.d = lua_tonumber (L, i);
					memcpy (vp, &val, sizeof (gdouble));
					vp += sizeof (gdouble);
				}
				else if (type == LUA_TBOOLEAN) {
					val.b = lua_toboolean (L, i);
					memcpy (vp, &val, sizeof (gboolean));
					vp += sizeof (gboolean);
				}
				else if (type == LUA_TSTRING) {
					val.s = lua_tolstring (L, i, &slen);
					memcpy (vp, val.s, slen + 1);
					vp += slen + 1;
				}
				else {
					msg_err ("cannot handle lua type %s", lua_typename (L, type));
				}
			}

			rspamd_mempool_set_variable (mempool, var, value, NULL);
		}

		return 0;
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}


static int
lua_mempool_get_variable (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);
	const gchar *var = luaL_checkstring (L, 2);
	const gchar *type = NULL, *pt;
	gchar *value, *pv;
	guint len, nvar, slen;

	if (mempool && var) {
		value = rspamd_mempool_get_variable (mempool, var);

		if (lua_gettop (L) >= 3) {
			type = luaL_checkstring (L, 3);
		}

		if (value) {

			if (type) {
				pt = type;
				pv = value;
				nvar = 0;

				while ((len = strcspn (pt, ", ")) > 0) {
					if (len == sizeof ("double") - 1 &&
							g_ascii_strncasecmp (pt, "double", len) == 0) {
						lua_pushnumber (L, *(gdouble *)pv);
						pv += sizeof (gdouble);
					}
					else if (len == sizeof ("int") - 1 &&
							g_ascii_strncasecmp (pt, "int", len) == 0) {
						lua_pushnumber (L, *(gint *)pv);
						pv += sizeof (gint);
					}
					else if (len == sizeof ("int64") - 1 &&
							g_ascii_strncasecmp (pt, "int64", len) == 0) {
						lua_pushnumber (L, *(gint64 *)pv);
						pv += sizeof (gint64);
					}
					else if (len == sizeof ("bool") - 1 &&
							g_ascii_strncasecmp (pt, "bool", len) == 0) {
						lua_pushboolean (L, *(gboolean *)pv);
						pv += sizeof (gboolean);
					}
					else if (len == sizeof ("string") - 1 &&
							g_ascii_strncasecmp (pt, "string", len) == 0) {
						slen = strlen ((const gchar *)pv);
						lua_pushlstring (L, (const gchar *)pv, slen);
						pv += slen + 1;
					}
					else {
						msg_err ("unknown type for get_variable: %s", pt);
						lua_pushnil (L);
					}

					pt += len;
					pt += strspn (pt, ", ");

					nvar ++;
				}

				return nvar;
			}

			lua_pushstring (L, value);
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static int
lua_mempool_has_variable (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);
	const gchar *var = luaL_checkstring (L, 2);
	gboolean ret = FALSE;

	if (mempool && var) {
		if (rspamd_mempool_get_variable (mempool, var) != NULL) {
			ret = TRUE;
		}
	}

	lua_pushboolean (L, ret);

	return 1;
}

static int
lua_mempool_delete_variable (lua_State *L)
{
	struct memory_pool_s *mempool = rspamd_lua_check_mempool (L, 1);
	const gchar *var = luaL_checkstring (L, 2);
	gboolean ret = FALSE;

	if (mempool && var) {
		if (rspamd_mempool_get_variable (mempool, var) != NULL) {
			ret = TRUE;

			rspamd_mempool_remove_variable (mempool, var);
		}
	}

	lua_pushboolean (L, ret);

	return 1;
}

static gint
lua_load_mempool (lua_State * L)
{
	lua_newtable (L);
	luaL_register (L, NULL, mempoollib_f);

	return 1;
}

void
luaopen_mempool (lua_State * L)
{
	luaL_newmetatable (L, "rspamd{mempool}");
	lua_pushstring (L, "__index");
	lua_pushvalue (L, -2);
	lua_settable (L, -3);

	lua_pushstring (L, "class");
	lua_pushstring (L, "rspamd{mempool}");
	lua_rawset (L, -3);

	luaL_register (L, NULL,				mempoollib_m);
	rspamd_lua_add_preload (L, "rspamd_mempool", lua_load_mempool);

	lua_pop (L, 1);                      /* remove metatable from stack */
}