Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
ostree_hash.cc
1 #include "ostree_hash.h"
2 
3 #include <cstring> // memcmp, memcpy
4 #include <iomanip>
5 #include <sstream>
6 
7 OSTreeHash OSTreeHash::Parse(const std::string& hash) {
8  std::array<uint8_t, 32> sha256{};
9  std::string trimmed_hash = hash.substr(0, hash.find_last_not_of(" \t\n\r\f\v") + 1);
10 
11  std::istringstream refstr(trimmed_hash);
12 
13  if (trimmed_hash.size() != 64) {
14  std::cout << "HASH size: " << trimmed_hash.size() << "\n";
15  throw OSTreeCommitParseError("OSTree Hash has invalid length");
16  }
17  // sha256 is always 256 bits == 32 bytes long
18  for (size_t i = 0; i < sha256.size(); i++) {
19  std::array<char, 3> byte_string{};
20  byte_string[2] = 0;
21  uint64_t byte_holder;
22 
23  refstr.read(byte_string.data(), 2);
24  char* next_char;
25  byte_holder = strtoul(byte_string.data(), &next_char, 16);
26  if (next_char != &byte_string[2]) {
27  throw OSTreeCommitParseError("Invalid character in OSTree commit hash");
28  }
29  sha256[i] = byte_holder & 0xFF; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
30  }
31  return OSTreeHash(sha256);
32 }
33 
34 // NOLINTNEXTLINE(modernize-avoid-c-arrays, cppcoreguidelines-avoid-c-arrays, hicpp-avoid-c-arrays)
35 OSTreeHash::OSTreeHash(const uint8_t hash[32]) { std::memcpy(hash_.data(), hash, hash_.size()); }
36 
37 OSTreeHash::OSTreeHash(const std::array<uint8_t, 32>& hash) { std::memcpy(hash_.data(), hash.data(), hash.size()); }
38 
39 std::string OSTreeHash::string() const {
40  std::stringstream str_str;
41  str_str.fill('0');
42 
43  // sha256 hash is always 256 bits = 32 bytes long
44  for (size_t i = 0; i < hash_.size(); i++) {
45  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
46  str_str << std::setw(2) << std::hex << static_cast<uint64_t>(hash_[i]);
47  }
48  return str_str.str();
49 }
50 
51 bool OSTreeHash::operator<(const OSTreeHash& other) const {
52  return memcmp(hash_.data(), other.hash_.data(), hash_.size()) < 0;
53 }
54 
55 std::ostream& operator<<(std::ostream& os, const OSTreeHash& obj) {
56  os << obj.string();
57  return os;
58 }
OSTreeHash
Definition: ostree_hash.h:10
OSTreeCommitParseError
Definition: ostree_hash.h:30
OSTreeHash::Parse
static OSTreeHash Parse(const std::string &hash)
Parse an OSTree hash from a string.
Definition: ostree_hash.cc:7