ext-respondd.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. #!/usr/bin/env python3
  2. # Code-Base: https://github.com/ffggrz/ffnord-alfred-announce
  3. # + https://github.com/freifunk-mwu/ffnord-alfred-announce
  4. # + https://github.com/FreifunkBremen/respondd
  5. import sys
  6. import socket
  7. import select
  8. import struct
  9. import subprocess
  10. import argparse
  11. import re
  12. # Force encoding to UTF-8
  13. import locale # Ensures that subsequent open()s
  14. locale.getpreferredencoding = lambda _=None: 'UTF-8' # are UTF-8 encoded.
  15. import json
  16. import zlib
  17. import netifaces as netif
  18. from cpuinfo import cpuinfo
  19. def toUTF8(line):
  20. return line.decode("utf-8")
  21. def call(cmdnargs):
  22. output = subprocess.check_output(cmdnargs)
  23. lines = output.splitlines()
  24. lines = [toUTF8(line) for line in lines]
  25. return lines
  26. def merge(a, b):
  27. if isinstance(a, dict) and isinstance(b, dict):
  28. d = dict(a)
  29. d.update({k: merge(a.get(k, None), b[k]) for k in b})
  30. return d
  31. if isinstance(a, list) and isinstance(b, list):
  32. return [merge(x, y) for x, y in itertools.izip_longest(a, b)]
  33. return a if b is None else b
  34. def getGateway():
  35. #/sys/kernel/debug/batman_adv/bat0/gateways
  36. output = subprocess.check_output(["batctl","-m",config['batman'],"gwl","-n"])
  37. output_utf8 = output.decode("utf-8")
  38. lines = output_utf8.splitlines()
  39. gw = None
  40. for line in lines:
  41. gw_line = re.match(r"^=> +([0-9a-f:]+) ", line)
  42. if gw_line:
  43. gw = gw_line.group(1)
  44. return gw
  45. def getClients():
  46. #/sys/kernel/debug/batman_adv/bat0/transtable_local
  47. output = subprocess.check_output(["batctl","-m",config['batman'],"tl","-n"])
  48. output_utf8 = output.decode("utf-8")
  49. lines = output_utf8.splitlines()
  50. batadv_mac = getDevice_MAC(config['batman'])
  51. j = {"total": 0, "wifi": 0}
  52. for line in lines:
  53. # batman-adv -> translation-table.c -> batadv_tt_local_seq_print_text
  54. # R = BATADV_TT_CLIENT_ROAM
  55. # P = BATADV_TT_CLIENT_NOPURGE
  56. # N = BATADV_TT_CLIENT_NEW
  57. # X = BATADV_TT_CLIENT_PENDING
  58. # W = BATADV_TT_CLIENT_WIFI
  59. # I = BATADV_TT_CLIENT_ISOLA
  60. # . = unset
  61. # * c0:11:73:b2:8f:dd -1 [.P..W.] 1.710 (0xe680a836)
  62. ml = re.match(r"^\s\*\s([0-9a-f:]+)\s+-\d\s\[([RPNXWI\.]+)\]", line, re.I)
  63. if ml:
  64. if not batadv_mac == ml.group(1): # Filter bat0
  65. j["total"] += 1
  66. if ml.group(2)[4] == 'W':
  67. j["wifi"] += 1
  68. return j
  69. def getDevice_Addresses(dev):
  70. l = []
  71. try:
  72. for ip6 in netif.ifaddresses(dev)[netif.AF_INET6]:
  73. raw6 = ip6['addr'].split('%')
  74. l.append(raw6[0])
  75. except:
  76. pass
  77. return l
  78. def getDevice_MAC(dev):
  79. try:
  80. interface = netif.ifaddresses(dev)
  81. mac = interface[netif.AF_LINK]
  82. return mac[0]['addr']
  83. except:
  84. return None
  85. def getMesh_Interfaces():
  86. j = {}
  87. output = subprocess.check_output(["batctl","-m",config['batman'],"if"])
  88. output_utf8 = output.decode("utf-8")
  89. lines = output_utf8.splitlines()
  90. for line in lines:
  91. dev_re = re.match(r"^([^:]*)", line)
  92. dev = dev_re.group(1)
  93. j[dev] = getDevice_MAC(dev)
  94. return j
  95. def getBat0_Interfaces():
  96. j = {}
  97. output = subprocess.check_output(["batctl","-m",config['batman'],"if"])
  98. output_utf8 = output.decode("utf-8")
  99. lines = output_utf8.splitlines()
  100. for line in lines:
  101. dev_line = re.match(r"^([^:]*)", line)
  102. nif = dev_line.group(0)
  103. if_group = ""
  104. if nif == config["fastd"]:
  105. if_group = "tunnel"
  106. elif "mesh-wlan" in config and nif == config["mesh-wlan"]:
  107. if_group = "wireless"
  108. else:
  109. if_group = "other"
  110. if not if_group in j:
  111. j[if_group] = []
  112. j[if_group].append(getDevice_MAC(nif))
  113. return j
  114. def getTraffic(): # BUG: falsches interfaces?
  115. return (lambda fields:
  116. dict(
  117. (key, dict(
  118. (type_, int(value_))
  119. for key_, type_, value_ in fields
  120. if key_ == key))
  121. for key in ['rx', 'tx', 'forward', 'mgmt_rx', 'mgmt_tx']
  122. )
  123. )(list(
  124. (
  125. key.replace('_bytes', '').replace('_dropped', ''),
  126. 'bytes' if key.endswith('_bytes') else 'dropped' if key.endswith('_dropped') else 'packets',
  127. value
  128. )
  129. for key, value in map(lambda s: list(map(str.strip, s.split(': ', 1))), call(['ethtool', '-S', config['batman']])[1:])
  130. ))
  131. def getMemory():
  132. return dict(
  133. (key.replace('Mem', '').lower(), int(value.split(' ')[0]))
  134. for key, value in map(lambda s: map(str.strip, s.split(': ', 1)), open('/proc/meminfo').readlines())
  135. if key in ('MemTotal', 'MemFree', 'Buffers', 'Cached')
  136. )
  137. def getFastd():
  138. fastd_data = b""
  139. try:
  140. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  141. sock.connect(config["fastd_socket"])
  142. except socket.error as err:
  143. print("socket error: ", sys.stderr, err)
  144. return None
  145. while True:
  146. data = sock.recv(1024)
  147. if not data: break
  148. fastd_data+= data
  149. sock.close()
  150. return json.loads(fastd_data.decode("utf-8"))
  151. def getMeshVPNPeers():
  152. j = {}
  153. if "fastd_socket" in config:
  154. fastd = getFastd()
  155. for peer, v in fastd["peers"].items():
  156. if v["connection"]:
  157. j[v["name"]] = {
  158. "established": v["connection"]["established"],
  159. }
  160. else:
  161. j[v["name"]] = None
  162. return j
  163. else:
  164. return None
  165. def getNode_ID():
  166. if 'node_id' in aliases["nodeinfo"]:
  167. return aliases["nodeinfo"]["node_id"]
  168. else:
  169. return getDevice_MAC(config["wan"]).replace(':','')
  170. def getStationDump(dev):
  171. try:
  172. j = {}
  173. # iw dev ibss3 station dump
  174. output = subprocess.check_output(["iw","dev",dev,"station", "dump"])
  175. output_utf8 = output.decode("utf-8")
  176. lines = output_utf8.splitlines()
  177. mac=""
  178. for line in lines:
  179. # Station 32:b8:c3:86:3e:e8 (on ibss3)
  180. ml = re.match('^Station ([0-9a-f:]+) \(on ([\w\d]+)\)', line, re.I)
  181. if ml:
  182. mac = ml.group(1)
  183. j[mac] = {}
  184. else:
  185. ml = re.match('^[\t ]+([^:]+):[\t ]+([^ ]+)', line, re.I)
  186. if ml:
  187. j[mac][ml.group(1)] = ml.group(2)
  188. return j
  189. except:
  190. return None
  191. def getNeighbours():
  192. # https://github.com/freifunk-gluon/packages/blob/master/net/respondd/src/respondd.c
  193. j = { "batadv": {}}
  194. stationDump = None
  195. if 'mesh-wlan' in config:
  196. j["wifi"] = {}
  197. stationDump = getStationDump(config["mesh-wlan"])
  198. mesh_ifs = getMesh_Interfaces()
  199. with open("/sys/kernel/debug/batman_adv/" + config['batman'] + "/originators", 'r') as fh:
  200. for line in fh:
  201. #62:e7:27:cd:57:78 0.496s (192) de:ad:be:ef:01:01 [ mesh-vpn]: de:ad:be:ef:01:01 (192) de:ad:be:ef:02:01 (148) de:ad:be:ef:03:01 (148)
  202. ml = re.match(r"^([0-9a-f:]+)[ ]*([\d\.]*)s[ ]*\((\d*)\)[ ]*([0-9a-f:]+)[ ]*\[[ ]*(.*)\]", line, re.I)
  203. if ml:
  204. dev = ml.group(5)
  205. mac_origin = ml.group(1)
  206. mac_nhop = ml.group(4)
  207. tq = ml.group(3)
  208. lastseen = ml.group(2)
  209. if mac_origin == mac_nhop:
  210. if 'mesh-wlan' in config and dev == config["mesh-wlan"] and not stationDump is None:
  211. if not mesh_ifs[dev] in j["wifi"]:
  212. j["wifi"][mesh_ifs[dev]] = {}
  213. j["wifi"][mesh_ifs[dev]]["neighbours"] = {}
  214. if mac_origin in stationDump:
  215. j["wifi"][mesh_ifs[dev]]["neighbours"][mac_origin] = {
  216. "signal": stationDump[mac_origin]["signal"],
  217. "noise": 0, # BUG: fehlt noch
  218. "inactive": stationDump[mac_origin]["inactive time"],
  219. }
  220. if not mesh_ifs[dev] in j["batadv"]:
  221. j["batadv"][mesh_ifs[dev]] = {}
  222. j["batadv"][mesh_ifs[dev]]["neighbours"] = {}
  223. j["batadv"][mesh_ifs[dev]]["neighbours"][mac_origin] = {
  224. "tq": int(tq),
  225. "lastseen": float(lastseen),
  226. }
  227. return j
  228. # ======================== Output =========================
  229. # =========================================================
  230. def createNodeinfo():
  231. j = {
  232. "node_id": getNode_ID(),
  233. "hostname": socket.gethostname(),
  234. "network": {
  235. "addresses": getDevice_Addresses(config['bridge']),
  236. "mesh": {
  237. "bat0": {
  238. "interfaces": getBat0_Interfaces(),
  239. },
  240. },
  241. "mac": getDevice_MAC(config["wan"]),
  242. "mesh_interfaces": list(getMesh_Interfaces().values()),
  243. },
  244. "software": {
  245. "firmware": {
  246. "base": call(['lsb_release','-is'])[0],
  247. "release": call(['lsb_release','-ds'])[0],
  248. },
  249. "batman-adv": {
  250. "version": open('/sys/module/batman_adv/version').read().strip(),
  251. # "compat": # /lib/gluon/mesh-batman-adv-core/compat
  252. },
  253. "fastd": {
  254. "version": call(['fastd','-v'])[0].split(' ')[1],
  255. "enabled": True,
  256. },
  257. "status-page": {
  258. "api": 0,
  259. },
  260. "autoupdater": {
  261. # "branch": "stable",
  262. "enabled": False,
  263. },
  264. },
  265. "hardware": {
  266. "model": cpuinfo.get_cpu_info()["brand"],
  267. "nproc": int(call(['nproc'])[0]),
  268. },
  269. # "vpn": True,
  270. "owner": {},
  271. "system": {},
  272. "location": {},
  273. }
  274. return merge(j, aliases["nodeinfo"])
  275. def createStatistics():
  276. j = {
  277. "node_id": getNode_ID(),
  278. "gateway" : getGateway(),
  279. "clients": getClients(),
  280. "traffic": getTraffic(),
  281. "idletime": float(open('/proc/uptime').read().split(' ')[1]),
  282. "loadavg": float(open('/proc/loadavg').read().split(' ')[0]),
  283. "memory": getMemory(),
  284. "processes": dict(zip(('running', 'total'), map(int, open('/proc/loadavg').read().split(' ')[3].split('/')))),
  285. "uptime": float(open('/proc/uptime').read().split(' ')[0]),
  286. "mesh_vpn" : { # HopGlass-Server: node.flags.uplink = parsePeerGroup(_.get(n, 'statistics.mesh_vpn'))
  287. "groups": {
  288. "backbone": {
  289. "peers": getMeshVPNPeers(),
  290. },
  291. },
  292. },
  293. }
  294. return j
  295. def createNeighbours():
  296. #/sys/kernel/debug/batman_adv/bat0/originators
  297. j = {
  298. "node_id": getNode_ID(),
  299. }
  300. j = merge(j, getNeighbours())
  301. return j
  302. def sendResponse(request, compress):
  303. json_data = {}
  304. #https://github.com/freifunk-gluon/packages/blob/master/net/respondd/src/respondd.c
  305. if request == 'statistics':
  306. json_data[request] = createStatistics()
  307. elif request == 'nodeinfo':
  308. json_data[request] = createNodeinfo()
  309. elif request == 'neighbours':
  310. json_data[request] = createNeighbours()
  311. else:
  312. print("unknown command: " + request)
  313. return
  314. json_str = bytes(json.dumps(json_data, separators=(',', ':')), 'UTF-8')
  315. if compress:
  316. encoder = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) # The data may be decompressed using zlib and many zlib bindings using -15 as the window size parameter.
  317. gzip_data = encoder.compress(json_str)
  318. gzip_data = gzip_data + encoder.flush()
  319. sock.sendto(gzip_data, sender)
  320. else:
  321. sock.sendto(json_str, sender)
  322. if options["verbose"]:
  323. print(json.dumps(json_data, sort_keys=True, indent=4))
  324. # ===================== Mainfunction ======================
  325. # =========================================================
  326. parser = argparse.ArgumentParser()
  327. parser.add_argument( '-d', '--debug', action='store_true', help='Debug Output',required=False,)
  328. parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose Output',required=False)
  329. args = parser.parse_args()
  330. options = vars(args)
  331. config = {}
  332. try:
  333. with open("config.json", 'r') as cfg_handle:
  334. config = json.load(cfg_handle)
  335. except IOError:
  336. raise
  337. aliases = {}
  338. try:
  339. with open("alias.json", 'r') as cfg_handle:
  340. aliases = json.load(cfg_handle)
  341. except IOError:
  342. raise
  343. if options["debug"]:
  344. print(json.dumps(createNodeinfo(), sort_keys=True, indent=4))
  345. print(json.dumps(createStatistics(), sort_keys=True, indent=4))
  346. print(json.dumps(createNeighbours(), sort_keys=True, indent=4))
  347. #print(json.dumps(getFastd(config["fastd_socket"]), sort_keys=True, indent=4))
  348. #print(json.dumps(getMesh_VPN(), sort_keys=True, indent=4))
  349. sys.exit(1)
  350. if 'addr' in config:
  351. addr = config['addr']
  352. else:
  353. addr = 'ff02::2'
  354. if 'addr' in config:
  355. port = config['port']
  356. else:
  357. port = 1001
  358. if_idx = socket.if_nametoindex(config["bridge"])
  359. group = socket.inet_pton(socket.AF_INET6, addr) + struct.pack("I", if_idx)
  360. sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  361. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
  362. sock.bind(('::', port))
  363. # =========================================================
  364. while True:
  365. if select.select([sock],[],[],1)[0]:
  366. msg, sender = sock.recvfrom(2048)
  367. if options["verbose"]:
  368. print(msg)
  369. msg_spl = str(msg, 'UTF-8').split(" ")
  370. if msg_spl[0] == 'GET': # multi_request
  371. for request in msg_spl[1:]:
  372. sendResponse(request, True)
  373. else: # single_request
  374. sendResponse(msg_spl[0], False)