summaryrefslogtreecommitdiffstats
path: root/Reaktor/UDP/index
blob: 3e0bbd155b35ee6475e3525fb797105acb559d1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python

import asyncore, socket
import logging,subprocess
import re
import sys
import json
log = logging.getLogger('ubot')

def enable_syslog(logger):
  import logging.handlers as handlers
  from logging import Formatter
  hdlr = handlers.SysLogHandler(
      facility=handlers.SysLogHandler.LOG_DAEMON)
  formatter = Formatter( 
      '%(filename)s: %(levelname)s: %(message)s')
  hdlr.setFormatter(formatter)
  logger.addHandler(hdlr)


class ubot(asyncore.dispatcher):
  """ UDP Bot """
  def __init__(self, port,pattern,action,comment="",bind_addr="",):
    asyncore.dispatcher.__init__(self)
    self.bind_addr = bind_addr
    self.port = port
    self.data = ''
    self.pattern = pattern
    self.action = action
    self.bind_socket()

  def bind_socket(self):
    """
    if the socket is already bound we want to reuse this socket anyway
    """
    self.create_socket(socket.AF_INET,socket.SOCK_DGRAM)
    self.set_reuse_addr()
    self.socket.setsockopt(
        socket.SOL_SOCKET,socket.SO_BROADCAST,1)
    log.info("Binding Socket at %s:%d" 
        %(self.bind_addr,self.port))
    self.bind( (self.bind_addr,self.port) )

  def handle_connect(self):
    log.info("Server Started")

  def handle_read(self):
    self.data,addr = self.recvfrom(2048)
    log.debug('<< %s' % self.data)

    if self.find_pattern():
      self.start_action()

  def find_pattern(self):
    """ returns true if own pattern is found"""
    log.debug("Pattern is %s" %self.pattern)
    ret = re.search(self.pattern,self.data)
    if ret:
      log.info("Match \"%s\" with pattern \"%s\"" % ((ret.string.strip()),self.pattern))
    else:
      log.info("No Match")
    return ret


  def start_action(self):
    """ runs all the defined actions"""
    log.debug("Actions: %s" % str(self.action))
    self.start_process()
    self.start_post()

  def start_process(self):
    try:
      act = self.action["PROCESS"]
      proc = []
      proc.append(act["path"])
      proc.extend(act["argv"])

      env = act["envp"]
      env["payload"] = json.dumps(self.data)
      log.info("Starting Process: %s (env: %s)" % (proc,env))
      subprocess.Popen(proc,env=env)
    except Exception as e:
      log.error(e)
  def start_post(self):
    pass

def load_conf(conf_file):
  return json.load(open(conf_file))


if __name__ == "__main__":
  import os
  #enable_syslog(log)
  HERE = os.path.dirname(os.path.realpath(__file__))
  lol = logging.DEBUG if os.environ.get('debug',False) else logging.INFO
  logging.basicConfig(level=lol)
  for i in load_conf("%s/config" %HERE):
    ubot(**i)
  asyncore.loop()