ext-respondd.py 14 KB

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