1#!/usr/local/bin/python3 2from enum import Enum 3from typing import Any 4from typing import Dict 5from typing import List 6from typing import NamedTuple 7 8 9class NlConst: 10 AF_NETLINK = 38 11 NETLINK_ROUTE = 0 12 NETLINK_GENERIC = 16 13 GENL_ID_CTRL = 16 14 15 16def roundup2(val: int, num: int) -> int: 17 if val % num: 18 return (val | (num - 1)) + 1 19 else: 20 return val 21 22 23def align4(val: int) -> int: 24 return roundup2(val, 4) 25 26 27def enum_or_int(val) -> int: 28 if isinstance(val, Enum): 29 return val.value 30 return val 31 32 33class AttrDescr(NamedTuple): 34 val: Enum 35 cls: "NlAttr" 36 child_map: Any = None 37 is_array: bool = False 38 39 40def prepare_attrs_map(attrs: List[AttrDescr]) -> Dict[str, Dict]: 41 ret = {} 42 for ad in attrs: 43 ret[ad.val.value] = {"ad": ad} 44 if ad.child_map: 45 ret[ad.val.value]["child"] = prepare_attrs_map(ad.child_map) 46 ret[ad.val.value]["is_array"] = ad.is_array 47 return ret 48 49 50def build_propmap(cls): 51 ret = {} 52 for prop in dir(cls): 53 if not prop.startswith("_"): 54 ret[getattr(cls, prop).value] = prop 55 return ret 56 57 58def get_bitmask_map(propmap, val): 59 v = 1 60 ret = {} 61 while val: 62 if v & val: 63 if v in propmap: 64 ret[v] = propmap[v] 65 else: 66 ret[v] = hex(v) 67 val -= v 68 v *= 2 69 return ret 70 71 72def get_bitmask_str(cls, val): 73 if isinstance(cls, type): 74 pmap = build_propmap(cls) 75 else: 76 pmap = {} 77 for _cls in cls: 78 pmap.update(build_propmap(_cls)) 79 bmap = get_bitmask_map(pmap, val) 80 return ",".join([v for k, v in bmap.items()]) 81