respondd_client.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. from lib.ratelimit import rateLimit
  3. from lib.nodeinfo import Nodeinfo
  4. from lib.neighbours import Neighbours
  5. from lib.statistics import Statistics
  6. import socket
  7. import select
  8. import struct
  9. class ResponddClient:
  10. def __init__(self, config):
  11. self._config = config
  12. if 'addr' in self._config:
  13. addr = self._config['addr']
  14. else:
  15. addr = 'ff02::2:1001'
  16. if 'addr' in self._config:
  17. port = self._config['port']
  18. else:
  19. port = 1001
  20. if_idx = socket.if_nametoindex(self._config["bridge"])
  21. group = socket.inet_pton(socket.AF_INET6, addr) + struct.pack("I", if_idx)
  22. self._sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  23. self._sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
  24. self._sock.bind(('::', port))
  25. if 'rate_limit' in self._config:
  26. if not 'rate_limit_burst' in self._config:
  27. self._config['rate_limit_burst'] = 10
  28. self.__RateLimit = rateLimit(self._config['rate_limit'], self._config['rate_limit_burst'])
  29. else:
  30. self.__RateLimit = None
  31. self._nodeinfo = Nodeinfo(self._config)
  32. self._neighbours = Neighbours(self._config)
  33. self._statistics = Statistics(self._config)
  34. def start(self):
  35. while True:
  36. if select.select([self._sock], [], [], 1)[0]:
  37. msg, sender = self._sock.recvfrom(2048)
  38. # if options["verbose"]:
  39. # print(msg)
  40. msg_spl = str(msg, 'UTF-8').split(" ")
  41. if msg_spl[0] == 'GET': # multi_request
  42. for req in msg_spl[1:]:
  43. self.sendResponse(sender, req, True)
  44. else: # single_request
  45. self.sendResponse(sender, msg_spl[0], False)
  46. def sendResponse(self, sender, request, compress):
  47. if not self.__RateLimit is None and not self.__RateLimit.limit():
  48. print("rate limit reached!")
  49. return
  50. response = None
  51. if request == 'statistics':
  52. response = self._statistics
  53. elif request == 'nodeinfo':
  54. response = self._nodeinfo
  55. elif request == 'neighbours':
  56. response = self._neighbours
  57. pass
  58. else:
  59. print("unknown command: " + request)
  60. return
  61. print(response.getJSON(request))
  62. return
  63. if compress:
  64. sock.sendto(response.getJSONCompressed(request), sender)
  65. else:
  66. sock.sendto(response.getJSON(request), sender)
  67. # if options["verbose"]:
  68. # print(json.dumps(json_data, sort_keys=True, indent=4))