1
1
Fork 0
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:
Sergei Zimmerman 2025-11-18 00:29:23 +03:00
parent 72dbd43882
commit 533cced249
No known key found for this signature in database
3 changed files with 22 additions and 2 deletions

View file

@ -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 } // namespace nix

View file

@ -5,6 +5,7 @@
#include "nix/util/strings-inline.hh" #include "nix/util/strings-inline.hh"
#include "nix/util/os-string.hh" #include "nix/util/os-string.hh"
#include "nix/util/error.hh" #include "nix/util/error.hh"
#include "nix/util/util.hh"
namespace nix { namespace nix {
@ -152,4 +153,14 @@ std::string optionalBracket(std::string_view prefix, std::string_view content, s
return result; 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 } // namespace nix

View file

@ -327,8 +327,11 @@ Path renderUrlPathEnsureLegal(const std::vector<std::string> & urlPath)
/* This is only really valid for UNIX. Windows has more restrictions. */ /* This is only really valid for UNIX. Windows has more restrictions. */
if (comp.contains('/')) if (comp.contains('/'))
throw BadURL("URL path component '%s' contains '/', which is not allowed in file names", comp); throw BadURL("URL path component '%s' contains '/', which is not allowed in file names", comp);
if (comp.contains(char(0))) if (comp.contains(char(0))) {
throw BadURL("URL path component '%s' contains NUL byte which is not allowed", comp); 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); return concatStringsSep("/", urlPath);