| 1 |
-- Test zbase32 encoding/decoding |
| 2 |
|
| 3 |
context("Base32 encodning", function() |
| 4 |
local ok, ffi = pcall(require, "ffi") |
| 5 |
if not ok then |
| 6 |
ffi = require("cffi") |
| 7 |
end |
| 8 |
ffi.cdef[[ |
| 9 |
void ottery_rand_bytes(void *buf, size_t n); |
| 10 |
unsigned ottery_rand_unsigned(void); |
| 11 |
unsigned char* rspamd_decode_base32 (const char *in, size_t inlen, size_t *outlen, int how); |
| 12 |
char * rspamd_encode_base32 (const unsigned char *in, size_t inlen, int how); |
| 13 |
void g_free(void *ptr); |
| 14 |
int memcmp(const void *a1, const void *a2, size_t len); |
| 15 |
]] |
| 16 |
|
| 17 |
-- Helper to convert cdata numbers to Lua numbers (cffi-lua compatibility) |
| 18 |
local function cdata_to_number(v) |
| 19 |
local n = tonumber(v) |
| 20 |
if n then return n end |
| 21 |
return tonumber(tostring(v):match("^(%d+)")) |
| 22 |
end |
| 23 |
|
| 24 |
local function random_buf(max_size) |
| 25 |
local l = ffi.C.ottery_rand_unsigned() % max_size + 1 |
| 26 |
local buf = ffi.new("unsigned char[?]", l) |
| 27 |
ffi.C.ottery_rand_bytes(buf, l) |
| 28 |
|
| 29 |
return buf, l |
| 30 |
end |
| 31 |
|
| 32 |
test("Base32 encode test", function() |
| 33 |
local cases = { |
| 34 |
{'test123', 'wm3g84fg13cy'}, |
| 35 |
{'hello', 'em3ags7p'} |
| 36 |
} |
| 37 |
|
| 38 |
for _,c in ipairs(cases) do |
| 39 |
local inp = ffi.new("unsigned char[?]", #c[1], c[1]) |
| 40 |
local b = ffi.C.rspamd_encode_base32(inp, #c[1], 0) |
| 41 |
local s = ffi.string(b) |
| 42 |
ffi.C.g_free(b) |
| 43 |
assert_equal(s, c[2], s .. " not equal " .. c[2]) |
| 44 |
end |
| 45 |
end) |
| 46 |
|
| 47 |
if os.getenv("RSPAMD_LUA_EXPENSIVE_TESTS") then |
| 48 |
test("Base32 fuzz test: zbase32", function() |
| 49 |
for i = 1,1000 do |
| 50 |
local b, l = random_buf(4096) |
| 51 |
local how = math.floor(math.random(3) - 1) |
| 52 |
local ben = ffi.C.rspamd_encode_base32(b, l, how) |
| 53 |
local bs = ffi.string(ben) |
| 54 |
local nl = ffi.new("size_t [1]") |
| 55 |
local nb = ffi.C.rspamd_decode_base32(bs, #bs, nl, how) |
| 56 |
|
| 57 |
local reported_len = cdata_to_number(nl[0]) or 0 |
| 58 |
assert_equal(reported_len, l, |
| 59 |
string.format("invalid size reported: %s reported vs %s expected", tostring(reported_len), tostring(l))) |
| 60 |
local cmp = ffi.C.memcmp(b, nb, l) |
| 61 |
ffi.C.g_free(ben) |
| 62 |
ffi.C.g_free(nb) |
| 63 |
assert_equal(cmp, 0, "fuzz test failed for length: " .. tostring(l)) |
| 64 |
end |
| 65 |
end) |
| 66 |
end |
| 67 |
end) |