File: protocol_parser_json.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (334 lines) | stat: -rw-r--r-- 10,469 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/update_client/protocol_parser_json.h"

#include <algorithm>
#include <cstdint>
#include <optional>
#include <string>
#include <utility>

#include "base/check.h"
#include "base/json/json_reader.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/types/expected.h"
#include "base/values.h"
#include "base/version.h"
#include "components/update_client/protocol_definition.h"

namespace update_client {

namespace {

std::string GetValueString(const base::Value::Dict& node, const char* key) {
  const std::string* value = node.FindString(key);
  return value ? *value : std::string();
}

base::expected<std::string, std::string> Parse(const base::Value::Dict& node,
                                               const std::string& key) {
  const std::string* value = node.FindString(key);
  if (!value) {
    return base::unexpected(base::StrCat({"Missing ", key}));
  }
  return base::expected<std::string, std::string>(*value);
}

base::expected<base::Version, std::string> ParseVersion(
    const base::Value::Dict& node,
    const std::string& key) {
  base::expected<std::string, std::string> value = Parse(node, key);
  if (!value.has_value()) {
    return base::unexpected(value.error());
  }
  base::Version version(value.value());
  if (!version.IsValid()) {
    return base::unexpected(
        base::StrCat({"Invalid version: '", value.value(), "'."}));
  }
  return version;
}

std::optional<std::string> ParseOptional(const base::Value::Dict& node,
                                         const std::string& key) {
  const std::string* value = node.FindString(key);
  if (value) {
    return *value;
  }
  return std::nullopt;
}

int64_t ParseNumberWithDefault(const base::Value::Dict& node,
                               const std::string& key,
                               int64_t def) {
  const std::optional<double> value = node.FindDouble(key);
  if (value) {
    const double val = value.value();
    if (0 <= val && val < protocol_request::kProtocolMaxInt) {
      return static_cast<int64_t>(val);
    }
  }
  return def;
}

std::string ParseWithDefault(const base::Value::Dict& node,
                             const std::string& key,
                             const std::string& def) {
  const std::string* value = node.FindString(key);
  if (value) {
    return *value;
  }
  return def;
}

std::string ParseWithDefault(const base::Value::Dict& node,
                             const std::string& outer_key,
                             const std::string& inner_key,
                             const std::string& def) {
  const base::Value::Dict* outer = node.FindDict(outer_key);
  return outer ? ParseWithDefault(*outer, inner_key, def) : def;
}

base::expected<ProtocolParser::Operation, std::string> ParseOperation(
    const base::Value& node_val) {
  if (!node_val.is_dict()) {
    return base::unexpected("'operation' contains a non-dictionary.");
  }
  const base::Value::Dict& node = node_val.GetDict();
  ProtocolParser::Operation op;
  base::expected<std::string, std::string> type = Parse(node, "type");
  if (!type.has_value()) {
    return base::unexpected(type.error());
  }
  op.type = type.value();
  op.sha256_out = ParseWithDefault(node, "out", "sha256", {});
  op.sha256_in = ParseWithDefault(node, "in", "sha256", {});
  op.sha256_previous = ParseWithDefault(node, "previous", "sha256", {});
  op.path = ParseWithDefault(node, "path", {});
  op.arguments = ParseWithDefault(node, "arguments", {});
  op.size = ParseNumberWithDefault(node, "size", 0);
  if (const base::Value::List* list = node.FindList("urls")) {
    for (const base::Value& url_node : *list) {
      if (!url_node.is_dict()) {
        return base::unexpected("url node is not a dict");
      }
      base::expected<std::string, std::string> url =
          Parse(url_node.GetDict(), "url");
      if (!url.has_value()) {
        return base::unexpected(url.error());
      }
      GURL gurl(url.value());
      if (!gurl.is_valid()) {
        return base::unexpected("operation contains a malformed url");
      }
      op.urls.push_back(gurl);
    }
  }
  return op;
}

base::expected<ProtocolParser::Pipeline, std::string> ParsePipeline(
    const base::Value& node_val) {
  if (!node_val.is_dict()) {
    return base::unexpected("'pipeline' contains a non-dictionary.");
  }
  ProtocolParser::Pipeline pipeline;
  pipeline.pipeline_id =
      ParseWithDefault(node_val.GetDict(), "pipeline_id", {});
  if (const base::Value::List* node =
          node_val.GetDict().FindList("operations")) {
    for (const base::Value& operation_node : *node) {
      base::expected<ProtocolParser::Operation, std::string> operation =
          ParseOperation(operation_node);
      if (!operation.has_value()) {
        return base::unexpected(operation.error());
      }
      pipeline.operations.push_back(operation.value());
    }
  }
  return pipeline;
}

void ParseData(const base::Value& data_node_val, ProtocolParser::App* result) {
  if (!data_node_val.is_dict()) {
    return;
  }
  const base::Value::Dict& data_node = data_node_val.GetDict();

  result->data.emplace_back(
      GetValueString(data_node, "index"), GetValueString(data_node, "#text"));
}

bool ParseUpdateCheck(const base::Value* node_val,
                      ProtocolParser::App* result,
                      std::string* error) {
  if (!node_val || !node_val->is_dict()) {
    *error = "'updatecheck' node is missing or not a dictionary.";
    return false;
  }
  const base::Value::Dict& node = node_val->GetDict();

  for (auto [k, v] : node) {
    if (!k.empty() && k.front() == '_' && v.is_string()) {
      result->custom_attributes[k] = v.GetString();
    }
  }

  // result->status was set to "ok" when parsing the app node; overwrite it with
  // the updatecheck status.
  base::expected<std::string, std::string> status = Parse(node, "status");
  if (!status.has_value()) {
    *error = status.error();
    return false;
  }
  result->status = status.value();

  if (result->status == "noupdate") {
    return true;
  }

  if (result->status == "ok") {
    base::expected<base::Version, std::string> nextversion =
        ParseVersion(node, "nextversion");
    if (nextversion.has_value()) {
      result->nextversion = nextversion.value();
    } else {
      *error = nextversion.error();
      return false;
    }

    if (const base::Value::List* list = node.FindList("pipelines")) {
      for (const base::Value& pipeline_node : *list) {
        base::expected<ProtocolParser::Pipeline, std::string> pipeline =
            ParsePipeline(pipeline_node);
        if (!pipeline.has_value()) {
          *error = pipeline.error();
          return false;
        }
        result->pipelines.push_back(pipeline.value());
      }
    }
    return true;
  }

  // Return the |updatecheck| element status as a parsing error.
  *error = result->status;
  return true;
}

bool ParseApp(const base::Value& node_value,
              ProtocolParser::App* result,
              std::string* error) {
  if (!node_value.is_dict()) {
    *error = "'app' is not a dictionary.";
    return false;
  }
  const base::Value::Dict& node = node_value.GetDict();

  result->cohort = ParseOptional(node, "cohort");
  result->cohort_name = ParseOptional(node, "cohortname");
  result->cohort_hint = ParseOptional(node, "cohorthint");
  base::expected<std::string, std::string> appid = Parse(node, "appid");
  if (!appid.has_value()) {
    *error = appid.error();
    return false;
  }
  result->app_id = appid.value();
  base::expected<std::string, std::string> status = Parse(node, "status");
  if (!status.has_value()) {
    *error = status.error();
    return false;
  }
  result->status = status.value();

  if (result->status == "ok") {
    if (const base::Value::List* data_node = node.FindList("data")) {
      std::ranges::for_each(*data_node, [&result](const base::Value& data) {
        ParseData(data, result);
      });
    }
    return ParseUpdateCheck(node.Find("updatecheck"), result, error);
  }

  return true;
}

}  // namespace

bool ProtocolParserJSON::DoParse(const std::string& response_json,
                                 Results* results) {
  CHECK(results);

  if (response_json.empty()) {
    ParseError("Empty JSON.");
    return false;
  }

  // The JSON response contains a prefix to prevent XSSI.
  static constexpr char kJSONPrefix[] = ")]}'";
  if (!base::StartsWith(response_json, kJSONPrefix,
                        base::CompareCase::SENSITIVE)) {
    ParseError("Missing secure JSON prefix.");
    return false;
  }
  const auto doc = base::JSONReader::ReadDict(base::MakeStringPiece(
      response_json.begin() + std::char_traits<char>::length(kJSONPrefix),
      response_json.end()));
  if (!doc) {
    ParseError("JSON read error.");
    return false;
  }
  const base::Value::Dict* response_node = doc->FindDict("response");
  if (!response_node) {
    ParseError("Missing 'response' element or 'response' is not a dictionary.");
    return false;
  }
  const std::string* protocol = response_node->FindString("protocol");
  if (!protocol) {
    ParseError("Missing/non-string protocol.");
    return false;
  }
  if (*protocol != protocol_request::kProtocolVersion) {
    ParseError("Incorrect protocol. (expected '%s', found '%s')",
               protocol_request::kProtocolVersion, protocol->c_str());
    return false;
  }

  const base::Value::Dict* daystart_node = response_node->FindDict("daystart");
  if (daystart_node) {
    const std::optional<int> elapsed_days =
        daystart_node->FindInt("elapsed_days");
    if (elapsed_days) {
      results->daystart_elapsed_days = *elapsed_days;
    }
  }

  const base::Value::List* app_node = response_node->FindList("apps");
  if (app_node) {
    for (const auto& app : *app_node) {
      App result;
      std::string error;
      if (ParseApp(app, &result, &error)) {
        results->apps.push_back(result);
      } else {
        ParseError("%s", error.c_str());
      }
    }
  }

  return true;
}

base::expected<ProtocolParser::Results, std::string>
ProtocolParserJSON::ParseJSON(const std::string& json) {
  ProtocolParserJSON parser;
  if (parser.Parse(json)) {
    return parser.results();
  }
  return base::unexpected(parser.errors());
}

}  // namespace update_client