protected_crc.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2010 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Protects CRC tables with its own CRC.
  15. // CRC tables get corrupted too, and if corruption is
  16. // not caught, data poisoning becomes a reality.
  17. #ifndef CRCUTIL_PROTECTED_CRC_H_
  18. #define CRCUTIL_PROTECTED_CRC_H_
  19. namespace crcutil {
  20. #pragma pack(push, 16)
  21. // Class CrcImplementation should not have virtual functions:
  22. // vptr is stored as the very first field, vptr value is defined
  23. // at runtime, so it is impossible to CRC(*this) once and
  24. // guarantee that this value will not change from run to run.
  25. //
  26. template<typename CrcImplementation> class ProtectedCrc
  27. : public CrcImplementation {
  28. public:
  29. typedef typename CrcImplementation::Crc Crc;
  30. // Returns check value that the caller should compare
  31. // against pre-computed, trusted constant.
  32. //
  33. // Computing SelfCheckValue() after CRC initialization,
  34. // storing it in memory, and periodically checking against
  35. // stored value may not work: if CRC tables were initialized
  36. // incorrectly and/or had been corrupted during initialization,
  37. // CheckValue() will return garbage. Garbage in, garbage out.
  38. // Consequitive checks will not detect a problem, the application
  39. // will happily produce and save the data with corrupt CRC.
  40. //
  41. // The application should call SelfCheckValue() regularly:
  42. // 1. First and foremost, on every CRC mismatch.
  43. // 2. After CRC'ing the data but before sending it out or writing it.
  44. // 3. Worst case, every Nth CRC'ed byte or every Nth call to CRC.
  45. //
  46. Crc SelfCheckValue() const {
  47. return CrcDefault(this, sizeof(*this), 0);
  48. }
  49. } GCC_ALIGN_ATTRIBUTE(16);
  50. #pragma pack(pop)
  51. } // namespace crcutil
  52. #endif // CRCUTIL_PROTECTED_CRC_H_