diff options
author | makefu <github@syntax-fehler.de> | 2014-01-14 00:52:14 +0100 |
---|---|---|
committer | makefu <github@syntax-fehler.de> | 2014-01-14 00:52:14 +0100 |
commit | e97a9f9244a13cd583344a1960799474da4c1321 (patch) | |
tree | 6190fa01622ca5ceea9cf49c5df858f3245221f6 | |
parent | 38ad7a96c55c15486ec87b51b91315021943f8c8 (diff) | |
parent | bc4c246294458ef8275188cbbb6697a695e3f351 (diff) |
Merge branch 'master' of ssh://github.com/krebscode/painload
-rwxr-xr-x | Reaktor/IRC/asybot.py | 180 | ||||
-rwxr-xr-x | Reaktor/IRC/index | 2 | ||||
-rw-r--r-- | Reaktor/IRC/ircasy.py | 164 | ||||
-rw-r--r-- | Reaktor/IRC/reaktor.py | 71 | ||||
-rwxr-xr-x | retiolum/scripts/tinc_setup/new_install.sh | 6 | ||||
-rwxr-xr-x | retiolum/scripts/tinc_setup/tinc-up | 6 |
6 files changed, 240 insertions, 189 deletions
diff --git a/Reaktor/IRC/asybot.py b/Reaktor/IRC/asybot.py deleted file mode 100755 index 8367b190..00000000 --- a/Reaktor/IRC/asybot.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python -# -# //Reaktor/IRC/asybot.py -# -import os -from translate_colors import translate_colors -def is_executable(x): - import os - return os.path.exists(x) and os.access(x, os.X_OK) - -from asynchat import async_chat as asychat -from asyncore import loop -from socket import AF_INET, SOCK_STREAM,gethostname -from signal import SIGALRM, signal, alarm -from datetime import datetime as date, timedelta -import shlex -from time import sleep -from sys import exit -from re import split, search, match -from textwrap import TextWrapper -import logging,logging.handlers -import shlex - -config_filename = './config.py' - -from getconf import make_getconf -getconf = make_getconf(config_filename) -log = logging.getLogger('asybot') -hdlr = logging.handlers.SysLogHandler(facility=logging.handlers.SysLogHandler.LOG_DAEMON) -formatter = logging.Formatter( '%(filename)s: %(levelname)s: %(message)s') -hdlr.setFormatter(formatter) -log.addHandler(hdlr) -logging.basicConfig(level = logging.DEBUG if getconf('debug') else logging.INFO) - -# s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g -- removes color codes - - -class asybot(asychat): - def __init__(self): - asychat.__init__(self) - self.server = getconf('irc_server') - self.port = getconf('irc_port') - self.channels = getconf('irc_channels') - self.realname = getconf('irc_nickname') - self.nickname = getconf('irc_nickname') - self.username = getconf('irc_nickname') - self.hostname = getconf('irc_nickname') - self.ircname = getconf('irc_nickname') - self.data = '' - self.myterminator = '\r\n' - self.set_terminator(self.myterminator.encode()) - self.create_socket(AF_INET, SOCK_STREAM) - self.connect((self.server, self.port)) - self.wrapper = TextWrapper(subsequent_indent=" ",width=400) - - log.info('=> irc://%s@%s:%s/%s' % (self.nickname, self.server, self.port, self.channels)) - - # When we don't receive data for alarm_timeout seconds then issue a - # PING every hammer_interval seconds until kill_timeout seconds have - # passed without a message. Any incoming message will reset alarm. - self.alarm_timeout = getconf('irc_alarm_timeout') - self.hammer_interval = getconf('irc_hammer_interval') - self.kill_timeout = getconf('irc_kill_timeout') - signal(SIGALRM, lambda signum, frame: self.alarm_handler()) - self.reset_alarm() - - - def reset_alarm(self): - self.last_activity = date.now() - alarm(self.alarm_timeout) - - def alarm_handler(self): - delta = date.now() - self.last_activity - if delta > timedelta(seconds=self.kill_timeout): - log.error('No data for %s. Giving up...' % delta) - exit(2) - else: - log.error('No data for %s. PINGing server...' % delta) - self.push('PING :%s' % self.nickname) - alarm(self.hammer_interval) - - def collect_incoming_data(self, data): - self.data += data.decode(encoding='UTF-8') - - def found_terminator(self): - log.debug('<< %s' % self.data) - - message = self.data - self.data = '' - - _, prefix, command, params, rest, _ = \ - split('^(?::(\S+)\s)?(\S+)((?:\s[^:]\S*)*)(?:\s:(.*))?$', message) - params = params.split(' ')[1:] - - if command == 'PING': - self.push('PONG :%s' % rest) - log.debug("Replying to servers PING with PONG :%s" %rest) - - elif command == 'PRIVMSG': - self.on_privmsg(prefix, command, params, rest) - - elif command == '433': - # ERR_NICKNAMEINUSE, retry with another name - _, nickname, int, _ = split('^.*[^0-9]([0-9]+)$', self.nickname) \ - if search('[0-9]$', self.nickname) \ - else ['', self.nickname, 0, ''] - self.nickname = nickname + str(int + 1) - self.handle_connect() - - self.reset_alarm() - - def push(self, message): - log.debug('>> %s' % message) - msg = (message + self.myterminator).encode() - log.debug('>> %s' % msg) - asychat.push(self, msg) - - def handle_connect(self): - self.push('NICK %s' % self.nickname) - self.push('USER %s %s %s :%s' % - (self.username, self.hostname, self.server, self.realname)) - self.push('JOIN %s' % ','.join(self.channels)) - - def on_privmsg(self, prefix, command, params, rest): - def PRIVMSG(text): - for line in self.wrapper.wrap(text): - msg = 'PRIVMSG %s :%s' % (','.join(params), line) - log.info(msg) - self.push(msg) - sleep(1) - - def ME(text): - PRIVMSG(('ACTION ' + text + '')) - - for command in getconf('commands'): - y = match(command['pattern'], rest) - if y: - self.execute_command(command, y, prefix, PRIVMSG, ME) - break - - def execute_command(self, command, match, prefix, PRIVMSG, ME): - from os.path import realpath, dirname, join - from subprocess import Popen as popen, PIPE - from time import time - - #TODO: allow only commands below ./commands/ - exe = join(dirname(realpath(dirname(__file__))), command['argv'][0]) - myargv = [exe] + command['argv'][1:] - if match.groupdict().get('args',None): - myargv += shlex.split(match.groupdict()['args']) - - env = {} - env['_from'] = prefix.split('!', 1)[0] - env['config_filename'] = os.path.abspath(config_filename) - start = time() - try: - p = popen(myargv, bufsize=1, stdout=PIPE, stderr=PIPE, env=env) - except (OSError, Exception) as error: - ME('brain damaged') - log.error('OSError@%s: %s' % (myargv, error)) - return - pid = p.pid - for line in iter(p.stdout.readline, ''.encode()): - try: - PRIVMSG(translate_colors(line.decode())) - except Exception as error: - log.error('no send: %s' % error) - log.debug('%s stdout: %s' % (pid, line)) - p.wait() - elapsed = time() - start - code = p.returncode - log.info('command: %s -> %s in %d seconds' % (myargv, code, elapsed)) - [log.debug('%s stderr: %s' % (pid, x)) for x in p.stderr.readlines()] - - if code != 0: - ME('mimimi') - -if __name__ == "__main__": - asybot() - loop() diff --git a/Reaktor/IRC/index b/Reaktor/IRC/index index 2dc803a1..af557a89 100755 --- a/Reaktor/IRC/index +++ b/Reaktor/IRC/index @@ -3,4 +3,4 @@ set -xeuf # cd //Reaktor cd $(dirname $(readlink -f $0))/.. -exec IRC/asybot.py "$@" +exec IRC/reaktor.py "$@" diff --git a/Reaktor/IRC/ircasy.py b/Reaktor/IRC/ircasy.py new file mode 100644 index 00000000..ca607f2b --- /dev/null +++ b/Reaktor/IRC/ircasy.py @@ -0,0 +1,164 @@ +#! /usr/bin/env python +# +# //Reaktor/IRC/asybot.py +# +from asynchat import async_chat as asychat +from asyncore import loop +from socket import AF_INET, SOCK_STREAM,gethostname +from signal import SIGALRM, signal, alarm +from datetime import datetime as date, timedelta +from time import sleep +from sys import exit +from re import split, search, match +from textwrap import TextWrapper + +import logging,logging.handlers + +# s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g -- removes color codes + + +class asybot(asychat): + def __init__(self, server, port, nickname, channels, realname=False, username=False, hostname=False, hammer_interval=10, alarm_timeout=300, kill_timeout=360, loglevel=logging.ERROR): + asychat.__init__(self) + #logger magic + self.log = logging.getLogger('asybot') + hdlr = logging.handlers.SysLogHandler(facility=logging.handlers.SysLogHandler.LOG_DAEMON) + formatter = logging.Formatter( '%(filename)s: %(levelname)s: %(message)s') + hdlr.setFormatter(formatter) + self.log.addHandler(hdlr) + logging.basicConfig(level = loglevel) + + self.nickname = nickname + + if realname: + self.realname = realname + else: + self.realname = nickname + + if username: + self.username = username + else: + self.username = nickname + + if hostname: + self.hostname = hostname + else: + self.hostname = nickname + + self.retry = False + self.server = server + self.port = port + self.channels = channels + self.data = '' + self.myterminator = '\r\n' + self.set_terminator(self.myterminator.encode()) + self.create_socket(AF_INET, SOCK_STREAM) + self.connect((self.server, self.port)) + self.wrapper = TextWrapper(subsequent_indent=" ",width=400) + + self.log.info('=> irc://%s@%s:%s/%s' % (self.nickname, self.server, self.port, self.channels)) + + # When we don't receive data for alarm_timeout seconds then issue a + # PING every hammer_interval seconds until kill_timeout seconds have + # passed without a message. Any incoming message will reset alarm. + self.alarm_timeout = alarm_timeout + self.hammer_interval = hammer_interval + self.kill_timeout = kill_timeout + signal(SIGALRM, lambda signum, frame: self.alarm_handler()) + self.reset_alarm() + + def reset_alarm(self): + self.last_activity = date.now() + alarm(self.alarm_timeout) + + def alarm_handler(self): + delta = date.now() - self.last_activity + if delta > timedelta(seconds=self.kill_timeout): + self.log.error('No data for %s. Giving up...' % delta) + self.handle_disconnect() + else: + self.log.error('No data for %s. PINGing server...' % delta) + self.push('PING :%s' % self.nickname) + alarm(self.hammer_interval) + + def collect_incoming_data(self, data): + self.data += data.decode() + + def found_terminator(self): + self.log.debug('<< %s' % self.data) + + message = self.data + self.data = '' + + _, prefix, command, params, rest, _ = \ + split('^(?::(\S+)\s)?(\S+)((?:\s[^:]\S*)*)(?:\s:(.*))?$', message) + params = params.split(' ')[1:] + + if command == 'PING': + self.push('PONG :%s' % rest) + self.log.debug("Replying to servers PING with PONG :%s" %rest) + + elif command == 'PRIVMSG': + self.on_privmsg(prefix, command, params, rest) + + elif command == 'INVITE': + self.on_invite(prefix, command, params, rest) + + elif command == '433': + # ERR_NICKNAMEINUSE, retry with another name + _, nickname, int, _ = split('^.*[^0-9]([0-9]+)$', self.nickname) \ + if search('[0-9]$', self.nickname) \ + else ['', self.nickname, 0, ''] + self.nickname = nickname + str(int + 1) + self.handle_connect() + + elif command == '376': + self.on_welcome(prefix, command, params, rest) + + self.reset_alarm() + + def push(self, message): + self.log.debug('>> %s' % message) + msg = (message + self.myterminator).encode() + self.log.debug('>> %s' % msg) + asychat.push(self, msg) + + def disconnect(self): + self.push('QUIT') + self.close() + + def reconnect(self): + self.push('QUIT') + self.close() + self.create_socket(AF_INET, SOCK_STREAM) + self.connect((self.server, self.port)) + + def handle_connect(self): + self.push('NICK %s' % self.nickname) + self.push('USER %s %s %s :%s' % + (self.username, self.hostname, self.server, self.realname)) + + def handle_disconnect(self): + if self.retry: + self.reconnect() + else: + self.log.error('No retry set, giving up') + + def PRIVMSG(self, target, text): + for line in self.wrapper.wrap(text): + msg = 'PRIVMSG %s :%s' % (','.join(target), line) + self.log.info(msg) + self.push(msg) + sleep(1) + + def ME(self, target, text): + self.PRIVMSG(target, ('ACTION ' + text + '')) + + def on_privmsg(self, prefix, command, params, rest): + pass + + def on_welcome(self, prefix, command, params, rest): + self.push('JOIN %s' % ','.join(self.channels)) + + def on_invite(self, prefix, command, params, rest): + pass diff --git a/Reaktor/IRC/reaktor.py b/Reaktor/IRC/reaktor.py new file mode 100644 index 00000000..990d47e5 --- /dev/null +++ b/Reaktor/IRC/reaktor.py @@ -0,0 +1,71 @@ +import os +from ircasy import asybot +from asyncore import loop +from translate_colors import translate_colors +import shlex +from re import split, search, match + +config_filename = './config.py' +from getconf import make_getconf +getconf = make_getconf(config_filename) + +import logging,logging.handlers +log = logging.getLogger('asybot') +hdlr = logging.handlers.SysLogHandler(facility=logging.handlers.SysLogHandler.LOG_DAEMON) +formatter = logging.Formatter( '%(filename)s: %(levelname)s: %(message)s') +hdlr.setFormatter(formatter) +log.addHandler(hdlr) +logging.basicConfig(level = logging.DEBUG if getconf('debug') else logging.INFO) + + +class Reaktor(asybot): + def __init__(self): + asybot.__init__(self, getconf('irc_server'), getconf('irc_port'), getconf('irc_nickname'), getconf('irc_channels'), hammer_interval=getconf('irc_hammer_interval'), alarm_timeout=getconf('irc_alarm_timeout'), kill_timeout=getconf('irc_kill_timeout')) + + def on_privmsg(self, prefix, command, params, rest): + for command in getconf('commands'): + y = match(command['pattern'], rest) + if y: + self.execute_command(command, y, prefix, params) + break + + def execute_command(self, command, match, prefix, target): + from os.path import realpath, dirname, join + from subprocess import Popen as popen, PIPE + from time import time + + #TODO: allow only commands below ./commands/ + exe = join(dirname(realpath(dirname(__file__))), command['argv'][0]) + myargv = [exe] + command['argv'][1:] + if match.groupdict().get('args',None): + myargv += shlex.split(match.groupdict()['args']) + + env = {} + env['_from'] = prefix.split('!', 1)[0] + env['config_filename'] = os.path.abspath(config_filename) + start = time() + try: + p = popen(myargv, bufsize=1, stdout=PIPE, stderr=PIPE, env=env) + except (OSError, Exception) as error: + self.ME(target, 'brain damaged') + log.error('OSError@%s: %s' % (myargv, error)) + return + pid = p.pid + for line in iter(p.stdout.readline, ''.encode()): + try: + self.PRIVMSG(target, translate_colors(line.decode())) + except Exception as error: + log.error('no send: %s' % error) + log.debug('%s stdout: %s' % (pid, line)) + p.wait() + elapsed = time() - start + code = p.returncode + log.info('command: %s -> %s in %d seconds' % (myargv, code, elapsed)) + [log.debug('%s stderr: %s' % (pid, x)) for x in p.stderr.readlines()] + + if code != 0: + self.ME(target, 'mimimi') + +if __name__ == "__main__": + Reaktor() + loop() diff --git a/retiolum/scripts/tinc_setup/new_install.sh b/retiolum/scripts/tinc_setup/new_install.sh index 50fbc3b5..b48649ec 100755 --- a/retiolum/scripts/tinc_setup/new_install.sh +++ b/retiolum/scripts/tinc_setup/new_install.sh @@ -209,9 +209,7 @@ EOF echo '' >> tinc-up echo 'conf=$dirname/tinc.conf' >> tinc-up echo '' >> tinc-up - echo 'name=$(sed -n "s|^ *Name *= *\([^ ]*\) *$|\\1|p" $conf)' >> tinc-up - echo '' >> tinc-up - echo 'host=$dirname/hosts/$name' >> tinc-up + echo 'host=$dirname/hosts/$NAME' >> tinc-up echo '' >> tinc-up echo 'ip link set $INTERFACE up' >> tinc-up echo '' >> tinc-up @@ -222,7 +220,7 @@ EOF echo "ip -4 route add 172.22.0.0/15 dev \$INTERFACE" >> tinc-up echo '' >> tinc-up echo "addr6=\$(sed -n \"s|^ *Subnet *= *\\($SUBNET6[:][^ ]*\\) *\$|\\\\1|p\" \$host)" >> tinc-up - echo 'ip -6 addr add $addr6 dev $INTERFACE' >> tinc-up + echo 'ip -6 addr add $addr6 dev $INTERFACE || exit 0' >> tinc-up echo "ip -6 route add $SUBNET6::/$MASK6 dev \$INTERFACE" >> tinc-up else echo 'dirname="`dirname "$0"`"' > tinc-up diff --git a/retiolum/scripts/tinc_setup/tinc-up b/retiolum/scripts/tinc_setup/tinc-up index 043e1e46..acb81b5d 100755 --- a/retiolum/scripts/tinc_setup/tinc-up +++ b/retiolum/scripts/tinc_setup/tinc-up @@ -4,9 +4,7 @@ dirname="`dirname "$0"`" conf=$dirname/tinc.conf -name=`sed -n 's|^ *Name *= *\([^ ]*\) *$|\1|p' $conf` - -host=$dirname/hosts/$name +host=$dirname/hosts/$NAME ip link set $INTERFACE up @@ -16,5 +14,5 @@ ip -4 route add 10.243.0.0/16 dev $INTERFACE ip -4 route add 172.22.0.0/15 dev $INTERFACE addr6=`sed -n 's|^ *Subnet *= *\(42[:][^ ]*\) *$|\1|p' $host` -ip -6 addr add $addr6 dev $INTERFACE +ip -6 addr add $addr6 dev $INTERFACE || exit 0 ip -6 route add 42::/16 dev $INTERFACE |