ffpb.py 27 KB

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