eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

testutil.py (9992B)


      1 #! /usr/bin/python3
      2 # Roughly based on wpa_supplicant's mac80211_hwsim/tools/hwsim_test.c utility.
      3 import socket
      4 import fcntl
      5 import struct
      6 import select
      7 import codecs
      8 import collections
      9 
     10 import iwd
     11 from config import ctx
     12 
     13 HWSIM_ETHERTYPE = 0x0800
     14 HWSIM_PACKETLEN = 250
     15 
     16 def raw_if_socket(intf):
     17     sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
     18                          socket.htons(HWSIM_ETHERTYPE))
     19 
     20     sock.bind((intf, HWSIM_ETHERTYPE))
     21 
     22     return (sock, sock.getsockname()[4])
     23 
     24 def checksum(buf):
     25     pairs = zip(buf[0::2], buf[1::2])
     26     s = sum([(h << 8) + l for h, l in pairs])
     27 
     28     while s >> 16:
     29         s = (s & 0xffff) + (s >> 16)
     30 
     31     return s ^ 0xffff
     32 
     33 def tx(fromsock, tosock, src, dst):
     34     frame = b''.join([
     35         dst, # eth.rmac
     36         src, # eth.lmac
     37         struct.pack('!H', HWSIM_ETHERTYPE), # eth.type
     38         b'\x45', # ip.hdr_len
     39         b'\x00', # ip.dsfield
     40         struct.pack('!H', HWSIM_PACKETLEN - 14), # ip.len
     41         b'\x01\x23', # ip.id
     42         b'\x40\x00', # ip.flags, ip.frag_offset
     43         b'\x40', # ip.ttl
     44         b'\x01', # ip.proto
     45         struct.pack('>H', 0), # ip.checksum
     46         socket.inet_aton('192.168.1.1'), # ip.src
     47         socket.inet_aton('192.168.1.2'), # ip.dst
     48         bytes(range(0, HWSIM_PACKETLEN - 14 - 20))
     49     ])
     50     frame = frame[:24] + struct.pack('>H', checksum(frame[14:34])) + frame[26:]
     51 
     52     fromsock.send(frame)
     53 
     54     return (frame, fromsock, tosock, src, dst)
     55 
     56 def tx_packets(if0, if1, num):
     57     sock0, addr0 = raw_if_socket(if0)
     58     sock1, addr1 = raw_if_socket(if1)
     59 
     60     for i in range(num):
     61         tx(sock0, sock1, addr0, addr1)
     62 
     63 def test_connected(if0=None, if1=None, group=True, expect_fail=False):
     64     if expect_fail:
     65         timeout = 0
     66     else:
     67         timeout = 10
     68 
     69     if if0 is None or if1 is None:
     70         iwd_list = [dev.name for dev in iwd.IWD.get_instance().list_devices()]
     71 
     72         non_iwd_list = [rad.interface.name for rad in ctx.radios if rad.interface is not None]
     73 
     74         for intf in iwd_list + non_iwd_list:
     75             if if0 is None:
     76                 if0 = intf
     77             elif if1 is None and intf != if0:
     78                 if1 = intf
     79 
     80     sock0, addr0 = raw_if_socket(if0)
     81     sock1, addr1 = raw_if_socket(if1)
     82     bcast = b'\xff\xff\xff\xff\xff\xff'
     83 
     84     try:
     85         frames = [
     86             tx(sock0, sock1, addr0, addr1),
     87             tx(sock1, sock0, addr1, addr0),
     88         ]
     89 
     90         rec = [False, False]
     91 
     92         if group:
     93             frames.append(tx(sock0, sock1, addr0, bcast))
     94             frames.append(tx(sock1, sock0, addr1, bcast))
     95             rec.append(False)
     96             rec.append(False)
     97 
     98         while not all(rec):
     99             r, w, x = select.select([sock0, sock1], [], [], timeout)
    100             if not r:
    101                 raise Exception('timeout waiting for packets: ' + repr(rec))
    102 
    103             for s in r:
    104                 data, src = s.recvfrom(HWSIM_PACKETLEN + 1)
    105                 print('received ' + repr(data[:40]) + '... from ' + str(src))
    106                 if len(data) != HWSIM_PACKETLEN:
    107                     continue
    108 
    109                 idx = 0
    110                 for origdata, fromsock, tosock, origsrc, origdst in frames:
    111                     if s is tosock and src[4] == origsrc and data == origdata:
    112                         print('matches frame ' + str(idx))
    113                         break
    114                     idx += 1
    115                 else:
    116                     print('doesn\'t match any of our frames')
    117                     continue
    118 
    119                 if rec[idx]:
    120                     raise Exception('duplicate frame ' + str(idx))
    121 
    122                 rec[idx] = True
    123     finally:
    124         sock0.close()
    125         sock1.close()
    126 
    127 def test_ifaces_connected(if0=None, if1=None, group=True, expect_fail=False):
    128     retry = 0
    129     while True:
    130         try:
    131             test_connected(if0, if1, group, expect_fail)
    132             break
    133 
    134         except Exception as e:
    135             if retry < 3 and not expect_fail:
    136                 print('retrying connection test: %i' % retry)
    137                 retry += 1
    138                 continue
    139             raise e
    140 
    141 SIOCGIFFLAGS = 0x8913
    142 SIOCGIFADDR = 0x8915
    143 SIOCGIFNETMASK = 0x891b
    144 IFF_UP = 1 << 0
    145 IFF_RUNNING = 1 << 6
    146 
    147 def _test_operstate(intf):
    148     sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW)
    149 
    150     try:
    151         ifreq = struct.pack('16sh', intf.encode('utf8'), 0)
    152         flags = struct.unpack('16sh', fcntl.ioctl(sock, SIOCGIFFLAGS, ifreq))[1]
    153 
    154         # IFF_LOWER_UP and IFF_DORMANT not returned by SIOCGIFFLAGS
    155         if flags & (IFF_UP | IFF_RUNNING) != IFF_UP | IFF_RUNNING:
    156             return False
    157 
    158         return True
    159     finally:
    160         sock.close()
    161 
    162 def test_iface_operstate(intf=None):
    163     if not intf:
    164         intf = iwd.IWD.get_instance().list_devices()[0].name
    165 
    166     ctx.non_block_wait(_test_operstate, 10, intf,
    167                         exception=Exception(intf + ' operstate wrong'))
    168 
    169 def get_addrs6(ifname):
    170     f = open('/proc/net/if_inet6', 'r')
    171     lines = f.readlines()
    172     f.close()
    173     for line in lines:
    174         addr_str, _, plen, _, _, addr_ifname = line.split()
    175         if ifname is not None and addr_ifname != ifname:
    176             continue
    177 
    178         yield (codecs.decode(addr_str, 'hex'), int(plen, 16), addr_ifname)
    179 
    180 def test_ip_address_match(intf, expected_addr_str, expected_plen=None, match_plen=None):
    181     def mask_addr(addr, plen):
    182         if plen is None or len(addr) * 8 <= plen:
    183             return addr
    184         bytelen = int(plen / 8)
    185         return addr[0:bytelen] + bytes([addr[bytelen] & (0xff00 >> (plen & 7))]) + b'\0' * (len(addr) - bytelen - 1)
    186     if expected_addr_str is not None:
    187         try:
    188             expected_addr = socket.inet_pton(socket.AF_INET, expected_addr_str)
    189             family = socket.AF_INET
    190         except OSError as e:
    191             try:
    192                 expected_addr = socket.inet_pton(socket.AF_INET6, expected_addr_str)
    193                 family = socket.AF_INET6
    194             except OSError as e2:
    195                 raise e2 from None
    196         expected_addr = mask_addr(expected_addr, match_plen)
    197     else:
    198         expected_addr = None
    199         family = socket.AF_INET
    200 
    201     if family == socket.AF_INET:
    202         try:
    203             s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    204             out = fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', intf.encode('utf-8')))
    205             actual_addr = mask_addr(out[20:24], match_plen)
    206             out = fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, struct.pack('256s', intf.encode('utf-8')))
    207             actual_plen = sum([sum([(byte >> bit) & 1 for bit in range(0, 8)]) for byte in out[20:24]]) # count bits
    208         except OSError as e:
    209             if e.errno == 99 and expected_addr is None:
    210                 return
    211 
    212             raise Exception('SIOCGIFADDR/SIOCGIFNETMASK failed with %d' % e.errno)
    213     else:
    214         # The "get" ioctls don't work for IPv6, netdevice(7) recommends reading /proc/net instead,
    215         # which on the other hand works *only* for IPv6
    216         actual_addr = None
    217         actual_plen = None
    218         for addr, plen, _ in get_addrs6(intf):
    219             actual_addr = mask_addr(addr, match_plen)
    220             actual_plen = plen
    221             if actual_addr == expected_addr:
    222                 break
    223 
    224     if expected_addr != actual_addr:
    225         raise Exception('IP for %s did not match %s (was %s)' %
    226                         (intf, expected_addr_str, socket.inet_ntop(family, actual_addr)))
    227 
    228     if expected_plen is not None and expected_plen != actual_plen:
    229         raise Exception('Prefix Length for %s did not match %i (was %i)' %
    230                         (intf, expected_plen, actual_plen))
    231 
    232 def test_ip_connected(tup0, tup1):
    233     ip0, ns0 = tup0
    234     ip1, ns1 = tup1
    235 
    236     try:
    237         ns0.start_process(['ping', '-c', '5', '-i', '0.2', ip1], check=True)
    238         ns1.start_process(['ping', '-c', '5', '-i', '0.2', ip0], check=True)
    239     except:
    240         raise Exception('Could not ping between %s and %s' % (ip0, ip1))
    241 
    242 RouteInfo = collections.namedtuple('RouteInfo', 'dst plen gw flags ifname',
    243         defaults=(None, None, None, 0, ''))
    244 
    245 def get_routes4(ifname=None):
    246     f = open('/proc/net/route', 'r')
    247     lines = f.readlines()
    248     f.close()
    249     for line in lines[1:]: # Skip header line
    250         route_ifname, dst_str, gw_str, flags, ref_cnt, use_cnt, metric, mask_str, \
    251                 mtu = line.strip().split(maxsplit=8)
    252         if ifname is not None and route_ifname != ifname:
    253             continue
    254 
    255         dst = codecs.decode(dst_str, 'hex')[::-1]
    256         mask = int(mask_str, 16)
    257         plen = sum([(mask >> bit) & 1 for bit in range(0, 32)]) # count bits
    258         gw = codecs.decode(gw_str, 'hex')[::-1]
    259 
    260         if dst == b'\0\0\0\0':
    261             dst = None
    262             plen = None
    263         if gw == b'\0\0\0\0':
    264             gw = None
    265         yield RouteInfo(dst, plen, gw, int(flags, 16), route_ifname)
    266 
    267 def get_routes6(ifname=None):
    268     f = open('/proc/net/ipv6_route', 'r')
    269     lines = f.readlines()
    270     f.close()
    271     for line in lines:
    272         dst_str, dst_plen_str, src_str, src_plen_str, gw_str, metric, ref_cnt, \
    273                 use_cnt, flags, route_ifname = line.strip().split(maxsplit=9)
    274         if ifname is not None and route_ifname != ifname:
    275             continue
    276 
    277         dst = codecs.decode(dst_str, 'hex')
    278         plen = int(dst_plen_str, 16)
    279         gw = codecs.decode(gw_str, 'hex')
    280 
    281         if dst[0] == 0xff or dst[:2] == b'\xfe\x80': # Skip link-local and multicast
    282             continue
    283 
    284         # Skip RTN_LOCAL-type routes, we don't need to validate them since they're added by
    285         # the kernel and we can't simply add them to the expected list (the list that we
    286         # validate against) because they're added a short time after an address (due to DAD?)
    287         # and would create race conditions
    288         if int(flags, 16) & (1 << 31):
    289             continue
    290 
    291         if dst == b'\0' * 16:
    292             dst = None
    293             plen = None
    294         if gw == b'\0' * 16:
    295             gw = None
    296         yield RouteInfo(dst, plen, gw, int(flags, 16) & 0xf, route_ifname)