Exemple #1
0
 def __recv(self):
     data = self.request.recv(2048)
     logger.logDebug('RECV({}): {}'.format(len(data), repr(data)))
     if len(data) == 0 and self.request.gettimeout() is None:
         raise socket.error(errno.ECONNRESET, os.strerror(errno.ECONNRESET))
     if data[0] == '\x04':
         raise socket.error(errno.ECONNRESET, os.strerror(errno.ECONNRESET))
     self.__buffer += data
     return self.__buffer
Exemple #2
0
    def preprocess(self, script):
        logger.logDebug("preprocess", "Preprocessing: %s" % script)

        index = 0
        values = {}
        objects = {}
        specials = {}

        while True:
            valueref = re_valueref.search(script, index)
            objectref = re_objectref.search(script, index)
            specialref = re_specialref.search(script, index)
            matches = []
            if valueref: matches.append((valueref.start(), valueref))
            if objectref: matches.append((objectref.start(), objectref))
            if specialref: matches.append((specialref.start(), specialref))
            if matches:
                start, match = min(matches)
                if match:
                    index = match.end()
                    id = match.group(1)
                    if match == valueref: values[id] = True
                    elif match == objectref: objects[id] = True
                    elif match == specialref: specials[id] = True
                    continue
            break

        variables = []

        for valueid in values.keys():
            variables.append(("$" + valueid, self.__values.get(int(valueid))))

        for objectid in objects.keys():
            object = ESObject.getByPrintedId(int(objectid))
            if object: value = ESValue(ESValue.TYPE_OBJECT, object)
            else: value = None
            variables.append(("$$" + objectid, value))

        if specials:
            if specials.has_key("n"): variables.append(("$n", ESValue(ESValue.TYPE_NULL)))
            if specials.has_key("u"): variables.append(("$u", ESValue(ESValue.TYPE_UNDEFINED)))
            if specials.has_key("t"): variables.append(("$t", ESValue(ESValue.TYPE_BOOLEAN, True)))
            if specials.has_key("f"): variables.append(("$f", ESValue(ESValue.TYPE_BOOLEAN, False)))
            if specials.has_key("z"): variables.append(("$z", ESValue(ESValue.TYPE_NUMBER, 0)))
            if specials.has_key("e"): variables.append(("$e", ESValue(ESValue.TYPE_STRING, "")))

        variables.sort()

        for name, value in variables:
            logger.logDebug("preprocess", "Variable: %s => %s" % (name, value))

        return variables
Exemple #3
0
    def preprocess(self, script):
        logger.logDebug("preprocess", "Preprocessing: %s" % script)

        index = 0
        values = {}
        objects = {}
        specials = {}

        while True:
            valueref = re_valueref.search(script, index)
            objectref = re_objectref.search(script, index)
            specialref = re_specialref.search(script, index)
            matches = []
            if valueref: matches.append((valueref.start(), valueref))
            if objectref: matches.append((objectref.start(), objectref))
            if specialref: matches.append((specialref.start(), specialref))
            if matches:
                start, match = min(matches)
                if match:
                    index = match.end()
                    id = match.group(1)
                    if match == valueref: values[id] = True
                    elif match == objectref: objects[id] = True
                    elif match == specialref: specials[id] = True
                    continue
            break

        variables = []

        for valueid in values.keys():
            variables.append(("$" + valueid, self.__values.get(int(valueid))))

        for objectid in objects.keys():
            object = ESObject.getByPrintedId(int(objectid))
            if object: value = ESValue(ESValue.TYPE_OBJECT, object)
            else: value = None
            variables.append(("$$" + objectid, value))

        if specials:
            if specials.has_key("n"): variables.append(("$n", ESValue(ESValue.TYPE_NULL)))
            if specials.has_key("u"): variables.append(("$u", ESValue(ESValue.TYPE_UNDEFINED)))
            if specials.has_key("t"): variables.append(("$t", ESValue(ESValue.TYPE_BOOLEAN, True)))
            if specials.has_key("f"): variables.append(("$f", ESValue(ESValue.TYPE_BOOLEAN, False)))
            if specials.has_key("z"): variables.append(("$z", ESValue(ESValue.TYPE_NUMBER, 0)))
            if specials.has_key("e"): variables.append(("$e", ESValue(ESValue.TYPE_STRING, "")))

        variables.sort()

        for name, value in variables:
            logger.logDebug("preprocess", "Variable: %s => %s" % (name, value))

        return variables
