ext-respondd.py 15 KB

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