89 lines
2.6 KiB
C
89 lines
2.6 KiB
C
#include <criterion/criterion.h>
|
|
#include <string.h>
|
|
#include "internal/icmp_packet_internal.h"
|
|
#include "internal/icmp_packet.h"
|
|
|
|
Test(packet_parse_icmp, echo_reply)
|
|
{
|
|
uint8_t buffer[20 + 8 + 4] = {0}; // 20 bytes IP header, 8 ICMP, 4 payload
|
|
size_t ip_hdr_len = 20;
|
|
|
|
// fake ICMP header: type=0 (echo reply), code=0
|
|
struct icmp_header *icmp = (struct icmp_header *)(buffer + ip_hdr_len);
|
|
icmp->type = 0;
|
|
icmp->code = 0;
|
|
|
|
// payload: "PONG"
|
|
memcpy(buffer + ip_hdr_len + 8, "PONG", 4);
|
|
|
|
uint8_t type = 255, code = 255;
|
|
const void *payload = NULL;
|
|
size_t payload_len = 0;
|
|
|
|
int ret = icmp_parse_icmp_payload(buffer, sizeof(buffer),
|
|
ip_hdr_len, &type, &code, &payload, &payload_len);
|
|
|
|
cr_assert_eq(ret, 0, "Should succeed for valid ICMP echo reply");
|
|
cr_assert_eq(type, 0, "Type should be 0 (echo reply)");
|
|
cr_assert_eq(code, 0, "Code should be 0");
|
|
cr_assert_eq(payload_len, 4, "Payload length should be 4");
|
|
cr_assert(memcmp(payload, "PONG", 4) == 0, "Payload should be 'PONG'");
|
|
}
|
|
|
|
Test(packet_parse_icmp, no_payload)
|
|
{
|
|
// Only IP header + ICMP header (20+8=28)
|
|
uint8_t buffer[28] = {0};
|
|
size_t ip_hdr_len = 20;
|
|
struct icmp_header *icmp = (struct icmp_header *)(buffer + ip_hdr_len);
|
|
icmp->type = 8; // Echo request
|
|
icmp->code = 1;
|
|
|
|
uint8_t type = 0, code = 0;
|
|
const void *payload = NULL;
|
|
size_t payload_len = 123;
|
|
|
|
int ret = icmp_parse_icmp_payload(buffer, sizeof(buffer),
|
|
ip_hdr_len, &type, &code, &payload, &payload_len);
|
|
|
|
cr_assert_eq(ret, 0, "Should succeed for ICMP with no payload");
|
|
cr_assert_eq(payload_len, 0, "Payload length should be 0");
|
|
}
|
|
|
|
Test(packet_parse_icmp, extract_type_code)
|
|
{
|
|
// Build with type=11 (time exceeded), code=0
|
|
uint8_t buffer[20 + 8] = {0};
|
|
size_t ip_hdr_len = 20;
|
|
struct icmp_header *icmp = (struct icmp_header *)(buffer + ip_hdr_len);
|
|
icmp->type = 11;
|
|
icmp->code = 0;
|
|
|
|
uint8_t type = 0, code = 100;
|
|
const void *payload = NULL;
|
|
size_t payload_len = 0;
|
|
|
|
int ret = icmp_parse_icmp_payload(buffer, sizeof(buffer),
|
|
ip_hdr_len, &type, &code, &payload, &payload_len);
|
|
|
|
cr_assert_eq(ret, 0, "Should succeed for ICMP Time Exceeded");
|
|
cr_assert_eq(type, 11, "Type should be 11");
|
|
cr_assert_eq(code, 0, "Code should be 0");
|
|
}
|
|
|
|
Test(packet_parse_icmp, buffer_too_small)
|
|
{
|
|
// Only enough for IP header + 4 bytes of ICMP header (need 8)
|
|
uint8_t buffer[20 + 4] = {0};
|
|
size_t ip_hdr_len = 20;
|
|
|
|
uint8_t type = 0, code = 0;
|
|
const void *payload = NULL;
|
|
size_t payload_len = 0;
|
|
|
|
int ret = icmp_parse_icmp_payload(buffer, sizeof(buffer),
|
|
ip_hdr_len, &type, &code, &payload, &payload_len);
|
|
|
|
cr_assert_eq(ret, -1,
|
|
"Should fail when buffer is too small for ICMP header");
|
|
}
|