Exemple #4
0
 def parseMessage(session, data):
     type = data.parseUnsigned()
     messageType = messageTypes.get(type, GenericMessage)
     logger.logDebug("message", "Parsing message: %r" % messageType)
     message = messageType(session)
     try:
         message.parse(data)
     except Close:
         raise
     except:
         logger.logException()
         logger.logDebug("parsing-failed", data.getMessageText())
     return message
Exemple #5
0
 def parseString(self):
     if self.__data[0] == "s":
         length = int(self.__data[1:5], 16)
         logger.logDebug("parsing",
                         "parseString: " + repr(self.__data[5:5 + length]))
         value = unicode(self.__data[5:5 + length], "utf-8")
         self -= 5 + length
     else:
         length = int(self.__data[1:9], 16)
         logger.logDebug("parsing",
                         "parseString: " + repr(self.__data[9:9 + length]))
         value = unicode(self.__data[9:9 + length], "utf-8")
         self -= 9 + length
     return value
Exemple #6
0
 def __repl(self, data):
     if data is None or len(data) == 0:
         return None
     logger.logDebug('REPL({}): {}'.format(len(data), repr(data)))
     try:
         buffer = io.BytesIO()
         sys.stdout = buffer
         sys.stdin = open(os.devnull, 'r')
         try:
             result = str(eval(data, self.local_vars))
         except SyntaxError:
             exec data in self.local_vars
             result = ''
     except Exception:
         import traceback
         result = traceback.format_exc()
     finally:
         sys.stdin = sys.__stdin__
         sys.stdout = sys.__stdout__
         logger.logDebug('REPL({}): {}'.format(len(result), repr(result)))
         logger.logDebug('REPL({}): {}'.format(len(buffer.getvalue()),
                                               repr(buffer.getvalue())))
         if len(result) == 0:
             if len(buffer.getvalue()) == 0:
                 result = None
             else:
                 result = buffer.getvalue()
         else:
             if len(buffer.getvalue()) > 0:
                 result += '\n' + buffer.getvalue()
     if result is not None:
         logger.logDebug('REPL({}): {}'.format(len(result), repr(result)))
     return result
Exemple #7
0
    def parse(self, data):
        logger.logDebug("parsing", "StoppedAt: " + str(data))

        self.__runtime = self.getSession().getRuntime(data.parseUnsigned())
        self.__thread = self.__runtime.getThread(data.parseUnsigned())

        script = self.getSession().getScript(data.parseUnsigned())
        linenr = data.parseUnsigned()

        self.parseAuxiliary(data)

        logger.logDebug("parsing", "Parsed StoppedAt: %d\n" % linenr)

        self.__position = Position(script, linenr)
        self.__thread.setCurrentPosition(self.__position)
Exemple #8
0
 def __getRequestRemoteSubstate(self, msg):
     result = None
     cmd, opt, subcmd, arg = msg.cmd, msg.opt, msg.subcmd, msg.arg
     state = self.__state['U'].get(opt, None)
     if state == STATE.ACCEPT:
         if opt in requestOptionsSubstate['U']:
             self.__state['U'][opt] = STATE.REQUEST
             result = _Command(TOKEN.SB, opt, TOKEN.SEND)
     elif state == STATE.REQUEST:
         if cmd == TOKEN.SB and subcmd == TOKEN.IS:
             value = arg
             self.__state['U'][opt] = { 'value': value }
             logger.logDebug('TELNET SUB: {} = {}'.format(opt, value))
             if opt in self.__optionHandler:
                 result = self.__optionHandler[opt](value)
     return result
Exemple #9
0
    def parseAuxiliary(self, data):
        logger.logDebug("parsing", str(data))

        while data:
            try:
                type = data.parseUnsigned()
            except:
                logger.logDebug("auxbug", "While parsing: %d" % self.getType())
                logger.logException()
            auxiliaryType = auxiliaryTypes.get(type)
            if not auxiliaryType:
                logger.logWarning(
                    "Unknown auxiliary type: %d (skipping rest of message)" %
                    type)
                while data:
                    data.parseAny()
            else:
                auxiliary = auxiliaryType(self)
                auxiliary.parse(data)
                self.__auxiliary.append(auxiliary)
