ext-respondd.py 15 KB

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