ffpb.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. # must be called via private message by a bot admin
  441. if not playitsafe(bot, trigger, botadmin=True, via_privmsg=True):
  442. return
  443. alfred_data = get_alfred_data(bot)
  444. if alfred_data is None:
  445. bot.say("Keine ALFRED-Daten vorhanden.")
  446. else:
  447. bot.say("ALFRED Daten: count={0} lastupdate={1}".format(len(alfred_data), bot.memory['alfred_update']))
  448. @willie.module.interval(60)
  449. def ffpb_updatepeers(bot):
  450. """Refresh list of peers and message the diff."""
  451. if peers_repo is None:
  452. print('WARNING: peers_repo is None')
  453. return
  454. old_head = peers_repo.head.commit
  455. peers_repo.remotes.origin.pull()
  456. new_head = peers_repo.head.commit
  457. if new_head != old_head:
  458. print('git pull: from ' + str(old_head) + ' to ' + str(new_head))
  459. added = []
  460. changed = []
  461. renamed = []
  462. deleted = []
  463. for f in old_head.diff(new_head):
  464. if f.new_file:
  465. added.append(f.b_blob.name)
  466. elif f.deleted_file:
  467. deleted.append(f.a_blob.name)
  468. elif f.renamed:
  469. renamed.append([f.rename_from, f.rename_to])
  470. else:
  471. changed.append(f.a_blob.name)
  472. response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(len(added), len(renamed)+len(changed), len(deleted))
  473. for f in added:
  474. response += " +'{}'".format(f)
  475. for f in changed:
  476. response += " %'{}'".format(f)
  477. for f in renamed:
  478. response += " '{}'->'{}'".format(f[0],f[1])
  479. for f in deleted:
  480. response += " -'{}'".format(f)
  481. bot.msg(bot.config.ffpb.msg_target, response)
  482. def ffpb_fetch_stats(bot, url, memoryid):
  483. """Fetch a ffmap-style nodes.json from the given URL and
  484. store it in the bot's memory."""
  485. response = urllib2.urlopen(url)
  486. data = json.load(response)
  487. nodes_active = 0
  488. nodes_total = 0
  489. clients_count = 0
  490. for node in data['nodes']:
  491. if node['flags']['gateway'] or node['flags']['client']:
  492. continue
  493. nodes_total += 1
  494. if node['flags']['online']:
  495. nodes_active += 1
  496. if 'legacy' in node['flags'] and node['flags']['legacy']:
  497. clients_count -= 1
  498. for link in data['links']:
  499. if link['type'] == 'client':
  500. clients_count += 1
  501. if not memoryid in bot.memory:
  502. bot.memory[memoryid] = { }
  503. stats = bot.memory[memoryid]
  504. stats["fetchtime"] = time.time()
  505. stats["nodes_active"] = nodes_active
  506. stats["nodes_total"] = nodes_total
  507. stats["clients"] = clients_count
  508. return (nodes_active, nodes_total, clients_count)
  509. def pretty_date(time=False):
  510. """
  511. Get a datetime object or a int() Epoch timestamp and return a
  512. pretty string like 'an hour ago', 'Yesterday', '3 months ago',
  513. 'just now', etc
  514. """
  515. from datetime import datetime
  516. now = datetime.now()
  517. compare = None
  518. if type(time) is int:
  519. compare = datetime.fromtimestamp(time)
  520. elif type(time) is float:
  521. compare = datetime.fromtimestamp(int(time))
  522. elif isinstance(time,datetime):
  523. compare = time
  524. elif not time:
  525. compare = now
  526. diff = now - compare
  527. second_diff = diff.seconds
  528. day_diff = diff.days
  529. if day_diff < 0:
  530. return ''
  531. if day_diff == 0:
  532. if second_diff < 10:
  533. return "gerade eben"
  534. if second_diff < 60:
  535. return "vor " + str(second_diff) + " Sekunden"
  536. if second_diff < 120:
  537. return "vor einer Minute"
  538. if second_diff < 3600:
  539. return "vor " + str(second_diff / 60) + " Minuten"
  540. if second_diff < 7200:
  541. return "vor einer Stunde"
  542. if second_diff < 86400:
  543. return "vor " + str(second_diff / 3600) + " Stunden"
  544. if day_diff == 1:
  545. return "gestern"
  546. if day_diff < 7:
  547. return "vor " + str(day_diff) + " Tagen"
  548. return "am " + compare.strftime('%d.%m.%Y um %H:%M Uhr')
  549. @willie.module.commands('ping')
  550. def ffpb_ping(bot, trigger=None, target_name=None, reply_directly=True):
  551. """Ping the given node"""
  552. # identify node or bail out
  553. if target_name is None: target_name = trigger.group(2)
  554. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  555. if node is None: return None
  556. # get the first non-linklocal address from the node
  557. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  558. target_alias = node["hostname"]
  559. # execute the actual ping and reply the result
  560. print("pinging '{0}' at {1} ...".format(target_name, target))
  561. result = os.system('ping6 -c 2 -W 1 ' + target + ' >/dev/null')
  562. if result == 0:
  563. print("ping to '{0}' succeeded".format(target_name))
  564. if reply_directly: bot.say('Knoten "' + target_alias + '" antwortet \o/')
  565. return True
  566. elif result == 1 or result == 256:
  567. print("ping to '{0}' failed".format(target_name))
  568. if reply_directly: bot.say('Keine Antwort von "' + target_alias + '" :-(')
  569. return False
  570. else:
  571. print("ping to '{0}' broken: result='{1}'".format(target_name, result))
  572. if reply_directly: bot.say('Uh oh, irgendwas ist kaputt. Chef, ping result = ' + str(result) + ' - darf ich das essen?')
  573. return None
  574. @willie.module.commands('mesh')
  575. def ffpb_nodemesh(bot, trigger):
  576. """Display mesh partners of the given node."""
  577. # identify node or bail out
  578. target_name = trigger.group(2)
  579. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  580. if node is None: return None
  581. # derive node's id
  582. nodeid = node['node_id'] if 'node_id' in node else None
  583. if nodeid is None:
  584. msg = 'Mist, ich habe gerade den Zettel verlegt auf dem die Node-ID von \'{0}\' steht, bitte frag später noch einmal.'
  585. bot.say(msg.format(node['hostname'] if 'hostname' in node else target_name))
  586. return
  587. # query BATCAVE for node's neighbours (result is a list of MAC addresses)
  588. cave_result = ffpb_get_batcave_nodefield(nodeid, 'neighbours')
  589. # query BATCAVE for neighbour's names
  590. d = '&'.join([ str(n) for n in cave_result ])
  591. req = urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/idmac2name', d)
  592. # filter out duplicate names
  593. neighbours = set()
  594. for n in req:
  595. ident,name = n.strip().split('=')
  596. neighbours.add(name)
  597. neighbours = [ x for x in neighbours ]
  598. # respond to the user
  599. if len(neighbours) == 0:
  600. bot.say(u'{0} hat keinen Mesh-Partner *schnüff*'.format(node['hostname']))
  601. elif len(neighbours) == 1:
  602. bot.say(u'{0} mesht mit \'{1}\''.format(node['hostname'], neighbours[0]))
  603. else:
  604. bot.say('{0} mesht mit \'{1}\' und \'{2}\''.format(node['hostname'], '\', \''.join(neighbours[:-1]), neighbours[-1]))
  605. @willie.module.commands('exec-on-peer')
  606. def ffpb_remoteexec(bot, trigger):
  607. """Remote execution on the given node"""
  608. bot_params = trigger.group(2).split(' ',1)
  609. if len(bot_params) != 2:
  610. bot.say('Wenn du nicht sagst wo mach ich remote execution bei dir!')
  611. bot.say('Tipp: !exec-on-peer <peer> <cmd>')
  612. return
  613. target_name = bot_params[0]
  614. target_cmd = bot_params[1]
  615. # identify requested node or bail out
  616. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  617. if node is None: return
  618. # check ACL
  619. if not playitsafe(bot, trigger, via_channel=True, node=node):
  620. return
  621. # use the node's first non-linklocal address
  622. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  623. target_alias = node["hostname"]
  624. # assemble SSH command
  625. cmd = 'ssh -6 -l root ' + target + ' -- "' + target_cmd + '"'
  626. print("REMOTE EXEC = " + cmd)
  627. try:
  628. # call SSH
  629. result = subprocess.check_output(['ssh', '-6n', '-l', 'root', '-o', 'BatchMode=yes', '-o','StrictHostKeyChecking=no', target, target_cmd], stderr=subprocess.STDOUT, shell=False)
  630. # fetch results and sent at most 8 of them as response
  631. lines = str(result).splitlines()
  632. if len(lines) == 0:
  633. bot.say('exec-on-peer(' + target_alias + '): No output')
  634. return
  635. msg = 'exec-on-peer(' + target_alias + '): ' + str(len(lines)) + ' Zeilen'
  636. if len(lines) > 8:
  637. msg += ' (zeige max. 8)'
  638. bot.say(msg + ':')
  639. for line in lines[0:8]:
  640. bot.say(line)
  641. except subprocess.CalledProcessError as e:
  642. bot.say('Fehler '+str(e.returncode)+' bei exec-on-peer('+target_alias+'): ' + e.output)