web_bundle_builder.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_WEB_PACKAGE_WEB_BUNDLE_BUILDER_H_
  5. #define COMPONENTS_WEB_PACKAGE_WEB_BUNDLE_BUILDER_H_
  6. #include <map>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/strings/string_piece.h"
  11. #include "components/cbor/writer.h"
  12. namespace web_package {
  13. enum class BundleVersion {
  14. kB2,
  15. };
  16. // This class can be used to create a Web Bundle.
  17. class WebBundleBuilder {
  18. public:
  19. using Headers = std::vector<std::pair<std::string, std::string>>;
  20. struct ResponseLocation {
  21. // /components/cbor uses int64_t for integer types.
  22. int64_t offset;
  23. int64_t length;
  24. };
  25. explicit WebBundleBuilder(
  26. BundleVersion version = BundleVersion::kB2,
  27. bool allow_invalid_utf8_strings_for_testing = false);
  28. ~WebBundleBuilder();
  29. void AddExchange(base::StringPiece url,
  30. const Headers& response_headers,
  31. base::StringPiece payload);
  32. ResponseLocation AddResponse(const Headers& headers,
  33. base::StringPiece payload);
  34. void AddIndexEntry(base::StringPiece url,
  35. const ResponseLocation& response_location);
  36. void AddSection(base::StringPiece name, cbor::Value section);
  37. void AddAuthority(cbor::Value::MapValue authority);
  38. void AddVouchedSubset(cbor::Value::MapValue vouched_subset);
  39. void AddPrimaryURL(base::StringPiece url);
  40. std::vector<uint8_t> CreateBundle();
  41. // Creates a signed-subset structure with single subset-hashes entry,
  42. // and returns it as a CBOR bytestring.
  43. cbor::Value CreateEncodedSigned(base::StringPiece validity_url,
  44. base::StringPiece auth_sha256,
  45. int64_t date,
  46. int64_t expires,
  47. base::StringPiece url,
  48. base::StringPiece header_sha256,
  49. base::StringPiece payload_integrity_header);
  50. private:
  51. std::vector<uint8_t> CreateTopLevel();
  52. std::vector<uint8_t> Encode(const cbor::Value& value);
  53. cbor::Value GetCborValueOfURL(base::StringPiece url);
  54. int64_t EncodedLength(const cbor::Value& value);
  55. cbor::Writer::Config writer_config_;
  56. cbor::Value::ArrayValue section_lengths_;
  57. cbor::Value::ArrayValue sections_;
  58. std::map<std::string, ResponseLocation> delayed_index_;
  59. cbor::Value::ArrayValue responses_;
  60. cbor::Value::ArrayValue authorities_;
  61. cbor::Value::ArrayValue vouched_subsets_;
  62. BundleVersion version_;
  63. int64_t current_responses_offset_ = 0;
  64. };
  65. } // namespace web_package
  66. #endif // COMPONENTS_WEB_PACKAGE_WEB_BUNDLE_BUILDER_H_