2026-04-11 08:15:41 +09:00
|
|
|
#include "ipv4.h"
|
|
|
|
|
#include "icmp.h"
|
2026-04-11 09:04:55 +09:00
|
|
|
#include "igmp.h"
|
2026-04-19 08:26:57 -07:00
|
|
|
#include "net.h"
|
2026-04-19 00:32:13 -07:00
|
|
|
#include "udp.h"
|
2026-04-11 09:04:55 +09:00
|
|
|
#include "parse_buffer.h"
|
2026-04-11 08:15:41 +09:00
|
|
|
|
|
|
|
|
namespace ipv4 {
|
|
|
|
|
|
|
|
|
|
static constexpr ip4_addr IP_BROADCAST_ALL = {255, 255, 255, 255};
|
|
|
|
|
|
|
|
|
|
uint16_t checksum(const void* data, size_t len) {
|
|
|
|
|
auto p = static_cast<const uint8_t*>(data);
|
|
|
|
|
uint32_t sum = 0;
|
|
|
|
|
for (size_t i = 0; i < len - 1; i += 2)
|
|
|
|
|
sum += (p[i] << 8) | p[i + 1];
|
|
|
|
|
if (len & 1)
|
|
|
|
|
sum += p[len - 1] << 8;
|
|
|
|
|
while (sum >> 16)
|
|
|
|
|
sum = (sum & 0xFFFF) + (sum >> 16);
|
|
|
|
|
return __builtin_bswap16(~sum);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-19 08:26:57 -07:00
|
|
|
static bool ip_match(const ip4_addr& dst, const ip4_addr& our_ip) {
|
|
|
|
|
return dst == our_ip || dst == IP_BROADCAST_ALL || dst == SUBNET_BROADCAST || igmp::is_member(dst);
|
2026-04-11 08:15:41 +09:00
|
|
|
}
|
|
|
|
|
|
2026-04-19 08:26:57 -07:00
|
|
|
void handle(std::span<const uint8_t> frame, span_writer& tx) {
|
|
|
|
|
const auto& ns = net_get_state();
|
2026-04-11 09:04:55 +09:00
|
|
|
parse_buffer pb(frame);
|
|
|
|
|
pb.consume<eth::header>();
|
|
|
|
|
auto* ip = pb.consume<header>();
|
|
|
|
|
if (!ip) return;
|
|
|
|
|
if ((ip->ver_ihl >> 4) != 4) return;
|
2026-04-11 08:15:41 +09:00
|
|
|
|
2026-04-11 09:04:55 +09:00
|
|
|
size_t options_len = ip->header_len() - sizeof(header);
|
|
|
|
|
if (options_len > 0 && !pb.skip(options_len)) return;
|
|
|
|
|
|
|
|
|
|
switch (ip->protocol) {
|
2026-04-11 08:15:41 +09:00
|
|
|
case 1:
|
2026-04-19 08:26:57 -07:00
|
|
|
if (!ip_match(ip->dst, ns.ip))
|
2026-04-11 08:15:41 +09:00
|
|
|
return;
|
2026-04-19 08:26:57 -07:00
|
|
|
icmp::handle(frame, tx, ns.mac, ns.ip);
|
2026-04-11 08:15:41 +09:00
|
|
|
break;
|
2026-04-11 09:04:55 +09:00
|
|
|
case 2:
|
2026-04-19 08:26:57 -07:00
|
|
|
igmp::handle(frame, tx, ns.mac, ns.ip);
|
2026-04-11 09:04:55 +09:00
|
|
|
break;
|
2026-04-11 08:15:41 +09:00
|
|
|
case 17:
|
2026-04-19 08:26:57 -07:00
|
|
|
if (!ip_match(ip->dst, ns.ip))
|
2026-04-11 08:15:41 +09:00
|
|
|
return;
|
2026-04-19 00:32:13 -07:00
|
|
|
udp::handle(frame, tx);
|
2026-04-11 08:15:41 +09:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-19 08:26:57 -07:00
|
|
|
__attribute__((constructor))
|
|
|
|
|
static void register_ethertype() {
|
|
|
|
|
net_register_ethertype(eth::ETH_IPV4, handle);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-11 08:15:41 +09:00
|
|
|
} // namespace ipv4
|