]> git.sesse.net Git - cubemap/blob - metacube2.cpp
Support quoted spaces in configuration files.
[cubemap] / metacube2.cpp
1 /*
2  * Implementation of Metacube2 utility functions.
3  *
4  * Note: This file is meant to compile as both C and C++, for easier inclusion
5  * in other projects.
6  */
7
8 #include "metacube2.h"
9
10 #include <arpa/inet.h>
11
12 /*
13  * https://www.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf
14  * recommends this for messages as short as ours (see table at page 34).
15  */
16 #define METACUBE2_CRC_POLYNOMIAL 0x8FDB
17
18 /* Semi-random starting value to make sure all-zero won't pass. */
19 #define METACUBE2_CRC_START 0x1234
20
21 /* This code is based on code generated by pycrc. */
22 uint16_t metacube2_compute_crc(const struct metacube2_block_header *hdr)
23 {
24         static const int data_len = sizeof(hdr->size) + sizeof(hdr->flags);
25         const uint8_t *data = (uint8_t *)&hdr->size;
26         uint16_t crc = METACUBE2_CRC_START;
27         int i, j;
28
29         for (i = 0; i < data_len; ++i) {
30                 uint8_t c = data[i];
31                 for (j = 0; j < 8; j++) {
32                         int bit = crc & 0x8000;
33                         crc = (crc << 1) | ((c >> (7 - j)) & 0x01);
34                         if (bit) {
35                                 crc ^= METACUBE2_CRC_POLYNOMIAL;
36                         }
37                 }
38         }
39
40         /* Finalize. */
41         for (i = 0; i < 16; i++) {
42                 int bit = crc & 0x8000;
43                 crc = crc << 1;
44                 if (bit) {
45                         crc ^= METACUBE2_CRC_POLYNOMIAL;
46                 }
47         }
48
49         /*
50          * Invert the checksum for metadata packets, so that clients that
51          * don't understand metadata will ignore it as broken. There will
52          * probably be logging, but apart from that, it's harmless.
53          */
54         if (ntohs(hdr->flags) & METACUBE_FLAGS_METADATA) {
55                 crc ^= 0xffff;
56         }
57
58         return crc;
59 }