netlink: improve interface handling

* Separate interface creation from interface modification code
* Support setting some interface attributes (ifdescr, mtu, up/down, promisc)
* Improve interaction with the cloners requiring to parse/write custom
 interface attributes
* Add bitmask-based way of checking if the attribute is present in the
message
* Don't use multipart RTM_GETLINK replies when searching for the
specific interface names
* Use ENODEV instead of ENOENT in case of failed RTM_GETLINK search
* Add python netlink test helpers
* Add some netlink interface tests

Differential Revision: https://reviews.freebsd.org/D37668
This commit is contained in:
Alexander V. Chernikov 2022-12-14 19:45:01 +00:00
parent 1cac76c93f
commit 80f03e63d6
12 changed files with 2122 additions and 59 deletions

View File

@ -826,6 +826,8 @@
tunnel
..
..
netlink
..
netmap
..
netpfil

View File

@ -309,6 +309,8 @@ IFLA_ALT_IFNAME interface name
(binary) (readonly) Link-level broadcast address.
.It Dv IFLA_IFNAME
(string) New interface name.
.It Dv IFLA_IFALIAS
(string) Interface description.
.It Dv IFLA_LINK
(uint32_t) (readonly) Interface index.
.It Dv IFLA_MASTER

View File

@ -147,17 +147,23 @@ nl_parse_attrs_raw(struct nlattr *nla_head, int len, const struct nlattr_parser
return (0);
}
int
nl_parse_attrs(struct nlmsghdr *hdr, int hdrlen, struct nlattr_parser *ps, int pslen,
struct nl_pstate *npt, void *target)
void
nl_get_attrs_bmask_raw(struct nlattr *nla_head, int len, struct nlattr_bmask *bm)
{
int off = NLMSG_HDRLEN + NETLINK_ALIGN(hdrlen);
int len = hdr->nlmsg_len - off;
struct nlattr *nla_head = (struct nlattr *)((char *)hdr + off);
struct nlattr *nla = NULL;
return (nl_parse_attrs_raw(nla_head, len, ps, pslen, npt, target));
bzero(bm->mask, sizeof(bm->mask));
NLA_FOREACH(nla, nla_head, len) {
if (nla->nla_len < sizeof(struct nlattr))
return;
int nla_type = nla->nla_type & NLA_TYPE_MASK;
if (nla_type <= sizeof(bm->mask) * 8)
bm->mask[nla_type / 8] |= 1 << (nla_type % 8);
}
}
int
nlattr_get_flag(struct nlattr *nla, struct nl_pstate *npt, const void *arg, void *target)
{

View File

@ -152,15 +152,21 @@ static const struct nlhdr_parser _name = { \
.np_size = NL_ARRAY_LEN(_np), \
}
struct nlarr_hdr {
int num_items;
int max_items;
struct nlattr_bmask {
uint64_t mask[2];
};
static inline bool
nl_has_attr(const struct nlattr_bmask *bm, unsigned int attr_type)
{
MPASS(attr_type < sizeof(bm->mask) * 8);
return ((bm->mask[attr_type / 8] & (1 << (attr_type % 8))));
}
void nl_get_attrs_bmask_raw(struct nlattr *nla_head, int len, struct nlattr_bmask *bm);
int nl_parse_attrs_raw(struct nlattr *nla_head, int len, const struct nlattr_parser *ps,
int pslen, struct nl_pstate *npt, void *target);
int nl_parse_attrs(struct nlmsghdr *hdr, int hdrlen, struct nlattr_parser *ps,
int pslen, struct nl_pstate *npt, void *target);
int nlattr_get_flag(struct nlattr *nla, struct nl_pstate *npt,
const void *arg, void *target);
@ -270,5 +276,17 @@ nl_parse_nlmsg(struct nlmsghdr *hdr, const struct nlhdr_parser *parser,
return (nl_parse_header(hdr + 1, hdr->nlmsg_len - sizeof(*hdr), parser, npt, target));
}
static inline void
nl_get_attrs_bmask_nlmsg(struct nlmsghdr *hdr, const struct nlhdr_parser *parser,
struct nlattr_bmask *bm)
{
struct nlattr *nla_head;
nla_head = (struct nlattr *)((char *)(hdr + 1) + parser->nl_hdr_off);
int len = hdr->nlmsg_len - sizeof(*hdr) - parser->nl_hdr_off;
nl_get_attrs_bmask_raw(nla_head, len, bm);
}
#endif
#endif

View File

@ -75,6 +75,8 @@ static SLIST_HEAD(, nl_cloner) nl_cloners = SLIST_HEAD_INITIALIZER(nl_cloners);
static struct sx rtnl_cloner_lock;
SX_SYSINIT(rtnl_cloner_lock, &rtnl_cloner_lock, "rtnl cloner lock");
static struct nl_cloner *rtnl_iface_find_cloner_locked(const char *name);
/*
* RTM_GETLINK request
* sendto(3, {{len=32, type=RTM_GETLINK, flags=NLM_F_REQUEST|NLM_F_DUMP, seq=1641940952, pid=0},
@ -286,11 +288,23 @@ dump_iface(struct nl_writer *nw, struct ifnet *ifp, const struct nlmsghdr *hdr,
nlattr_add_u32(nw, IFLA_MAX_MTU, 9000);
nlattr_add_u32(nw, IFLA_GROUP, 0);
*/
if (ifp->if_description != NULL)
nlattr_add_string(nw, IFLA_IFALIAS, ifp->if_description);
get_stats(nw, ifp);
uint32_t val = (ifp->if_flags & IFF_PROMISC) != 0;
nlattr_add_u32(nw, IFLA_PROMISCUITY, val);
sx_slock(&rtnl_cloner_lock);
struct nl_cloner *cloner = rtnl_iface_find_cloner_locked(ifp->if_dname);
if (cloner != NULL && cloner->dump_f != NULL) {
/* Ignore any dump error */
cloner->dump_f(ifp, nw);
}
sx_sunlock(&rtnl_cloner_lock);
if (nlmsg_end(nw))
return (true);
@ -320,6 +334,8 @@ check_ifmsg(void *hdr, struct nl_pstate *npt)
static const struct nlfield_parser nlf_p_if[] = {
{ .off_in = _IN(ifi_type), .off_out = _OUT(ifi_type), .cb = nlf_get_u16 },
{ .off_in = _IN(ifi_index), .off_out = _OUT(ifi_index), .cb = nlf_get_u32 },
{ .off_in = _IN(ifi_flags), .off_out = _OUT(ifi_flags), .cb = nlf_get_u32 },
{ .off_in = _IN(ifi_change), .off_out = _OUT(ifi_change), .cb = nlf_get_u32 },
};
static const struct nlattr_parser nla_p_linfo[] = {
@ -333,6 +349,7 @@ static const struct nlattr_parser nla_p_if[] = {
{ .type = IFLA_MTU, .off = _OUT(ifla_mtu), .cb = nlattr_get_uint32 },
{ .type = IFLA_LINK, .off = _OUT(ifi_index), .cb = nlattr_get_uint32 },
{ .type = IFLA_LINKINFO, .arg = &linfo_parser, .cb = nlattr_get_nested },
{ .type = IFLA_IFALIAS, .off = _OUT(ifla_ifalias), .cb = nlattr_get_string },
{ .type = IFLA_GROUP, .off = _OUT(ifla_group), .cb = nlattr_get_string },
{ .type = IFLA_ALT_IFNAME, .off = _OUT(ifla_ifname), .cb = nlattr_get_string },
};
@ -379,28 +396,39 @@ rtnl_handle_getlink(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *n
.nw = npt->nw,
.hdr.nlmsg_pid = hdr->nlmsg_pid,
.hdr.nlmsg_seq = hdr->nlmsg_seq,
.hdr.nlmsg_flags = hdr->nlmsg_flags | NLM_F_MULTI,
.hdr.nlmsg_flags = hdr->nlmsg_flags,
.hdr.nlmsg_type = NL_RTM_NEWLINK,
};
/* Fast track for an interface w/ explicit index match */
if (attrs.ifi_index != 0) {
NET_EPOCH_ENTER(et);
ifp = ifnet_byindex_ref(attrs.ifi_index);
NET_EPOCH_EXIT(et);
NLP_LOG(LOG_DEBUG3, nlp, "fast track -> searching index %u", attrs.ifi_index);
/* Fast track for an interface w/ explicit name or index match */
if ((attrs.ifi_index != 0) || (attrs.ifla_ifname != NULL)) {
if (attrs.ifi_index != 0) {
NLP_LOG(LOG_DEBUG3, nlp, "fast track -> searching index %u",
attrs.ifi_index);
NET_EPOCH_ENTER(et);
ifp = ifnet_byindex_ref(attrs.ifi_index);
NET_EPOCH_EXIT(et);
} else {
NLP_LOG(LOG_DEBUG3, nlp, "fast track -> searching name %s",
attrs.ifla_ifname);
ifp = ifunit_ref(attrs.ifla_ifname);
}
if (ifp != NULL) {
if (match_iface(&attrs, ifp)) {
if (!dump_iface(wa.nw, ifp, &wa.hdr, 0))
error = ENOMEM;
} else
error = ESRCH;
error = ENODEV;
if_rele(ifp);
} else
error = ESRCH;
error = ENODEV;
return (error);
}
/* Always treat non-direct-match as a multipart message */
wa.hdr.nlmsg_flags |= NLM_F_MULTI;
/*
* Fetching some link properties require performing ioctl's that may be blocking.
* Address it by saving referenced pointers of the matching links,
@ -504,46 +532,144 @@ rtnl_handle_dellink(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *n
return (error);
}
/*
* New link:
* type=RTM_NEWLINK, flags=NLM_F_REQUEST|NLM_F_ACK|NLM_F_EXCL|NLM_F_CREATE, seq=1668185590, pid=0},
* {ifi_family=AF_UNSPEC, ifi_type=ARPHRD_NETROM, ifi_index=0, ifi_flags=0, ifi_change=0}
* [
* {{nla_len=8, nla_type=IFLA_MTU}, 123},
* {{nla_len=10, nla_type=IFLA_IFNAME}, "vlan1"},
* {{nla_len=24, nla_type=IFLA_LINKINFO},
* [
* {{nla_len=8, nla_type=IFLA_INFO_KIND}, "vlan"...},
* {{nla_len=12, nla_type=IFLA_INFO_DATA}, "\x06\x00\x01\x00\x7b\x00\x00\x00"}]}]}
*
* Update link:
* type=RTM_NEWLINK, flags=NLM_F_REQUEST|NLM_F_ACK, seq=1668185923, pid=0},
* {ifi_family=AF_UNSPEC, ifi_type=ARPHRD_NETROM, ifi_index=if_nametoindex("lo"), ifi_flags=0, ifi_change=0},
* {{nla_len=8, nla_type=IFLA_MTU}, 123}}
*
*
* Check command availability:
* type=RTM_NEWLINK, flags=NLM_F_REQUEST|NLM_F_ACK, seq=0, pid=0},
* {ifi_family=AF_UNSPEC, ifi_type=ARPHRD_NETROM, ifi_index=0, ifi_flags=0, ifi_change=0}
*/
static int
create_link(struct nlmsghdr *hdr, struct nl_parsed_link *lattrs,
struct nlattr_bmask *bm, struct nlpcb *nlp, struct nl_pstate *npt)
{
if (lattrs->ifla_ifname == NULL || strlen(lattrs->ifla_ifname) == 0) {
NLMSG_REPORT_ERR_MSG(npt, "empty IFLA_IFNAME attribute");
return (EINVAL);
}
if (lattrs->ifla_cloner == NULL || strlen(lattrs->ifla_cloner) == 0) {
NLMSG_REPORT_ERR_MSG(npt, "empty IFLA_INFO_KIND attribute");
return (EINVAL);
}
bool found = false;
int error = 0;
sx_slock(&rtnl_cloner_lock);
struct nl_cloner *cloner = rtnl_iface_find_cloner_locked(lattrs->ifla_cloner);
if (cloner != NULL) {
found = true;
error = cloner->create_f(lattrs, bm, nlp, npt);
}
sx_sunlock(&rtnl_cloner_lock);
if (!found)
error = generic_cloner.create_f(lattrs, bm, nlp, npt);
return (error);
}
static int
modify_link(struct nlmsghdr *hdr, struct nl_parsed_link *lattrs,
struct nlattr_bmask *bm, struct nlpcb *nlp, struct nl_pstate *npt)
{
struct ifnet *ifp = NULL;
struct epoch_tracker et;
if (lattrs->ifi_index == 0 && lattrs->ifla_ifname == NULL) {
/*
* Applications like ip(8) verify RTM_NEWLINK command
* existence by calling it with empty arguments. Always
* return "innocent" error in that case.
*/
NLMSG_REPORT_ERR_MSG(npt, "empty ifi_index field");
return (EPERM);
}
if (lattrs->ifi_index != 0) {
NET_EPOCH_ENTER(et);
ifp = ifnet_byindex_ref(lattrs->ifi_index);
NET_EPOCH_EXIT(et);
if (ifp == NULL) {
NLMSG_REPORT_ERR_MSG(npt, "unable to find interface #%u",
lattrs->ifi_index);
return (ENOENT);
}
}
if (ifp == NULL && lattrs->ifla_ifname != NULL) {
ifp = ifunit_ref(lattrs->ifla_ifname);
if (ifp == NULL) {
NLMSG_REPORT_ERR_MSG(npt, "unable to find interface %s",
lattrs->ifla_ifname);
return (ENOENT);
}
}
MPASS(ifp != NULL);
/*
* There can be multiple kinds of interfaces:
* 1) cloned, with additional options
* 2) cloned, but w/o additional options
* 3) non-cloned (e.g. "physical).
*
* Thus, try to find cloner-specific callback and fallback to the
* "default" handler if not found.
*/
bool found = false;
int error = 0;
sx_slock(&rtnl_cloner_lock);
struct nl_cloner *cloner = rtnl_iface_find_cloner_locked(ifp->if_dname);
if (cloner != NULL) {
found = true;
error = cloner->modify_f(ifp, lattrs, bm, nlp, npt);
}
sx_sunlock(&rtnl_cloner_lock);
if (!found)
error = generic_cloner.modify_f(ifp, lattrs, bm, nlp, npt);
if_rele(ifp);
return (error);
}
static int
rtnl_handle_newlink(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *npt)
{
struct nl_cloner *cloner;
struct nlattr_bmask bm;
int error;
struct nl_parsed_link attrs = {};
error = nl_parse_nlmsg(hdr, &ifmsg_parser, npt, &attrs);
if (error != 0)
return (error);
nl_get_attrs_bmask_nlmsg(hdr, &ifmsg_parser, &bm);
if (attrs.ifla_ifname == NULL || strlen(attrs.ifla_ifname) == 0) {
/* Applications like ip(8) verify RTM_NEWLINK existance
* by calling it with empty arguments. Always return "innocent"
* error.
*/
NLMSG_REPORT_ERR_MSG(npt, "empty IFLA_IFNAME attribute");
return (EPERM);
}
if (attrs.ifla_cloner == NULL || strlen(attrs.ifla_cloner) == 0) {
NLMSG_REPORT_ERR_MSG(npt, "empty IFLA_INFO_KIND attribute");
return (EINVAL);
}
sx_slock(&rtnl_cloner_lock);
SLIST_FOREACH(cloner, &nl_cloners, next) {
if (!strcmp(attrs.ifla_cloner, cloner->name)) {
error = cloner->create_f(&attrs, nlp, npt);
sx_sunlock(&rtnl_cloner_lock);
return (error);
}
}
sx_sunlock(&rtnl_cloner_lock);
/* TODO: load cloner module if not exists & privilege permits */
NLMSG_REPORT_ERR_MSG(npt, "interface type %s not supported", attrs.ifla_cloner);
return (ENOTSUP);
return (error);
if (hdr->nlmsg_flags & NLM_F_CREATE)
return (create_link(hdr, &attrs, &bm, nlp, npt));
else
return (modify_link(hdr, &attrs, &bm, nlp, npt));
}
/*
@ -863,13 +989,27 @@ rtnl_iface_add_cloner(struct nl_cloner *cloner)
sx_xunlock(&rtnl_cloner_lock);
}
void rtnl_iface_del_cloner(struct nl_cloner *cloner)
void
rtnl_iface_del_cloner(struct nl_cloner *cloner)
{
sx_xlock(&rtnl_cloner_lock);
SLIST_REMOVE(&nl_cloners, cloner, nl_cloner, next);
sx_xunlock(&rtnl_cloner_lock);
}
static struct nl_cloner *
rtnl_iface_find_cloner_locked(const char *name)
{
struct nl_cloner *cloner;
SLIST_FOREACH(cloner, &nl_cloners, next) {
if (!strcmp(name, cloner->name))
return (cloner);
}
return (NULL);
}
void
rtnl_ifaces_init(void)
{

View File

@ -58,6 +58,95 @@ __FBSDID("$FreeBSD$");
#include <netlink/netlink_debug.h>
_DECLARE_DEBUG(LOG_DEBUG);
/*
* Generic modification interface handler.
* Responsible for changing network stack interface attributes
* such as state, mtu or description.
*/
static int
modify_generic(struct ifnet *ifp, struct nl_parsed_link *lattrs,
const struct nlattr_bmask *bm, struct nlpcb *nlp, struct nl_pstate *npt)
{
int error;
if (lattrs->ifla_ifalias != NULL) {
if (nlp_has_priv(nlp, PRIV_NET_SETIFDESCR)) {
int len = strlen(lattrs->ifla_ifalias) + 1;
char *buf = if_allocdescr(len, true);
memcpy(buf, lattrs->ifla_ifalias, len);
if_setdescr(ifp, buf);
getmicrotime(&ifp->if_lastchange);
} else {
nlmsg_report_err_msg(npt, "Not enough privileges to set descr");
return (EPERM);
}
}
if ((lattrs->ifi_change & IFF_UP) && (lattrs->ifi_flags & IFF_UP) == 0) {
/* Request to down the interface */
if_down(ifp);
}
if (lattrs->ifla_mtu > 0) {
if (nlp_has_priv(nlp, PRIV_NET_SETIFMTU)) {
struct ifreq ifr = { .ifr_mtu = lattrs->ifla_mtu };
error = ifhwioctl(SIOCSIFMTU, ifp, (char *)&ifr, curthread);
} else {
nlmsg_report_err_msg(npt, "Not enough privileges to set mtu");
return (EPERM);
}
}
if (lattrs->ifi_change & IFF_PROMISC) {
error = ifpromisc(ifp, lattrs->ifi_flags & IFF_PROMISC);
if (error != 0) {
nlmsg_report_err_msg(npt, "unable to set promisc");
return (error);
}
}
return (0);
}
/*
* Generic creation interface handler.
* Responsible for creating interfaces w/o parameters and setting
* misc attributes such as state, mtu or description.
*/
static int
create_generic(struct nl_parsed_link *lattrs, const struct nlattr_bmask *bm,
struct nlpcb *nlp, struct nl_pstate *npt)
{
int error = 0;
struct ifc_data ifd = {};
struct ifnet *ifp = NULL;
error = ifc_create_ifp(lattrs->ifla_ifname, &ifd, &ifp);
NLP_LOG(LOG_DEBUG2, nlp, "clone for %s returned %d", lattrs->ifla_ifname, error);
if (error == 0) {
struct epoch_tracker et;
NET_EPOCH_ENTER(et);
bool success = if_try_ref(ifp);
NET_EPOCH_EXIT(et);
if (!success)
return (EINVAL);
error = modify_generic(ifp, lattrs, bm, nlp, npt);
if_rele(ifp);
}
return (error);
}
struct nl_cloner generic_cloner = {
.name = "_default_",
.create_f = create_generic,
.modify_f = modify_generic,
};
/*
*
* {len=76, type=RTM_NEWLINK, flags=NLM_F_REQUEST|NLM_F_ACK|NLM_F_EXCL|NLM_F_CREATE, seq=1662892737, pid=0},
@ -87,7 +176,8 @@ static const struct nlattr_parser nla_p_vlan[] = {
NL_DECLARE_ATTR_PARSER(vlan_parser, nla_p_vlan);
static int
create_vlan(struct nl_parsed_link *lattrs, struct nlpcb *nlp, struct nl_pstate *npt)
create_vlan(struct nl_parsed_link *lattrs, const struct nlattr_bmask *bm,
struct nlpcb *nlp, struct nl_pstate *npt)
{
struct epoch_tracker et;
struct ifnet *ifp;
@ -147,9 +237,17 @@ create_vlan(struct nl_parsed_link *lattrs, struct nlpcb *nlp, struct nl_pstate *
return (error);
}
static int
dump_vlan(struct ifnet *ifp, struct nl_writer *nw)
{
return (0);
}
static struct nl_cloner vlan_cloner = {
.name = "vlan",
.create_f = create_vlan,
.modify_f = modify_generic,
.dump_f = dump_vlan,
};

View File

@ -92,7 +92,7 @@ enum {
#define IFLA_LINKINFO IFLA_LINKINFO
IFLA_NET_NS_PID = 19, /* u32: vnet id (not supported) */
#define IFLA_NET_NS_PID IFLA_NET_NS_PID
IFLA_IFALIAS = 20, /* not supported */
IFLA_IFALIAS = 20, /* string: interface description */
#define IFLA_IFALIAS IFLA_IFALIAS
IFLA_NUM_VF = 21, /* not supported */
#define IFLA_NUM_VF IFLA_NUM_VF

View File

@ -66,24 +66,31 @@ struct nl_parsed_link {
char *ifla_group;
char *ifla_ifname;
char *ifla_cloner;
char *ifla_ifalias;
struct nlattr *ifla_idata;
unsigned short ifi_type;
int ifi_index;
uint32_t ifla_mtu;
uint32_t ifi_flags;
uint32_t ifi_change;
};
typedef int rtnl_iface_create_f(struct nl_parsed_link *lattrs, struct nlpcb *nlp,
struct nl_pstate *npt);
typedef int rtnl_iface_modify_f(struct nl_parsed_link *lattrs, struct nlpcb *nlp,
struct nl_pstate *npt);
typedef int rtnl_iface_create_f(struct nl_parsed_link *lattrs,
const struct nlattr_bmask *bm, struct nlpcb *nlp, struct nl_pstate *npt);
typedef int rtnl_iface_modify_f(struct ifnet *ifp, struct nl_parsed_link *lattrs,
const struct nlattr_bmask *bm, struct nlpcb *nlp, struct nl_pstate *npt);
typedef int rtnl_iface_dump_f(struct ifnet *ifp, struct nl_writer *nw);
struct nl_cloner {
const char *name;
rtnl_iface_create_f *create_f;
rtnl_iface_modify_f *modify_f;
rtnl_iface_dump_f *dump_f;
SLIST_ENTRY(nl_cloner) next;
};
extern struct nl_cloner generic_cloner;
void rtnl_ifaces_init(void);
void rtnl_ifaces_destroy(void);
void rtnl_iface_add_cloner(struct nl_cloner *cloner);

View File

@ -2,7 +2,7 @@
.PATH: ${.CURDIR}
FILES= __init__.py rtsock.py tools.py vnet.py
FILES= __init__.py netlink.py rtsock.py tools.py vnet.py
.include <bsd.own.mk>
FILESDIR= ${TESTSBASE}/atf_python/sys/net

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
# $FreeBSD$
PACKAGE= tests
WARNS?= 1
TESTSDIR= ${TESTSBASE}/sys/netlink
#ATF_TESTS_C += test_rtsock_l3
#ATF_TESTS_C += test_rtsock_lladdr
ATF_TESTS_PYTEST += test_rtnl_iface.py
CFLAGS+= -I${.CURDIR:H:H:H}
.include <bsd.test.mk>

View File

@ -0,0 +1,281 @@
import errno
import socket
import pytest
from atf_python.sys.net.netlink import IflattrType
from atf_python.sys.net.netlink import IflinkInfo
from atf_python.sys.net.netlink import IfLinkInfoDataVlan
from atf_python.sys.net.netlink import NetlinkIflaMessage
from atf_python.sys.net.netlink import NlAttrNested
from atf_python.sys.net.netlink import NlAttrStr
from atf_python.sys.net.netlink import NlAttrStrn
from atf_python.sys.net.netlink import NlAttrU16
from atf_python.sys.net.netlink import NlAttrU32
from atf_python.sys.net.netlink import NlConst
from atf_python.sys.net.netlink import NlHelper
from atf_python.sys.net.netlink import NlmBaseFlags
from atf_python.sys.net.netlink import NlmNewFlags
from atf_python.sys.net.netlink import NlMsgType
from atf_python.sys.net.netlink import NlRtMsgType
from atf_python.sys.net.netlink import Nlsock
from atf_python.sys.net.vnet import SingleVnetTestTemplate
class TestRtNlIface(SingleVnetTestTemplate):
def setup_method(self, method):
super().setup_method(method)
self.helper = NlHelper()
self.nlsock = Nlsock(NlConst.NETLINK_ROUTE, self.helper)
def write_message(self, msg):
print("")
print("============= >> TX MESSAGE =============")
msg.print_message()
self.nlsock.write_data(bytes(msg))
msg.print_as_bytes(bytes(msg), "-- DATA --")
def read_message(self):
msg = self.nlsock.read_message()
print("")
print("============= << RX MESSAGE =============")
msg.print_message()
return msg
def get_reply(self, tx_msg):
self.write_message(tx_msg)
while True:
rx_msg = self.read_message()
if tx_msg.nl_hdr.nlmsg_seq == rx_msg.nl_hdr.nlmsg_seq:
return rx_msg
def get_interface_byname(self, ifname):
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_GETLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, ifname))
self.write_message(msg)
while True:
rx_msg = self.read_message()
if msg.nl_hdr.nlmsg_seq == rx_msg.nl_hdr.nlmsg_seq:
if rx_msg.is_type(NlMsgType.NLMSG_ERROR):
if rx_msg.error_code != 0:
raise ValueError("unable to get interface {}".format(ifname))
elif rx_msg.is_type(NlRtMsgType.RTM_NEWLINK):
return rx_msg
else:
raise ValueError("bad message")
def test_get_iface_byname_error(self):
"""Tests error on fetching non-existing interface name"""
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_GETLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == errno.ENODEV
def test_get_iface_byindex_error(self):
"""Tests error on fetching non-existing interface index"""
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_GETLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.base_hdr.ifi_index = 2147483647
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == errno.ENODEV
@pytest.mark.require_user("root")
def test_create_iface_plain(self):
"""Tests loopback creation w/o any parameters"""
flags = NlmNewFlags.NLM_F_EXCL.value | NlmNewFlags.NLM_F_CREATE.value
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
flags | NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
msg.add_nla(
NlAttrNested(
IflattrType.IFLA_LINKINFO,
[
NlAttrStrn(IflinkInfo.IFLA_INFO_KIND, "lo"),
],
)
)
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
self.get_interface_byname("lo10")
@pytest.mark.require_user("root")
def test_create_iface_attrs(self):
"""Tests interface creation with additional properties"""
flags = NlmNewFlags.NLM_F_EXCL.value | NlmNewFlags.NLM_F_CREATE.value
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
flags | NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
msg.add_nla(
NlAttrNested(
IflattrType.IFLA_LINKINFO,
[
NlAttrStrn(IflinkInfo.IFLA_INFO_KIND, "lo"),
],
)
)
# Custom attributes
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFALIAS, "test description"))
msg.add_nla(NlAttrU32(IflattrType.IFLA_MTU, 1024))
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
iface_msg = self.get_interface_byname("lo10")
assert iface_msg.get_nla(IflattrType.IFLA_IFALIAS).text == "test description"
assert iface_msg.get_nla(IflattrType.IFLA_MTU).u32 == 1024
@pytest.mark.require_user("root")
def test_modify_iface_attrs(self):
"""Tests interface modifications"""
flags = NlmNewFlags.NLM_F_EXCL.value | NlmNewFlags.NLM_F_CREATE.value
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
flags | NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
msg.add_nla(
NlAttrNested(
IflattrType.IFLA_LINKINFO,
[
NlAttrStrn(IflinkInfo.IFLA_INFO_KIND, "lo"),
],
)
)
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
# Custom attributes
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFALIAS, "test description"))
msg.add_nla(NlAttrU32(IflattrType.IFLA_MTU, 1024))
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
iface_msg = self.get_interface_byname("lo10")
assert iface_msg.get_nla(IflattrType.IFLA_IFALIAS).text == "test description"
assert iface_msg.get_nla(IflattrType.IFLA_MTU).u32 == 1024
@pytest.mark.require_user("root")
def test_delete_iface(self):
"""Tests interface modifications"""
flags = NlmNewFlags.NLM_F_EXCL.value | NlmNewFlags.NLM_F_CREATE.value
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
flags | NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
msg.add_nla(
NlAttrNested(
IflattrType.IFLA_LINKINFO,
[
NlAttrStrn(IflinkInfo.IFLA_INFO_KIND, "lo"),
],
)
)
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
iface_msg = self.get_interface_byname("lo10")
iface_idx = iface_msg.base_hdr.ifi_index
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_DELLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.base_hdr.ifi_index = iface_idx
# msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "lo10"))
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_GETLINK.value)
msg.nl_hdr.nlmsg_flags = (
NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.base_hdr.ifi_index = 2147483647
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == errno.ENODEV
#
# *
# * {len=76, type=RTM_NEWLINK, flags=NLM_F_REQUEST|NLM_F_ACK|NLM_F_EXCL|NLM_F_CREATE, seq=1662892737, pid=0},
# * {ifi_family=AF_UNSPEC, ifi_type=ARPHRD_NETROM, ifi_index=0, ifi_flags=0, ifi_change=0},
# * [
# * {{nla_len=8, nla_type=IFLA_LINK}, 2},
# * {{nla_len=12, nla_type=IFLA_IFNAME}, "xvlan22"},
# * {{nla_len=24, nla_type=IFLA_LINKINFO},
# * [
# * {{nla_len=8, nla_type=IFLA_INFO_KIND}, "vlan"...},
# * {{nla_len=12, nla_type=IFLA_INFO_DATA}, "\x06\x00\x01\x00\x16\x00\x00\x00"}]}]}, iov_len=76}], msg_iovlen=1, msg_controllen=0, msg_flags=0}, 0) = 76
# */
@pytest.mark.skip(reason="vlan support needs more work")
@pytest.mark.require_user("root")
def test_create_vlan_plain(self):
"""Creates 802.1Q VLAN interface in vlanXX and ifX fashion"""
os_ifname = self.vnet.iface_alias_map["if1"].name
ifindex = socket.if_nametoindex(os_ifname)
flags = NlmNewFlags.NLM_F_EXCL.value | NlmNewFlags.NLM_F_CREATE.value
msg = NetlinkIflaMessage(self.helper, NlRtMsgType.RTM_NEWLINK.value)
msg.nl_hdr.nlmsg_flags = (
flags | NlmBaseFlags.NLM_F_ACK.value | NlmBaseFlags.NLM_F_REQUEST.value
)
msg.add_nla(NlAttrU32(IflattrType.IFLA_LINK, ifindex))
msg.add_nla(NlAttrStr(IflattrType.IFLA_IFNAME, "vlan22"))
msg.add_nla(
NlAttrNested(
IflattrType.IFLA_LINKINFO,
[
NlAttrStrn(IflinkInfo.IFLA_INFO_KIND, "vlan"),
NlAttrNested(
IflinkInfo.IFLA_INFO_DATA,
[
NlAttrU16(IfLinkInfoDataVlan.IFLA_VLAN_ID, 22),
],
),
],
)
)
rx_msg = self.get_reply(msg)
assert rx_msg.is_type(NlMsgType.NLMSG_ERROR)
assert rx_msg.error_code == 0
self.get_interface_byname("vlan22")
# ToolsHelper.print_net_debug()