From 3e4a873429d56fc24a5ae37871cd11cef90b6cdc Mon Sep 17 00:00:00 2001 From: kervala Date: Sun, 5 Nov 2017 19:07:51 +0100 Subject: [PATCH] Changed: Implement escapeArgument function --HG-- branch : develop --- code/nel/include/nel/misc/common.h | 3 +++ code/nel/src/misc/common.cpp | 35 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/code/nel/include/nel/misc/common.h b/code/nel/include/nel/misc/common.h index 4c2b38cca..180139ec0 100644 --- a/code/nel/include/nel/misc/common.h +++ b/code/nel/include/nel/misc/common.h @@ -394,6 +394,9 @@ std::string expandEnvironmentVariables(const std::string &s); bool explodeArguments(const std::string &str, std::vector &args); std::string joinArguments(const std::vector &args); +/// Escape an argument to not evaluate environment variables or special cases +std::string escapeArgument(const std::string &arg); + /// This function kills a program using his pid (on unix, it uses the kill() POSIX function) bool killProgram(uint32 pid); diff --git a/code/nel/src/misc/common.cpp b/code/nel/src/misc/common.cpp index 4d849b2d5..23b02e668 100644 --- a/code/nel/src/misc/common.cpp +++ b/code/nel/src/misc/common.cpp @@ -1247,6 +1247,41 @@ std::string joinArguments(const std::vector &args) return res; } +std::string escapeArgument(const std::string &arg) +{ +#ifdef NL_OS_WINDOWS + // we can't escape %VARIABLE% on command-line under Windows + return arg; +#else + // characters to escapce, only " and $ (to prevent a $something replaced by an environment variable) + static const char s_charsToEscape[] = "\"$"; + + std::string res; + std::string::size_type pos = 0, lastPos = 0; + + // to avoid reallocations + res.reserve(arg.size() * 2); + + while ((pos = arg.find_first_of(s_charsToEscape, lastPos)) != std::string::npos) + { + // add previous part + res += arg.substr(lastPos, pos - lastPos); + + // not already escaped + if (!pos || arg[pos - 1] != '\\') res += '\\'; + + // add escaped character + res += arg[pos]; + + lastPos = pos+1; + } + + res += arg.substr(lastPos); + + return res; +#endif +} + /* * Display the bits (with 0 and 1) composing a byte (from right to left) */