mirror of
https://github.com/NixOS/nix.git
synced 2025-11-22 18:29:36 +01:00
libutil: Add requireCString, make renderUrlPathEnsureLegal error on NUL bytes better
Same utility as in lix's change I3caf476e59dcb7899ac5a3d83dfa3fb7ceaaabf0. Co-authored-by: eldritch horrors <pennae@lix.systems>
This commit is contained in:
parent
72dbd43882
commit
533cced249
3 changed files with 22 additions and 2 deletions
|
|
@ -166,4 +166,10 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check that the string does not contain any NUL bytes and return c_str().
|
||||
* @throws Error if str contains '\0' bytes.
|
||||
*/
|
||||
const char * requireCString(const std::string & str);
|
||||
|
||||
} // namespace nix
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
#include "nix/util/strings-inline.hh"
|
||||
#include "nix/util/os-string.hh"
|
||||
#include "nix/util/error.hh"
|
||||
#include "nix/util/util.hh"
|
||||
|
||||
namespace nix {
|
||||
|
||||
|
|
@ -152,4 +153,14 @@ std::string optionalBracket(std::string_view prefix, std::string_view content, s
|
|||
return result;
|
||||
}
|
||||
|
||||
const char * requireCString(const std::string & s)
|
||||
{
|
||||
if (std::memchr(s.data(), '\0', s.size())) [[unlikely]] {
|
||||
using namespace std::string_view_literals;
|
||||
auto str = replaceStrings(s, "\0"sv, "␀"sv);
|
||||
throw Error("string '%s' with null (\\0) bytes used where it's not allowed", str);
|
||||
}
|
||||
return s.c_str();
|
||||
}
|
||||
|
||||
} // namespace nix
|
||||
|
|
|
|||
|
|
@ -327,8 +327,11 @@ Path renderUrlPathEnsureLegal(const std::vector<std::string> & urlPath)
|
|||
/* This is only really valid for UNIX. Windows has more restrictions. */
|
||||
if (comp.contains('/'))
|
||||
throw BadURL("URL path component '%s' contains '/', which is not allowed in file names", comp);
|
||||
if (comp.contains(char(0)))
|
||||
throw BadURL("URL path component '%s' contains NUL byte which is not allowed", comp);
|
||||
if (comp.contains(char(0))) {
|
||||
using namespace std::string_view_literals;
|
||||
auto str = replaceStrings(comp, "\0"sv, "␀"sv);
|
||||
throw BadURL("URL path component '%s' contains NUL byte which is not allowed", str);
|
||||
}
|
||||
}
|
||||
|
||||
return concatStringsSep("/", urlPath);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue