Debian Codegraph @

lualib/lua_selectors/common.lua

raw
1 --[[
2 Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 ]]--
16
17 local T = require "lua_shape.core"
18 local exports = {}
19 local cr_hash = require 'rspamd_cryptobox_hash'
20
21 local blake2b_key = cr_hash.create_specific('blake2'):update('rspamd'):bin()
22
23 local function digest_schema()
24 return {
25 T.enum({ 'hex', 'base32', 'bleach32', 'rbase32', 'base64' }):optional():doc({ summary = "Encoding format" }),
26 T.enum({ 'blake2', 'sha256', 'sha1', 'sha512', 'md5' }):optional():doc({ summary = "Hash algorithm" })
27 }
28 end
29
30 exports.digest_schema = digest_schema
31
32 local function create_raw_digest(data, args)
33 local ht = args[2] or 'blake2'
34
35 local h
36
37 if ht == 'blake2' then
38 -- Hack to be compatible with various 'get_digest' methods
39 h = cr_hash.create_keyed(blake2b_key):update(data)
40 else
41 h = cr_hash.create_specific(ht):update(data)
42 end
43
44 return h
45 end
46
47 local function encode_digest(h, args)
48 local encoding = args[1] or 'hex'
49
50 local s
51 if encoding == 'hex' then
52 s = h:hex()
53 elseif encoding == 'base32' then
54 s = h:base32()
55 elseif encoding == 'bleach32' then
56 s = h:base32('bleach')
57 elseif encoding == 'rbase32' then
58 s = h:base32('rfc')
59 elseif encoding == 'base64' then
60 s = h:base64()
61 end
62
63 return s
64 end
65
66 local function create_digest(data, args)
67 local h = create_raw_digest(data, args)
68 return encode_digest(h, args)
69 end
70
71 local function get_cached_or_raw_digest(task, idx, mime_part, args)
72 if #args == 0 then
73 -- Optimise as we already have this hash in the API
74 return mime_part:get_digest()
75 end
76
77 local ht = args[2] or 'blake2'
78 local cache_key = 'mp_digest_' .. ht .. tostring(idx)
79
80 local cached = task:cache_get(cache_key)
81
82 if cached then
83 return encode_digest(cached, args)
84 end
85
86 local h = create_raw_digest(mime_part:get_content('raw_parsed'), args)
87 task:cache_set(cache_key, h)
88
89 return encode_digest(h, args)
90 end
91
92 exports.create_digest = create_digest
93 exports.create_raw_digest = create_raw_digest
94 exports.get_cached_or_raw_digest = get_cached_or_raw_digest
95 exports.encode_digest = encode_digest
96
97 return exports