aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/libexpr/primops/fetchGit.cc2
-rw-r--r--src/libexpr/primops/fetchMercurial.cc2
-rw-r--r--src/libfetchers/fetchers.cc3
-rw-r--r--src/libfetchers/git.cc8
-rw-r--r--src/libfetchers/github.cc8
-rw-r--r--src/libfetchers/mercurial.cc6
-rw-r--r--src/libfetchers/path.cc4
-rw-r--r--src/libfetchers/tarball.cc6
-rw-r--r--src/libstore/content-address.cc72
-rw-r--r--src/libstore/daemon.cc2
-rw-r--r--src/libstore/derivations.cc4
-rw-r--r--src/libstore/legacy-ssh-store.cc2
-rw-r--r--src/libstore/local-store.cc2
-rw-r--r--src/libstore/nar-info-disk-cache.cc4
-rw-r--r--src/libstore/nar-info.cc2
-rw-r--r--src/libstore/remote-store.cc2
-rw-r--r--src/libstore/store-api.cc2
-rw-r--r--src/libutil/hash.cc93
-rw-r--r--src/libutil/hash.hh17
-rw-r--r--src/libutil/parser.hh33
-rw-r--r--src/libutil/util.cc2
-rw-r--r--src/nix-prefetch-url/nix-prefetch-url.cc2
-rw-r--r--src/nix-store/nix-store.cc4
-rw-r--r--src/nix/hash.cc2
24 files changed, 181 insertions, 103 deletions
diff --git a/src/libexpr/primops/fetchGit.cc b/src/libexpr/primops/fetchGit.cc
index dd7229a3d..0421318d1 100644
--- a/src/libexpr/primops/fetchGit.cc
+++ b/src/libexpr/primops/fetchGit.cc
@@ -29,7 +29,7 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
else if (n == "ref")
ref = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "rev")
- rev = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA1);
+ rev = Hash::parseAny(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA1);
else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "submodules")
diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc
index 9bace8f89..236219a6f 100644
--- a/src/libexpr/primops/fetchMercurial.cc
+++ b/src/libexpr/primops/fetchMercurial.cc
@@ -31,7 +31,7 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar
// be both a revision or a branch/tag name.
auto value = state.forceStringNoCtx(*attr.value, *attr.pos);
if (std::regex_match(value, revRegex))
- rev = Hash(value, htSHA1);
+ rev = Hash::parseAny(value, htSHA1);
else
ref = value;
}
diff --git a/src/libfetchers/fetchers.cc b/src/libfetchers/fetchers.cc
index 9174c3de4..b1782feab 100644
--- a/src/libfetchers/fetchers.cc
+++ b/src/libfetchers/fetchers.cc
@@ -35,8 +35,7 @@ std::unique_ptr<Input> inputFromAttrs(const Attrs & attrs)
auto res = inputScheme->inputFromAttrs(attrs2);
if (res) {
if (auto narHash = maybeGetStrAttr(attrs, "narHash"))
- // FIXME: require SRI hash.
- res->narHash = newHashAllowEmpty(*narHash, {});
+ res->narHash = Hash::parseSRI(*narHash);
return res;
}
}
diff --git a/src/libfetchers/git.cc b/src/libfetchers/git.cc
index 75ce5ee8b..909bac78d 100644
--- a/src/libfetchers/git.cc
+++ b/src/libfetchers/git.cc
@@ -225,14 +225,14 @@ struct GitInput : Input
if (isLocal) {
if (!input->rev)
- input->rev = Hash(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input->ref })), htSHA1);
+ input->rev = Hash::parseAny(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input->ref })), htSHA1);
repoDir = actualUrl;
} else {
if (auto res = getCache()->lookup(store, mutableAttrs)) {
- auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1);
+ auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1);
if (!rev || rev == rev2) {
input->rev = rev2;
return makeResult(res->first, std::move(res->second));
@@ -301,7 +301,7 @@ struct GitInput : Input
}
if (!input->rev)
- input->rev = Hash(chomp(readFile(localRefFile)), htSHA1);
+ input->rev = Hash::parseAny(chomp(readFile(localRefFile)), htSHA1);
}
bool isShallow = chomp(runProgram("git", true, { "-C", repoDir, "rev-parse", "--is-shallow-repository" })) == "true";
@@ -426,7 +426,7 @@ struct GitInputScheme : InputScheme
input->ref = *ref;
}
if (auto rev = maybeGetStrAttr(attrs, "rev"))
- input->rev = Hash(*rev, htSHA1);
+ input->rev = Hash::parseAny(*rev, htSHA1);
input->shallow = maybeGetBoolAttr(attrs, "shallow").value_or(false);
diff --git a/src/libfetchers/github.cc b/src/libfetchers/github.cc
index 0bee1d6b3..449481092 100644
--- a/src/libfetchers/github.cc
+++ b/src/libfetchers/github.cc
@@ -76,7 +76,7 @@ struct GitHubInput : Input
readFile(
store->toRealPath(
downloadFile(store, url, "source", false).storePath)));
- rev = Hash(std::string { json["sha"] }, htSHA1);
+ rev = Hash::parseAny(std::string { json["sha"] }, htSHA1);
debug("HEAD revision for '%s' is %s", url, rev->gitRev());
}
@@ -140,7 +140,7 @@ struct GitHubInputScheme : InputScheme
if (path.size() == 2) {
} else if (path.size() == 3) {
if (std::regex_match(path[2], revRegex))
- input->rev = Hash(path[2], htSHA1);
+ input->rev = Hash::parseAny(path[2], htSHA1);
else if (std::regex_match(path[2], refRegex))
input->ref = path[2];
else
@@ -152,7 +152,7 @@ struct GitHubInputScheme : InputScheme
if (name == "rev") {
if (input->rev)
throw BadURL("GitHub URL '%s' contains multiple commit hashes", url.url);
- input->rev = Hash(value, htSHA1);
+ input->rev = Hash::parseAny(value, htSHA1);
}
else if (name == "ref") {
if (!std::regex_match(value, refRegex))
@@ -185,7 +185,7 @@ struct GitHubInputScheme : InputScheme
input->repo = getStrAttr(attrs, "repo");
input->ref = maybeGetStrAttr(attrs, "ref");
if (auto rev = maybeGetStrAttr(attrs, "rev"))
- input->rev = Hash(*rev, htSHA1);
+ input->rev = Hash::parseAny(*rev, htSHA1);
return input;
}
};
diff --git a/src/libfetchers/mercurial.cc b/src/libfetchers/mercurial.cc
index 2e0d4bf4d..29f2a9d5b 100644
--- a/src/libfetchers/mercurial.cc
+++ b/src/libfetchers/mercurial.cc
@@ -167,7 +167,7 @@ struct MercurialInput : Input
});
if (auto res = getCache()->lookup(store, mutableAttrs)) {
- auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1);
+ auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1);
if (!rev || rev == rev2) {
input->rev = rev2;
return makeResult(res->first, std::move(res->second));
@@ -210,7 +210,7 @@ struct MercurialInput : Input
runProgram("hg", true, { "log", "-R", cacheDir, "-r", revOrRef, "--template", "{node} {rev} {branch}" }));
assert(tokens.size() == 3);
- input->rev = Hash(tokens[0], htSHA1);
+ input->rev = Hash::parseAny(tokens[0], htSHA1);
auto revCount = std::stoull(tokens[1]);
input->ref = tokens[2];
@@ -293,7 +293,7 @@ struct MercurialInputScheme : InputScheme
input->ref = *ref;
}
if (auto rev = maybeGetStrAttr(attrs, "rev"))
- input->rev = Hash(*rev, htSHA1);
+ input->rev = Hash::parseAny(*rev, htSHA1);
return input;
}
};
diff --git a/src/libfetchers/path.cc b/src/libfetchers/path.cc
index ba2cc192e..1caab4165 100644
--- a/src/libfetchers/path.cc
+++ b/src/libfetchers/path.cc
@@ -101,7 +101,7 @@ struct PathInputScheme : InputScheme
for (auto & [name, value] : url.query)
if (name == "rev")
- input->rev = Hash(value, htSHA1);
+ input->rev = Hash::parseAny(value, htSHA1);
else if (name == "revCount") {
uint64_t revCount;
if (!string2Int(value, revCount))
@@ -129,7 +129,7 @@ struct PathInputScheme : InputScheme
for (auto & [name, value] : attrs)
if (name == "rev")
- input->rev = Hash(getStrAttr(attrs, "rev"), htSHA1);
+ input->rev = Hash::parseAny(getStrAttr(attrs, "rev"), htSHA1);
else if (name == "revCount")
input->revCount = getIntAttr(attrs, "revCount");
else if (name == "lastModified")
diff --git a/src/libfetchers/tarball.cc b/src/libfetchers/tarball.cc
index f5356f0af..6ca51269b 100644
--- a/src/libfetchers/tarball.cc
+++ b/src/libfetchers/tarball.cc
@@ -242,15 +242,13 @@ struct TarballInputScheme : InputScheme
auto hash = input->url.query.find("hash");
if (hash != input->url.query.end()) {
- // FIXME: require SRI hash.
- input->hash = Hash(hash->second);
+ input->hash = Hash::parseSRI(hash->second);
input->url.query.erase(hash);
}
auto narHash = input->url.query.find("narHash");
if (narHash != input->url.query.end()) {
- // FIXME: require SRI hash.
- input->narHash = Hash(narHash->second);
+ input->narHash = Hash::parseSRI(narHash->second);
input->url.query.erase(narHash);
}
diff --git a/src/libstore/content-address.cc b/src/libstore/content-address.cc
index 5ccb1a7b3..470cc62c9 100644
--- a/src/libstore/content-address.cc
+++ b/src/libstore/content-address.cc
@@ -1,4 +1,6 @@
+#include "args.hh"
#include "content-address.hh"
+#include "parser.hh"
namespace nix {
@@ -40,38 +42,46 @@ std::string renderContentAddress(ContentAddress ca) {
}
ContentAddress parseContentAddress(std::string_view rawCa) {
- auto prefixSeparator = rawCa.find(':');
- if (prefixSeparator != string::npos) {
- auto prefix = string(rawCa, 0, prefixSeparator);
- if (prefix == "text") {
- auto hashTypeAndHash = rawCa.substr(prefixSeparator+1, string::npos);
- Hash hash = Hash(string(hashTypeAndHash));
- if (hash.type != htSHA256) {
- throw Error("parseContentAddress: the text hash should have type SHA256");
- }
- return TextHash { hash };
- } else if (prefix == "fixed") {
- // This has to be an inverse of makeFixedOutputCA
- auto methodAndHash = rawCa.substr(prefixSeparator+1, string::npos);
- if (methodAndHash.substr(0,2) == "r:") {
- std::string_view hashRaw = methodAndHash.substr(2,string::npos);
- return FixedOutputHash {
- .method = FileIngestionMethod::Recursive,
- .hash = Hash(string(hashRaw)),
- };
- } else {
- std::string_view hashRaw = methodAndHash;
- return FixedOutputHash {
- .method = FileIngestionMethod::Flat,
- .hash = Hash(string(hashRaw)),
- };
- }
- } else {
- throw Error("parseContentAddress: format not recognized; has to be text or fixed");
- }
- } else {
- throw Error("Not a content address because it lacks an appropriate prefix");
+ auto rest = rawCa;
+
+ std::string_view prefix;
+ {
+ auto optPrefix = splitPrefixTo(rest, ':');
+ if (!optPrefix)
+ throw UsageError("not a content address because it is not in the form \"<prefix>:<rest>\": %s", rawCa);
+ prefix = *optPrefix;
}
+
+ auto parseHashType_ = [&](){
+ auto hashTypeRaw = splitPrefixTo(rest, ':');
+ if (!hashTypeRaw)
+ throw UsageError("content address hash must be in form \"<algo>:<hash>\", but found: %s", rawCa);
+ HashType hashType = parseHashType(*hashTypeRaw);
+ return std::move(hashType);
+ };
+
+ // Switch on prefix
+ if (prefix == "text") {
+ // No parsing of the method, "text" only support flat.
+ HashType hashType = parseHashType_();
+ if (hashType != htSHA256)
+ throw Error("text content address hash should use %s, but instead uses %s",
+ printHashType(htSHA256), printHashType(hashType));
+ return TextHash {
+ .hash = Hash::parseNonSRIUnprefixed(rest, std::move(hashType)),
+ };
+ } else if (prefix == "fixed") {
+ // Parse method
+ auto method = FileIngestionMethod::Flat;
+ if (splitPrefix(rest, "r:"))
+ method = FileIngestionMethod::Recursive;
+ HashType hashType = parseHashType_();
+ return FixedOutputHash {
+ .method = method,
+ .hash = Hash::parseNonSRIUnprefixed(rest, std::move(hashType)),
+ };
+ } else
+ throw UsageError("content address prefix \"%s\" is unrecognized. Recogonized prefixes are \"text\" or \"fixed\"", prefix);
};
std::optional<ContentAddress> parseContentAddressOpt(std::string_view rawCaOpt) {
diff --git a/src/libstore/daemon.cc b/src/libstore/daemon.cc
index c66b58251..cee5cd484 100644
--- a/src/libstore/daemon.cc
+++ b/src/libstore/daemon.cc
@@ -715,7 +715,7 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
auto deriver = readString(from);
if (deriver != "")
info.deriver = store->parseStorePath(deriver);
- info.narHash = Hash(readString(from), htSHA256);
+ info.narHash = Hash::parseAny(readString(from), htSHA256);
info.references = readStorePaths<StorePathSet>(*store, from);
from >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(from);
diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc
index 42551ef6b..149994e3e 100644
--- a/src/libstore/derivations.cc
+++ b/src/libstore/derivations.cc
@@ -118,7 +118,7 @@ static DerivationOutput parseDerivationOutput(const Store & store, istringstream
const HashType hashType = parseHashType(hashAlgo);
fsh = FixedOutputHash {
.method = std::move(method),
- .hash = Hash(hash, hashType),
+ .hash = Hash::parseNonSRIUnprefixed(hash, hashType),
};
}
@@ -416,7 +416,7 @@ static DerivationOutput readDerivationOutput(Source & in, const Store & store)
auto hashType = parseHashType(hashAlgo);
fsh = FixedOutputHash {
.method = std::move(method),
- .hash = Hash(hash, hashType),
+ .hash = Hash::parseNonSRIUnprefixed(hash, hashType),
};
}
diff --git a/src/libstore/legacy-ssh-store.cc b/src/libstore/legacy-ssh-store.cc
index 35caf23e7..f9d95fd2b 100644
--- a/src/libstore/legacy-ssh-store.cc
+++ b/src/libstore/legacy-ssh-store.cc
@@ -113,7 +113,7 @@ struct LegacySSHStore : public Store
if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) {
auto s = readString(conn->from);
- info->narHash = s.empty() ? std::optional<Hash>{} : Hash{s};
+ info->narHash = s.empty() ? std::optional<Hash>{} : Hash::parseAnyPrefixed(s);
info->ca = parseContentAddressOpt(readString(conn->from));
info->sigs = readStrings<StringSet>(conn->from);
}
diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc
index c9758f680..749429355 100644
--- a/src/libstore/local-store.cc
+++ b/src/libstore/local-store.cc
@@ -647,7 +647,7 @@ void LocalStore::queryPathInfoUncached(const StorePath & path,
info->id = useQueryPathInfo.getInt(0);
try {
- info->narHash = Hash(useQueryPathInfo.getStr(1));
+ info->narHash = Hash::parseAnyPrefixed(useQueryPathInfo.getStr(1));
} catch (BadHash & e) {
throw Error("in valid-path entry for '%s': %s", printStorePath(path), e.what());
}
diff --git a/src/libstore/nar-info-disk-cache.cc b/src/libstore/nar-info-disk-cache.cc
index 9ddb9957f..92da14e23 100644
--- a/src/libstore/nar-info-disk-cache.cc
+++ b/src/libstore/nar-info-disk-cache.cc
@@ -193,9 +193,9 @@ public:
narInfo->url = queryNAR.getStr(2);
narInfo->compression = queryNAR.getStr(3);
if (!queryNAR.isNull(4))
- narInfo->fileHash = Hash(queryNAR.getStr(4));
+ narInfo->fileHash = Hash::parseAnyPrefixed(queryNAR.getStr(4));
narInfo->fileSize = queryNAR.getInt(5);
- narInfo->narHash = Hash(queryNAR.getStr(6));
+ narInfo->narHash = Hash::parseAnyPrefixed(queryNAR.getStr(6));
narInfo->narSize = queryNAR.getInt(7);
for (auto & r : tokenizeString<Strings>(queryNAR.getStr(8), " "))
narInfo->references.insert(StorePath(r));
diff --git a/src/libstore/nar-info.cc b/src/libstore/nar-info.cc
index ca471463c..5812aa4ac 100644
--- a/src/libstore/nar-info.cc
+++ b/src/libstore/nar-info.cc
@@ -12,7 +12,7 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string &
auto parseHashField = [&](const string & s) {
try {
- return Hash(s);
+ return Hash::parseAnyPrefixed(s);
} catch (BadHash &) {
throw corrupt();
}
diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc
index 2b328ea77..56e5fe958 100644
--- a/src/libstore/remote-store.cc
+++ b/src/libstore/remote-store.cc
@@ -398,7 +398,7 @@ void RemoteStore::queryPathInfoUncached(const StorePath & path,
info = std::make_shared<ValidPathInfo>(StorePath(path));
auto deriver = readString(conn->from);
if (deriver != "") info->deriver = parseStorePath(deriver);
- info->narHash = Hash(readString(conn->from), htSHA256);
+ info->narHash = Hash::parseAny(readString(conn->from), htSHA256);
info->references = readStorePaths<StorePathSet>(*this, conn->from);
conn->from >> info->registrationTime >> info->narSize;
if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) {
diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc
index 0bfffbc36..54d067502 100644
--- a/src/libstore/store-api.cc
+++ b/src/libstore/store-api.cc
@@ -713,7 +713,7 @@ std::optional<ValidPathInfo> decodeValidPathInfo(const Store & store, std::istre
if (hashGiven) {
string s;
getline(str, s);
- info.narHash = Hash(s, htSHA256);
+ info.narHash = Hash::parseAny(s, htSHA256);
getline(str, s);
if (!string2Int(s, info.narSize)) throw Error("number expected");
}
diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc
index 39eb28936..4b82f191e 100644
--- a/src/libutil/hash.cc
+++ b/src/libutil/hash.cc
@@ -7,6 +7,7 @@
#include "args.hh"
#include "hash.hh"
#include "archive.hh"
+#include "parser.hh"
#include "util.hh"
#include "istringstream_nocopy.hh"
@@ -26,7 +27,7 @@ static size_t regularHashSize(HashType type) {
abort();
}
-void Hash::init()
+Hash::Hash(HashType type) : type(type)
{
hashSize = regularHashSize(type);
assert(hashSize <= maxHashSize);
@@ -131,57 +132,89 @@ std::string Hash::to_string(Base base, bool includeType) const
return s;
}
-Hash::Hash(std::string_view s, HashType type) : Hash(s, std::optional { type }) { }
-Hash::Hash(std::string_view s) : Hash(s, std::optional<HashType>{}) { }
-
-Hash::Hash(std::string_view original, std::optional<HashType> optType)
-{
+Hash Hash::parseSRI(std::string_view original) {
auto rest = original;
- size_t pos = 0;
+ // Parse the has type before the separater, if there was one.
+ auto hashRaw = splitPrefixTo(rest, '-');
+ if (!hashRaw)
+ throw BadHash("hash '%s' is not SRI", original);
+ HashType parsedType = parseHashType(*hashRaw);
+
+ return Hash(rest, parsedType, true);
+}
+
+// Mutates the string to eliminate the prefixes when found
+static std::pair<std::optional<HashType>, bool> getParsedTypeAndSRI(std::string_view & rest) {
bool isSRI = false;
// Parse the has type before the separater, if there was one.
std::optional<HashType> optParsedType;
{
- auto sep = rest.find(':');
- if (sep == std::string_view::npos) {
- sep = rest.find('-');
- if (sep != std::string_view::npos)
+ auto hashRaw = splitPrefixTo(rest, ':');
+
+ if (!hashRaw) {
+ hashRaw = splitPrefixTo(rest, '-');
+ if (hashRaw)
isSRI = true;
}
- if (sep != std::string_view::npos) {
- auto hashRaw = rest.substr(0, sep);
- optParsedType = parseHashType(hashRaw);
- rest = rest.substr(sep + 1);
- }
+ if (hashRaw)
+ optParsedType = parseHashType(*hashRaw);
}
+ return {optParsedType, isSRI};
+}
+
+Hash Hash::parseAnyPrefixed(std::string_view original)
+{
+ auto rest = original;
+ auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest);
+
// Either the string or user must provide the type, if they both do they
// must agree.
- if (!optParsedType && !optType) {
+ if (!optParsedType)
+ throw BadHash("hash '%s' does not include a type.", rest);
+
+ return Hash(rest, *optParsedType, isSRI);
+}
+
+Hash Hash::parseAny(std::string_view original, std::optional<HashType> optType)
+{
+ auto rest = original;
+ auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest);
+
+ // Either the string or user must provide the type, if they both do they
+ // must agree.
+ if (!optParsedType && !optType)
throw BadHash("hash '%s' does not include a type, nor is the type otherwise known from context.", rest);
- } else {
- this->type = optParsedType ? *optParsedType : *optType;
- if (optParsedType && optType && *optParsedType != *optType)
- throw BadHash("hash '%s' should have type '%s'", original, printHashType(*optType));
- }
+ else if (optParsedType && optType && *optParsedType != *optType)
+ throw BadHash("hash '%s' should have type '%s'", original, printHashType(*optType));
+
+ HashType hashType = optParsedType ? *optParsedType : *optType;
+ return Hash(rest, hashType, isSRI);
+}
- init();
+Hash Hash::parseNonSRIUnprefixed(std::string_view s, HashType type)
+{
+ return Hash(s, type, false);
+}
+Hash::Hash(std::string_view rest, HashType type, bool isSRI)
+ : Hash(type)
+{
if (!isSRI && rest.size() == base16Len()) {
auto parseHexDigit = [&](char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
- throw BadHash("invalid base-16 hash '%s'", original);
+ throw BadHash("invalid base-16 hash '%s'", rest);
};
for (unsigned int i = 0; i < hashSize; i++) {
hash[i] =
- parseHexDigit(rest[pos + i * 2]) << 4
- | parseHexDigit(rest[pos + i * 2 + 1]);
+ parseHexDigit(rest[i * 2]) << 4
+ | parseHexDigit(rest[i * 2 + 1]);
}
}
@@ -193,7 +226,7 @@ Hash::Hash(std::string_view original, std::optional<HashType> optType)
for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */
if (base32Chars[digit] == c) break;
if (digit >= 32)
- throw BadHash("invalid base-32 hash '%s'", original);
+ throw BadHash("invalid base-32 hash '%s'", rest);
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
@@ -203,7 +236,7 @@ Hash::Hash(std::string_view original, std::optional<HashType> optType)
hash[i + 1] |= digit >> (8 - j);
} else {
if (digit >> (8 - j))
- throw BadHash("invalid base-32 hash '%s'", original);
+ throw BadHash("invalid base-32 hash '%s'", rest);
}
}
}
@@ -211,7 +244,7 @@ Hash::Hash(std::string_view original, std::optional<HashType> optType)
else if (isSRI || rest.size() == base64Len()) {
auto d = base64Decode(rest);
if (d.size() != hashSize)
- throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", original);
+ throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", rest);
assert(hashSize);
memcpy(hash, d.data(), hashSize);
}
@@ -229,7 +262,7 @@ Hash newHashAllowEmpty(std::string hashStr, std::optional<HashType> ht)
warn("found empty hash, assuming '%s'", h.to_string(SRI, true));
return h;
} else
- return Hash(hashStr, ht);
+ return Hash::parseAny(hashStr, ht);
}
diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh
index a55295912..af11a028d 100644
--- a/src/libutil/hash.hh
+++ b/src/libutil/hash.hh
@@ -32,21 +32,26 @@ struct Hash
HashType type;
/* Create a zero-filled hash object. */
- Hash(HashType type) : type(type) { init(); };
+ Hash(HashType type);
/* Initialize the hash from a string representation, in the format
"[<type>:]<base16|base32|base64>" or "<type>-<base64>" (a
Subresource Integrity hash expression). If the 'type' argument
is not present, then the hash type must be specified in the
string. */
- Hash(std::string_view s, std::optional<HashType> type);
- // type must be provided
- Hash(std::string_view s, HashType type);
+ static Hash parseAny(std::string_view s, std::optional<HashType> type);
// hash type must be part of string
- Hash(std::string_view s);
+ static Hash parseAnyPrefixed(std::string_view s);
+ // prefix parsed separately; non SRI hash
+ static Hash parseNonSRIUnprefixed(std::string_view s, HashType type);
- void init();
+ static Hash parseSRI(std::string_view original);
+private:
+ // type must be provided, s must not include <type> prefix
+ Hash(std::string_view s, HashType type, bool isSRI);
+
+public:
/* Check whether a hash is set. */
operator bool () const { return (bool) type; }
diff --git a/src/libutil/parser.hh b/src/libutil/parser.hh
new file mode 100644
index 000000000..d19d7d8ed
--- /dev/null
+++ b/src/libutil/parser.hh
@@ -0,0 +1,33 @@
+#pragma once
+
+#include <optional>
+#include <string_view>
+
+#include "util.hh"
+
+namespace nix {
+
+// If `separator` is found, we return the portion of the string before the
+// separator, and modify the string argument to contain only the part after the
+// separator. Otherwise, wer return `std::nullopt`, and we leave the argument
+// string alone.
+static inline std::optional<std::string_view> splitPrefixTo(std::string_view & string, char separator) {
+ auto sepInstance = string.find(separator);
+
+ if (sepInstance != std::string_view::npos) {
+ auto prefix = string.substr(0, sepInstance);
+ string.remove_prefix(sepInstance+1);
+ return prefix;
+ }
+
+ return std::nullopt;
+}
+
+static inline bool splitPrefix(std::string_view & string, std::string_view prefix) {
+ bool res = hasPrefix(string, prefix);
+ if (res)
+ string.remove_prefix(prefix.length());
+ return res;
+}
+
+}
diff --git a/src/libutil/util.cc b/src/libutil/util.cc
index 1268b146a..ed43c403f 100644
--- a/src/libutil/util.cc
+++ b/src/libutil/util.cc
@@ -1433,7 +1433,7 @@ string base64Decode(std::string_view s)
char digit = decode[(unsigned char) c];
if (digit == -1)
- throw Error("invalid character in Base64 string");
+ throw Error("invalid character in Base64 string: '%c'", c);
bits += 6;
d = d << 6 | digit;
diff --git a/src/nix-prefetch-url/nix-prefetch-url.cc b/src/nix-prefetch-url/nix-prefetch-url.cc
index 22410c44c..f752e0448 100644
--- a/src/nix-prefetch-url/nix-prefetch-url.cc
+++ b/src/nix-prefetch-url/nix-prefetch-url.cc
@@ -156,7 +156,7 @@ static int _main(int argc, char * * argv)
Hash hash(ht), expectedHash(ht);
std::optional<StorePath> storePath;
if (args.size() == 2) {
- expectedHash = Hash(args[1], ht);
+ expectedHash = Hash::parseAny(args[1], ht);
const auto recursive = unpack ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat;
storePath = store->makeFixedOutputPath(recursive, expectedHash, name);
if (store->isValidPath(*storePath))
diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc
index ff04cbefc..cc3b07c31 100644
--- a/src/nix-store/nix-store.cc
+++ b/src/nix-store/nix-store.cc
@@ -208,7 +208,7 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs)
string hash = *i++;
string name = *i++;
- cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash(hash, hashAlgo), name)));
+ cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash::parseAny(hash, hashAlgo), name)));
}
@@ -950,7 +950,7 @@ static void opServe(Strings opFlags, Strings opArgs)
auto deriver = readString(in);
if (deriver != "")
info.deriver = store->parseStorePath(deriver);
- info.narHash = Hash(readString(in), htSHA256);
+ info.narHash = Hash::parseAny(readString(in), htSHA256);
info.references = readStorePaths<StorePathSet>(*store, in);
in >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(in);
diff --git a/src/nix/hash.cc b/src/nix/hash.cc
index b97c6d21f..fb0843ce2 100644
--- a/src/nix/hash.cc
+++ b/src/nix/hash.cc
@@ -103,7 +103,7 @@ struct CmdToBase : Command
void run() override
{
for (auto s : args)
- logger->stdout(Hash(s, ht).to_string(base, base == SRI));
+ logger->stdout(Hash::parseAny(s, ht).to_string(base, base == SRI));
}
};