ffpb.py 29 KB

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