#include #include "udp_packet.h" #include "../../utils.h" #include "ipv4_packet.h" #include "ethernet_frame.h" #include "tcp_udp_common.h" #define ETH_UDP_HEADER_SIZE (8) static bool check_udp_validity(const uint8_t * hdr, const PcktHeaderElement *pcktHdrLe) { const UdpProps *udpProps = HEADER_FETCH_PROPS(UdpProps, pcktHdrLe); const IPv4Props *ipProps = (IPv4Props *) &pcktHdrLe->prev->props; IPv4PseudoHeader ph = {ipProps->SourceIPAddr, ipProps->DestIPAddr, 0, ETH_UDP_PACKET_CLASS, htons(udpProps->Length)}; uint16_t chkSum = tcp_udp_checksum(&ph, hdr, udpProps->Length); bool valid = chkSum == 0; return valid; } int parse_udp(const uint8_t *hdr, uint32_t size, PcktHeaderElement *pcktHdrLe, struct EthInterface_ *intf) { const uint8_t * hdrBegin = hdr; UdpProps *udpProps = HEADER_FETCH_PROPS(UdpProps, pcktHdrLe); FETCH_WORD_H2N_ADVANCE(&udpProps->SourcePort, hdr); FETCH_WORD_H2N_ADVANCE(&udpProps->DestinationPort, hdr); FETCH_WORD_H2N_ADVANCE(&udpProps->Length, hdr); FETCH_WORD_H2N_ADVANCE(&udpProps->Checksum, hdr); // common fields... udpProps->headerSize = ETH_UDP_HEADER_SIZE; udpProps->validityOK = check_udp_validity(hdrBegin, pcktHdrLe); udpProps->containedPacketClass = 0; return udpProps->validityOK ? 0 : -1; } void insert_udp_header(uint8_t *hdr, const PcktHeaderElement *headers) { uint8_t *hdrBegin = hdr; UdpProps *udpProps = (UdpProps *) &headers->props; FILL_WORD_H2N_ADVANCE(hdr, udpProps->SourcePort); FILL_WORD_H2N_ADVANCE(hdr, udpProps->DestinationPort); FILL_WORD_H2N_ADVANCE(hdr, udpProps->Length); uint8_t *ChkSumPtr = hdr; udpProps->Checksum = 0; FILL_WORD_H2N_ADVANCE(hdr, udpProps->Checksum); // calculate checksum const IPv4Props *ipProps = (IPv4Props *) &headers->prev->props; IPv4PseudoHeader ph = {ipProps->SourceIPAddr, ipProps->DestIPAddr, 0, ETH_UDP_PACKET_CLASS, htons(udpProps->Length)}; udpProps->Checksum = tcp_udp_checksum(&ph, hdrBegin, udpProps->Length); memcpy(ChkSumPtr, &udpProps->Checksum, 2); }