Skip to content

Commit 79717b5

Browse files
committed
bugfix: resty.core.regex: data corruptions might happen when recursively calling ngx.re.gsub via the user replacement function argument because of incorrect reusing a globally shared captures Lua table. thanks James Hurst for the report in openresty/lua-nginx-module#445.
1 parent 7d92e90 commit 79717b5

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

lib/resty/core/regex.lua

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ local regex_sub_str_cache = new_tab(0, 4)
7272
local max_regex_cache_size
7373
local regex_cache_size = 0
7474
local script_engine
75-
local tmp_captures = new_tab(4, 4)
7675

7776

7877
ffi.cdef[[
@@ -636,7 +635,7 @@ local function re_sub_func_helper(subj, regex, replace, opts, global)
636635
count = count + 1
637636
local prefix_len = compiled.captures[0] - cp_pos
638637

639-
local res = collect_captures(compiled, rc, subj, flags, tmp_captures)
638+
local res = collect_captures(compiled, rc, subj, flags)
640639

641640
local bit = replace(res)
642641
local bit_len = #bit

t/re-sub.t

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use Cwd qw(cwd);
99

1010
repeat_each(2);
1111

12-
plan tests => repeat_each() * (blocks() * 4 + 8);
12+
plan tests => repeat_each() * (blocks() * 4 + 9);
1313

1414
my $pwd = cwd();
1515

@@ -277,3 +277,50 @@ GET /t
277277
bad argument type
278278
NYI
279279
280+
281+
282+
=== TEST 8: ngx.re.gsub: recursive calling (github openresty/lua-nginx-module#445)
283+
--- http_config eval: $::HttpConfig
284+
--- config
285+
286+
location = /t {
287+
content_by_lua '
288+
function test()
289+
local data = [[
290+
OUTER {FIRST}
291+
]]
292+
293+
local p1 = "(OUTER)(.+)"
294+
local p2 = "{([A-Z]+)}"
295+
296+
ngx.print(data)
297+
298+
local res = ngx.re.gsub(data, p1, function(m)
299+
-- ngx.say("pre: m[1]: [", m[1], "]")
300+
-- ngx.say("pre: m[2]: [", m[2], "]")
301+
302+
local res = ngx.re.gsub(m[2], p2, function(_)
303+
return "REPLACED"
304+
end, "")
305+
306+
-- ngx.say("post: m[1]: [", m[1], "]")
307+
-- ngx.say("post m[2]: [", m[2], "]")
308+
return m[1] .. res
309+
end, "")
310+
311+
ngx.print(res)
312+
end
313+
314+
test()
315+
';
316+
}
317+
--- request
318+
GET /t
319+
--- response_body
320+
OUTER {FIRST}
321+
OUTER REPLACED
322+
--- no_error_log
323+
[error]
324+
bad argument type
325+
NYI
326+

0 commit comments

Comments
 (0)