Exemple #10
0
    def setReadBuffer(self, buffer):
        logger.logDebug("send", "Buffer length (in): %d" % len(buffer))

        while len(buffer) >= 12:
            size = int(buffer[0:8], 16)
            length = int(buffer[8:12], 16)

            if len(buffer) - 12 < size: break

            try: self.parseMessage(size, length, buffer[12:12 + size])
            except Close: raise
            except: logger.logException()

            buffer = buffer[12 + size:]
            logger.logDebug("send", "Buffer length (loop): %d" % len(buffer))

        logger.logDebug("send", "Buffer length (out): %d" % len(buffer))
        self.__rbuffer = buffer
Exemple #11
0
    def parse(self, data):
        self.__runtime = self.getSession().getRuntime(data.parseUnsigned())
        self.__thread = self.__runtime.getThread(data.parseUnsigned())
        self.__thread.setParentThread(
            self.__runtime.getThread(data.parseUnsigned()))
        self.__thread.setType(data.parseUnsigned())

        logger.logDebug("threads", "New thread: %d" % self.__thread.getId())
        if self.__thread.getParentThread():
            logger.logDebug(
                "threads",
                "Parent thread: %d" % self.__thread.getParentThread().getId())
        else:
            logger.logDebug("threads", "No parent thread")

        if self.__thread.getType() == ThreadStartedMessage.TYPE_EVENT:
            self.__thread.setNamespaceURI(data.parseString())
            self.__thread.setEventType(data.parseString())

        self.parseAuxiliary(data)
Exemple #12
0
    def setReadBuffer(self, buffer):
        logger.logDebug("send", "Buffer length (in): %d" % len(buffer))

        while len(buffer) >= 12:
            size = int(buffer[0:8], 16)
            length = int(buffer[8:12], 16)

            if len(buffer) - 12 < size: break

            try:
                self.parseMessage(size, length, buffer[12:12 + size])
            except Close:
                raise
            except:
                logger.logException()

            buffer = buffer[12 + size:]
            logger.logDebug("send", "Buffer length (loop): %d" % len(buffer))

        logger.logDebug("send", "Buffer length (out): %d" % len(buffer))
        self.__rbuffer = buffer
Exemple #13
0
    def control(self, msg):
        request = []
        if msg is None:
            for opt in requestOptions['U']:
                request.append(self.__getRequestRemoteState(None, opt))
                request.append(self.__getRequestLocalState(None, opt))
        else:
            logger.logDebug('TELNET RCVD: {}'.format(msg.info()))
            if self.__commandHandler and msg.cmd in self.__commandHandler:
                self.__commandHandler[msg.cmd]()
            request.append(self.__getRequestRemoteState(msg.cmd, msg.opt))
            request.append(self.__getRequestLocalState(msg.cmd, msg.opt))
            request.append(self.__getRequestRemoteSubstate(msg))
        logger.logDebug('STATE: {}'.format(self.__state))

        result = ''
        for msg in request:
            if msg is None:
                continue
            logger.logDebug('TELNET SENT: {}, {}'.format(msg.info(), repr(msg.code())))
            result += msg.code()
        return result
Exemple #14
0
    def run(self):
        while not self.__closed:
            pollobject = poll()

            if sys.platform != "win32": pollobject.register(self.__rfd, POLLIN)

            self.__lock.acquire()
            for handler in self.__sockets:
                if handler.getSocket() is not None:
                    flags = 0

                    if handler.getReadBuffer() is not None: flags = POLLIN
                    if handler.getWriteBuffer() is not None: flags = POLLOUT

                    pollobject.register(handler.getSocket().fileno(), flags)
            if self.__listenSocket:
                pollobject.register(self.__listenSocket.fileno(), POLLIN)
            self.__lock.release()

            if sys.platform == "win32": timeout = 0.1
            else: timeout = None

            while True:
                try:
                    ready = pollobject.poll(timeout)
                    break
                except error, (code, msg):
                    if code != EINTR: raise

            self.__lock.acquire()
            for fileno, flag in ready:
                if sys.platform != "win32" and fileno == self.__rfd:
                    os.read(self.__rfd, 1024)
                    continue

                if self.__listenSocket and fileno == self.__listenSocket.fileno():
                    logger.logDebug("connections", "New connection.")
                    newSocket, newAddress = self.__listenSocket.accept()
                    newSocket.setblocking(0)
                    newHandler = self.__listener.getSocketHandler(newSocket)
                    if newHandler:
                        self.__add(newHandler)

                for handler in self.__sockets[:]:
                    if handler.getSocket() is not None and handler.getSocket().fileno() == fileno:
                        if flag == POLLIN:
                            try:
                                data = handler.getSocket().recv(16384)
                                if len(data) == 0: self.__close(handler)
                                else:
                                    try:
                                        handler.setReadBuffer(handler.getReadBuffer() + data)
                                    except Close:
                                        self.__close(handler)
                            except:
                                logger.logException()
                                self.__close(handler)
                                break
                        elif flag == POLLOUT:
                            try:
                                buffer = handler.getWriteBuffer()
                                written = handler.getSocket().send(buffer)
                                if written == len(buffer): handler.setWriteBuffer(None)
                                else: handler.setWriteBuffer(buffer[written:])
                            except:
                                logger.logException()
                                self.__close(handler)
                                break
                        else:
                            self.__close(handler)
                            break
            self.__lock.release()
