lokinet/llarp/ip.cpp

96 lines
2.4 KiB
C++
Raw Normal View History

#include <llarp/endian.h>
2018-08-21 13:02:05 +00:00
#include <algorithm>
2018-08-23 18:48:41 +00:00
#include <llarp/ip.hpp>
#include "llarp/buffer.hpp"
2018-08-22 15:52:10 +00:00
#include "mem.hpp"
2018-09-18 23:44:23 +00:00
#ifndef _WIN32
#include <netinet/in.h>
#endif
#include <llarp/endian.h>
#include <map>
namespace llarp
{
namespace net
{
2018-08-20 19:12:12 +00:00
bool
IPv4Packet::Load(llarp_buffer_t pkt)
{
2018-08-23 18:02:02 +00:00
#ifndef MIN
#define MIN(a, b) (a < b ? a : b)
sz = MIN(pkt.sz, sizeof(buf));
#undef MIN
#endif
2018-08-22 15:52:10 +00:00
memcpy(buf, pkt.base, sz);
2018-08-20 19:12:12 +00:00
return true;
}
2018-08-20 19:12:12 +00:00
2018-08-22 15:52:10 +00:00
llarp_buffer_t
IPv4Packet::Buffer()
{
return llarp::InitBuffer(buf, sz);
}
static uint16_t
ipchksum(const byte_t *buf, size_t sz, uint32_t sum = 0)
{
while(sz > 1)
2018-08-20 19:12:12 +00:00
{
sum += *(const uint16_t *)buf;
sz -= sizeof(uint16_t);
buf += sizeof(uint16_t);
2018-08-20 19:12:12 +00:00
}
if(sz > 0)
sum += *(const byte_t *)buf;
2018-08-20 19:12:12 +00:00
while(sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return ~sum;
}
static std::map<
byte_t, std::function< void(const ip_header *, byte_t *, size_t) > >
protoCheckSummer = {
2018-09-19 11:53:16 +00:00
/// ICMP
{1,
[](const ip_header *hdr, byte_t *buf, size_t sz) {
auto len = hdr->ihl * 4;
uint16_t *check = (uint16_t *)buf + len + 2;
*check = 0;
*check = ipchksum(buf, sz);
}},
2018-09-19 11:53:16 +00:00
/// TCP
{6, [](const ip_header *hdr, byte_t *pkt, size_t sz) {
2018-09-18 22:53:48 +00:00
byte_t pktbuf[1500];
auto len = hdr->ihl * 4;
2018-09-18 22:53:48 +00:00
size_t pktsz = sz - len;
uint16_t *check = (uint16_t *)(pkt + len + 16);
*check = 0;
2018-09-18 22:53:48 +00:00
memcpy(pktbuf, &hdr->saddr, 4);
memcpy(pktbuf + 4, &hdr->daddr, 4);
pktbuf[8] = 0;
2018-09-19 11:53:16 +00:00
pktbuf[9] = 6;
2018-09-18 22:53:48 +00:00
// TODO: endian (?)
pktbuf[10] = (pktsz & 0xff00) >> 8;
pktbuf[11] = pktsz & 0x00ff;
memcpy(pktbuf + 12, pkt + len, pktsz);
*check = ipchksum(pktbuf, 12 + pktsz);
}}};
void
IPv4Packet::UpdateChecksum()
{
auto hdr = Header();
hdr->check = 0;
auto len = hdr->ihl * 4;
hdr->check = ipchksum(buf, len);
2018-09-17 18:59:12 +00:00
auto proto = hdr->protocol;
auto itr = protoCheckSummer.find(proto);
if(itr != protoCheckSummer.end())
{
itr->second(hdr, buf, sz);
}
2018-08-20 19:12:12 +00:00
}
} // namespace net
} // namespace llarp