ffpb.py 28 KB

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