ffpb.py 26 KB

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