]> source.dussan.org Git - rspamd.git/commitdiff
[Feature] Add function to generate random hex string
authorVsevolod Stakhov <vsevolod@highsecure.ru>
Fri, 10 Jun 2016 08:27:25 +0000 (09:27 +0100)
committerVsevolod Stakhov <vsevolod@highsecure.ru>
Fri, 10 Jun 2016 08:27:25 +0000 (09:27 +0100)
src/libutil/util.c
src/libutil/util.h
src/lua/lua_util.c

index 4ce90ba065cc5f2b662b4c66bccc2e501597b49f..212cb7f1b486ed6e22ec0984770f39b8e2f770a5 100644 (file)
@@ -1875,6 +1875,25 @@ randombytes (guchar *buf, guint64 len)
        ottery_rand_bytes (buf, (size_t)len);
 }
 
+void
+rspamd_random_hex (guchar *buf, guint64 len)
+{
+       static const gchar hexdigests[16] = "0123456789abcdef";
+       gint64 i;
+
+       g_assert (len > 0);
+
+       ottery_rand_bytes (buf, (len / 2.0 + 0.5));
+
+       for (i = (gint64)len - 1; i >= 0; i -= 2) {
+               buf[i] = hexdigests[buf[i / 2] & 0xf];
+
+               if (i > 0) {
+                       buf[i - 1] = hexdigests[(buf[i / 2] >> 4) & 0xf];
+               }
+       }
+}
+
 
 void
 rspamd_ptr_array_free_hard (gpointer p)
index 48e91cb4f6c3ba6f527e438c31cd530ff8d96934..5c0e82a0d49d9d2a8ddd3f298318c5b100db83b9 100644 (file)
@@ -404,6 +404,13 @@ void rspamd_deinit_libs (struct rspamd_external_libs_ctx *ctx);
  */
 guint64 rspamd_hash_seed (void);
 
+/**
+ * Returns random hex string of the specified length
+ * @param buf
+ * @param len
+ */
+void rspamd_random_hex (guchar *buf, guint64 len);
+
 /**
  * Return jittered time value
  */
index a5b5eac844693d8d8f2026815248c122ca26cf53..272e39463ae11f8ed2a2bbf1f9e2d55cfd3a4882 100644 (file)
@@ -324,6 +324,15 @@ LUA_FUNCTION_DEF (util, create_file);
  */
 LUA_FUNCTION_DEF (util, close_file);
 
+/**
+ * @function util.random_hex(size)
+ * Returns random hex string of the specified size
+ *
+ * @param {number} len length of desired string in bytes
+ * @return {string} string with random hex digests
+ */
+LUA_FUNCTION_DEF (util, random_hex);
+
 static const struct luaL_reg utillib_f[] = {
        LUA_INTERFACE_DEF (util, create_event_base),
        LUA_INTERFACE_DEF (util, load_rspamd_config),
@@ -358,6 +367,7 @@ static const struct luaL_reg utillib_f[] = {
        LUA_INTERFACE_DEF (util, unlock_file),
        LUA_INTERFACE_DEF (util, create_file),
        LUA_INTERFACE_DEF (util, close_file),
+       LUA_INTERFACE_DEF (util, random_hex),
        {NULL, NULL}
 };
 
@@ -1470,6 +1480,26 @@ lua_util_close_file (lua_State *L)
        return 1;
 }
 
+static gint
+lua_util_random_hex (lua_State *L)
+{
+       gchar *buf;
+       gint buflen;
+
+       buflen = lua_tonumber (L, 1);
+
+       if (buflen <= 0) {
+               return luaL_error (L, "invalid arguments");
+       }
+
+       buf = g_malloc (buflen);
+       rspamd_random_hex (buf, buflen);
+       lua_pushlstring (L, buf, buflen);
+       g_free (buf);
+
+       return 1;
+}
+
 static gint
 lua_load_util (lua_State * L)
 {