def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.rfile = SocketIO(socket, "r") self.wfile = SocketIO(socket, "w") socket.settimeout(60)
def connect(self): """Rewrite of KQMLModule connect, only handles send_socket and output connections""" try: self.send_socket = socket() self.send_socket.connect((self.host, self.port)) socket_write = SocketIO(self.send_socket, 'w') self.out = BufferedWriter(socket_write) except OSError as error_msg: LOGGER.error('Connection failed: %s', error_msg) # Verify that you can send messages... assert self.out is not None, \ 'Connection formed but output (%s) not set.' % (self.out)
def listen(self): """Socket server, listens for new KQML messages and dispatches them accordingly. Doesn't necessarily need threading; Could just start dispatcher and after it returns accept next connection. This couldn't handle loads of inputs while being bogged down processing. To avoid this issue we thread the dispatching so the functions that get called are run in a separate Thread. We're using ThreadPoolExecutor because sockets use io, io is blocking and threads allow you to not block. """ with ThreadPoolExecutor(max_workers=5) as executor: while self.ready: connection, _ = self.listen_socket.accept() LOGGER.debug('Received connection: %s', connection) socket_write = SocketIO(connection, 'w') self.local_out = BufferedWriter(socket_write) socket_read = SocketIO(connection, 'r') read_input = KQMLReader(BufferedReader(socket_read)) self.dispatcher = KQMLDispatcher(self, read_input, self.name) LOGGER.debug('Starting dispatcher: %s', self.dispatcher) executor.submit(self.dispatcher.start) self.state = 'dispatching'
def backport_makefile(self, mode="r", buffering=None, encoding=None, errors=None, newline=None): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= set(["r", "w", "b"]): raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode, )) writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._makefile_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text
raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) ======= raise ValueError( "invalid mode %r (only r, w, b allowed)" % (mode,) ) >>>>>>> 71358189c5e72ee2ac9883b408a2f540a7f5745e writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._makefile_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing
def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.input_type = "" self.user_input = "" self.io = SocketIO(self._skt, "rw") self._session = None
class TelnetPlugin(BasePlugin): def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.input_type = "" self.user_input = "" self.io = SocketIO(self._skt, "rw") self._session = None def do_track(self): self.get_session() self.username() self.password() self.options() while self._skt and not self.kill_plugin: self.command() def get_session(self): self._session = str(self.get_uuid4()) def close_descriptors(self): self.io.close() def get_input(self): try: data = self.io.readline(1024).decode() except OSError: self.kill_plugin = True return data = data.strip("\r\n") data = data.strip("\n") return data def username(self): self.io.write(b"Username: "******"username" self.user_input = self.get_input() self.do_save() def password(self): self.io.write(b"Password: "******"password" self.user_input = self.get_input() self.do_save() def command(self): self.input_type = "command" self.io.write(b". ") line = self.get_input() commands = line.split(";") for i in commands: if self.kill_plugin: break self.handle(i) def handle(self, command): if len(command) == 0: return self.input_type = "command" self.user_input = command self.do_save() arguments = command.split(" ", 1) command = arguments.pop(0) if self.is_command(command): if len(arguments) == 0: getattr(self, command)() else: getattr(self, command)(arguments.pop(0)) else: self.io.write(b"%unrecognized command - type options for a list\r\n") def is_command(self, command): if hasattr(self, command): if hasattr(getattr(self, command), "get_command"): return True else: return False else: return False @set_command("basic list of options available to user") def options(self, arguments=None): self.io.write(b"\r\nWelcome, Please choose from the following options\r\n") line_count = 0 for option in dir(self): if self.is_command(option): if line_count == 5: self.io.write(b"\r\n") line_count = 0 tabs = b"" i = 0 try: for i in range(0, ceil((16 - len(option)) / 8)): tabs += b"\t" except ZeroDivisionError: tabs = ":" self.io.write(option.encode() + tabs) line_count += 1 self.io.write(b"\r\n") @set_command("detailed description of options") def help(self, arguments=None): for help in dir(self): if self.is_command(help): tabs = b":" i = 0 try: for i in range(0, ceil((16 - len(help) - 1) / 8)): tabs += b"\t" except ZeroDivisionError: tabs = ":" self.io.write(help.encode() + tabs + getattr(getattr(self, help), "get_description").encode() + b"\r\n") @set_command("prompt to echo back typing") def echo(self, arguments=None): self.input_type = "echo" if arguments: self.user_input = arguments else: self.io.write(b"Text? ") self.user_input = self.get_input() self.do_save() self.io.write(self.user_input.encode() + b"\r\n") @set_command("close telnet connection to server") def quit(self, arguments=None): self.io.write(b"\nGoodbye\n") self.io.close() self.kill_plugin = True
class HTTPPlugin(BasePlugin, BaseHTTPRequestHandler): def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.rfile = SocketIO(socket, "r") self.wfile = SocketIO(socket, "w") socket.settimeout(60) def do_track(self): try: self.handle_one_request() except OSError: self.kill_plugin = True return except AttributeError: self.kill_plugin = True return except UnicodeDecodeError: self.kill_plugin = True return self.format_data() self.do_save() self.kill_plugin = True def get_body(self): too_long = False if not hasattr(self, 'headers'): return else: try: body_length = int(self.headers.get('content-length', 0)) if body_length > 65536: body_length = 65536 too_long = True except TypeError: self.body = '' return try: self.body = self.rfile.read(body_length) self.body = str(self.body, 'utf-8') if too_long: self.body += '*' except timeout: self.body = '' def get_session(self): if not hasattr(self, 'headers'): return try: cookie = self.headers.get('cookie', None) except AttributeError: cookie = self.get_uuid4() self.send_header('Set-Cookie', 'SESSION=' + cookie) return if cookie is None: cookie = self.get_uuid4() else: cookie = cookie.split("SESSION=") if len(cookie) > 1: cookie = cookie[1].split()[0] self.send_header('Set-Cookie', 'SESSION=' + cookie) self._session = cookie def format_data(self): if not hasattr(self, 'command'): self.command = '' if not hasattr(self, 'path'): self.path = '' if not hasattr(self, 'headers'): self.headers = '' else: self.headers = self.headers.as_string() if not hasattr(self, 'body'): self.body = '' def address_string(self): return self._skt.getsockname()[0] def end_headers(self): self.get_session() if self.request_version != 'HTTP/0.9': self._headers_buffer.append(b"\r\n") self.flush_headers() def do_GET(self): if self.path in GOOD_PATHS: self.do_HEAD() self.wfile.write(PAGE_LOGIN) else: self.send_error(404) def do_HEAD(self): if self.path in GOOD_PATHS: self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'close') self.send_header('Content-Length', str(len(PAGE_LOGIN))) self.end_headers() else: content = (self.error_message_format % {'code': 404, 'message': _quote_html('File not found'), 'explain': _quote_html('Nothing matches the given URI')}) body = content.encode('UTF-8', 'replace') self.send_response(404, "File not found") self.send_header("Content-Type", self.error_content_type) self.send_header('Connection', 'close') self.send_header('Content-Length', int(len(body))) self.end_headers() def do_POST(self): self.get_body() if self.path in GOOD_PATHS: self.go_GET() elif self.path == '/login': self.send_error(403) else: self.send_error(404) def do_PUT(self): self.send_error(501) def do_OPTIONS(self): self.send_error(501) def do_DELETE(self): self.send_error(501) def do_TRACE(self): self.send_error(501) def do_CONNECT(self): self.send_error(501)
def makefile(self, *args, **kwargs): return SocketIO(self, *args, **kwargs)
def __init__(self, sock): SocketIO.__init__(self, sock, mode="rb")