This repository has been archived by the owner on Jun 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
example.c
69 lines (61 loc) · 1.96 KB
/
example.c
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
#include "crc32cr.h"
unsigned long
generate_crc32c(unsigned char *buffer, unsigned int length)
{
unsigned int i;
uint32_t crc32 = 0xffffffffUL;
uint32_t result;
uint8_t byte0, byte1, byte2, byte3;
for (i = 0; i < length; i++) {
CRC32C(crc32, buffer[i]);
}
result = ~crc32;
/* result now holds the negated polynomial remainder;
* since the table and algorithm is "reflected" [williams95].
* That is, result has the same value as if we mapped the message
* to a polynomial, computed the host-bit-order polynomial
* remainder, performed final negation, then did an end-for-end
* bit-reversal.
* Note that a 32-bit bit-reversal is identical to four inplace
* 8-bit reversals followed by an end-for-end byteswap.
* In other words, the bits of each byte are in the right order,
* but the bytes have been byteswapped. So we now do an explicit
* byteswap. On a little-endian machine, this byteswap and
* the final ntohl cancel out and could be elided.
*/
byte0 = result & 0xff;
byte1 = (result>>8) & 0xff;
byte2 = (result>>16) & 0xff;
byte3 = (result>>24) & 0xff;
crc32 = ((byte0 << 24) |
(byte1 << 16) |
(byte2 << 8) |
byte3);
return (crc32);
}
int
insert_crc32(unsigned char *buffer, unsigned int length)
{
SCTP_message *message;
uint32_t crc32;
message = (SCTP_message *) buffer;
message->common_header.checksum = 0UL;
crc32 = generate_crc32c(buffer,length);
/* and insert it into the message */
message->common_header.checksum = htonl(crc32);
return 1;
}
int
validate_crc32(unsigned char *buffer, unsigned int length)
{
SCTP_message *message;
unsigned int i;
uint32_t original_crc32;
uint32_t crc32;
/* save and zero checksum */
message = (SCTP_message *)buffer;
original_crc32 = ntohl(message->common_header.checksum);
message->common_header.checksum = 0L;
crc32 = generate_crc32c(buffer, length);
return ((original_crc32 == crc32)? 1 : -1);
}