-
Notifications
You must be signed in to change notification settings - Fork 0
/
nlsocket.hpp
106 lines (98 loc) · 2.74 KB
/
nlsocket.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2014-2020 Nicholas J. Kain <njkain at gmail dot com>
// SPDX-License-Identifier: MIT
#ifndef NRAD6_NLSOCKET_HPP_
#define NRAD6_NLSOCKET_HPP_
#include <stdint.h>
#include <vector>
#include <string>
#include <array>
#include <map>
#include <optional>
#include <nk/sys/posix/handle.hpp>
#include <nk/net/ip_address.hpp>
extern "C" {
#include "nl.h"
}
struct netif_addr
{
enum class Scope {
Global = RT_SCOPE_UNIVERSE,
Site = RT_SCOPE_SITE,
Link = RT_SCOPE_LINK,
Host = RT_SCOPE_HOST,
None = RT_SCOPE_NOWHERE,
};
std::string if_name;
int if_index;
nk::ip_address address;
nk::ip_address peer_address;
nk::ip_address broadcast_address;
nk::ip_address anycast_address;
unsigned char addr_type;
unsigned char prefixlen;
unsigned char flags;
Scope scope;
};
struct netif_info
{
std::string name;
std::string qdisc;
unsigned char family;
unsigned short device_type;
int index;
unsigned int flags;
unsigned int change_mask;
unsigned int mtu;
int link_type;
char macaddr[6];
char macbc[6];
bool is_active:1;
std::vector<netif_addr> addrs;
};
class NLSocket
{
public:
NLSocket(std::vector<std::string> &&ifnames);
NLSocket(const NLSocket &) = delete;
NLSocket &operator=(const NLSocket &) = delete;
void process_input();
auto fd() const { return fd_(); }
[[nodiscard]] std::optional<int> get_ifindex(const std::string &name) {
auto elt = name_to_ifindex_.find(name);
if (elt == name_to_ifindex_.end()) return {};
return elt->second;
}
[[nodiscard]] netif_info *get_ifinfo(int ifindex)
{
if (auto elt = interfaces_.find(ifindex); elt != interfaces_.end()) {
return &elt->second;
}
return nullptr;
}
[[nodiscard]] netif_info *get_ifinfo(const std::string &name)
{
auto alt = name_to_ifindex_.find(name);
if (alt != name_to_ifindex_.end()) {
if (auto elt = interfaces_.find(alt->second); elt != interfaces_.end()) {
return &elt->second;
}
}
return nullptr;
}
private:
void process_receive(const char *buf, std::size_t bytes_xferred,
unsigned seq, unsigned portid);
void process_rt_link_msgs(const struct nlmsghdr *nlh);
void process_rt_addr_msgs(const struct nlmsghdr *nlh);
void process_nlmsg(const struct nlmsghdr *nlh);
void request_links();
void request_addrs(int ifidx);
std::map<std::string, int> name_to_ifindex_;
std::map<int, netif_info> interfaces_;
std::vector<std::string> ifnames_;
std::optional<int> query_ifindex_;
nk::sys::handle fd_;
uint32_t nlseq_;
bool got_newlink_:1;
};
#endif