ffpb.py 31 KB

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