connection_endpoint_metadata.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2021 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 "net/base/connection_endpoint_metadata.h"
  5. #include <string>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/base64.h"
  9. #include "base/values.h"
  10. #include "third_party/abseil-cpp/absl/types/optional.h"
  11. namespace net {
  12. namespace {
  13. const char kSupportedProtocolAlpnsKey[] = "supported_protocol_alpns";
  14. const char kEchConfigListKey[] = "ech_config_list";
  15. const char kTargetNameKey[] = "target_name";
  16. } // namespace
  17. ConnectionEndpointMetadata::ConnectionEndpointMetadata() = default;
  18. ConnectionEndpointMetadata::~ConnectionEndpointMetadata() = default;
  19. ConnectionEndpointMetadata::ConnectionEndpointMetadata(
  20. const ConnectionEndpointMetadata&) = default;
  21. ConnectionEndpointMetadata::ConnectionEndpointMetadata(
  22. ConnectionEndpointMetadata&&) = default;
  23. base::Value ConnectionEndpointMetadata::ToValue() const {
  24. base::Value::Dict dict;
  25. base::Value::List alpns_list;
  26. for (const std::string& alpn : supported_protocol_alpns) {
  27. alpns_list.Append(alpn);
  28. }
  29. dict.Set(kSupportedProtocolAlpnsKey, std::move(alpns_list));
  30. dict.Set(kEchConfigListKey, base::Base64Encode(ech_config_list));
  31. if (!target_name.empty()) {
  32. dict.Set(kTargetNameKey, target_name);
  33. }
  34. return base::Value(std::move(dict));
  35. }
  36. // static
  37. absl::optional<ConnectionEndpointMetadata>
  38. ConnectionEndpointMetadata::FromValue(const base::Value& value) {
  39. const base::Value::Dict* dict = value.GetIfDict();
  40. if (!dict)
  41. return absl::nullopt;
  42. const base::Value::List* alpns_list =
  43. dict->FindList(kSupportedProtocolAlpnsKey);
  44. const std::string* ech_config_list_value =
  45. dict->FindString(kEchConfigListKey);
  46. const std::string* target_name_value = dict->FindString(kTargetNameKey);
  47. if (!alpns_list || !ech_config_list_value)
  48. return absl::nullopt;
  49. ConnectionEndpointMetadata metadata;
  50. std::vector<std::string> alpns;
  51. for (const base::Value& alpn : *alpns_list) {
  52. if (!alpn.is_string())
  53. return absl::nullopt;
  54. metadata.supported_protocol_alpns.push_back(alpn.GetString());
  55. }
  56. absl::optional<std::vector<uint8_t>> decoded =
  57. base::Base64Decode(*ech_config_list_value);
  58. if (!decoded)
  59. return absl::nullopt;
  60. metadata.ech_config_list = std::move(*decoded);
  61. if (target_name_value) {
  62. metadata.target_name = *target_name_value;
  63. }
  64. return metadata;
  65. }
  66. } // namespace net