Skip to content

Commit 4b6bff4

Browse files
ClobberXDSmallJoker
authored andcommitted
Use a safer implementation of gsub in core.chat_format_message (#9133)
This search-and-replace implementation does not use Lua pattern-matching
1 parent 0b2f091 commit 4b6bff4

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

builtin/game/chat.lua

+22-8
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,41 @@
11
-- Minetest: builtin/game/chat.lua
22

3+
-- Helper function that implements search and replace without pattern matching
4+
-- Returns the string and a boolean indicating whether or not the string was modified
5+
local function safe_gsub(s, replace, with)
6+
local i1, i2 = s:find(replace, 1, true)
7+
if not i1 then
8+
return s, false
9+
end
10+
11+
return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
12+
end
13+
314
--
415
-- Chat message formatter
516
--
617

718
-- Implemented in Lua to allow redefinition
819
function core.format_chat_message(name, message)
9-
local str = core.settings:get("chat_message_format")
1020
local error_str = "Invalid chat message format - missing %s"
11-
local i
21+
local str = core.settings:get("chat_message_format")
22+
local replaced
1223

13-
str, i = str:gsub("@name", name, 1)
14-
if i == 0 then
24+
-- Name
25+
str, replaced = safe_gsub(str, "@name", name)
26+
if not replaced then
1527
error(error_str:format("@name"), 2)
1628
end
1729

18-
str, i = str:gsub("@message", message, 1)
19-
if i == 0 then
30+
-- Timestamp
31+
str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
32+
33+
-- Insert the message into the string only after finishing all other processing
34+
str, replaced = safe_gsub(str, "@message", message)
35+
if not replaced then
2036
error(error_str:format("@message"), 2)
2137
end
2238

23-
str = str:gsub("@timestamp", os.date("%H:%M:%S", os.time()), 1)
24-
2539
return str
2640
end
2741

0 commit comments

Comments
 (0)