ffpb.py 25 KB

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