Exemple #15
0
 def __telnetHandlerTerm(self, value):
     logger.logDebug('HANDLER: set TERM={}'.format(value))
     self.__termtype = value
     return None
Exemple #16
0
 def __write(self, data):
     if data is None or len(data) == 0:
         return
     logger.logDebug('SEND({}): {}'.format(len(data), repr(data)))
     self.request.sendall(data)
Exemple #17
0
 def parse(self, data):
     logger.logDebug("generic", "Parsing generic message")
     while data:
         self.__items.append(data.parseAny())
     logger.logDebug("generic", "Parsed %d items" % len(self.__items))
Exemple #18
0
def runReplServer():
    server = SocketServer.TCPServer((HOST, PORT), ReplRequestHandler)
    logger.logDebug('REPL server start')
    server.serve_forever()
Exemple #19
0
 def __telnetHandlerExtend(self, value):
     logger.logDebug('HANDLER: exec msg={}'.format(repr(value)))
     data = self.__repl(value)
     result = self.telnet.getRequestExtendMsg(data)
     self.telnet.setRequireOption(TOKEN.EXTEND_MSG)
     return result
    def run(self):
        while not self.__closed:
            pollobject = poll()

            if sys.platform != "win32": pollobject.register(self.__rfd, POLLIN)

            self.__lock.acquire()
            for handler in self.__sockets:
                if handler.getSocket() is not None:
                    flags = 0

                    if handler.getReadBuffer() is not None: flags = POLLIN
                    if handler.getWriteBuffer() is not None: flags = POLLOUT

                    pollobject.register(handler.getSocket().fileno(), flags)
            if self.__listenSocket:
                pollobject.register(self.__listenSocket.fileno(), POLLIN)
            self.__lock.release()

            if sys.platform == "win32": timeout = 0.1
            else: timeout = None

            while True:
                try:
                    ready = pollobject.poll(timeout)
                    break
                except error, (code, msg):
                    if code != EINTR: raise

            self.__lock.acquire()
            for fileno, flag in ready:
                if sys.platform != "win32" and fileno == self.__rfd:
                    os.read(self.__rfd, 1024)
                    continue

                if self.__listenSocket and fileno == self.__listenSocket.fileno(
                ):
                    logger.logDebug("connections", "New connection.")
                    newSocket, newAddress = self.__listenSocket.accept()
                    newSocket.setblocking(0)
                    newHandler = self.__listener.getSocketHandler(newSocket)
                    if newHandler:
                        self.__add(newHandler)

                for handler in self.__sockets[:]:
                    if handler.getSocket() is not None and handler.getSocket(
                    ).fileno() == fileno:
                        if flag == POLLIN:
                            try:
                                data = handler.getSocket().recv(16384)
                                if len(data) == 0: self.__close(handler)
                                else:
                                    try:
                                        handler.setReadBuffer(
                                            handler.getReadBuffer() + data)
                                    except Close:
                                        self.__close(handler)
                            except:
                                logger.logException()
                                self.__close(handler)
                                break
                        elif flag == POLLOUT:
                            try:
                                buffer = handler.getWriteBuffer()
                                written = handler.getSocket().send(buffer)
                                if written == len(buffer):
                                    handler.setWriteBuffer(None)
                                else:
                                    handler.setWriteBuffer(buffer[written:])
                            except:
                                logger.logException()
                                self.__close(handler)
                                break
                        else:
                            self.__close(handler)
                            break
            self.__lock.release()