libwifi 0.0.3
An 802.11 Frame Parsing and Generation library in C
crc.c
Go to the documentation of this file.
1/* Copyright 2021 The libwifi Authors
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 */
15
16#include "crc.h"
17#include "../misc/byteswap.h"
18
19#include <stdint.h>
20#include <sys/types.h>
21
22/*
23 * Basic CRC32 implementation for getting the frame check sum of
24 * a supplied message, usually frame data.
25 */
26uint32_t libwifi_crc32(const unsigned char *message, int message_len) {
27 int i, j;
28 unsigned int byte, crc, mask;
29 i = 0;
30 crc = 0xFFFFFFFF;
31 while (i < message_len) {
32 byte = message[i];
33 crc = crc ^ byte;
34 for (j = 7; j >= 0; j--) {
35 mask = -(crc & 1);
36 crc = (crc >> 1) ^ (0xEDB88320 & mask);
37 }
38 i = i + 1;
39 }
40 return ~crc;
41}
42
43/*
44 * Specific function for calculating a frame FCS, byteswapped for the
45 * host endianess.
46 */
47uint32_t libwifi_calculate_fcs(const unsigned char *frame, size_t frame_len) {
48 return BYTESWAP32(libwifi_crc32(frame, frame_len));
49}
50
51/*
52 * Verify a raw frame containing a FCS at the end to the FCS calculated
53 * by libwifi.
54 */
55int libwifi_frame_verify(void *frame, size_t frame_len) {
56 // A frame with a CRC will have the CRC placed at the end, and is 4 bytes long.
57 uint32_t oCRC = *((uint32_t *) ((char *) frame + (frame_len - 4)));
58 uint32_t rCRC = libwifi_calculate_fcs(frame, frame_len);
59
60 if (rCRC == oCRC) {
61 return 1;
62 }
63
64 return 0;
65}
#define BYTESWAP32(x)
Definition: byteswap.h:23
int libwifi_frame_verify(void *frame, size_t frame_len)
Check if the given raw 802.11 frame has a valid FCS.
Definition: crc.c:55
uint32_t libwifi_crc32(const unsigned char *message, int message_len)
Calculate the CRC32 sum of a given buffer.
Definition: crc.c:26
uint32_t libwifi_calculate_fcs(const unsigned char *frame, size_t frame_len)
Calculate the frame checksum for an 802.11 frame.
Definition: crc.c:47