commit 09fc651: [Minor] Allow to have __index in rspamd "classes"

Vsevolod Stakhov vsevolod at highsecure.ru
Wed Aug 5 20:07:13 UTC 2020


Author: Vsevolod Stakhov
Date: 2020-08-05 21:04:06 +0100
URL: https://github.com/rspamd/rspamd/commit/09fc651620d5d55949fb0ad60e402fb5e62668e2

[Minor] Allow to have __index in rspamd "classes"

---
 src/lua/lua_common.c | 13 ++++++++++---
 src/lua/lua_logger.c | 28 +++++++++++++++++++++++++++-
 2 files changed, 37 insertions(+), 4 deletions(-)

diff --git a/src/lua/lua_common.c b/src/lua/lua_common.c
index 92da12d52..d27bf0529 100644
--- a/src/lua/lua_common.c
+++ b/src/lua/lua_common.c
@@ -89,6 +89,7 @@ rspamd_lua_new_class (lua_State * L,
 	void *class_ptr;
 	khiter_t k;
 	gint r, nmethods = 0;
+	gboolean seen_index = false;
 
 	k = kh_put (lua_class_set, lua_classes, classname, &r);
 	class_ptr = RSPAMD_LIGHTUSERDATA_MASK (kh_key (lua_classes, k));
@@ -96,6 +97,9 @@ rspamd_lua_new_class (lua_State * L,
 	if (methods) {
 		for (;;) {
 			if (methods[nmethods].name != NULL) {
+				if (strcmp (methods[nmethods].name, "__index") == 0) {
+					seen_index = true;
+				}
 				nmethods ++;
 			}
 			else {
@@ -105,9 +109,12 @@ rspamd_lua_new_class (lua_State * L,
 	}
 
 	lua_createtable (L, 0, 3 + nmethods);
-	lua_pushstring (L, "__index");
-	lua_pushvalue (L, -2);      /* pushes the metatable */
-	lua_settable (L, -3);       /* metatable.__index = metatable */
+
+	if (!seen_index) {
+		lua_pushstring (L, "__index");
+		lua_pushvalue (L, -2);      /* pushes the metatable */
+		lua_settable (L, -3);       /* metatable.__index = metatable */
+	}
 
 	lua_pushstring (L, "class");
 	lua_pushstring (L, classname);
diff --git a/src/lua/lua_logger.c b/src/lua/lua_logger.c
index fc0f5fe9f..17705947b 100644
--- a/src/lua/lua_logger.c
+++ b/src/lua/lua_logger.c
@@ -389,7 +389,7 @@ static gsize
 lua_logger_out_userdata (lua_State *L, gint pos, gchar *outbuf, gsize len,
 						 struct lua_logger_trace *trace)
 {
-	gint r, top;
+	gint r = 0, top;
 	const gchar *str = NULL;
 	gboolean converted_to_str = FALSE;
 
@@ -403,6 +403,32 @@ lua_logger_out_userdata (lua_State *L, gint pos, gchar *outbuf, gsize len,
 	lua_gettable (L, -2);
 
 	if (!lua_istable (L, -1)) {
+
+		if (lua_isfunction (L, -1)) {
+			/* Functional metatable, try to get __tostring directly */
+			lua_pushstring (L, "__tostring");
+			lua_gettable (L, -3);
+
+			if (lua_isfunction (L, -1)) {
+				lua_pushvalue (L, pos);
+
+				if (lua_pcall (L, 1, 1, 0) != 0) {
+					lua_settop (L, top);
+
+					return 0;
+				}
+
+				str = lua_tostring (L, -1);
+
+				if (str) {
+					r = rspamd_snprintf (outbuf, len, "%s", str);
+				}
+
+				lua_settop (L, top);
+
+				return r;
+			}
+		}
 		lua_settop (L, top);
 
 		return 0;


More information about the Commits mailing list