Implement a secure ICS protocol targeting LoRa Node151 microcontroller for controlling irrigation.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1119 lines
27 KiB

  1. # Copyright 2021 John-Mark Gurney.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions
  5. # are met:
  6. # 1. Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # 2. Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. #
  12. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  13. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  15. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  16. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  17. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  18. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  19. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  20. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  21. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22. # SUCH DAMAGE.
  23. #
  24. import asyncio
  25. import contextlib
  26. import functools
  27. import itertools
  28. import os
  29. import sys
  30. import unittest
  31. from Strobe.Strobe import Strobe, KeccakF
  32. from Strobe.Strobe import AuthenticationFailed
  33. import lora_comms
  34. from lora_comms import make_pktbuf
  35. import multicast
  36. from util import *
  37. domain = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  38. # Response to command will be the CMD and any arguments if needed.
  39. # The command is encoded as an unsigned byte
  40. CMD_TERMINATE = 1 # no args: terminate the sesssion, reply confirms
  41. # The follow commands are queue up, but will be acknoledged when queued
  42. CMD_WAITFOR = 2 # arg: (length): waits for length seconds
  43. CMD_RUNFOR = 3 # arg: (chan, length): turns on chan for length seconds
  44. CMD_PING = 4 # arg: (): a no op command
  45. CMD_SETUNSET = 5 # arg: (chan, val): sets chan to val
  46. class LORANode(object):
  47. '''Implement a LORANode initiator.'''
  48. MAC_LEN = 8
  49. def __init__(self, syncdatagram, shared=None):
  50. self.sd = syncdatagram
  51. self.st = Strobe(domain, F=KeccakF(800))
  52. if shared is not None:
  53. self.st.key(shared)
  54. async def start(self):
  55. resp = await self.sendrecvvalid(os.urandom(16) + b'reqreset')
  56. self.st.ratchet()
  57. pkt = await self.sendrecvvalid(b'confirm')
  58. if pkt != b'confirmed':
  59. raise RuntimeError('got invalid response: %s' %
  60. repr(pkt))
  61. async def sendrecvvalid(self, msg):
  62. msg = self.st.send_enc(msg) + self.st.send_mac(self.MAC_LEN)
  63. origstate = self.st.copy()
  64. while True:
  65. resp = await self.sd.sendtillrecv(msg, .25)
  66. #_debprint('got:', resp)
  67. # skip empty messages
  68. if len(resp) == 0:
  69. continue
  70. try:
  71. decmsg = self.st.recv_enc(resp[:-self.MAC_LEN])
  72. self.st.recv_mac(resp[-self.MAC_LEN:])
  73. break
  74. except AuthenticationFailed:
  75. # didn't get a valid packet, restore
  76. # state and retry
  77. #_debprint('failed')
  78. self.st.set_state_from(origstate)
  79. #_debprint('got rep:', repr(resp), repr(decmsg))
  80. return decmsg
  81. @staticmethod
  82. def _encodeargs(*args):
  83. r = []
  84. for i in args:
  85. r.append(i.to_bytes(4, byteorder='little'))
  86. return b''.join(r)
  87. async def _sendcmd(self, cmd, *args):
  88. cmdbyte = cmd.to_bytes(1, byteorder='little')
  89. resp = await self.sendrecvvalid(cmdbyte + self._encodeargs(*args))
  90. if resp[0:1] != cmdbyte:
  91. raise RuntimeError(
  92. 'response does not match, got: %s, expected: %s' %
  93. (repr(resp[0:1]), repr(cmdbyte)))
  94. async def waitfor(self, length):
  95. return await self._sendcmd(CMD_WAITFOR, length)
  96. async def runfor(self, chan, length):
  97. return await self._sendcmd(CMD_RUNFOR, chan, length)
  98. async def setunset(self, chan, val):
  99. return await self._sendcmd(CMD_SETUNSET, chan, val)
  100. async def ping(self):
  101. return await self._sendcmd(CMD_PING)
  102. async def terminate(self):
  103. return await self._sendcmd(CMD_TERMINATE)
  104. class SyncDatagram(object):
  105. '''Base interface for a more simple synchronous interface.'''
  106. async def recv(self, timeout=None): #pragma: no cover
  107. '''Receive a datagram. If timeout is not None, wait that many
  108. seconds, and if nothing is received in that time, raise an
  109. asyncio.TimeoutError exception.'''
  110. raise NotImplementedError
  111. async def send(self, data): #pragma: no cover
  112. raise NotImplementedError
  113. async def sendtillrecv(self, data, freq):
  114. '''Send the datagram in data, every freq seconds until a datagram
  115. is received. If timeout seconds happen w/o receiving a datagram,
  116. then raise an TimeoutError exception.'''
  117. while True:
  118. #_debprint('sending:', repr(data))
  119. await self.send(data)
  120. try:
  121. return await self.recv(freq)
  122. except asyncio.TimeoutError:
  123. pass
  124. class MulticastSyncDatagram(SyncDatagram):
  125. '''
  126. An implementation of SyncDatagram that uses the provided
  127. multicast address maddr as the source/sink of the packets.
  128. Note that once created, the start coroutine needs to be
  129. await'd before being passed to a LORANode so that everything
  130. is running.
  131. '''
  132. # Note: sent packets will be received. A similar method to
  133. # what was done in multicast.{to,from}_loragw could be done
  134. # here as well, that is passing in a set of packets to not
  135. # pass back up.
  136. def __init__(self, maddr):
  137. self.maddr = maddr
  138. self._ignpkts = set()
  139. async def start(self):
  140. self.mr = await multicast.create_multicast_receiver(self.maddr)
  141. self.mt = await multicast.create_multicast_transmitter(
  142. self.maddr)
  143. async def _recv(self):
  144. while True:
  145. pkt = await self.mr.recv()
  146. pkt = pkt[0]
  147. if pkt not in self._ignpkts:
  148. return pkt
  149. self._ignpkts.remove(pkt)
  150. async def recv(self, timeout=None): #pragma: no cover
  151. r = await asyncio.wait_for(self._recv(), timeout=timeout)
  152. return r
  153. async def send(self, data): #pragma: no cover
  154. self._ignpkts.add(bytes(data))
  155. await self.mt.send(data)
  156. def close(self):
  157. '''Shutdown communications.'''
  158. self.mr.close()
  159. self.mr = None
  160. self.mt.close()
  161. self.mt = None
  162. def listsplit(lst, item):
  163. try:
  164. idx = lst.index(item)
  165. except ValueError:
  166. return lst, []
  167. return lst[:idx], lst[idx + 1:]
  168. async def main():
  169. import argparse
  170. from loraserv import DEFAULT_MADDR as maddr
  171. parser = argparse.ArgumentParser()
  172. parser.add_argument('-r', dest='client', metavar='module:function', type=str,
  173. help='Create a respondant instead of sending commands. Commands will be passed to the function.')
  174. parser.add_argument('-s', dest='shared_key', metavar='shared_key', type=str, required=True,
  175. help='The shared key (encoded as UTF-8) to use.')
  176. parser.add_argument('args', metavar='CMD_ARG', type=str, nargs='*',
  177. help='Various commands to send to the device.')
  178. args = parser.parse_args()
  179. shared_key = args.shared_key.encode('utf-8')
  180. if args.client:
  181. # Run a client
  182. mr = await multicast.create_multicast_receiver(maddr)
  183. mt = await multicast.create_multicast_transmitter(maddr)
  184. from ctypes import c_uint8
  185. # seed the RNG
  186. prngseed = os.urandom(64)
  187. lora_comms.strobe_seed_prng((c_uint8 *
  188. len(prngseed))(*prngseed), len(prngseed))
  189. # Create the state for testing
  190. commstate = lora_comms.CommsState()
  191. import util_load
  192. client_func = util_load.load_application(args.client)
  193. def client_call(msg, outbuf):
  194. ret = client_func(msg._from())
  195. if len(ret) > outbuf[0].pktlen:
  196. ret = b'error, too long buffer: %d' % len(ret)
  197. outbuf[0].pktlen = min(len(ret), outbuf[0].pktlen)
  198. for i in range(outbuf[0].pktlen):
  199. outbuf[0].pkt[i] = ret[i]
  200. cb = lora_comms.process_msgfunc_t(client_call)
  201. # Initialize everything
  202. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  203. try:
  204. while True:
  205. pkt = await mr.recv()
  206. msg = pkt[0]
  207. out = lora_comms.comms_process_wrap(
  208. commstate, msg)
  209. if out:
  210. await mt.send(out)
  211. finally:
  212. mr.close()
  213. mt.close()
  214. sys.exit(0)
  215. msd = MulticastSyncDatagram(maddr)
  216. await msd.start()
  217. l = LORANode(msd, shared=shared_key)
  218. await l.start()
  219. valid_cmds = { 'waitfor', 'setunset', 'runfor', 'ping', 'terminate', }
  220. cmdargs = list(args.args)
  221. while cmdargs:
  222. cmd = cmdargs.pop(0)
  223. if cmd not in valid_cmds:
  224. print('invalid command:', repr(cmd))
  225. sys.exit(1)
  226. fun = getattr(l, cmd)
  227. args, cmdargs = listsplit(cmdargs, '--')
  228. await fun(*(int(x) for x in args))
  229. if __name__ == '__main__':
  230. asyncio.run(main())
  231. class MockSyncDatagram(SyncDatagram):
  232. '''A testing version of SyncDatagram. Define a method runner which
  233. implements part of the sequence. In the function, await on either
  234. self.get, to wait for the other side to send something, or await
  235. self.put w/ data to send.'''
  236. def __init__(self):
  237. self.sendq = asyncio.Queue()
  238. self.recvq = asyncio.Queue()
  239. self.task = asyncio.create_task(self.runner())
  240. self.get = self.sendq.get
  241. self.put = self.recvq.put
  242. async def drain(self):
  243. '''Wait for the runner thread to finish up.'''
  244. return await self.task
  245. async def runner(self): #pragma: no cover
  246. raise NotImplementedError
  247. async def recv(self, timeout=None):
  248. return await self.recvq.get()
  249. async def send(self, data):
  250. return await self.sendq.put(data)
  251. def __del__(self): #pragma: no cover
  252. if self.task is not None and not self.task.done():
  253. self.task.cancel()
  254. class TestSyncData(unittest.IsolatedAsyncioTestCase):
  255. async def test_syncsendtillrecv(self):
  256. class MySync(SyncDatagram):
  257. def __init__(self):
  258. self.sendq = []
  259. self.resp = [ asyncio.TimeoutError(), b'a' ]
  260. async def recv(self, timeout=None):
  261. assert timeout == 1
  262. r = self.resp.pop(0)
  263. if isinstance(r, Exception):
  264. raise r
  265. return r
  266. async def send(self, data):
  267. self.sendq.append(data)
  268. ms = MySync()
  269. r = await ms.sendtillrecv(b'foo', 1)
  270. self.assertEqual(r, b'a')
  271. self.assertEqual(ms.sendq, [ b'foo', b'foo' ])
  272. class AsyncSequence(object):
  273. '''
  274. Object used for sequencing async functions. To use, use the
  275. asynchronous context manager created by the sync method. For
  276. example:
  277. seq = AsyncSequence()
  278. async func1():
  279. async with seq.sync(1):
  280. second_fun()
  281. async func2():
  282. async with seq.sync(0):
  283. first_fun()
  284. This will make sure that function first_fun is run before running
  285. the function second_fun. If a previous block raises an Exception,
  286. it will be passed up, and all remaining blocks (and future ones)
  287. will raise a CancelledError to help ensure that any tasks are
  288. properly cleaned up.
  289. '''
  290. def __init__(self, positerfactory=lambda: itertools.count()):
  291. '''The argument positerfactory, is a factory that will
  292. create an iterator that will be used for the values that
  293. are passed to the sync method.'''
  294. self.positer = positerfactory()
  295. self.token = object()
  296. self.die = False
  297. self.waiting = {
  298. next(self.positer): self.token
  299. }
  300. async def simpsync(self, pos):
  301. async with self.sync(pos):
  302. pass
  303. @contextlib.asynccontextmanager
  304. async def sync(self, pos):
  305. '''An async context manager that will be run when it's
  306. turn arrives. It will only run when all the previous
  307. items in the iterator has been successfully run.'''
  308. if self.die:
  309. raise asyncio.CancelledError('seq cancelled')
  310. if pos in self.waiting:
  311. if self.waiting[pos] is not self.token:
  312. raise RuntimeError('pos already waiting!')
  313. else:
  314. fut = asyncio.Future()
  315. self.waiting[pos] = fut
  316. await fut
  317. # our time to shine!
  318. del self.waiting[pos]
  319. try:
  320. yield None
  321. except Exception as e:
  322. # if we got an exception, things went pear shaped,
  323. # shut everything down, and any future calls.
  324. #_debprint('dieing...', repr(e))
  325. self.die = True
  326. # cancel existing blocks
  327. while self.waiting:
  328. k, v = self.waiting.popitem()
  329. #_debprint('canceling: %s' % repr(k))
  330. if v is self.token:
  331. continue
  332. # for Python 3.9:
  333. # msg='pos %s raised exception: %s' %
  334. # (repr(pos), repr(e))
  335. v.cancel()
  336. # populate real exception up
  337. raise
  338. else:
  339. # handle next
  340. nextpos = next(self.positer)
  341. if nextpos in self.waiting:
  342. #_debprint('np:', repr(self), nextpos,
  343. # repr(self.waiting[nextpos]))
  344. self.waiting[nextpos].set_result(None)
  345. else:
  346. self.waiting[nextpos] = self.token
  347. class TestSequencing(unittest.IsolatedAsyncioTestCase):
  348. @timeout(2)
  349. async def test_seq_alreadywaiting(self):
  350. waitseq = AsyncSequence()
  351. seq = AsyncSequence()
  352. async def fun1():
  353. async with waitseq.sync(1):
  354. pass
  355. async def fun2():
  356. async with seq.sync(1):
  357. async with waitseq.sync(1): # pragma: no cover
  358. pass
  359. task1 = asyncio.create_task(fun1())
  360. task2 = asyncio.create_task(fun2())
  361. # spin things to make sure things advance
  362. await asyncio.sleep(0)
  363. async with seq.sync(0):
  364. pass
  365. with self.assertRaises(RuntimeError):
  366. await task2
  367. async with waitseq.sync(0):
  368. pass
  369. await task1
  370. @timeout(2)
  371. async def test_seqexc(self):
  372. seq = AsyncSequence()
  373. excseq = AsyncSequence()
  374. async def excfun1():
  375. async with seq.sync(1):
  376. pass
  377. async with excseq.sync(0):
  378. raise ValueError('foo')
  379. # that a block that enters first, but runs after
  380. # raises an exception
  381. async def excfun2():
  382. async with seq.sync(0):
  383. pass
  384. async with excseq.sync(1): # pragma: no cover
  385. pass
  386. # that a block that enters after, raises an
  387. # exception
  388. async def excfun3():
  389. async with seq.sync(2):
  390. pass
  391. async with excseq.sync(2): # pragma: no cover
  392. pass
  393. task1 = asyncio.create_task(excfun1())
  394. task2 = asyncio.create_task(excfun2())
  395. task3 = asyncio.create_task(excfun3())
  396. with self.assertRaises(ValueError):
  397. await task1
  398. with self.assertRaises(asyncio.CancelledError):
  399. await task2
  400. with self.assertRaises(asyncio.CancelledError):
  401. await task3
  402. @timeout(2)
  403. async def test_seq(self):
  404. # test that a seq object when created
  405. seq = AsyncSequence(lambda: itertools.count(1))
  406. col = []
  407. async def fun1():
  408. async with seq.sync(1):
  409. col.append(1)
  410. async with seq.sync(2):
  411. col.append(2)
  412. async with seq.sync(4):
  413. col.append(4)
  414. async def fun2():
  415. async with seq.sync(3):
  416. col.append(3)
  417. async with seq.sync(6):
  418. col.append(6)
  419. async def fun3():
  420. async with seq.sync(5):
  421. col.append(5)
  422. # and various functions are run
  423. task1 = asyncio.create_task(fun1())
  424. task2 = asyncio.create_task(fun2())
  425. task3 = asyncio.create_task(fun3())
  426. # and the functions complete
  427. await task3
  428. await task2
  429. await task1
  430. # that the order they ran in was correct
  431. self.assertEqual(col, list(range(1, 7)))
  432. class TestLORANode(unittest.IsolatedAsyncioTestCase):
  433. @timeout(2)
  434. async def test_lora(self):
  435. _self = self
  436. shared_key = os.urandom(32)
  437. class TestSD(MockSyncDatagram):
  438. async def sendgettest(self, msg):
  439. '''Send the message, but make sure that if a
  440. bad message is sent afterward, that it replies
  441. w/ the same previous message.
  442. '''
  443. await self.put(msg)
  444. resp = await self.get()
  445. await self.put(b'bogusmsg' * 5)
  446. resp2 = await self.get()
  447. _self.assertEqual(resp, resp2)
  448. return resp
  449. async def runner(self):
  450. l = Strobe(domain, F=KeccakF(800))
  451. l.key(shared_key)
  452. # start handshake
  453. r = await self.get()
  454. pkt = l.recv_enc(r[:-8])
  455. l.recv_mac(r[-8:])
  456. assert pkt.endswith(b'reqreset')
  457. # make sure junk gets ignored
  458. await self.put(b'sdlfkj')
  459. # and that the packet remains the same
  460. _self.assertEqual(r, await self.get())
  461. # and a couple more times
  462. await self.put(b'0' * 24)
  463. _self.assertEqual(r, await self.get())
  464. await self.put(b'0' * 32)
  465. _self.assertEqual(r, await self.get())
  466. # send the response
  467. await self.put(l.send_enc(os.urandom(16)) +
  468. l.send_mac(8))
  469. # require no more back tracking at this point
  470. l.ratchet()
  471. # get the confirmation message
  472. r = await self.get()
  473. # test the resend capabilities
  474. await self.put(b'0' * 24)
  475. _self.assertEqual(r, await self.get())
  476. # decode confirmation message
  477. c = l.recv_enc(r[:-8])
  478. l.recv_mac(r[-8:])
  479. # assert that we got it
  480. _self.assertEqual(c, b'confirm')
  481. # send confirmed reply
  482. r = await self.sendgettest(l.send_enc(
  483. b'confirmed') + l.send_mac(8))
  484. # test and decode remaining command messages
  485. cmd = l.recv_enc(r[:-8])
  486. l.recv_mac(r[-8:])
  487. assert cmd[0] == CMD_WAITFOR
  488. assert int.from_bytes(cmd[1:],
  489. byteorder='little') == 30
  490. r = await self.sendgettest(l.send_enc(
  491. cmd[0:1]) + l.send_mac(8))
  492. cmd = l.recv_enc(r[:-8])
  493. l.recv_mac(r[-8:])
  494. assert cmd[0] == CMD_RUNFOR
  495. assert int.from_bytes(cmd[1:5],
  496. byteorder='little') == 1
  497. assert int.from_bytes(cmd[5:],
  498. byteorder='little') == 50
  499. r = await self.sendgettest(l.send_enc(
  500. cmd[0:1]) + l.send_mac(8))
  501. cmd = l.recv_enc(r[:-8])
  502. l.recv_mac(r[-8:])
  503. assert cmd[0] == CMD_TERMINATE
  504. await self.put(l.send_enc(cmd[0:1]) +
  505. l.send_mac(8))
  506. tsd = TestSD()
  507. l = LORANode(tsd, shared=shared_key)
  508. await l.start()
  509. await l.waitfor(30)
  510. await l.runfor(1, 50)
  511. await l.terminate()
  512. await tsd.drain()
  513. # Make sure all messages have been processed
  514. self.assertTrue(tsd.sendq.empty())
  515. self.assertTrue(tsd.recvq.empty())
  516. #_debprint('done')
  517. @timeout(2)
  518. async def test_ccode_badmsgs(self):
  519. # Test to make sure that various bad messages in the
  520. # handshake process are rejected even if the attacker
  521. # has the correct key. This just keeps the protocol
  522. # tight allowing for variations in the future.
  523. # seed the RNG
  524. prngseed = b'abc123'
  525. from ctypes import c_uint8
  526. lora_comms.strobe_seed_prng((c_uint8 *
  527. len(prngseed))(*prngseed), len(prngseed))
  528. # Create the state for testing
  529. commstate = lora_comms.CommsState()
  530. cb = lora_comms.process_msgfunc_t(lambda msg, outbuf: None)
  531. # Generate shared key
  532. shared_key = os.urandom(32)
  533. # Initialize everything
  534. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  535. # Create test fixture, only use it to init crypto state
  536. tsd = SyncDatagram()
  537. l = LORANode(tsd, shared=shared_key)
  538. # copy the crypto state
  539. cstate = l.st.copy()
  540. # compose an incorrect init message
  541. msg = os.urandom(16) + b'othre'
  542. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  543. out = lora_comms.comms_process_wrap(commstate, msg)
  544. self.assertFalse(out)
  545. # copy the crypto state
  546. cstate = l.st.copy()
  547. # compose an incorrect init message
  548. msg = os.urandom(16) + b' eqreset'
  549. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  550. out = lora_comms.comms_process_wrap(commstate, msg)
  551. self.assertFalse(out)
  552. # compose the correct init message
  553. msg = os.urandom(16) + b'reqreset'
  554. msg = l.st.send_enc(msg) + l.st.send_mac(l.MAC_LEN)
  555. out = lora_comms.comms_process_wrap(commstate, msg)
  556. l.st.recv_enc(out[:-l.MAC_LEN])
  557. l.st.recv_mac(out[-l.MAC_LEN:])
  558. l.st.ratchet()
  559. # copy the crypto state
  560. cstate = l.st.copy()
  561. # compose an incorrect confirmed message
  562. msg = b'onfirm'
  563. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  564. out = lora_comms.comms_process_wrap(commstate, msg)
  565. self.assertFalse(out)
  566. # copy the crypto state
  567. cstate = l.st.copy()
  568. # compose an incorrect confirmed message
  569. msg = b' onfirm'
  570. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  571. out = lora_comms.comms_process_wrap(commstate, msg)
  572. self.assertFalse(out)
  573. @timeout(2)
  574. async def test_ccode(self):
  575. _self = self
  576. from ctypes import c_uint8
  577. # seed the RNG
  578. prngseed = b'abc123'
  579. lora_comms.strobe_seed_prng((c_uint8 *
  580. len(prngseed))(*prngseed), len(prngseed))
  581. # Create the state for testing
  582. commstate = lora_comms.CommsState()
  583. # These are the expected messages and their arguments
  584. exptmsgs = [
  585. (CMD_WAITFOR, [ 30 ]),
  586. (CMD_RUNFOR, [ 1, 50 ]),
  587. (CMD_PING, [ ]),
  588. (CMD_TERMINATE, [ ]),
  589. ]
  590. def procmsg(msg, outbuf):
  591. msgbuf = msg._from()
  592. cmd = msgbuf[0]
  593. args = [ int.from_bytes(msgbuf[x:x + 4],
  594. byteorder='little') for x in range(1, len(msgbuf),
  595. 4) ]
  596. if exptmsgs[0] == (cmd, args):
  597. exptmsgs.pop(0)
  598. outbuf[0].pkt[0] = cmd
  599. outbuf[0].pktlen = 1
  600. else: #pragma: no cover
  601. raise RuntimeError('cmd not found')
  602. # wrap the callback function
  603. cb = lora_comms.process_msgfunc_t(procmsg)
  604. class CCodeSD(MockSyncDatagram):
  605. async def runner(self):
  606. for expectlen in [ 24, 17, 9, 9, 9, 9 ]:
  607. # get message
  608. inmsg = await self.get()
  609. # process the test message
  610. out = lora_comms.comms_process_wrap(
  611. commstate, inmsg)
  612. # make sure the reply matches length
  613. _self.assertEqual(expectlen, len(out))
  614. # save what was originally replied
  615. origmsg = out
  616. # pretend that the reply didn't make it
  617. out = lora_comms.comms_process_wrap(
  618. commstate, inmsg)
  619. # make sure that the reply matches
  620. # the previous
  621. _self.assertEqual(origmsg, out)
  622. # pass the reply back
  623. await self.put(out)
  624. # Generate shared key
  625. shared_key = os.urandom(32)
  626. # Initialize everything
  627. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  628. # Create test fixture
  629. tsd = CCodeSD()
  630. l = LORANode(tsd, shared=shared_key)
  631. # Send various messages
  632. await l.start()
  633. await l.waitfor(30)
  634. await l.runfor(1, 50)
  635. await l.ping()
  636. await l.terminate()
  637. await tsd.drain()
  638. # Make sure all messages have been processed
  639. self.assertTrue(tsd.sendq.empty())
  640. self.assertTrue(tsd.recvq.empty())
  641. # Make sure all the expected messages have been
  642. # processed.
  643. self.assertFalse(exptmsgs)
  644. #_debprint('done')
  645. @timeout(2)
  646. async def test_ccode_newsession(self):
  647. '''This test is to make sure that if an existing session
  648. is running, that a new session can be established, and that
  649. when it does, the old session becomes inactive.
  650. '''
  651. _self = self
  652. from ctypes import c_uint8
  653. seq = AsyncSequence()
  654. # seed the RNG
  655. prngseed = b'abc123'
  656. lora_comms.strobe_seed_prng((c_uint8 *
  657. len(prngseed))(*prngseed), len(prngseed))
  658. # Create the state for testing
  659. commstate = lora_comms.CommsState()
  660. # These are the expected messages and their arguments
  661. exptmsgs = [
  662. (CMD_WAITFOR, [ 30 ]),
  663. (CMD_WAITFOR, [ 70 ]),
  664. (CMD_WAITFOR, [ 40 ]),
  665. (CMD_TERMINATE, [ ]),
  666. ]
  667. def procmsg(msg, outbuf):
  668. msgbuf = msg._from()
  669. cmd = msgbuf[0]
  670. args = [ int.from_bytes(msgbuf[x:x + 4],
  671. byteorder='little') for x in range(1, len(msgbuf),
  672. 4) ]
  673. if exptmsgs[0] == (cmd, args):
  674. exptmsgs.pop(0)
  675. outbuf[0].pkt[0] = cmd
  676. outbuf[0].pktlen = 1
  677. else: #pragma: no cover
  678. raise RuntimeError('cmd not found: %d' % cmd)
  679. # wrap the callback function
  680. cb = lora_comms.process_msgfunc_t(procmsg)
  681. class FlipMsg(object):
  682. async def flipmsg(self):
  683. # get message
  684. inmsg = await self.get()
  685. # process the test message
  686. out = lora_comms.comms_process_wrap(
  687. commstate, inmsg)
  688. # pass the reply back
  689. await self.put(out)
  690. # this class always passes messages, this is
  691. # used for the first session.
  692. class CCodeSD1(MockSyncDatagram, FlipMsg):
  693. async def runner(self):
  694. for i in range(3):
  695. await self.flipmsg()
  696. async with seq.sync(0):
  697. # create bogus message
  698. inmsg = b'0'*24
  699. # process the bogus message
  700. out = lora_comms.comms_process_wrap(
  701. commstate, inmsg)
  702. # make sure there was not a response
  703. _self.assertFalse(out)
  704. await self.flipmsg()
  705. # this one is special in that it will pause after the first
  706. # message to ensure that the previous session will continue
  707. # to work, AND that if a new "new" session comes along, it
  708. # will override the previous new session that hasn't been
  709. # confirmed yet.
  710. class CCodeSD2(MockSyncDatagram, FlipMsg):
  711. async def runner(self):
  712. # pass one message from the new session
  713. async with seq.sync(1):
  714. # There might be a missing case
  715. # handled for when the confirmed
  716. # message is generated, but lost.
  717. await self.flipmsg()
  718. # and the old session is still active
  719. await l.waitfor(70)
  720. async with seq.sync(2):
  721. for i in range(3):
  722. await self.flipmsg()
  723. # Generate shared key
  724. shared_key = os.urandom(32)
  725. # Initialize everything
  726. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  727. # Create test fixture
  728. tsd = CCodeSD1()
  729. l = LORANode(tsd, shared=shared_key)
  730. # Send various messages
  731. await l.start()
  732. await l.waitfor(30)
  733. # Ensure that a new one can take over
  734. tsd2 = CCodeSD2()
  735. l2 = LORANode(tsd2, shared=shared_key)
  736. # Send various messages
  737. await l2.start()
  738. await l2.waitfor(40)
  739. await l2.terminate()
  740. await tsd.drain()
  741. await tsd2.drain()
  742. # Make sure all messages have been processed
  743. self.assertTrue(tsd.sendq.empty())
  744. self.assertTrue(tsd.recvq.empty())
  745. self.assertTrue(tsd2.sendq.empty())
  746. self.assertTrue(tsd2.recvq.empty())
  747. # Make sure all the expected messages have been
  748. # processed.
  749. self.assertFalse(exptmsgs)
  750. class TestLoRaNodeMulticast(unittest.IsolatedAsyncioTestCase):
  751. # see: https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#multicast-addresses-1
  752. maddr = ('224.0.0.198', 48542)
  753. @timeout(2)
  754. async def test_multisyncdgram(self):
  755. # Test the implementation of the multicast version of
  756. # SyncDatagram
  757. _self = self
  758. from ctypes import c_uint8
  759. # seed the RNG
  760. prngseed = b'abc123'
  761. lora_comms.strobe_seed_prng((c_uint8 *
  762. len(prngseed))(*prngseed), len(prngseed))
  763. # Create the state for testing
  764. commstate = lora_comms.CommsState()
  765. # These are the expected messages and their arguments
  766. exptmsgs = [
  767. (CMD_WAITFOR, [ 30 ]),
  768. (CMD_PING, [ ]),
  769. (CMD_TERMINATE, [ ]),
  770. ]
  771. def procmsg(msg, outbuf):
  772. msgbuf = msg._from()
  773. cmd = msgbuf[0]
  774. args = [ int.from_bytes(msgbuf[x:x + 4],
  775. byteorder='little') for x in range(1, len(msgbuf),
  776. 4) ]
  777. if exptmsgs[0] == (cmd, args):
  778. exptmsgs.pop(0)
  779. outbuf[0].pkt[0] = cmd
  780. outbuf[0].pktlen = 1
  781. else: #pragma: no cover
  782. raise RuntimeError('cmd not found')
  783. # wrap the callback function
  784. cb = lora_comms.process_msgfunc_t(procmsg)
  785. # Generate shared key
  786. shared_key = os.urandom(32)
  787. # Initialize everything
  788. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  789. # create the object we are testing
  790. msd = MulticastSyncDatagram(self.maddr)
  791. seq = AsyncSequence()
  792. async def clienttask():
  793. mr = await multicast.create_multicast_receiver(
  794. self.maddr)
  795. mt = await multicast.create_multicast_transmitter(
  796. self.maddr)
  797. try:
  798. # make sure the above threads are running
  799. await seq.simpsync(0)
  800. while True:
  801. pkt = await mr.recv()
  802. msg = pkt[0]
  803. out = lora_comms.comms_process_wrap(
  804. commstate, msg)
  805. if out:
  806. await mt.send(out)
  807. finally:
  808. mr.close()
  809. mt.close()
  810. task = asyncio.create_task(clienttask())
  811. # start it
  812. await msd.start()
  813. # pass it to a node
  814. l = LORANode(msd, shared=shared_key)
  815. await seq.simpsync(1)
  816. # Send various messages
  817. await l.start()
  818. await l.waitfor(30)
  819. await l.ping()
  820. await l.terminate()
  821. # shut things down
  822. ln = None
  823. msd.close()
  824. task.cancel()
  825. with self.assertRaises(asyncio.CancelledError):
  826. await task