web_bundle_parser.cc 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. // Copyright 2019 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. #include "components/web_package/web_bundle_parser.h"
  5. #include <algorithm>
  6. #include "base/callback.h"
  7. #include "base/callback_helpers.h"
  8. #include "base/containers/span.h"
  9. #include "base/memory/weak_ptr.h"
  10. #include "base/numerics/checked_math.h"
  11. #include "base/strings/string_number_conversions.h"
  12. #include "base/strings/string_piece.h"
  13. #include "base/strings/string_util.h"
  14. #include "base/strings/stringprintf.h"
  15. #include "components/cbor/reader.h"
  16. #include "components/web_package/input_reader.h"
  17. #include "components/web_package/signed_web_bundles/integrity_block_parser.h"
  18. #include "components/web_package/web_bundle_utils.h"
  19. #include "mojo/public/cpp/bindings/remote.h"
  20. #include "net/http/http_util.h"
  21. #include "url/url_constants.h"
  22. namespace web_package {
  23. namespace {
  24. // The number of bytes used to specify the length of the web bundle.
  25. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-trailing-length
  26. constexpr uint64_t kTrailingLengthNumBytes = 8;
  27. // The maximum size of the section-lengths CBOR item.
  28. constexpr uint64_t kMaxSectionLengthsCBORSize = 8192;
  29. // The maximum size of a metadata section allowed in this implementation.
  30. constexpr uint64_t kMaxMetadataSectionSize = 1 * 1024 * 1024;
  31. // The maximum size of the response header CBOR.
  32. constexpr uint64_t kMaxResponseHeaderLength = 512 * 1024;
  33. // The initial buffer size for reading an item from the response section.
  34. constexpr uint64_t kInitialBufferSizeForResponse = 4096;
  35. // The first byte of WebBundle format >=b2 (Array of length 5).
  36. constexpr uint8_t kBundleHeadByte = 0x85;
  37. // The first byte of WebBundle format b1 (Array of length 6).
  38. constexpr uint8_t kBundleB1HeadByte = 0x86;
  39. // CBOR of the magic string "🌐📦".
  40. // MetadataParser::ParseMagicBytes() checks the first byte (0x85) and this.
  41. //
  42. // The first 10 bytes of the web bundle format are:
  43. // 85 -- Array of length 5
  44. // 48 -- Byte string of length 8
  45. // F0 9F 8C 90 F0 9F 93 A6 -- "🌐📦" in UTF-8
  46. const uint8_t kBundleMagicBytes[] = {
  47. 0x48, 0xF0, 0x9F, 0x8C, 0x90, 0xF0, 0x9F, 0x93, 0xA6,
  48. };
  49. // CBOR of the version string "b2\0\0".
  50. // 44 -- Byte string of length 4
  51. // 62 32 00 00 -- "b2\0\0"
  52. const uint8_t kVersionB2MagicBytes[] = {
  53. 0x44, 0x62, 0x32, 0x00, 0x00,
  54. };
  55. // CBOR of the version string "b1\0\0".
  56. // 44 -- Byte string of length 4
  57. // 62 31 00 00 -- "b1\0\0"
  58. const uint8_t kVersionB1MagicBytes[] = {
  59. 0x44, 0x62, 0x31, 0x00, 0x00,
  60. };
  61. // Section names.
  62. constexpr char kCriticalSection[] = "critical";
  63. constexpr char kIndexSection[] = "index";
  64. constexpr char kPrimarySection[] = "primary";
  65. constexpr char kResponsesSection[] = "responses";
  66. constexpr char kSignaturesSection[] = "signatures";
  67. // A list of (section-name, length) pairs.
  68. using SectionLengths = std::vector<std::pair<std::string, uint64_t>>;
  69. // A map from section name to (offset, length) pair.
  70. using SectionOffsets = std::map<std::string, std::pair<uint64_t, uint64_t>>;
  71. bool IsMetadataSection(const std::string& name) {
  72. return (name == kCriticalSection || name == kIndexSection ||
  73. name == kPrimarySection || name == kSignaturesSection);
  74. }
  75. // Parses a `section-lengths` CBOR item.
  76. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-bundle-sections
  77. // section-lengths = [* (section-name: tstr, length: uint) ]
  78. absl::optional<SectionLengths> ParseSectionLengths(
  79. base::span<const uint8_t> data) {
  80. cbor::Reader::DecoderError error;
  81. absl::optional<cbor::Value> value = cbor::Reader::Read(data, &error);
  82. if (!value.has_value() || !value->is_array())
  83. return absl::nullopt;
  84. const cbor::Value::ArrayValue& array = value->GetArray();
  85. if (array.size() % 2 != 0)
  86. return absl::nullopt;
  87. SectionLengths result;
  88. for (size_t i = 0; i < array.size(); i += 2) {
  89. if (!array[i].is_string() || !array[i + 1].is_unsigned())
  90. return absl::nullopt;
  91. result.emplace_back(array[i].GetString(), array[i + 1].GetUnsigned());
  92. }
  93. return result;
  94. }
  95. struct ParsedHeaders {
  96. base::flat_map<std::string, std::string> headers;
  97. base::flat_map<std::string, std::string> pseudos;
  98. };
  99. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-responses
  100. // headers = {* bstr => bstr}
  101. absl::optional<ParsedHeaders> ConvertCBORValueToHeaders(
  102. const cbor::Value& headers_value) {
  103. // |headers_value| of headers must be a map.
  104. if (!headers_value.is_map())
  105. return absl::nullopt;
  106. ParsedHeaders result;
  107. for (const auto& item : headers_value.GetMap()) {
  108. if (!item.first.is_bytestring() || !item.second.is_bytestring())
  109. return absl::nullopt;
  110. base::StringPiece name = item.first.GetBytestringAsString();
  111. base::StringPiece value = item.second.GetBytestringAsString();
  112. // If name contains any upper-case or non-ASCII characters, return an error.
  113. // This matches the requirement in Section 8.1.2 of [RFC7540].
  114. if (!base::IsStringASCII(name) ||
  115. std::any_of(name.begin(), name.end(), base::IsAsciiUpper<char>))
  116. return absl::nullopt;
  117. if (!name.empty() && name[0] == ':') {
  118. // pseudos[name] must not exist, because CBOR maps cannot contain
  119. // duplicate keys. This is ensured by cbor::Reader.
  120. DCHECK(!result.pseudos.contains(name));
  121. result.pseudos.insert(
  122. std::make_pair(std::string(name), std::string(value)));
  123. continue;
  124. }
  125. // Both name and value must be valid.
  126. if (!net::HttpUtil::IsValidHeaderName(name) ||
  127. !net::HttpUtil::IsValidHeaderValue(value))
  128. return absl::nullopt;
  129. // headers[name] must not exist, because CBOR maps cannot contain duplicate
  130. // keys. This is ensured by cbor::Reader.
  131. DCHECK(!result.headers.contains(name));
  132. result.headers.insert(
  133. std::make_pair(std::string(name), std::string(value)));
  134. }
  135. return result;
  136. }
  137. GURL ParseExchangeURL(base::StringPiece str, const GURL& base_url) {
  138. DCHECK(base_url.is_empty() || base_url.is_valid());
  139. if (!base::IsStringUTF8(str))
  140. return GURL();
  141. GURL url = base_url.is_valid() ? base_url.Resolve(str) : GURL(str);
  142. if (!url.is_valid())
  143. return GURL();
  144. // Exchange URL must not have a fragment or credentials.
  145. if (url.has_ref() || url.has_username() || url.has_password())
  146. return GURL();
  147. return url;
  148. }
  149. } // namespace
  150. // A parser for bundle's metadata. This class owns itself and will self destruct
  151. // after calling the ParseMetadataCallback.
  152. class WebBundleParser::MetadataParser
  153. : WebBundleParser::SharedBundleDataSource::Observer {
  154. public:
  155. MetadataParser(scoped_refptr<SharedBundleDataSource> data_source,
  156. const GURL& base_url,
  157. ParseMetadataCallback callback)
  158. : data_source_(data_source),
  159. base_url_(base_url),
  160. callback_(std::move(callback)) {
  161. DCHECK(base_url_.is_empty() || base_url_.is_valid());
  162. data_source_->AddObserver(this);
  163. }
  164. MetadataParser(const MetadataParser&) = delete;
  165. MetadataParser& operator=(const MetadataParser&) = delete;
  166. ~MetadataParser() override { data_source_->RemoveObserver(this); }
  167. // Starts parsing of the web bundle. If the data source is backed by a
  168. // random-access, read the trailing `length` field at the end of the web
  169. // bundle file and start from that offset.
  170. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-trailing-length
  171. void Start() {
  172. data_source_->IsRandomAccessContext(base::BindOnce(
  173. &MetadataParser::OnIsRandomAccessContext, weak_factory_.GetWeakPtr()));
  174. }
  175. // Starts parsing of the web bundle at the specified offset, ignoring the
  176. // `length` field of the web bundle.
  177. void StartAtOffset(const uint64_t offset) { ReadMagicBytes(offset); }
  178. private:
  179. void OnIsRandomAccessContext(const bool is_random_access_context) {
  180. if (!is_random_access_context) {
  181. // If the data source is not backed by a random-access context, assume
  182. // that the web bundle starts at the very first byte of the file and
  183. // ignore the trailing length field of the bundle.
  184. ReadMagicBytes(0);
  185. } else {
  186. // Otherwise read the length of the file (not the web bundle).
  187. data_source_->Length(base::BindOnce(&MetadataParser::OnFileLengthRead,
  188. weak_factory_.GetWeakPtr()));
  189. }
  190. }
  191. void OnFileLengthRead(const int64_t file_length) {
  192. if (file_length < 0) {
  193. RunErrorCallbackAndDestroy("Error reading bundle length.");
  194. return;
  195. }
  196. if (static_cast<uint64_t>(file_length) < kTrailingLengthNumBytes) {
  197. RunErrorCallbackAndDestroy("Error reading bundle length.");
  198. return;
  199. }
  200. // Read the last 8 bytes of the file that correspond to the trailing length
  201. // field of the web bundle.
  202. data_source_->Read(file_length - kTrailingLengthNumBytes,
  203. kTrailingLengthNumBytes,
  204. base::BindOnce(&MetadataParser::ParseWebBundleLength,
  205. weak_factory_.GetWeakPtr(), file_length));
  206. }
  207. void ParseWebBundleLength(const uint64_t file_length,
  208. const absl::optional<std::vector<uint8_t>>& data) {
  209. if (!data.has_value()) {
  210. RunErrorCallbackAndDestroy("Error reading bundle length.");
  211. return;
  212. }
  213. // "Recipients loading the bundle in a random-access context SHOULD start by
  214. // reading the last 8 bytes and seeking backwards by that many bytes to find
  215. // the start of the bundle, instead of assuming that the start of the file
  216. // is also the start of the bundle. This allows the bundle to be appended to
  217. // another format such as a generic self-extracting executable."
  218. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#section-4.1.1-3
  219. InputReader input(*data);
  220. uint64_t web_bundle_length;
  221. if (!input.ReadBigEndian(&web_bundle_length)) {
  222. RunErrorCallbackAndDestroy("Error reading bundle length.");
  223. return;
  224. }
  225. if (web_bundle_length > file_length) {
  226. RunErrorCallbackAndDestroy("Invalid bundle length.");
  227. return;
  228. }
  229. const uint64_t web_bundle_offset = file_length - web_bundle_length;
  230. ReadMagicBytes(web_bundle_offset);
  231. }
  232. void ReadMagicBytes(const uint64_t offset_in_stream) {
  233. // First, we will parse the CBOR header of the top level array (1-byte),
  234. // `magic`, `version`, and the CBOR header of `section-lengths`.
  235. const uint64_t length = 1 + sizeof(kBundleMagicBytes) +
  236. sizeof(kVersionB2MagicBytes) +
  237. kMaxCBORItemHeaderSize;
  238. data_source_->Read(
  239. offset_in_stream, length,
  240. base::BindOnce(&MetadataParser::ParseMagicBytes,
  241. weak_factory_.GetWeakPtr(), offset_in_stream));
  242. }
  243. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-top-level-structure
  244. void ParseMagicBytes(uint64_t offset_in_stream,
  245. const absl::optional<std::vector<uint8_t>>& data) {
  246. if (!data) {
  247. RunErrorCallbackAndDestroy("Error reading bundle magic bytes.");
  248. return;
  249. }
  250. InputReader input(*data);
  251. // Read the first byte denoting a CBOR array size. It must be equal to 0x85
  252. // (5).
  253. const auto array_size = input.ReadByte();
  254. if (!array_size) {
  255. RunErrorCallbackAndDestroy("Missing CBOR array size byte.");
  256. return;
  257. }
  258. // Let kBundleB1HeadByte pass this check, to report custom error message for
  259. // b1 bundles.
  260. if (*array_size != kBundleHeadByte && *array_size != kBundleB1HeadByte) {
  261. RunErrorCallbackAndDestroy("Wrong magic bytes.");
  262. return;
  263. }
  264. // Check the magic bytes "48 F0 9F 8C 90 F0 9F 93 A6".
  265. const auto magic = input.ReadBytes(sizeof(kBundleMagicBytes));
  266. if (!magic ||
  267. !std::equal(magic->begin(), magic->end(), std::begin(kBundleMagicBytes),
  268. std::end(kBundleMagicBytes))) {
  269. RunErrorCallbackAndDestroy("Wrong magic bytes.");
  270. return;
  271. }
  272. // Let version be the result of reading 5 bytes from stream.
  273. const auto version = input.ReadBytes(sizeof(kVersionB2MagicBytes));
  274. if (!version) {
  275. RunErrorCallbackAndDestroy("Cannot read version bytes.");
  276. return;
  277. }
  278. if (!std::equal(version->begin(), version->end(),
  279. std::begin(kVersionB2MagicBytes),
  280. std::end(kVersionB2MagicBytes))) {
  281. const char* message;
  282. if (std::equal(version->begin(), version->end(),
  283. std::begin(kVersionB1MagicBytes),
  284. std::end(kVersionB1MagicBytes))) {
  285. message =
  286. "Bundle format version is 'b1' which is no longer supported."
  287. " Currently supported version is: 'b2'";
  288. } else {
  289. message =
  290. "Version error: bundle format does not correspond to the specifed "
  291. "version. Currently supported version is: 'b2'";
  292. }
  293. RunErrorCallbackAndDestroy(message,
  294. mojom::BundleParseErrorType::kVersionError);
  295. return;
  296. }
  297. if (*array_size != kBundleHeadByte) {
  298. RunErrorCallbackAndDestroy(
  299. "Wrong CBOR array size of the top-level structure");
  300. return;
  301. }
  302. const auto section_lengths_length =
  303. input.ReadCBORHeader(CBORType::kByteString);
  304. if (!section_lengths_length) {
  305. RunErrorCallbackAndDestroy("Cannot parse the size of section-lengths.");
  306. return;
  307. }
  308. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-top-level-structure
  309. // "The section-lengths array is embedded in a byte string to facilitate
  310. // reading it from a network. This byte string MUST be less than 8192
  311. // (8*1024) bytes long, and parsers MUST NOT load any data from a
  312. // section-lengths item longer than this."
  313. if (*section_lengths_length >= kMaxSectionLengthsCBORSize) {
  314. RunErrorCallbackAndDestroy(
  315. "The section-lengths CBOR must be smaller than 8192 bytes.");
  316. return;
  317. }
  318. // In the next step, we will parse the content of `section-lengths`,
  319. // and the CBOR header of `sections`.
  320. const uint64_t length = *section_lengths_length + kMaxCBORItemHeaderSize;
  321. offset_in_stream += input.CurrentOffset();
  322. data_source_->Read(
  323. offset_in_stream, length,
  324. base::BindOnce(&MetadataParser::ParseBundleHeader,
  325. weak_factory_.GetWeakPtr(), offset_in_stream,
  326. *section_lengths_length));
  327. }
  328. void ParseBundleHeader(uint64_t offset_in_stream,
  329. uint64_t section_lengths_length,
  330. const absl::optional<std::vector<uint8_t>>& data) {
  331. if (!data) {
  332. RunErrorCallbackAndDestroy("Error reading bundle header.");
  333. return;
  334. }
  335. InputReader input(*data);
  336. // webbundle = [
  337. // magic: h'F0 9F 8C 90 F0 9F 93 A6',
  338. // version: bytes .size 4,
  339. // section-lengths: bytes .cbor section-lengths, <==== here
  340. // sections: [* any ],
  341. // length: bytes .size 8, ; Big-endian number of bytes in the bundle.
  342. // ]
  343. const auto section_lengths_bytes = input.ReadBytes(section_lengths_length);
  344. if (!section_lengths_bytes) {
  345. RunErrorCallbackAndDestroy("Cannot read section-lengths.");
  346. return;
  347. }
  348. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-bundle-sections
  349. // section-lengths = [* (section-name: tstr, length: uint) ]
  350. const auto section_lengths = ParseSectionLengths(*section_lengths_bytes);
  351. if (!section_lengths) {
  352. RunErrorCallbackAndDestroy("Cannot parse section-lengths.");
  353. return;
  354. }
  355. // webbundle = [
  356. // magic: h'F0 9F 8C 90 F0 9F 93 A6',
  357. // version: bytes .size 4,
  358. // section-lengths: bytes .cbor section-lengths,
  359. // sections: [* any ], <==== here
  360. // length: bytes .size 8, ; Big-endian number of bytes in the bundle.
  361. // ]
  362. const auto num_sections = input.ReadCBORHeader(CBORType::kArray);
  363. if (!num_sections) {
  364. RunErrorCallbackAndDestroy("Cannot parse the number of sections.");
  365. return;
  366. }
  367. // "The sections array contains the sections' content. The length of this
  368. // array MUST be exactly half the length of the section-lengths array, and
  369. // parsers MUST NOT load any data if that is not the case."
  370. if (*num_sections != section_lengths->size()) {
  371. RunErrorCallbackAndDestroy("Unexpected number of sections.");
  372. return;
  373. }
  374. const uint64_t sections_start = offset_in_stream + input.CurrentOffset();
  375. uint64_t current_offset = sections_start;
  376. // Convert |section_lengths| to |section_offsets_|.
  377. for (const auto& pair : *section_lengths) {
  378. const std::string& name = pair.first;
  379. const uint64_t length = pair.second;
  380. bool added = section_offsets_
  381. .insert(std::make_pair(
  382. name, std::make_pair(current_offset, length)))
  383. .second;
  384. if (!added) {
  385. RunErrorCallbackAndDestroy("Duplicated section.");
  386. return;
  387. }
  388. if (!base::CheckAdd(current_offset, length)
  389. .AssignIfValid(&current_offset)) {
  390. RunErrorCallbackAndDestroy(
  391. "Integer overflow calculating section offsets.");
  392. return;
  393. }
  394. }
  395. // "The "responses" section MUST appear after the other three sections
  396. // defined here, and parsers MUST NOT load any data if that is not the
  397. // case."
  398. if (section_lengths->empty() ||
  399. section_lengths->back().first != kResponsesSection) {
  400. RunErrorCallbackAndDestroy(
  401. "Responses section is not the last in section-lengths.");
  402. return;
  403. }
  404. // Initialize |metadata_|.
  405. metadata_ = mojom::BundleMetadata::New();
  406. metadata_->version = mojom::BundleFormatVersion::kB2;
  407. ReadMetadataSections(section_offsets_.begin());
  408. }
  409. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-bundle-sections
  410. void ReadMetadataSections(SectionOffsets::const_iterator section_iter) {
  411. for (; section_iter != section_offsets_.end(); ++section_iter) {
  412. const auto& name = section_iter->first;
  413. if (!IsMetadataSection(name))
  414. continue;
  415. const uint64_t section_offset = section_iter->second.first;
  416. const uint64_t section_length = section_iter->second.second;
  417. if (section_length > kMaxMetadataSectionSize) {
  418. RunErrorCallbackAndDestroy(
  419. "Metadata sections larger than 1MB are not supported.");
  420. return;
  421. }
  422. data_source_->Read(section_offset, section_length,
  423. base::BindOnce(&MetadataParser::ParseMetadataSection,
  424. weak_factory_.GetWeakPtr(),
  425. section_iter, section_length));
  426. // This loop will be resumed by ParseMetadataSection().
  427. return;
  428. }
  429. // The bundle MUST contain the "index" and "responses" sections.
  430. if (metadata_->requests.empty()) {
  431. RunErrorCallbackAndDestroy("Bundle must have an index section.");
  432. return;
  433. }
  434. RunSuccessCallbackAndDestroy();
  435. }
  436. void ParseMetadataSection(SectionOffsets::const_iterator section_iter,
  437. uint64_t expected_data_length,
  438. const absl::optional<std::vector<uint8_t>>& data) {
  439. if (!data || data->size() != expected_data_length) {
  440. RunErrorCallbackAndDestroy("Error reading section content.");
  441. return;
  442. }
  443. // Parse the section contents as a CBOR item.
  444. cbor::Reader::DecoderError error;
  445. absl::optional<cbor::Value> section_value =
  446. cbor::Reader::Read(*data, &error);
  447. if (!section_value) {
  448. RunErrorCallbackAndDestroy(
  449. std::string("Error parsing section contents as CBOR: ") +
  450. cbor::Reader::ErrorCodeToString(error));
  451. return;
  452. }
  453. const auto& name = section_iter->first;
  454. // Note: Parse*Section() delete |this| on failure.
  455. if (name == kIndexSection) {
  456. if (!ParseIndexSection(*section_value))
  457. return;
  458. } else if (name == kSignaturesSection) {
  459. if (!ParseSignaturesSection(*section_value))
  460. return;
  461. } else if (name == kCriticalSection) {
  462. if (!ParseCriticalSection(*section_value))
  463. return;
  464. } else if (name == kPrimarySection) {
  465. if (!ParsePrimarySection(*section_value))
  466. return;
  467. } else {
  468. NOTREACHED();
  469. }
  470. // Read the next metadata section.
  471. ReadMetadataSections(++section_iter);
  472. }
  473. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-the-index-section
  474. // The index section has the following structure:
  475. // index = {* whatwg-url => [ location-in-responses ] }
  476. // location-in-responses = (offset: uint, length: uint)
  477. bool ParseIndexSection(const cbor::Value& section_value) {
  478. // |section_value| of index section must be a map.
  479. if (!section_value.is_map()) {
  480. RunErrorCallbackAndDestroy("Index section must be a map.");
  481. return false;
  482. }
  483. base::flat_map<GURL, mojom::BundleResponseLocationPtr> requests;
  484. auto responses_section = section_offsets_.find(kResponsesSection);
  485. DCHECK(responses_section != section_offsets_.end());
  486. const uint64_t responses_section_offset = responses_section->second.first;
  487. const uint64_t responses_section_length = responses_section->second.second;
  488. // For each (url, responses) entry in the index map.
  489. for (const auto& item : section_value.GetMap()) {
  490. if (!item.first.is_string()) {
  491. RunErrorCallbackAndDestroy("Index section: key must be a string.");
  492. return false;
  493. }
  494. if (!item.second.is_array()) {
  495. RunErrorCallbackAndDestroy("Index section: value must be an array.");
  496. return false;
  497. }
  498. const std::string& url = item.first.GetString();
  499. const cbor::Value::ArrayValue& responses_array = item.second.GetArray();
  500. GURL parsed_url = ParseExchangeURL(url, base_url_);
  501. if (!parsed_url.is_valid()) {
  502. std::string message = base::StringPrintf(
  503. "Index section: exchange URL \"%s\" is not valid.", url.c_str());
  504. if (base_url_.is_empty())
  505. message += " (Relative URLs are not allowed in this context.)";
  506. RunErrorCallbackAndDestroy(message);
  507. return false;
  508. }
  509. if (responses_array.size() != 2) {
  510. RunErrorCallbackAndDestroy(
  511. "Index section: the size of a response array per URL should be "
  512. "exactly 2.");
  513. return false;
  514. }
  515. if (!responses_array[0].is_unsigned() ||
  516. !responses_array[1].is_unsigned()) {
  517. RunErrorCallbackAndDestroy(
  518. "Index section: offset and length values must be unsigned.");
  519. return false;
  520. }
  521. uint64_t offset = responses_array[0].GetUnsigned();
  522. uint64_t length = responses_array[1].GetUnsigned();
  523. uint64_t response_end;
  524. if (!base::CheckAdd(offset, length).AssignIfValid(&response_end) ||
  525. response_end > responses_section_length) {
  526. RunErrorCallbackAndDestroy("Index section: response out of range.");
  527. return false;
  528. }
  529. uint64_t offset_within_stream = responses_section_offset + offset;
  530. requests.insert(std::make_pair(
  531. parsed_url,
  532. mojom::BundleResponseLocation::New(offset_within_stream, length)));
  533. }
  534. metadata_->requests = std::move(requests);
  535. return true;
  536. }
  537. // https://github.com/WICG/webpackage/blob/main/extensions/signatures-section.md
  538. // signatures = [
  539. // authorities: [*authority],
  540. // vouched-subsets: [*{
  541. // authority: index-in-authorities,
  542. // sig: bstr,
  543. // signed: bstr ; Expected to hold a signed-subset item.
  544. // }],
  545. // ]
  546. // authority = augmented-certificate
  547. // index-in-authorities = uint
  548. //
  549. // signed-subset = {
  550. // validity-url: whatwg-url,
  551. // auth-sha256: bstr,
  552. // date: uint,
  553. // expires: uint,
  554. // subset-hashes: {+
  555. // whatwg-url => [variants-value, +resource-integrity]
  556. // },
  557. // * tstr => any,
  558. // }
  559. // resource-integrity = (
  560. // header-sha256: bstr,
  561. // payload-integrity-header: tstr
  562. // )
  563. bool ParseSignaturesSection(const cbor::Value& section_value) {
  564. if (!section_value.is_array() || section_value.GetArray().size() != 2) {
  565. RunErrorCallbackAndDestroy(
  566. "Signatures section must be an array of size 2.");
  567. return false;
  568. }
  569. const cbor::Value& authorities_value = section_value.GetArray()[0];
  570. const cbor::Value& vouched_subsets_value = section_value.GetArray()[1];
  571. if (!authorities_value.is_array()) {
  572. RunErrorCallbackAndDestroy("Authorities must be an array.");
  573. return false;
  574. }
  575. std::vector<mojom::AugmentedCertificatePtr> authorities;
  576. for (const cbor::Value& value : authorities_value.GetArray()) {
  577. // ParseAugmentedCertificate deletes |this| on failure.
  578. auto authority = ParseAugmentedCertificate(value);
  579. if (!authority)
  580. return false;
  581. authorities.push_back(std::move(authority));
  582. }
  583. if (!vouched_subsets_value.is_array()) {
  584. RunErrorCallbackAndDestroy("Vouched-subsets must be an array.");
  585. return false;
  586. }
  587. std::vector<mojom::VouchedSubsetPtr> vouched_subsets;
  588. for (const cbor::Value& value : vouched_subsets_value.GetArray()) {
  589. if (!value.is_map()) {
  590. RunErrorCallbackAndDestroy(
  591. "An element of vouched-subsets must be a map.");
  592. return false;
  593. }
  594. const cbor::Value::MapValue& item_map = value.GetMap();
  595. auto* authority_value = Lookup(item_map, "authority");
  596. if (!authority_value || !authority_value->is_unsigned()) {
  597. RunErrorCallbackAndDestroy(
  598. "authority is not found in vouched-subsets map, or not an "
  599. "unsigned.");
  600. return false;
  601. }
  602. int64_t authority = authority_value->GetUnsigned();
  603. auto* sig_value = Lookup(item_map, "sig");
  604. if (!sig_value || !sig_value->is_bytestring()) {
  605. RunErrorCallbackAndDestroy(
  606. "sig is not found in vouched-subsets map, or not a bytestring.");
  607. return false;
  608. }
  609. const cbor::Value::BinaryValue& sig = sig_value->GetBytestring();
  610. auto* signed_value = Lookup(item_map, "signed");
  611. if (!signed_value || !signed_value->is_bytestring()) {
  612. RunErrorCallbackAndDestroy(
  613. "signed is not found in vouched-subsets map, or not a bytestring.");
  614. return false;
  615. }
  616. const cbor::Value::BinaryValue& raw_signed =
  617. signed_value->GetBytestring();
  618. // ParseSignedSubset deletes |this| on failure.
  619. auto parsed_signed = ParseSignedSubset(raw_signed);
  620. if (!parsed_signed)
  621. return false;
  622. vouched_subsets.push_back(mojom::VouchedSubset::New(
  623. authority, sig, raw_signed, std::move(parsed_signed)));
  624. }
  625. metadata_->authorities = std::move(authorities);
  626. metadata_->vouched_subsets = std::move(vouched_subsets);
  627. return true;
  628. }
  629. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#critical-section
  630. // critical = [*tstr]
  631. bool ParseCriticalSection(const cbor::Value& section_value) {
  632. if (!section_value.is_array()) {
  633. RunErrorCallbackAndDestroy("Critical section must be an array.");
  634. return false;
  635. }
  636. // "If the client has not implemented a section named by one of the items in
  637. // this list, the client MUST fail to parse the bundle as a whole."
  638. for (const cbor::Value& elem : section_value.GetArray()) {
  639. if (!elem.is_string()) {
  640. RunErrorCallbackAndDestroy(
  641. "Non-string element in the critical section.");
  642. return false;
  643. }
  644. const auto& section_name = elem.GetString();
  645. if (!IsMetadataSection(section_name) &&
  646. section_name != kResponsesSection) {
  647. RunErrorCallbackAndDestroy("Unknown critical section.");
  648. return false;
  649. }
  650. }
  651. return true;
  652. }
  653. // https://github.com/WICG/webpackage/blob/main/extensions/primary-section.md
  654. // primary = whatwg-url
  655. bool ParsePrimarySection(const cbor::Value& section_value) {
  656. if (!section_value.is_string()) {
  657. RunErrorCallbackAndDestroy("Primary section must be a string.");
  658. return false;
  659. }
  660. GURL parsed_url = ParseExchangeURL(section_value.GetString(), base_url_);
  661. if (!parsed_url.is_valid()) {
  662. RunErrorCallbackAndDestroy("Primary URL is not a valid exchange URL.");
  663. return false;
  664. }
  665. metadata_->primary_url = std::move(parsed_url);
  666. return true;
  667. }
  668. // https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html#cert-chain-format
  669. mojom::AugmentedCertificatePtr ParseAugmentedCertificate(
  670. const cbor::Value& value) {
  671. if (!value.is_map()) {
  672. RunErrorCallbackAndDestroy("augmented-certificate must be a map.");
  673. return nullptr;
  674. }
  675. const cbor::Value::MapValue& item_map = value.GetMap();
  676. mojom::AugmentedCertificatePtr authority =
  677. mojom::AugmentedCertificate::New();
  678. auto* cert_value = Lookup(item_map, "cert");
  679. if (!cert_value || !cert_value->is_bytestring()) {
  680. RunErrorCallbackAndDestroy(
  681. "cert is not found in augmented-certificate, or not a bytestring.");
  682. return nullptr;
  683. }
  684. authority->cert = cert_value->GetBytestring();
  685. if (auto* ocsp_value = Lookup(item_map, "ocsp")) {
  686. if (!ocsp_value->is_bytestring()) {
  687. RunErrorCallbackAndDestroy("ocsp is not a bytestring.");
  688. return nullptr;
  689. }
  690. authority->ocsp = ocsp_value->GetBytestring();
  691. }
  692. if (auto* sct_value = Lookup(item_map, "sct")) {
  693. if (!sct_value->is_bytestring()) {
  694. RunErrorCallbackAndDestroy("sct is not a bytestring.");
  695. return nullptr;
  696. }
  697. authority->sct = sct_value->GetBytestring();
  698. }
  699. return authority;
  700. }
  701. // https://github.com/WICG/webpackage/blob/main/extensions/signatures-section.md
  702. mojom::SignedSubsetPtr ParseSignedSubset(
  703. const cbor::Value::BinaryValue& signed_bytes) {
  704. // Parse |signed_bytes| as a CBOR item.
  705. cbor::Reader::DecoderError error;
  706. absl::optional<cbor::Value> value =
  707. cbor::Reader::Read(signed_bytes, &error);
  708. if (!value) {
  709. RunErrorCallbackAndDestroy(
  710. std::string("Error parsing signed bytes as CBOR: ") +
  711. cbor::Reader::ErrorCodeToString(error));
  712. return nullptr;
  713. }
  714. if (!value->is_map()) {
  715. RunErrorCallbackAndDestroy("signed-subset must be a CBOR map");
  716. return nullptr;
  717. }
  718. const cbor::Value::MapValue& value_map = value->GetMap();
  719. auto* validity_url_value = Lookup(value_map, "validity-url");
  720. if (!validity_url_value || !validity_url_value->is_string()) {
  721. RunErrorCallbackAndDestroy(
  722. "validity-url is not found in signed-subset, or not a string.");
  723. return nullptr;
  724. }
  725. // TODO(crbug.com/966753): Revisit this once requirements for validity URL
  726. // are speced.
  727. // TODO(crbug.com/1247939): Consider supporting relative validity URL.
  728. GURL validity_url(validity_url_value->GetString());
  729. if (!validity_url.is_valid()) {
  730. RunErrorCallbackAndDestroy("Cannot parse validity-url.");
  731. return nullptr;
  732. }
  733. auto* auth_sha256_value = Lookup(value_map, "auth-sha256");
  734. if (!auth_sha256_value || !auth_sha256_value->is_bytestring()) {
  735. RunErrorCallbackAndDestroy(
  736. "auth-sha256 is not found in signed-subset, or not a bytestring.");
  737. return nullptr;
  738. }
  739. auto auth_sha256 = auth_sha256_value->GetBytestring();
  740. auto* date_value = Lookup(value_map, "date");
  741. if (!date_value || !date_value->is_unsigned()) {
  742. RunErrorCallbackAndDestroy(
  743. "date is not found in signed-subset, or not an unsigned.");
  744. return nullptr;
  745. }
  746. auto date = date_value->GetUnsigned();
  747. auto* expires_value = Lookup(value_map, "expires");
  748. if (!expires_value || !expires_value->is_unsigned()) {
  749. RunErrorCallbackAndDestroy(
  750. "expires is not found in signed-subset, or not an unsigned.");
  751. return nullptr;
  752. }
  753. auto expires = expires_value->GetUnsigned();
  754. auto* subset_hashes_value = Lookup(value_map, "subset-hashes");
  755. if (!subset_hashes_value || !subset_hashes_value->is_map()) {
  756. RunErrorCallbackAndDestroy(
  757. "subset-hashes is not found in signed-subset, or not a map.");
  758. return nullptr;
  759. }
  760. base::flat_map<GURL, mojom::SubsetHashesValuePtr> subset_hashes;
  761. for (const auto& item : subset_hashes_value->GetMap()) {
  762. if (!item.first.is_string()) {
  763. RunErrorCallbackAndDestroy("subset-hashes: key must be a string.");
  764. return nullptr;
  765. }
  766. if (!item.second.is_array()) {
  767. RunErrorCallbackAndDestroy("subset-hashes: value must be an array.");
  768. return nullptr;
  769. }
  770. const std::string& url = item.first.GetString();
  771. const cbor::Value::ArrayValue& value_array = item.second.GetArray();
  772. // TODO(crbug.com/1247939): Consider supporting relative URL in the
  773. // signature section.
  774. GURL parsed_url = ParseExchangeURL(url, /*base_url=*/GURL());
  775. if (!parsed_url.is_valid()) {
  776. RunErrorCallbackAndDestroy("subset-hashes: exchange URL is not valid.");
  777. return nullptr;
  778. }
  779. if (value_array.empty() || !value_array[0].is_bytestring()) {
  780. RunErrorCallbackAndDestroy(
  781. "subset-hashes: the first element of array must be a bytestring.");
  782. return nullptr;
  783. }
  784. base::StringPiece variants_value = value_array[0].GetBytestringAsString();
  785. if (value_array.size() < 3 || value_array.size() % 2 != 1) {
  786. RunErrorCallbackAndDestroy(
  787. "subset-hashes: unexpected size of value array.");
  788. return nullptr;
  789. }
  790. std::vector<mojom::ResourceIntegrityPtr> resource_integrities;
  791. for (size_t i = 1; i < value_array.size(); i += 2) {
  792. if (!value_array[i].is_bytestring()) {
  793. RunErrorCallbackAndDestroy(
  794. "subset-hashes: header-sha256 must be a byte string.");
  795. return nullptr;
  796. }
  797. if (!value_array[i + 1].is_string()) {
  798. RunErrorCallbackAndDestroy(
  799. "subset-hashes: payload-integrity-header must be a string.");
  800. return nullptr;
  801. }
  802. resource_integrities.push_back(mojom::ResourceIntegrity::New(
  803. value_array[i].GetBytestring(), value_array[i + 1].GetString()));
  804. }
  805. subset_hashes.insert(std::make_pair(
  806. parsed_url,
  807. mojom::SubsetHashesValue::New(std::string(variants_value),
  808. std::move(resource_integrities))));
  809. }
  810. return mojom::SignedSubset::New(validity_url, auth_sha256, date, expires,
  811. std::move(subset_hashes));
  812. }
  813. // Returns nullptr if |key| is not in |map|.
  814. const cbor::Value* Lookup(const cbor::Value::MapValue& map, const char* key) {
  815. auto iter = map.find(cbor::Value(key));
  816. if (iter == map.end())
  817. return nullptr;
  818. return &iter->second;
  819. }
  820. void RunSuccessCallbackAndDestroy() {
  821. std::move(callback_).Run(std::move(metadata_), nullptr);
  822. delete this;
  823. }
  824. void RunErrorCallbackAndDestroy(
  825. const std::string& message,
  826. mojom::BundleParseErrorType error_type =
  827. mojom::BundleParseErrorType::kFormatError) {
  828. DLOG(ERROR) << "Parsing web bundle error: " << message;
  829. mojom::BundleMetadataParseErrorPtr err =
  830. mojom::BundleMetadataParseError::New(error_type, message);
  831. std::move(callback_).Run(nullptr, std::move(err));
  832. delete this;
  833. }
  834. // Implements SharedBundleDataSource::Observer.
  835. void OnDisconnect() override {
  836. RunErrorCallbackAndDestroy("Data source disconnected.");
  837. }
  838. scoped_refptr<SharedBundleDataSource> data_source_;
  839. const GURL base_url_;
  840. ParseMetadataCallback callback_;
  841. SectionOffsets section_offsets_;
  842. mojom::BundleMetadataPtr metadata_;
  843. base::WeakPtrFactory<MetadataParser> weak_factory_{this};
  844. };
  845. // A parser for reading single item from the responses section. This class owns
  846. // itself and will self destruct after calling the ParseResponseCallback.
  847. class WebBundleParser::ResponseParser
  848. : public WebBundleParser::SharedBundleDataSource::Observer {
  849. public:
  850. ResponseParser(scoped_refptr<SharedBundleDataSource> data_source,
  851. uint64_t response_offset,
  852. uint64_t response_length,
  853. WebBundleParser::ParseResponseCallback callback)
  854. : data_source_(data_source),
  855. response_offset_(response_offset),
  856. response_length_(response_length),
  857. callback_(std::move(callback)) {
  858. data_source_->AddObserver(this);
  859. }
  860. ResponseParser(const ResponseParser&) = delete;
  861. ResponseParser& operator=(const ResponseParser&) = delete;
  862. ~ResponseParser() override { data_source_->RemoveObserver(this); }
  863. void Start(uint64_t buffer_size = kInitialBufferSizeForResponse) {
  864. const uint64_t length = std::min(response_length_, buffer_size);
  865. data_source_->Read(response_offset_, length,
  866. base::BindOnce(&ResponseParser::ParseResponseHeader,
  867. weak_factory_.GetWeakPtr(), length));
  868. }
  869. private:
  870. // https://www.ietf.org/archive/id/draft-ietf-wpack-bundled-responses-01.html#name-responses
  871. // responses = [*response]
  872. // response = [headers: bstr .cbor headers, payload: bstr]
  873. // headers = {* bstr => bstr}
  874. void ParseResponseHeader(uint64_t expected_data_length,
  875. const absl::optional<std::vector<uint8_t>>& data) {
  876. if (!data || data->size() != expected_data_length) {
  877. RunErrorCallbackAndDestroy("Error reading response header.");
  878. return;
  879. }
  880. InputReader input(*data);
  881. // |response| must be an array of length 2 (headers and payload).
  882. auto num_elements = input.ReadCBORHeader(CBORType::kArray);
  883. if (!num_elements || *num_elements != 2) {
  884. RunErrorCallbackAndDestroy("Array size of response must be 2.");
  885. return;
  886. }
  887. auto header_length = input.ReadCBORHeader(CBORType::kByteString);
  888. if (!header_length) {
  889. RunErrorCallbackAndDestroy("Cannot parse response header length.");
  890. return;
  891. }
  892. // "The length of the headers byte string in a response MUST be less than
  893. // 524288 (512*1024) bytes, and recipients MUST fail to load a response with
  894. // longer headers"
  895. if (*header_length >= kMaxResponseHeaderLength) {
  896. RunErrorCallbackAndDestroy("Response header is too big.");
  897. return;
  898. }
  899. // If we don't have enough data for the headers and the CBOR header of the
  900. // payload, re-read with a larger buffer size.
  901. const uint64_t required_buffer_size = std::min(
  902. input.CurrentOffset() + *header_length + kMaxCBORItemHeaderSize,
  903. response_length_);
  904. if (data->size() < required_buffer_size) {
  905. DVLOG(1) << "Re-reading response header with a buffer of size "
  906. << required_buffer_size;
  907. Start(required_buffer_size);
  908. return;
  909. }
  910. // Parse headers.
  911. auto headers_bytes = input.ReadBytes(*header_length);
  912. if (!headers_bytes) {
  913. RunErrorCallbackAndDestroy("Cannot read response headers.");
  914. return;
  915. }
  916. cbor::Reader::DecoderError error;
  917. absl::optional<cbor::Value> headers_value =
  918. cbor::Reader::Read(*headers_bytes, &error);
  919. if (!headers_value) {
  920. RunErrorCallbackAndDestroy("Cannot parse response headers.");
  921. return;
  922. }
  923. auto parsed_headers = ConvertCBORValueToHeaders(*headers_value);
  924. if (!parsed_headers) {
  925. RunErrorCallbackAndDestroy("Cannot parse response headers.");
  926. return;
  927. }
  928. // "Each response's headers MUST include a :status pseudo-header with
  929. // exactly 3 ASCII decimal digits and MUST NOT include any other
  930. // pseudo-headers."
  931. const auto pseudo_status = parsed_headers->pseudos.find(":status");
  932. if (parsed_headers->pseudos.size() != 1 ||
  933. pseudo_status == parsed_headers->pseudos.end()) {
  934. RunErrorCallbackAndDestroy(
  935. "Response headers map must have exactly one pseudo-header, :status.");
  936. return;
  937. }
  938. int status;
  939. const auto& status_str = pseudo_status->second;
  940. if (status_str.size() != 3 ||
  941. !std::all_of(status_str.begin(), status_str.end(),
  942. base::IsAsciiDigit<char>) ||
  943. !base::StringToInt(status_str, &status)) {
  944. RunErrorCallbackAndDestroy(":status must be 3 ASCII decimal digits.");
  945. return;
  946. }
  947. // Parse payload.
  948. auto payload_length = input.ReadCBORHeader(CBORType::kByteString);
  949. if (!payload_length) {
  950. RunErrorCallbackAndDestroy("Cannot parse response payload length.");
  951. return;
  952. }
  953. // "If a response's payload is not empty, its headers MUST include a
  954. // Content-Type header (Section 8.3 of [I-D.ietf-httpbis-semantics])."
  955. if (*payload_length > 0 &&
  956. !parsed_headers->headers.contains("content-type")) {
  957. RunErrorCallbackAndDestroy(
  958. "Non-empty response must have a content-type header.");
  959. return;
  960. }
  961. if (input.CurrentOffset() + *payload_length != response_length_) {
  962. RunErrorCallbackAndDestroy("Unexpected payload length.");
  963. return;
  964. }
  965. mojom::BundleResponsePtr response = mojom::BundleResponse::New();
  966. response->response_code = status;
  967. response->response_headers = std::move(parsed_headers->headers);
  968. response->payload_offset = response_offset_ + input.CurrentOffset();
  969. response->payload_length = *payload_length;
  970. RunSuccessCallbackAndDestroy(std::move(response));
  971. }
  972. void RunSuccessCallbackAndDestroy(mojom::BundleResponsePtr response) {
  973. std::move(callback_).Run(std::move(response), nullptr);
  974. delete this;
  975. }
  976. void RunErrorCallbackAndDestroy(
  977. const std::string& message,
  978. mojom::BundleParseErrorType error_type =
  979. mojom::BundleParseErrorType::kFormatError) {
  980. std::move(callback_).Run(
  981. nullptr, mojom::BundleResponseParseError::New(error_type, message));
  982. delete this;
  983. }
  984. // Implements SharedBundleDataSource::Observer.
  985. void OnDisconnect() override {
  986. RunErrorCallbackAndDestroy("Data source disconnected.");
  987. }
  988. scoped_refptr<SharedBundleDataSource> data_source_;
  989. uint64_t response_offset_;
  990. uint64_t response_length_;
  991. ParseResponseCallback callback_;
  992. base::WeakPtrFactory<ResponseParser> weak_factory_{this};
  993. };
  994. WebBundleParser::SharedBundleDataSource::SharedBundleDataSource(
  995. mojo::PendingRemote<mojom::BundleDataSource> pending_data_source)
  996. : data_source_(std::move(pending_data_source)) {
  997. data_source_.set_disconnect_handler(base::BindOnce(
  998. &SharedBundleDataSource::OnDisconnect, base::Unretained(this)));
  999. }
  1000. void WebBundleParser::SharedBundleDataSource::AddObserver(Observer* observer) {
  1001. DCHECK(observers_.end() == observers_.find(observer));
  1002. observers_.insert(observer);
  1003. }
  1004. void WebBundleParser::SharedBundleDataSource::RemoveObserver(
  1005. Observer* observer) {
  1006. auto it = observers_.find(observer);
  1007. DCHECK(observers_.end() != it);
  1008. observers_.erase(it);
  1009. }
  1010. WebBundleParser::SharedBundleDataSource::~SharedBundleDataSource() = default;
  1011. void WebBundleParser::SharedBundleDataSource::OnDisconnect() {
  1012. for (auto* observer : observers_)
  1013. observer->OnDisconnect();
  1014. }
  1015. void WebBundleParser::SharedBundleDataSource::Read(
  1016. uint64_t offset,
  1017. uint64_t length,
  1018. mojom::BundleDataSource::ReadCallback callback) {
  1019. data_source_->Read(offset, length, std::move(callback));
  1020. }
  1021. void WebBundleParser::SharedBundleDataSource::Length(
  1022. mojom::BundleDataSource::LengthCallback callback) {
  1023. data_source_->Length(std::move(callback));
  1024. }
  1025. void WebBundleParser::SharedBundleDataSource::IsRandomAccessContext(
  1026. mojom::BundleDataSource::IsRandomAccessContextCallback callback) {
  1027. data_source_->IsRandomAccessContext(std::move(callback));
  1028. }
  1029. WebBundleParser::WebBundleParser(
  1030. mojo::PendingReceiver<mojom::WebBundleParser> receiver,
  1031. mojo::PendingRemote<mojom::BundleDataSource> data_source,
  1032. const GURL& base_url)
  1033. : receiver_(this, std::move(receiver)),
  1034. data_source_(
  1035. base::MakeRefCounted<SharedBundleDataSource>(std::move(data_source))),
  1036. base_url_(base_url) {
  1037. DCHECK(base_url_.is_empty() || base_url_.is_valid());
  1038. receiver_.set_disconnect_handler(base::BindOnce(
  1039. &base::DeletePointer<WebBundleParser>, base::Unretained(this)));
  1040. }
  1041. WebBundleParser::~WebBundleParser() = default;
  1042. void WebBundleParser::ParseIntegrityBlock(
  1043. ParseIntegrityBlockCallback callback) {
  1044. IntegrityBlockParser* parser =
  1045. new IntegrityBlockParser(data_source_, std::move(callback));
  1046. parser->Start();
  1047. }
  1048. void WebBundleParser::ParseMetadata(int64_t offset,
  1049. ParseMetadataCallback callback) {
  1050. MetadataParser* parser =
  1051. new MetadataParser(data_source_, base_url_, std::move(callback));
  1052. if (offset >= 0) {
  1053. parser->StartAtOffset(offset);
  1054. } else {
  1055. DCHECK_EQ(offset, -1);
  1056. // If no offset is specified, then where we start parsing the web bundle
  1057. // metadata depends on whether or not it is loaded in a random-access
  1058. // context. If random-access into the web bundle is possible, then we use
  1059. // the `length` field at its end to determine the start of the web bundle.
  1060. // If random-access into the web bundle is not possible, then we simply
  1061. // start at the top.
  1062. parser->Start();
  1063. }
  1064. }
  1065. void WebBundleParser::ParseResponse(uint64_t response_offset,
  1066. uint64_t response_length,
  1067. ParseResponseCallback callback) {
  1068. ResponseParser* parser = new ResponseParser(
  1069. data_source_, response_offset, response_length, std::move(callback));
  1070. parser->Start();
  1071. }
  1072. } // namespace web_package