ffpb.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function
  3. import willie
  4. import datetime
  5. import difflib
  6. from email.utils import mktime_tz
  7. from fnmatch import fnmatch
  8. import git
  9. import netaddr
  10. import json
  11. import urllib2
  12. import re
  13. import os
  14. import random
  15. import shelve
  16. import subprocess
  17. import time
  18. import dns.resolver,dns.reversename
  19. import socket
  20. import SocketServer
  21. import threading
  22. msgserver = None
  23. peers_repo = None
  24. monitored_nodes = None
  25. highscores = None
  26. nodeaccess = None
  27. alfred_method = None
  28. alfred_data = None
  29. alfred_update = datetime.datetime(1970,1,1,23,42)
  30. ffpb_resolver = dns.resolver.Resolver ()
  31. ffpb_resolver.nameservers = ['10.132.254.53']
  32. class MsgHandler(SocketServer.BaseRequestHandler):
  33. """Reads line from TCP stream and forwards it to configured IRC channels."""
  34. def handle(self):
  35. data = self.request.recv(2048).strip()
  36. sender = self._resolve_name (self.client_address[0])
  37. bot = self.server.bot
  38. if bot is None:
  39. print("ERROR: No bot in handle() :-(")
  40. return
  41. target = bot.config.core.owner
  42. if bot.config.has_section('ffpb'):
  43. is_public = data.lstrip().lower().startswith("public:")
  44. if is_public and not (bot.config.ffpb.msg_target_public is None):
  45. data = data[7:].lstrip()
  46. target = bot.config.ffpb.msg_target_public
  47. elif not (bot.config.ffpb.msg_target is None):
  48. target = bot.config.ffpb.msg_target
  49. bot.msg(target, "[{0}] {1}".format(sender, str(data)))
  50. def _resolve_name (self, ip):
  51. """Resolves the host name of the given IP address
  52. and strips away the suffix (.infra)?.ffpb"""
  53. if ip.startswith ("127."):
  54. return "localhost"
  55. try:
  56. addr = dns.reversename.from_address (ip)
  57. return re.sub ("(.infra)?.ffpb.", "", str (ffpb_resolver.query (addr, "PTR")[0]))
  58. except dns.resolver.NXDOMAIN:
  59. return ip
  60. class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  61. pass
  62. def setup(bot):
  63. global msgserver, peers_repo, alfred_method, highscores, monitored_nodes, nodeaccess
  64. # signal begin of setup routine
  65. bot.memory['ffpb_in_setup'] = True
  66. # load highscores from disk
  67. highscores = shelve.open('highscoredata', writeback=True)
  68. if not 'nodes' in highscores:
  69. highscores['nodes'] = 0
  70. highscores['nodes_ts'] = time.time()
  71. if not 'clients' in highscores:
  72. highscores['clients'] = 0
  73. highscores['clients_ts'] = time.time()
  74. # load list of monitored nodes and their last status from disk
  75. monitored_nodes = shelve.open('nodes.monitored', writeback=True)
  76. # load list of seen nodes from disk
  77. seen_nodes = shelve.open('nodes.seen', writeback=True)
  78. bot.memory['seen_nodes'] = seen_nodes
  79. # load list of node ACL from disk (used in playitsafe())
  80. nodeaccess = shelve.open('nodes.acl', writeback=True)
  81. # no need to configure anything else if the ffpb config section is missing
  82. if not bot.config.has_section('ffpb'):
  83. bot.memory['ffpb_in_setup'] = False
  84. return
  85. # open the git repository containing the peers files
  86. if not bot.config.ffpb.peers_directory is None:
  87. peers_repo = git.Repo(bot.config.ffpb.peers_directory)
  88. assert peers_repo.bare == False
  89. # if configured, start the messaging server
  90. if int(bot.config.ffpb.msg_enable) == 1:
  91. host = "localhost"
  92. port = 2342
  93. if not bot.config.ffpb.msg_host is None: host = bot.config.ffpb.msg_host
  94. if not bot.config.ffpb.msg_port is None: port = int(bot.config.ffpb.msg_port)
  95. msgserver = ThreadingTCPServer((host,port), MsgHandler)
  96. msgserver.bot = bot
  97. ip, port = msgserver.server_address
  98. print("Messaging server listening on {}:{}".format(ip,port))
  99. msgserver_thread = threading.Thread(target=msgserver.serve_forever)
  100. msgserver_thread.daemon = True
  101. msgserver_thread.start()
  102. # initially fetch ALFRED data
  103. alfred_method = bot.config.ffpb.alfred_method
  104. ffpb_updatealfred(bot)
  105. # signal end of setup routine
  106. bot.memory['ffpb_in_setup'] = False
  107. def shutdown(bot):
  108. global msgserver, highscores, monitored_nodes, nodeaccess
  109. # store highscores
  110. if not highscores is None:
  111. highscores.sync()
  112. highscores.close()
  113. highscores = None
  114. # store monitored nodes
  115. if not monitored_nodes is None:
  116. monitored_nodes.sync()
  117. monitored_nodes.close()
  118. monitored_nodes = None
  119. # store node acl
  120. if not nodeaccess is None:
  121. nodeaccess.sync()
  122. nodeaccess.close()
  123. nodeaccess = None
  124. # store seen nodes
  125. if 'seen_nodes' in bot.memory and bot.memory['seen_nodes'] != None:
  126. bot.memory['seen_nodes'].close()
  127. bot.memory['seen_nodes'] = None
  128. del(bot.memory['seen_nodes'])
  129. # shutdown messaging server
  130. if not msgserver is None:
  131. msgserver.shutdown()
  132. print("Closed messaging server.")
  133. msgserver = None
  134. @willie.module.commands("help")
  135. @willie.module.commands("hilfe")
  136. @willie.module.commands("man")
  137. def ffpb_help(bot, trigger):
  138. """Display commony ulsed functions."""
  139. functions = {
  140. "!ping <knoten>": "Prüfe ob der Knoten erreichbar ist.",
  141. "!status": "Aktuellen Status des Netzwerks (insb. Anzahl Knoten und Clients) ausgegeben.",
  142. "!info <knoten>": "Allgemeine Information zu dem Knoten anzeigen.",
  143. "!link <knoten>": "MAC-Adresse und Link zur Status-Seite des Knotens anzeigen.",
  144. "!exec-on-peer <knoten> <kommando>": "Befehl auf dem Knoten ausführen (nur möglich bei eigenen Knoten oder als Admin, in beiden Fällen auch nur wenn der SSH-Key des Bots hinterlegt wurde)",
  145. "!mesh <knoten>": "Zeige Mesh-Partner eines Knotens",
  146. }
  147. param = trigger.group(2)
  148. if param is None:
  149. bot.say("Funktionen: " + str.join(", ", sorted(functions.keys())))
  150. return
  151. if param.startswith("!"): param = param[1:]
  152. for fun in functions.keys():
  153. if fun.startswith("!" + param + " "):
  154. bot.say("Hilfe zu '" + fun + "': " + functions[fun])
  155. return
  156. bot.say("Allgemeine Hilfe gibt's mit !help - ohne Parameter.")
  157. def playitsafe(bot, trigger,
  158. botadmin=False, admin_channel=False, via_channel=False, via_privmsg=False, need_op=False, node=None,
  159. reply_directly=True, debug_user=None, debug_ignorebotadmin=False):
  160. """helper: checks that the triggering user has the necessary rights
  161. Returns true if everything is okay. If it's not, a reply is send via the bot and false is returned.
  162. """
  163. if via_channel and via_privmsg:
  164. raise Exception('Der Entwickler ist ein dummer, dummer Junge (playitsafe hat via_channel und via_privmsg gleichzeitig gesetzt).')
  165. user = trigger.nick if debug_user is None else debug_user
  166. user = user.lower()
  167. # botadmin: you need to be configured as a bot admin
  168. if botadmin and not trigger.admin:
  169. if reply_directly: bot.say('Du brauchst Super-Kuh-Kräfte um dieses Kommando auszuführen.')
  170. return False
  171. # via_channel: the request must not be a private conversation
  172. if via_channel and trigger.is_privmsg:
  173. if reply_directly: bot.say('Bitte per Channel - mehr Transparenz wagen und so!')
  174. return False
  175. # via_privmsg: the request must be a private conversation
  176. if via_privmsg and not trigger.is_privmsg:
  177. if reply_directly: bot.say('Solche Informationen gibt es nur per PM, da bin ich ja schon ein klein wenig sensibel ...')
  178. return False
  179. # need_op: if the message is in a channel, check that the user has OP there
  180. if need_op and (not trigger.is_privmsg) and (not user in bot.ops[trigger.sender]):
  181. if reply_directly: bot.say('Keine Zimtschnecke, keine Kekse.')
  182. return False
  183. # node: check that the user is whitelisted (or is admin)
  184. if not node is None and (debug_ignorebotadmin or not trigger.admin):
  185. acluser = [ x for x in nodeaccess if x.lower() == user ]
  186. acluser = acluser[0] if len(acluser) == 1 else None
  187. if nodeaccess is None or acluser is None:
  188. if reply_directly: bot.reply('You! Shall! Not! Access!')
  189. return False
  190. nodeid = node['node_id'] if 'node_id' in node else None
  191. matched = False
  192. for x in nodeaccess[acluser]:
  193. if x == nodeid or fnmatch(node['hostname'], x):
  194. matched = True
  195. break
  196. if not matched:
  197. if reply_directly: bot.reply('Mach das doch bitte auf deinen Knoten, kthxbye.')
  198. return False
  199. return True
  200. @willie.module.commands('nodeacl')
  201. def ffpb_nodeacl(bot, trigger):
  202. """Configure ACL for nodes."""
  203. if not playitsafe(bot, trigger, botadmin=True):
  204. # the check function already gives a bot reply, just exit here
  205. return
  206. # ensure the user gave arguments (group 2 is the concatenation of all following groups)
  207. if trigger.group(2) is None or len(trigger.group(2)) == 0:
  208. bot.say('Sag doch was du willst ... einmal mit Profis arbeiten, ey -.-')
  209. return
  210. # read additional arguments
  211. cmd = trigger.group(3).lower()
  212. if cmd == 'list':
  213. user = trigger.group(4)
  214. if user is None:
  215. bot.say('ACLs gesetzt für die User: ' + ', '.join([x for x in nodeaccess]))
  216. return
  217. user = user.lower()
  218. uid = [ x for x in nodeaccess if x.lower() == user ]
  219. if len(uid) == 0:
  220. bot.say('Für \'{0}\' ist keine Node ACL gesetzt.'.format(user))
  221. return
  222. bot.say('Node ACL für \'{0}\' = \'{1}\''.format(uid[0], '\', \''.join(nodeaccess[uid[0]])))
  223. return
  224. if cmd in [ 'add', 'del', 'check' ]:
  225. user = trigger.group(4)
  226. value = trigger.group(5)
  227. if user is None or value is None:
  228. bot.say('Du bist eine Pappnase - User und Knoten, bitte.')
  229. return
  230. user = str(user)
  231. print('NodeACL ' + cmd + ' \'' + value + '\' for user \'' + user + '\'')
  232. uid = [ x for x in nodeaccess if x == user or x.lower() == user ]
  233. if cmd == 'add':
  234. uid = uid[0] if len(uid) > 0 else user
  235. if not uid in nodeaccess:
  236. nodeaccess[uid] = []
  237. if not value in nodeaccess[uid]:
  238. nodeaccess[uid].append(value)
  239. bot.say('201 nodeACL \'{0}\' +\'{1}\''.format(uid, value))
  240. else:
  241. bot.say('304 nodeACL \'{0}\' contains \'{1}\''.format(uid, value))
  242. elif cmd == 'del':
  243. if len(uid) == 0:
  244. bot.say('404 nodeACL \'{0}\''.format(uid))
  245. return
  246. if value in nodeaccess[uid]:
  247. nodeaccess[uid].remove(value)
  248. bot.say('200 nodeACL \'{0}\' -\'{1}\''.format(uid, value))
  249. else:
  250. bot.say('404 nodeACL \'{0}\' does not contain \'{1}\''.format(uid, value))
  251. elif cmd == 'check':
  252. if len(uid) == 0:
  253. bot.say('Nope, keine ACL gesetzt.')
  254. return
  255. node = ffpb_findnode(value)
  256. if node is None:
  257. bot.say('Nope, kein Plan was für ein Knoten das ist.')
  258. return
  259. result = playitsafe(bot, trigger, debug_user=uid[0], debug_ignorebotadmin=True, node=node, reply_directly=False)
  260. if result == True:
  261. bot.say('Jupp.')
  262. elif result == False:
  263. bot.say('Nope.')
  264. else:
  265. bot.say('Huh? result=' + str(result))
  266. return
  267. bot.say('Unbekanntes Kommando. Probier "list [user]", "add user value" oder "del user value". Value kann node_id oder hostname-Maske sein.')
  268. def ffpb_findnode(name):
  269. """helper: try to identify the node the user meant by the given name"""
  270. # no name, no node
  271. if name is None or len(name) == 0:
  272. return None
  273. name = str(name).strip()
  274. names = {}
  275. # try to match MAC
  276. m = re.search("^([0-9a-fA-F][0-9a-fA-F]:){5}[0-9a-fA-F][0-9a-fA-F]$", name)
  277. if (not m is None):
  278. mac = m.group(0).lower()
  279. if mac in alfred_data:
  280. return alfred_data[mac]
  281. # try to find alias MAC in ALFRED data
  282. for nodeid in alfred_data:
  283. node = alfred_data[nodeid]
  284. if "network" in node:
  285. if "mac" in node["network"] and node["network"]["mac"].lower() == mac:
  286. return node
  287. if "mesh_interfaces" in node["network"]:
  288. for mim in node["network"]["mesh_interfaces"]:
  289. if mim.lower() == mac:
  290. return node
  291. return {
  292. 'hostname': '?-' + mac.replace(':','').lower(),
  293. 'network': { 'addresses': [ mac2ipv6(mac, 'fdca:ffee:ff12:132:') ], 'mac': mac, },
  294. 'hardware': { 'model': 'derived-from-mac' },
  295. }
  296. # look through the ALFRED peers
  297. for nodeid in alfred_data:
  298. node = alfred_data[nodeid]
  299. if 'hostname' in node:
  300. h = node['hostname']
  301. if h.lower() == name.lower():
  302. return node
  303. else:
  304. names[h] = nodeid
  305. # not found in ALFRED data -> try peers_repo
  306. if not peers_repo is None:
  307. peer_name = None
  308. peer_mac = None
  309. peer_file = None
  310. for b in peers_repo.heads.master.commit.tree.blobs:
  311. if b.name.lower() == name.lower():
  312. peer_name = b.name
  313. peer_file = b.abspath
  314. break
  315. if (not peer_file is None) and os.path.exists(peer_file):
  316. peerfile = open(peer_file, "r")
  317. for line in peerfile:
  318. if line.startswith("# MAC:"):
  319. peer_mac = line[6:].strip()
  320. peerfile.close()
  321. if not (peer_mac is None):
  322. return {
  323. 'hostname': peer_name,
  324. 'network': { 'addresses': [ mac2ipv6(peer_mac, 'fdca:ffee:ff12:132:') ], 'mac': peer_mac },
  325. 'hardware': { 'model': 'derived-from-vpnkeys' },
  326. }
  327. # do a similar name lookup in the ALFRED data
  328. possibilities = difflib.get_close_matches(name, [ x for x in names ], cutoff=0.75)
  329. print('findnode: Fuzzy matching \'{0}\' got {1} entries: {2}'.format(name, len(possibilities), ', '.join(possibilities)))
  330. if len(possibilities) == 1:
  331. # if we got exactly one candidate that might be it
  332. return alfred_data[names[possibilities[0]]]
  333. # none of the above was able to identify the requested node
  334. return None
  335. def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata = True):
  336. """helper: call ffpb_findnode() and give common answers via bot if nothing has been found"""
  337. if (name is None or len(name) == 0):
  338. if not bot is None: bot.reply("Grün.")
  339. return None
  340. if ensure_recent_alfreddata and alfred_data is None:
  341. if not bot is None: bot.say("Informationen sind ausverkauft, kommen erst morgen wieder rein.")
  342. return None
  343. if ensure_recent_alfreddata and ffpb_alfred_data_outdated():
  344. if not bot is None: bot.say("Ich habe gerade keine aktuellen Informationen, daher sage ich mal lieber nichts zu '" + name + "'.")
  345. return None
  346. node = ffpb_findnode(name)
  347. if node is None:
  348. if not bot is None: bot.say("Kein Plan wer oder was mit '" + name + "' gemeint ist :(")
  349. return node
  350. def mac2ipv6(mac, prefix=None):
  351. """Calculate IPv6 address from given MAC,
  352. optionally replacing the fe80:: prefix with a given one."""
  353. result = str(netaddr.EUI(mac).ipv6_link_local())
  354. if (not prefix is None) and (result.startswith("fe80::")):
  355. result = prefix + result[6:]
  356. return result
  357. @willie.module.interval(30)
  358. def ffpb_updatealfred(bot):
  359. """Aktualisiere ALFRED-Daten"""
  360. global alfred_data, alfred_update
  361. if alfred_method is None or alfred_method == "None":
  362. return
  363. updated = None
  364. if alfred_method == "exec":
  365. rawdata = subprocess.check_output(['alfred-json', '-z', '-r', '158'])
  366. updated = datetime.datetime.now()
  367. elif alfred_method.startswith("http"):
  368. try:
  369. rawdata = urllib2.urlopen(alfred_method)
  370. except:
  371. print("Failed to download ALFRED data.")
  372. return
  373. updated = datetime.datetime.fromtimestamp(mktime_tz(rawdata.info().getdate_tz("Last-Modified")))
  374. else:
  375. print("Unknown ALFRED data method '", alfred_method, "', cannot load new data.", sep="")
  376. alfred_data = None
  377. return
  378. try:
  379. alfred_data = json.load(rawdata)
  380. #print("Fetched new ALFRED data:", len(alfred_data), "entries")
  381. alfred_update = updated
  382. except ValueError as e:
  383. print("Failed to parse ALFRED data: " + str(e))
  384. return
  385. seen_nodes = bot.memory['seen_nodes'] if 'seen_nodes' in bot.memory else None
  386. if not seen_nodes is None:
  387. new = []
  388. for nodeid in alfred_data:
  389. nodeid = str(nodeid)
  390. if not nodeid in seen_nodes:
  391. seen_nodes[nodeid] = updated
  392. new.append((nodeid,alfred_data[nodeid]['hostname']))
  393. print('First time seen: ' + str(nodeid))
  394. if len(new) > 0 and not bot.memory['ffpb_in_setup']:
  395. action_msg = None
  396. if len(new) == 1:
  397. action_msg = random.choice((
  398. 'bemerkt den neuen Knoten {0}',
  399. 'entdeckt {0}',
  400. 'reibt sich die Augen und erblickt einen verpackungsfrischen Knoten {0}',
  401. u'heißt {0} im Mesh willkommen',
  402. 'freut sich, dass {0} aufgetaucht ist',
  403. 'traut seinen Augen kaum. {0} sagt zum ersten Mal: Hallo Freifunk Paderborn',
  404. u'sieht die ersten Herzschläge von {0}',
  405. u'stellt einen großen Pott Heißgetränk zu {0} und fragt ob es hier Meshpartner gibt.',
  406. )).format('\'' + str(new[0][1]) + '\'')
  407. else:
  408. action_msg = random.choice((
  409. 'bemerkt die neuen Knoten {0} und {1}',
  410. 'hat {0} und {1} entdeckt',
  411. 'bewundert {0} sowie {1}',
  412. 'freut sich, dass {0} und {1} nun auch online sind',
  413. u'heißt {0} und {1} im Mesh willkommen',
  414. 'fragt sich ob die noch jungen Herzen von {0} und {1} synchron schlagen',
  415. )).format('\'' + '\', \''.join([ str(x[1]) for x in new[0:-1] ]) + '\'', '\'' + str(new[-1][1]) + '\'')
  416. action_target = bot.config.ffpb.msg_target
  417. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
  418. def ffpb_alfred_data_outdated():
  419. timeout = datetime.datetime.now() - datetime.timedelta(minutes=5)
  420. is_outdated = timeout > alfred_update
  421. #print("ALFRED outdated? {0} (timeout={1} vs. lastupdate={2})".format(is_outdated, timeout, alfred_update))
  422. return is_outdated
  423. def ffpb_get_batcave_nodefield(nodeid, field):
  424. raw_data = None
  425. try:
  426. # query BATCAVE for node's field
  427. raw_data = urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/node/{0}/{1}'.format(nodeid, field))
  428. except Exception as err:
  429. print('Failed to contact BATCAVE for \'{0}\'->\'{1}\': {2}'.format(nodeid, field, err))
  430. return None
  431. try:
  432. return json.load(raw_data)
  433. except:
  434. print('Could not parse BATCAVE\'s response as JSON for \'{0}\'->\'{1}\''.format(nodeid, field))
  435. return None
  436. @willie.module.commands('debug-alfred')
  437. def ffpb_debug_alfred(bot, trigger):
  438. """Show statistics of available ALFRED data."""
  439. if alfred_data is None:
  440. bot.say("Keine ALFRED-Daten vorhanden.")
  441. else:
  442. bot.say("ALFRED Daten: count={0} lastupdate={1}".format(len(alfred_data), alfred_update))
  443. @willie.module.commands('alfred-data')
  444. def ffpb_peerdata(bot, trigger):
  445. """Show ALFRED data of the given node."""
  446. # identify node or bail out
  447. target_name = trigger.group(2)
  448. node = ffpb_findnode_from_botparam(bot, target_name)
  449. if node is None: return
  450. # query must be a PM or as OP in the channel
  451. if not playitsafe(bot, trigger, need_op=True, node=node):
  452. # the check function already gives a bot reply, just exit here
  453. return
  454. # reply each key in the node's data
  455. for key in node:
  456. if key in [ 'hostname' ]: continue
  457. bot.say("{0}.{1} = {2}".format(node['hostname'], key, str(node[key])))
  458. @willie.module.commands('info')
  459. def ffpb_peerinfo(bot, trigger):
  460. """Show information of the given node."""
  461. # identify node or bail out
  462. target_name = trigger.group(2)
  463. node = ffpb_findnode_from_botparam(bot, target_name)
  464. if node is None: return
  465. # read node information
  466. info_mac = node['network']['mac'] if 'network' in node and 'mac' in node['network'] else '??:??:??:??:??:??'
  467. info_id = node['node_id'] if 'node_id' in node else info_mac.replace(':','')
  468. info_name = node['hostname'] if 'hostname' in node else '?-' + info_id
  469. info_hw = ""
  470. if "hardware" in node:
  471. if "model" in node["hardware"]:
  472. model = node["hardware"]["model"]
  473. info_hw = " model='" + model + "'"
  474. info_fw = ""
  475. info_update = ""
  476. if "software" in node:
  477. if "firmware" in node["software"]:
  478. fwinfo = str(node["software"]["firmware"]["release"]) if "release" in node["software"]["firmware"] else "unknown"
  479. info_fw = " firmware=" + fwinfo
  480. if "autoupdater" in node["software"]:
  481. autoupdater = node["software"]["autoupdater"]["branch"] if node["software"]["autoupdater"]["enabled"] else "off"
  482. info_update = " (autoupdater="+autoupdater+")"
  483. info_uptime = ""
  484. u = -1
  485. if "statistics" in node and "uptime" in node["statistics"]:
  486. u = int(float(node["statistics"]["uptime"]))
  487. elif 'uptime' in node:
  488. u = int(float(node['uptime']))
  489. if u > 0:
  490. d, r1 = divmod(u, 86400)
  491. h, r2 = divmod(r1, 3600)
  492. m, s = divmod(r2, 60)
  493. if d > 0:
  494. info_uptime = ' up {0}d {1}h'.format(d,h)
  495. elif h > 0:
  496. info_uptime = ' up {0}h {1}m'.format(h,m)
  497. else:
  498. info_uptime = ' up {0}m'.format(m)
  499. info_clients = ""
  500. clientcount = ffpb_get_batcave_nodefield(info_id, 'clientcount')
  501. if not clientcount is None:
  502. clientcount = int(clientcount)
  503. info_clients = ' clients={0}'.format(clientcount)
  504. bot.say('[{1}]{2}{3}{4}{5}{6}'.format(info_mac, info_name, info_hw, info_fw, info_update, info_uptime, info_clients))
  505. @willie.module.commands('uptime')
  506. def ffpb_peeruptime(bot, trigger):
  507. """Display the uptime of the given node."""
  508. # identify node or bail out
  509. target_name = trigger.group(2)
  510. node = ffpb_findnode_from_botparam(bot, target_name)
  511. if node is None: return
  512. # get name and raw uptime from node
  513. info_name = node["hostname"]
  514. info_uptime = ''
  515. u_raw = None
  516. if 'statistics' in node and 'uptime' in node['statistics']:
  517. u_raw = node['statistics']['uptime']
  518. elif 'uptime' in node:
  519. u_raw = node['uptime']
  520. # pretty print uptime
  521. if not u_raw is None:
  522. u = int(float(u_raw))
  523. d, r1 = divmod(u, 86400)
  524. h, r2 = divmod(r1, 3600)
  525. m, s = divmod(r2, 60)
  526. if d > 0:
  527. info_uptime += '{0}d '.format(d)
  528. if h > 0:
  529. info_uptime += '{0}h '.format(h)
  530. info_uptime += '{0}m'.format(m)
  531. info_uptime += ' # raw: \'{0}\''.format(u_raw)
  532. else:
  533. info_uptime += '?'
  534. # reply to user
  535. bot.say('uptime(\'{0}\') = {1}'.format(info_name, info_uptime))
  536. @willie.module.commands('link')
  537. def ffpb_peerlink(bot, trigger):
  538. """Display MAC and link to statuspage for the given node."""
  539. # identify node or bail out
  540. target_name = trigger.group(2)
  541. node = ffpb_findnode_from_botparam(bot, target_name)
  542. if node is None: return
  543. # get node's MAC
  544. info_mac = node["network"]["mac"]
  545. info_name = node["hostname"]
  546. # get node's v6 address in the mesh (derived from MAC address)
  547. info_v6 = mac2ipv6(info_mac, 'fdca:ffee:ff12:132:')
  548. # reply to user
  549. bot.say('[{1}] mac {0} -> http://[{2}]/'.format(info_mac, info_name, info_v6))
  550. @willie.module.interval(60)
  551. def ffpb_updatepeers(bot):
  552. """Refresh list of peers and message the diff."""
  553. if peers_repo is None:
  554. print('WARNING: peers_repo is None')
  555. return
  556. old_head = peers_repo.head.commit
  557. peers_repo.remotes.origin.pull()
  558. new_head = peers_repo.head.commit
  559. if new_head != old_head:
  560. print('git pull: from ' + str(old_head) + ' to ' + str(new_head))
  561. added = []
  562. changed = []
  563. renamed = []
  564. deleted = []
  565. for f in old_head.diff(new_head):
  566. if f.new_file:
  567. added.append(f.b_blob.name)
  568. elif f.deleted_file:
  569. deleted.append(f.a_blob.name)
  570. elif f.renamed:
  571. renamed.append([f.rename_from, f.rename_to])
  572. else:
  573. changed.append(f.a_blob.name)
  574. response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(len(added), len(renamed)+len(changed), len(deleted))
  575. for f in added:
  576. response += " +'{}'".format(f)
  577. for f in changed:
  578. response += " %'{}'".format(f)
  579. for f in renamed:
  580. response += " '{}'->'{}'".format(f[0],f[1])
  581. for f in deleted:
  582. response += " -'{}'".format(f)
  583. bot.msg(bot.config.ffpb.msg_target, response)
  584. def ffpb_fetch_stats(bot, url, memoryid):
  585. """Fetch a ffmap-style nodes.json from the given URL and
  586. store it in the bot's memory."""
  587. response = urllib2.urlopen(url)
  588. data = json.load(response)
  589. nodes_active = 0
  590. nodes_total = 0
  591. clients_count = 0
  592. for node in data['nodes']:
  593. if node['flags']['gateway'] or node['flags']['client']:
  594. continue
  595. nodes_total += 1
  596. if node['flags']['online']:
  597. nodes_active += 1
  598. if 'legacy' in node['flags'] and node['flags']['legacy']:
  599. clients_count -= 1
  600. for link in data['links']:
  601. if link['type'] == 'client':
  602. clients_count += 1
  603. if not memoryid in bot.memory:
  604. bot.memory[memoryid] = { }
  605. stats = bot.memory[memoryid]
  606. stats["fetchtime"] = time.time()
  607. stats["nodes_active"] = nodes_active
  608. stats["nodes_total"] = nodes_total
  609. stats["clients"] = clients_count
  610. return (nodes_active, nodes_total, clients_count)
  611. @willie.module.interval(15)
  612. def ffpb_get_stats(bot):
  613. """Fetch current statistics, if the highscore changes signal this."""
  614. (nodes_active, nodes_total, clients_count) = ffpb_fetch_stats(bot, 'http://map.paderborn.freifunk.net/nodes.json', 'ffpb_stats')
  615. highscore_changed = False
  616. if nodes_active > highscores['nodes']:
  617. highscores['nodes'] = nodes_active
  618. highscores['nodes_ts'] = time.time()
  619. highscore_changed = True
  620. if clients_count > highscores['clients']:
  621. highscores['clients'] = clients_count
  622. highscores['clients_ts'] = time.time()
  623. highscore_changed = True
  624. if highscore_changed:
  625. print('HIGHSCORE changed: {0} nodes ({1}), {2} clients ({3})'.format(highscores['nodes'], highscores['nodes_ts'], highscores['clients'], highscores['clients_ts']))
  626. if not (bot.config.ffpb.msg_target is None):
  627. action_msg = 'notiert sich den neuen Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(highscores['nodes'], pretty_date(int(highscores['nodes_ts'])), highscores['clients'], pretty_date(int(highscores['clients_ts'])))
  628. action_target = bot.config.ffpb.msg_target
  629. if (not bot.config.ffpb.msg_target_public is None):
  630. action_target = bot.config.ffpb.msg_target_public
  631. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
  632. @willie.module.commands('status')
  633. def ffpb_status(bot, trigger):
  634. """State of the network: count of nodes + clients"""
  635. stats = bot.memory['ffpb_stats'] if 'ffpb_stats' in bot.memory else None
  636. if stats is None:
  637. bot.say('Uff, kein Plan wo der Zettel ist. Fragst du später nochmal?')
  638. return
  639. bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(stats["nodes_active"], stats["clients"]))
  640. def pretty_date(time=False):
  641. """
  642. Get a datetime object or a int() Epoch timestamp and return a
  643. pretty string like 'an hour ago', 'Yesterday', '3 months ago',
  644. 'just now', etc
  645. """
  646. from datetime import datetime
  647. now = datetime.now()
  648. compare = None
  649. if type(time) is int:
  650. compare = datetime.fromtimestamp(time)
  651. elif type(time) is float:
  652. compare = datetime.fromtimestamp(int(time))
  653. elif isinstance(time,datetime):
  654. compare = time
  655. elif not time:
  656. compare = now
  657. diff = now - compare
  658. second_diff = diff.seconds
  659. day_diff = diff.days
  660. if day_diff < 0:
  661. return ''
  662. if day_diff == 0:
  663. if second_diff < 10:
  664. return "gerade eben"
  665. if second_diff < 60:
  666. return "vor " + str(second_diff) + " Sekunden"
  667. if second_diff < 120:
  668. return "vor einer Minute"
  669. if second_diff < 3600:
  670. return "vor " + str(second_diff / 60) + " Minuten"
  671. if second_diff < 7200:
  672. return "vor einer Stunde"
  673. if second_diff < 86400:
  674. return "vor " + str(second_diff / 3600) + " Stunden"
  675. if day_diff == 1:
  676. return "gestern"
  677. if day_diff < 7:
  678. return "vor " + str(day_diff) + " Tagen"
  679. return "am " + compare.strftime('%d.%m.%Y um %H:%M Uhr')
  680. @willie.module.commands('highscore')
  681. def ffpb_highscore(bot, trigger):
  682. bot.say('Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(
  683. highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
  684. highscores['clients'], pretty_date(int(highscores['clients_ts']))))
  685. @willie.module.commands('rollout-status')
  686. def ffpb_rolloutstatus(bot, trigger):
  687. """Display statistic on how many nodes have installed the given firmware version."""
  688. # initialize results dictionary
  689. result = { }
  690. for branch in [ 'stable', 'testing' ]:
  691. result[branch] = None
  692. skipped = 0
  693. # command is restricted to bot-admins via PM or OPS in the channel
  694. if (not (trigger.admin and trigger.is_privmsg)) and (not trigger.nick in bot.ops[trigger.sender]):
  695. bot.say('Geh zur dunklen Seite, die haben Kekse - ohne Keks kein Rollout-Status.')
  696. return
  697. # read expected firmware version from command arguments
  698. expected_release = trigger.group(2)
  699. if expected_release is None or len(expected_release) == 0:
  700. bot.say('Von welcher Firmware denn?')
  701. return
  702. # check each node in ALFRED data
  703. for nodeid in alfred_data:
  704. item = alfred_data[nodeid]
  705. if (not 'software' in item) or (not 'firmware' in item['software']) or (not 'autoupdater' in item['software']):
  706. skipped+=1
  707. continue
  708. release = item['software']['firmware']['release']
  709. branch = item['software']['autoupdater']['branch']
  710. enabled = item['software']['autoupdater']['enabled']
  711. if not branch in result or result[branch] is None:
  712. result[branch] = { 'auto_count': 0, 'auto_not': 0, 'manual_count': 0, 'manual_not': 0, 'total': 0 }
  713. result[branch]['total'] += 1
  714. match = 'count' if release == expected_release else 'not'
  715. mode = 'auto' if enabled else 'manual'
  716. result[branch][mode+'_'+match] += 1
  717. # respond to user
  718. output = "Rollout von '{0}':".format(expected_release)
  719. for branch in result:
  720. auto_count = result[branch]['auto_count']
  721. auto_total = auto_count + result[branch]['auto_not']
  722. manual_count = result[branch]['manual_count']
  723. manual_total = manual_count + result[branch]['manual_not']
  724. bot.say("Rollout von '{0}': {1} = {2}/{3} per Auto-Update, {4}/{5} manuell".format(expected_release, branch, auto_count, auto_total, manual_count, manual_total))
  725. # output count of nodes for which the autoupdater's branch and/or
  726. # firmware version could not be retrieved
  727. if skipped > 0:
  728. bot.say("Rollout von '{0}': {1} Knoten unklar".format(expected_release, skipped))
  729. @willie.module.commands('ping')
  730. def ffpb_ping(bot, trigger=None, target_name=None):
  731. """Ping the given node"""
  732. # identify node or bail out
  733. if target_name is None: target_name = trigger.group(2)
  734. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  735. if node is None: return None
  736. # get the first non-linklocal address from the node
  737. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  738. target_alias = node["hostname"]
  739. # execute the actual ping and reply the result
  740. print("pinging '{0}' at {1} ...".format(target_name, target))
  741. result = os.system('ping6 -c 2 -W 1 ' + target + ' >/dev/null')
  742. if result == 0:
  743. print("ping to '{0}' succeeded".format(target_name))
  744. if not bot is None: bot.say('Knoten "' + target_alias + '" antwortet \o/')
  745. return True
  746. elif result == 1 or result == 256:
  747. print("ping to '{0}' failed".format(target_name))
  748. if not bot is None: bot.say('Keine Antwort von "' + target_alias + '" :-(')
  749. return False
  750. else:
  751. print("ping to '{0}' broken: result='{1}'".format(target_name, result))
  752. if not bot is None: bot.say('Uh oh, irgendwas ist kaputt. Chef, ping result = ' + str(result) + ' - darf ich das essen?')
  753. return None
  754. @willie.module.interval(3*60)
  755. def ffpb_monitor_ping(bot):
  756. """Ping each node currently under surveillance."""
  757. # determine where-to to send alerts
  758. notify_target = bot.config.core.owner
  759. if (not bot.config.ffpb.msg_target is None):
  760. notify_target = bot.config.ffpb.msg_target
  761. # check each node under surveillance
  762. for node in monitored_nodes:
  763. mon = monitored_nodes[node]
  764. added = mon['added']
  765. last_status = mon['status']
  766. last_check = mon['last_check']
  767. last_success = mon['last_success']
  768. current_status = ffpb_ping(bot=None, target_name=node)
  769. if current_status is None: current_status = False
  770. mon['status'] = current_status
  771. mon['last_check'] = time.time()
  772. if current_status == True: mon['last_success'] = time.time()
  773. print("Monitoring ({0}) {1} (last: {2} at {3})".format(node, current_status, last_status, time.strftime('%Y-%m-%d %H:%M', time.localtime(last_check))))
  774. if last_status != current_status and (last_status or current_status):
  775. if last_check is None:
  776. # erster Check, keine Ausgabe
  777. continue
  778. if current_status == True:
  779. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' pingt wieder (zuletzt {1})'.format(node, pretty_date(last_success) if not last_success is None else '[nie]'))
  780. else:
  781. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' DOWN'.format(node))
  782. @willie.module.commands('monitor')
  783. def ffpb_monitor(bot, trigger):
  784. """Monitoring capability of the bot, try subcommands add, del, info and list."""
  785. # command is restricted to bot admins
  786. if not trigger.admin:
  787. bot.say('Ich ping hier nicht für jeden durch die Weltgeschichte.')
  788. return
  789. # ensure the user gave arguments (group 2 is the concatenation of all following groups)
  790. if trigger.group(2) is None or len(trigger.group(2)) == 0:
  791. bot.say('Das Monitoring sagt du hast doofe Ohren.')
  792. return
  793. # read additional arguments
  794. cmd = trigger.group(3)
  795. node = trigger.group(4)
  796. if not node is None: node = str(node)
  797. # subcommand 'add': add a node to monitoring
  798. if cmd == "add":
  799. if node in monitored_nodes:
  800. bot.say('Knoten \'{0}\' wird bereits gemonitored.'.format(node))
  801. return
  802. monitored_nodes[node] = {
  803. 'added': trigger.sender,
  804. 'status': None,
  805. 'last_check': None,
  806. 'last_success': None,
  807. }
  808. bot.say('Knoten \'{0}\' wird jetzt ganz genau beobachtet.'.format(node))
  809. return
  810. # subcommand 'del': remote a node from monitoring
  811. if cmd == "del":
  812. if not node in monitored_nodes:
  813. bot.say('Knoten \'{0}\' war gar nicht im Monitoring?!?'.format(node))
  814. return
  815. del monitored_nodes[node]
  816. bot.say('Okidoki, \'{0}\' lasse ich jetzt links liegen.'.format(node))
  817. return
  818. # subcommand 'info': monitoring status of a node
  819. if cmd == "info":
  820. if node in monitored_nodes:
  821. info = monitored_nodes[node]
  822. bot.say('Knoten \'{0}\' wurde zuletzt {1} gepingt (Ergebnis: {2})'.format(node, pretty_date(info['last_check']) if not info['last_check'] is None else "^W noch nie", info['status']))
  823. else:
  824. bot.say('Knoten \'{0}\' ist nicht im Monitoring.'.format(node))
  825. return
  826. # subcommand 'list': enumerate all monitored nodes
  827. if cmd == "list":
  828. nodes = ""
  829. for node in monitored_nodes:
  830. nodes = nodes + " " + node
  831. bot.say('Monitoring aktiv für:' + nodes)
  832. return
  833. # subcommand 'help': give some hints what the user can do
  834. if cmd == "help":
  835. bot.say('Entweder "!monitor list" oder "!monitor {add|del|info} <node>"')
  836. return
  837. # no valid subcommand given: complain
  838. bot.say('Mit "' + str(cmd) + '" kann ich nix anfangen, probier doch mal "!monitor help".')
  839. @willie.module.commands('providers')
  840. def ffpb_providers(bot, trigger):
  841. """Fetch the top 5 providers from BATCAVE."""
  842. providers = json.load(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/providers?format=json'))
  843. providers.sort(key=lambda x: x['count'], reverse=True)
  844. bot.say('Unsere Top 5 Provider: ' + ', '.join(['{0} ({1:.0f}%)'.format(x['name'], x['percentage']) for x in providers[:5]]))
  845. @willie.module.commands('mesh')
  846. def ffpb_nodemesh(bot, trigger):
  847. """Display mesh partners of the given node."""
  848. # identify node or bail out
  849. target_name = trigger.group(2)
  850. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  851. if node is None: return None
  852. # derive node's id
  853. nodeid = node['node_id'] if 'node_id' in node else None
  854. if nodeid is None: nodeid = node['network']['mac'].replace(':','') if 'network' in node and 'mac' in node['network'] else None
  855. if nodeid is None:
  856. bot.say('Mist, ich habe gerade den Zettel verlegt auf dem die Node-ID von \'{0}\' steht, bitte frag später noch einmal.'.format(node['hostname'] if 'hostname' in node else target_name))
  857. return
  858. # query BATCAVE for node's neighbours (result is a list of MAC addresses)
  859. cave_result = ffpb_get_batcave_nodefield(nodeid, 'neighbours')
  860. # query BATCAVE for neighbour's names
  861. d = '&'.join([ str(n) for n in cave_result ])
  862. req = urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/idmac2name', d)
  863. # filter out duplicate names
  864. neighbours = set()
  865. for n in req:
  866. ident,name = n.strip().split('=')
  867. neighbours.add(name)
  868. neighbours = [ x for x in neighbours ]
  869. # respond to the user
  870. if len(neighbours) == 0:
  871. bot.say(u'{0} hat keinen Mesh-Partner *schnüff*'.format(node['hostname']))
  872. elif len(neighbours) == 1:
  873. bot.say(u'{0} mesht mit \'{1}\''.format(node['hostname'], neighbours[0]))
  874. else:
  875. bot.say('{0} mesht mit \'{1}\' und \'{2}\''.format(node['hostname'], '\', \''.join(neighbours[:-1]), neighbours[-1]))
  876. @willie.module.commands('exec-on-peer')
  877. def ffpb_remoteexec(bot, trigger):
  878. """Remote execution on the given node"""
  879. bot_params = trigger.group(2).split(' ',1)
  880. if len(bot_params) != 2:
  881. bot.say('Wenn du nicht sagst wo mach ich remote execution bei dir!')
  882. bot.say('Tipp: !exec-on-peer <peer> <cmd>')
  883. return
  884. target_name = bot_params[0]
  885. target_cmd = bot_params[1]
  886. # identify requested node or bail out
  887. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  888. if node is None: return
  889. # check ACL
  890. if not playitsafe(bot, trigger, via_channel=True, node=node):
  891. return
  892. # use the node's first non-linklocal address
  893. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  894. target_alias = node["hostname"]
  895. # assemble SSH command
  896. cmd = 'ssh -6 -l root ' + target + ' -- "' + target_cmd + '"'
  897. print("REMOTE EXEC = " + cmd)
  898. try:
  899. # call SSH
  900. result = subprocess.check_output(['ssh', '-6n', '-l', 'root', '-o', 'BatchMode=yes', '-o','StrictHostKeyChecking=no', target, target_cmd], stderr=subprocess.STDOUT, shell=False)
  901. # fetch results and sent at most 8 of them as response
  902. lines = str(result).splitlines()
  903. if len(lines) == 0:
  904. bot.say('exec-on-peer(' + target_alias + '): No output')
  905. return
  906. msg = 'exec-on-peer(' + target_alias + '): ' + str(len(lines)) + ' Zeilen'
  907. if len(lines) > 8:
  908. msg += ' (zeige max. 8)'
  909. bot.say(msg + ':')
  910. for line in lines[0:8]:
  911. bot.say(line)
  912. except subprocess.CalledProcessError as e:
  913. bot.say('Fehler '+str(e.returncode)+' bei exec-on-peer('+target_alias+'): ' + e.output)