aboutsummaryrefslogtreecommitdiff
path: root/builtin/game/chat.lua
diff options
context:
space:
mode:
authorANAND <ClobberXD@gmail.com>2019-11-26 00:33:34 +0530
committerSmallJoker <SmallJoker@users.noreply.github.com>2019-11-25 20:03:34 +0100
commit4b6bff46e14c6215828da5ca9ad2cb79aa517a6e (patch)
tree9795891bd31b4e66395a127579cf35545322f02c /builtin/game/chat.lua
parent0b2f0914cc800bb3ae4c1f21e0c28cfdacc65f3f (diff)
downloadminetest-4b6bff46e14c6215828da5ca9ad2cb79aa517a6e.tar.gz
minetest-4b6bff46e14c6215828da5ca9ad2cb79aa517a6e.tar.bz2
minetest-4b6bff46e14c6215828da5ca9ad2cb79aa517a6e.zip
Use a safer implementation of gsub in core.chat_format_message (#9133)
This search-and-replace implementation does not use Lua pattern-matching
Diffstat (limited to 'builtin/game/chat.lua')
-rw-r--r--builtin/game/chat.lua30
1 files changed, 22 insertions, 8 deletions
diff --git a/builtin/game/chat.lua b/builtin/game/chat.lua
index 37d12c458..291e72b70 100644
--- a/builtin/game/chat.lua
+++ b/builtin/game/chat.lua
@@ -1,27 +1,41 @@
-- Minetest: builtin/game/chat.lua
+-- Helper function that implements search and replace without pattern matching
+-- Returns the string and a boolean indicating whether or not the string was modified
+local function safe_gsub(s, replace, with)
+ local i1, i2 = s:find(replace, 1, true)
+ if not i1 then
+ return s, false
+ end
+
+ return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
+end
+
--
-- Chat message formatter
--
-- Implemented in Lua to allow redefinition
function core.format_chat_message(name, message)
- local str = core.settings:get("chat_message_format")
local error_str = "Invalid chat message format - missing %s"
- local i
+ local str = core.settings:get("chat_message_format")
+ local replaced
- str, i = str:gsub("@name", name, 1)
- if i == 0 then
+ -- Name
+ str, replaced = safe_gsub(str, "@name", name)
+ if not replaced then
error(error_str:format("@name"), 2)
end
- str, i = str:gsub("@message", message, 1)
- if i == 0 then
+ -- Timestamp
+ str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
+
+ -- Insert the message into the string only after finishing all other processing
+ str, replaced = safe_gsub(str, "@message", message)
+ if not replaced then
error(error_str:format("@message"), 2)
end
- str = str:gsub("@timestamp", os.date("%H:%M:%S", os.time()), 1)
-
return str
end