net_response_check.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2017 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. //
  5. #include "rlz/lib/net_response_check.h"
  6. #include "base/strings/string_util.h"
  7. #include "rlz/lib/assert.h"
  8. #include "rlz/lib/crc32.h"
  9. #include "rlz/lib/string_utils.h"
  10. // Checksum validation convenience call for RLZ responses.
  11. namespace rlz_lib {
  12. bool IsPingResponseValid(const char* response, int* checksum_idx) {
  13. if (!response || !response[0])
  14. return false;
  15. if (checksum_idx)
  16. *checksum_idx = -1;
  17. if (strlen(response) > kMaxPingResponseLength) {
  18. ASSERT_STRING("IsPingResponseValid: response is too long to parse.");
  19. return false;
  20. }
  21. // Find the checksum line.
  22. std::string response_string(response);
  23. std::string checksum_param("\ncrc32: ");
  24. int calculated_crc;
  25. int checksum_index = response_string.find(checksum_param);
  26. if (checksum_index >= 0) {
  27. // Calculate checksum of message preceeding checksum line.
  28. // (+ 1 to include the \n)
  29. std::string message(response_string.substr(0, checksum_index + 1));
  30. if (!Crc32(message.c_str(), &calculated_crc))
  31. return false;
  32. } else {
  33. checksum_param = "crc32: "; // Empty response case.
  34. if (!base::StartsWith(response_string, checksum_param,
  35. base::CompareCase::SENSITIVE))
  36. return false;
  37. checksum_index = 0;
  38. if (!Crc32("", &calculated_crc))
  39. return false;
  40. }
  41. // Find the checksum value on the response.
  42. int checksum_end = response_string.find("\n", checksum_index + 1);
  43. if (checksum_end < 0)
  44. checksum_end = response_string.size();
  45. int checksum_begin = checksum_index + checksum_param.size();
  46. std::string checksum =
  47. response_string.substr(checksum_begin, checksum_end - checksum_begin + 1);
  48. base::TrimWhitespaceASCII(checksum, base::TRIM_ALL, &checksum);
  49. if (checksum_idx)
  50. *checksum_idx = checksum_index;
  51. return calculated_crc == HexStringToInteger(checksum.c_str());
  52. }
  53. } // namespace rlz_lib