2 * Implementation of Metacube2 utility functions.
4 * Note: This file is meant to compile as both C and C++, for easier inclusion
11 #include <netinet/in.h>
14 * https://www.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf
15 * recommends this for messages as short as ours (see table at page 34).
17 #define METACUBE2_CRC_POLYNOMIAL 0x8FDB
19 /* Semi-random starting value to make sure all-zero won't pass. */
20 #define METACUBE2_CRC_START 0x1234
22 /* This code is based on code generated by pycrc. */
23 uint16_t metacube2_compute_crc(const struct metacube2_block_header *hdr)
25 static const int data_len = sizeof(hdr->size) + sizeof(hdr->flags);
26 const uint8_t *data = (uint8_t *)&hdr->size;
27 uint16_t crc = METACUBE2_CRC_START;
30 for (i = 0; i < data_len; ++i) {
32 for (j = 0; j < 8; j++) {
33 int bit = crc & 0x8000;
34 crc = (crc << 1) | ((c >> (7 - j)) & 0x01);
36 crc ^= METACUBE2_CRC_POLYNOMIAL;
42 for (i = 0; i < 16; i++) {
43 int bit = crc & 0x8000;
46 crc ^= METACUBE2_CRC_POLYNOMIAL;
51 * Invert the checksum for metadata packets, so that clients that
52 * don't understand metadata will ignore it as broken. There will
53 * probably be logging, but apart from that, it's harmless.
55 if (ntohs(hdr->flags) & METACUBE_FLAGS_METADATA) {