ffpb.py 33 KB

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