Esempio n. 1
0
    def do_prepare_connection(self):
        DBG("do_prepare_connection")
        try:
            if self.button_connect.GetLabelText() == "connect":
                query = {
                    "name": self.name,
                    "type": self.conn_type,
                    "op": "connect",
                    "remote_ip": self.remote_ip.GetValue(),
                    "remote_port": int(self.remote_port.GetValue()),
                    "random_port": self.radio_random_port.GetValue(),
                    "specific_port": int(self.specific_port.GetValue())
                }
            else:
                query = {
                    "name": self.name,
                    "type": self.conn_type,
                    "op": "disconnect"
                }

            re = self.command_sender.sendto(json.dumps(query),
                                            self.command_server_address)
            DBG('sent %d' % re)
            data = self.command_sender.recv(4096)
            DBG("do_prepare_connection get reply - %r" % data)
            data = json.loads(data)
            return data
        except:
            DBG_TRACE()
            return {'result': 'error'}
Esempio n. 2
0
    def make_preview(self):
        try:
            method = self.encoding_choices[
                self.choice_send_encoding.GetCurrentSelection()]
            DBG(method)
            preview = ''
            bytes_after_encoding = bytearray()
            DBG(type(self.input_send.GetValue()))
            if method == 'bytes-10':
                for string in self.input_send.GetValue().strip().split():
                    bytes_after_encoding += bytearray([int(string, 10)])
            elif method == 'bytes-16':
                for string in self.input_send.GetValue().strip().split():
                    bytes_after_encoding += bytearray([int(string, 16)])
            else:
                bytes_after_encoding = bytearray(
                    self.input_send.GetValue().encode(method))

            for b in bytes_after_encoding:
                preview += str.format('0x%02X ' % b)
            DBG(preview)
            self.send_bytes = bytes_after_encoding
            self.input_send_preview.SetValue(preview)
            self.text_encoding_result.SetLabelText('ok')
        except:
            self.input_send_preview.SetValue('')
            self.text_encoding_result.SetLabelText('error')
            DBG_TRACE()
Esempio n. 3
0
    def make_new_tcp_server(self, data, reply_address):
        DBG("NetoolCommandServer make_new_tcp_server %r" % data)
        try:
            g = Greenlet(start_tcp_server, data)
            g.start()

            result = AsyncResult()
            conn_greenlets[data['name']] = {
                'greenlet': g,
                'result': result,
                'data': None
            }
            re = result.get()
            value = re['result']
            if value != 'ok':
                del (conn_greenlets[data['name']])
            re = self.socket.sendto(json.dumps(re), reply_address)
            DBG("sent %d" % re)
        except:
            DBG_TRACE()
            self.socket.sendto(
                json.dumps({
                    'result': 'error',
                    'msg': base64.b64encode(sys.exc_info()[1])
                }), reply_address)
Esempio n. 4
0
def start_tcp_server(conn_data):
    DBG("start_tcp_server")
    server = None
    try:
        conn_greenlets[conn_data['name']]['result'].set({'result': 'ok'
                                                         })  # new server ok
        server = NetoolTcpServer(conn_data,
                                 (LOCAL_IP, conn_data['specific_port']),
                                 tcp_handler)
        server.serve_forever()
    except StopServer:
        DBG("StopServer")
        server.stop()
        conn_greenlets[conn_data['name']]['result'].set({'result': 'ok'
                                                         })  # new server ok
        return
    except:
        DBG_TRACE()
        data_pack = {
            'name': conn_data['name'],
            'type': conn_data['type'],
            'op': 'error',
            'msg': base64.b64encode(str(sys.exc_info()[1]))
        }
        server.stop()
        del conn_greenlets[conn_data['name']]
        guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS)
Esempio n. 5
0
 def do_read(self):
     DBG("xcc NetoolTcpServer.do_read()")
     try:
         client_socket, address = self.socket.accept()
     except _socket.error, err:
         if err[0] == socket.EWOULDBLOCK:
             DBG("NetoolTcpServer do_read() EWOULDBLOCK return")
             return
         raise
Esempio n. 6
0
    def close_app(self, event):
        DBG("close_app")
        DBG(event)

        self.save_status()

        all_done = True

        # close all connections
        node = self.nodes['connection']
        node = self.connection_tree.GetFirstChild(node)[0]
        while node.IsOk():
            name = self.connection_tree.GetItemText(node)
            node = self.connection_tree.GetNextSibling(node)
            if not self.close_node(name):
                all_done = False

        # close all servers
        node = self.nodes['server']
        node = self.connection_tree.GetFirstChild(node)[0]
        while node.IsOk():
            name = self.connection_tree.GetItemText(node)
            node = self.connection_tree.GetNextSibling(node)
            if not self.close_node(name):
                all_done = False

        # close command server
        try:
            query = {"name": 'netool', "type": 'netool', "op": "closeapp"}
            re = self.command_sender.sendto(json.dumps(query),
                                            self.command_server_address)
            DBG('sent %d' % re)
            data = self.command_sender.recv(4096)
            DBG("reply - %r" % data)
            data = json.loads(data)
            if data['result'] != 'ok':
                self.alert(base64.b64decode(data['msg']))
                all_done = False
        except:
            DBG_TRACE()
            self.alert(str(sys.exc_info()[1]))
            all_done = False

        if not all_done:
            DBG('not all_done')
            if wx.MessageDialog(
                    None,
                    'Some connections are not shut down properly, still quit?',
                    'warning',
                    wx.YES_NO | wx.ICON_QUESTION).ShowModal() == wx.ID_YES:
                pass
            else:
                return
        event.Skip()
Esempio n. 7
0
 def prepare_connection(self):
     DBG("prepare_connection")
     result = None
     if self.accepted_name:
         result = self.do_prepare_connection()
     if result['result'] == 'ok':
         wx.CallAfter(self.mainframe.delete_accepted_page,
                      self.accepted_name)
     else:
         self.alert(base64.b64decode(result['error']))
     DBG("prepare_connection result = %r" % result)
     event.Skip()
Esempio n. 8
0
    def handle(self, data, address):
        DBG('NetoolGUIFeeder %s %s: got %r' % (time.ctime(), address[0], data))

        try:
            data = json.loads(data)
            if data['op'] == 'closeapp':
                DBG("GUIFeeder stop")
                self.stop()
                return
            wx.CallAfter(self.window.eat, data)
        except:
            DBG_TRACE()
Esempio n. 9
0
    def new_server(self, event):
        DBG("new_server")
        try:
            dlg = NetoolNewServerDialog()
            name = ''
            conn_type = ''
            while True:
                if dlg.ShowModal() != wx.ID_OK:
                    dlg.Destroy()
                    return
                name = dlg.name.GetValue()
                if name in self.nodes or name == 'server' or name == 'connection' or name == 'root':
                    self.alert("this name already exist")
                else:
                    break

            if dlg.radio_tcp.GetValue():
                conn_type = 'tcpserver'
            else:
                conn_type = 'udpserver'
            query = {
                "name": name,
                "type": conn_type,
                "op": "start",
                "specific_port": int(dlg.specific_port.GetValue())
            }

            re = self.command_sender.sendto(json.dumps(query),
                                            self.command_server_address)
            DBG('sent %d' % re)
            data = self.command_sender.recv(4096)
            DBG("reply - %r" % data)
            data = json.loads(data)
            if data['result'] != 'ok':
                self.alert(base64.b64decode(result['error']))
            else:
                node = self.connection_tree.AppendItem(self.server_node,
                                                       dlg.name.GetValue())
                self.nodes[dlg.name.GetValue()] = node
                self.servers[dlg.name.GetValue()] = {
                    'name': name,
                    'type': conn_type,
                    'specific_port': int(dlg.specific_port.GetValue())
                }
                self.connection_tree.ExpandAll()
            dlg.Destroy()
        except:
            DBG_TRACE()
            self.alert(str(sys.exc_info()[1]))
        event.Skip()
Esempio n. 10
0
 def on_node_changed(self, event):
     DBG('on_node_changed')
     try:
         name = self.connection_tree.GetItemText(
             self.connection_tree.GetSelection())
         if name == 'server' or name == 'connection':
             pass
         else:
             DBG(name)
             for i in range(0, self.connection_notebook.GetPageCount()):
                 if self.connection_notebook.GetPageText(i) == name:
                     self.connection_notebook.SetSelection(i)
     except:
         DBG_TRACE()
     event.Skip()
Esempio n. 11
0
def start_command_server():
    DBG("start_command_server")
    from netool_conn import NetoolCommandServer
    try:
        NetoolCommandServer(':62223').serve_forever()
    except:
        DBG_TRACE()
Esempio n. 12
0
 def on_popup_stash_take(self, event):
     row = self.list_stash.GetSelectedRow()
     if row == -1:
         return
     DBG(self.list_stash.GetColumns()[0])
     self.connection_notebook.GetCurrentPage().input_send.SetValue(
         self.list_stash.GetTextValue(row, 1))
     event.Skip()
Esempio n. 13
0
def start_feeder():
    DBG("start_feeder")
    from netool_conn import NetoolGUIFeeder
    # DBG("start_feeder %d" % threading._get_ident())
    try:
        NetoolGUIFeeder(FRAME, ":62222").serve_forever()
    except:
        DBG_TRACE()
Esempio n. 14
0
    def handle(self, data, address):
        DBG('NetoolCommandServer %s %s:%d got %r' %
            (time.ctime(), address[0], address[1], data))
        DBG('len = %d' % len(data))

        try:
            data = json.loads(data)

            op = data['op']

            if op == 'closeapp':
                self.socket.sendto(json.dumps({'op': 'closeapp'}),
                                   GUIFEEDER_ADDRESS)
                self.socket.sendto(json.dumps({'result': 'ok'}), address)
                DBG("NetoolCommandServer stop")
                self.stop()
            elif op == 'disconnect':
                if data['type'] == 'tcpaccepted':
                    self.disconnect_accepted(data, address)
                else:
                    self.disconnect_connection(data, address)
            elif op == 'senddata':
                self.send_data(data, address)
            elif op == 'connect':
                if data['type'] == 'udpconn' or data['type'] == 'tcpconn':
                    self.make_new_connection(data, address)
            elif op == 'start':
                if data['type'] == 'tcpserver':
                    self.make_new_tcp_server(data, address)
            elif op == 'stop':
                if data['type'] == 'tcpserver':
                    self.stop_tcp_server(data, address)
            else:
                self.socket.sendto(
                    json.dumps({
                        'result': 'error',
                        'msg': 'unknown command'
                    }), address)
        except:
            DBG_TRACE()
            self.socket.sendto(
                json.dumps({
                    'result': 'error',
                    'msg': base64.b64encode(sys.exc_info()[1])
                }), address)
Esempio n. 15
0
 def on_page_changed(self, event):
     DBG('on_page_changed')
     try:
         name = self.connection_notebook.GetPageText(
             self.connection_notebook.GetSelection())
         self.connection_tree.SelectItem(self.nodes[name])
     except:
         DBG_TRACE()
     event.Skip()
Esempio n. 16
0
    def send_data(self, data, reply_address):
        DBG("NetoolCommandServer disconnect_connection %r" % data)
        try:
            conn_greenlets[data['name']]['greenlet'].kill(exception=SendData,
                                                          block=False)

            result = AsyncResult()
            conn_greenlets[data['name']]['result'] = result
            conn_greenlets[data['name']]['data'] = data['data']
            value = result.get()
            re = self.socket.sendto(value, reply_address)
            DBG("sent %d" % re)
        except:
            DBG_TRACE()
            self.socket.sendto(
                json.dumps({
                    'result': 'error',
                    'msg': base64.b64encode(sys.exc_info()[1])
                }), reply_address)
Esempio n. 17
0
    def prepare_connection(self):
        DBG("prepare_connection")
        result = None
        if self.radio_udp.GetValue():
            self.conn_type = 'udpconn'
            result = self.do_prepare_connection()
        elif self.radio_tcp.GetValue():
            self.conn_type = 'tcpconn'
            result = self.do_prepare_connection()
        elif self.radio_http.GetValue():
            self.conn_type = 'httpconn'
            result = self.do_prepare_connection()
        if result['result'] == 'ok':
            if self.button_connect.GetLabelText() == "connect":
                self.radio_udp.Disable()
                self.radio_tcp.Disable()
                self.radio_http.Disable()
                self.remote_ip.Disable()
                self.remote_port.Disable()
                self.radio_random_port.Disable()
                self.radio_specific_port.Disable()
                self.specific_port.Disable()
                self.button_send.Enable()
                self.button_connect.SetLabelText("close")

                self.specific_port.SetValue(str(result['port']))
                self.connected = True
            else:
                self.radio_udp.Enable()
                self.radio_tcp.Enable()
                self.radio_http.Enable()
                self.remote_ip.Enable()
                self.remote_port.Enable()
                self.radio_random_port.Enable()
                self.radio_specific_port.Enable()
                self.specific_port.Enable()
                self.button_send.Disable()
                self.button_connect.SetLabelText("connect")
                self.connected = False
        else:
            self.alert(base64.b64decode(result['error']))
        DBG("prepare_connection result = %r" % result)
Esempio n. 18
0
 def make_recv_bytes_content(self):
     DBG('make_recv_bytes_content len = %d' % len(self.recv_bytes))
     try:
         content = ''
         for b in self.recv_bytes:
             content += str.format('0x%02X ' % b)
         self.input_recv_bytes.SetValue(content)
         self.input_recv_bytes.ShowPosition(
             self.input_recv_bytes.GetLastPosition())
     except:
         DBG_TRACE()
Esempio n. 19
0
    def stop_tcp_server(self, data, reply_address):
        DBG("NetoolCommandServer stop_tcp_server %r" % data)
        try:
            conn_greenlets[data['name']]['greenlet'].kill(exception=StopServer,
                                                          block=False)

            result = AsyncResult()
            conn_greenlets[data['name']]['result'] = result
            re = result.get()
            value = re['result']
            if value != 'ok':
                del (conn_greenlets[data['name']])
            re = self.socket.sendto(json.dumps(re), reply_address)
            DBG("sent %d" % re)
        except:
            DBG_TRACE()
            self.socket.sendto(
                json.dumps({
                    'result': 'error',
                    'msg': base64.b64encode(sys.exc_info()[1])
                }), reply_address)
Esempio n. 20
0
    def do_prepare_connection(self):
        DBG("AcceptedPage do_prepare_connection")
        try:
            data = None
            query = {
                "name": self.name,
                'accepted_name': self.accepted_name,
                "type": self.conn_type,
                "op": "disconnect"
            }

            re = self.command_sender.sendto(json.dumps(query),
                                            self.command_server_address)
            DBG('sent %d' % re)
            data = self.command_sender.recv(4096)
            DBG("reply - %r" % data)
            data = json.loads(data)
            return data
        except:
            DBG_TRACE()
            return {'result': 'error'}
Esempio n. 21
0
 def on_page_close(self, event):  # close from otherwhere
     DBG(event.GetSelection())
     name = self.connection_notebook.GetPageText(event.GetSelection())
     result = self.pages[name].on_close()
     self.connection_tree.Delete(self.nodes[name])
     del self.nodes[name]
     del self.pages[name]
     if result['result'] == 'ok':
         pass
     else:
         self.alert(base64.b64decode(result['error']))
     event.Skip()
Esempio n. 22
0
 def __init__(self,
              parent=None,
              mainframe=None,
              name="unknown",
              conn_type='unknown',
              command_sender=None,
              command_server_address=COMMAND_SERVER_ADDRESS,
              accepted_name='accepted_name'):
     ConnectionPage.__init__(self, parent, mainframe, name, conn_type,
                             command_sender, command_server_address)
     self.accepted_name = accepted_name
     self.connected = True
     DBG(self.command_sender)
Esempio n. 23
0
    def on_item_right_click(self, event):
        DBG(event.GetId())
        self.connection_tree.SelectItem(event.GetItem())

        name = self.connection_tree.GetItemText(event.GetItem())

        for i in range(0, self.connection_notebook.GetPageCount()):
            if self.connection_notebook.GetPageText(i) == name:
                self.connection_notebook.SetSelection(i)

        self.connection_tree.SetFocus()

        self.PopupMenu(self.node_menu)
        event.Skip()
Esempio n. 24
0
    def disconnect_accepted(self, data, reply_address):
        DBG("NetoolCommandServer disconnect_accepted %r" % data)
        try:
            if not data['accepted_name'] in conn_greenlets:  # already closed
                self.socket.sendto(json.dumps({'result': 'ok'}), reply_address)
                return
            conn_greenlets[data['accepted_name']]['greenlet'].kill(
                exception=CloseSocket, block=False)

            result = AsyncResult()
            conn_greenlets[data['accepted_name']]['result'] = result
            value = result.get()
            conn_greenlets[data['accepted_name']]['greenlet'].join()
            del conn_greenlets[data['accepted_name']]
            re = self.socket.sendto(json.dumps(value), reply_address)
            DBG("sent %d" % re)
        except:
            DBG_TRACE()
            self.socket.sendto(
                json.dumps({
                    'result': 'error',
                    'msg': base64.b64encode(sys.exc_info()[1])
                }), reply_address)
Esempio n. 25
0
 def send_data(self, event):  # send button clicked
     DBG("send_data")
     if self.text_encoding_result.GetLabelText() != 'ok':
         self.alert('encoding error')
         return
     try:
         query = {
             "name": self.name,
             "op": "senddata",
             'data': base64.b64encode(self.send_bytes)
         }
         re = self.command_sender.sendto(json.dumps(query),
                                         self.command_server_address)
         DBG('sent %d' % re)
         data = self.command_sender.recv(4096)
         DBG("reply - %r" % data)
         if data == "ok":
             pass
         else:
             self.alert(data)
     except:
         DBG_TRACE()
         self.alert(str(sys.exc_info()[1]))
     event.Skip()
Esempio n. 26
0
class NetoolTcpServer(StreamServer):
    def __init__(self, conn_data=None, *args, **kwargs):
        StreamServer.__init__(self, *args, **kwargs)
        DBG("xcc NetoolTcpServer")
        self.conn_data = conn_data
        self.accept_count = 0

    def do_read(self):
        DBG("xcc NetoolTcpServer.do_read()")
        try:
            client_socket, address = self.socket.accept()
        except _socket.error, err:
            if err[0] == socket.EWOULDBLOCK:
                DBG("NetoolTcpServer do_read() EWOULDBLOCK return")
                return
            raise
        DBG("NetoolTcpServer do_read() return")
        self.accept_count += 1
        return socket.socket(
            _sock=client_socket), address, self.conn_data, self.accept_count
Esempio n. 27
0
    def make_recv_content(self):
        try:
            method = self.encoding_choices[
                self.choice_recv_encoding.GetCurrentSelection()]
            DBG(method)
            content = ''
            if method == 'bytes-10':
                for b in self.recv_bytes:
                    content += str.format('%d ' % b)
            elif method == 'bytes-16':
                for b in self.recv_bytes:
                    content += str.format('%02X ' % b)
            else:
                content = self.recv_bytes.decode(method)

            self.input_recv.SetValue(content)
            self.input_recv.ShowPosition(self.input_recv.GetLastPosition())
        except:
            self.input_recv.SetValue(
                "help! help! help! Can't decode! Change the method!")
            DBG_TRACE()
Esempio n. 28
0
    def new_connection(self, event):
        DBG("new_connection")
        try:
            default_name = "conn at %02d:%02d:%02d" % (
                time.localtime().tm_hour, time.localtime().tm_min,
                time.localtime().tm_sec)
            dlg = wx.TextEntryDialog(self,
                                     "name",
                                     "New connection",
                                     default_name,
                                     pos=wx.DefaultPosition)
            name = None
            while True:
                if dlg.ShowModal() != wx.ID_OK:
                    return
                name = dlg.GetValue()
                if name in self.pages or name == 'server' or name == 'connection' or name == 'root':
                    self.alert("this name already exist")
                else:
                    break
            dlg.Destroy()

            node = self.connection_tree.AppendItem(self.connection_node, name)
            self.nodes[name] = node

            page = ConnectionPage(self.connection_notebook,
                                  self,
                                  name,
                                  command_sender=self.command_sender)
            self.connection_notebook.AddPage(page, name)
            index = self.connection_notebook.GetPageCount(
            ) - 1  # get the index of the final page.
            self.connection_notebook.SetSelection(index)
            self.pages[name] = page

            self.connection_tree.ExpandAll()
        except:
            DBG_TRACE()
        event.Skip()
Esempio n. 29
0
    def eat(self, data):
        DBG('eat')
        try:
            op = data['op']
            name = data['name']
            if op == 'recvdata':
                self.pages[data['name']].get_bytes(
                    base64.b64decode(data['text']))
            elif op == 'disconnected':

                page = self.pages[name]
                if page.on_disconnect():
                    DBG('close page')
                    for i in range(0, self.connection_notebook.GetPageCount()):
                        if name == self.connection_notebook.GetPageText(i):
                            self.connection_notebook.DeletePage(i)
                    self.connection_tree.Delete(self.nodes[name])

                    del self.nodes[name]
                    del self.pages[name]
                else:
                    DBG('don\'t close page')
            elif op == 'error':
                if data['type'] == 'tcpserver':
                    self.connection_tree.Delete(self.nodes[name])
                    del self.nodes[name]
                else:
                    page = self.pages[name]
                    if page.on_disconnect():
                        for i in range(
                                0, self.connection_notebook.GetPageCount()):
                            if name == self.connection_notebook.GetPageText(i):
                                self.connection_notebook.DeletePage(i)
                        self.connection_tree.Delete(self.nodes[name])

                        del self.nodes[name]
                        del self.pages[name]
                self.alert(base64.b64decode(data['msg']))
            elif op == 'accepted':
                server_node = self.nodes[name]
                node = self.connection_tree.AppendItem(server_node,
                                                       data['accepted_name'])
                self.nodes[data['accepted_name']] = node
                page = AcceptedPage(
                    parent=self.connection_notebook,
                    mainframe=self,
                    name=name,
                    conn_type='tcpaccepted',
                    command_sender=self.command_sender,
                    command_server_address=COMMAND_SERVER_ADDRESS,
                    accepted_name=data['accepted_name'])
                self.connection_notebook.AddPage(page, data['accepted_name'])
                index = self.connection_notebook.GetPageCount(
                ) - 1  # get the index of the final page.
                self.connection_notebook.SetSelection(index)
                self.pages[data['accepted_name']] = page

                page.make_accepted_page(data)

                self.connection_tree.ExpandAll()
        except:
            DBG_TRACE()
Esempio n. 30
0
def start_feeder():
    DBG("start_feeder")
    from netool_conn import NetoolGUIFeeder
    # DBG("start_feeder %d" % threading._get_ident())
    try:
        NetoolGUIFeeder(FRAME, ":62222").serve_forever()
    except:
        DBG_TRACE()


if __name__ == '__main__':
    command_process = None
    feeder = None
    try:
        DBG("~~~~~~~~~~~~~~~~ netool main ~~~~~~~~~~~~~~~")
        freeze_support()
        command_process = Process(target=start_command_server)
        command_process.start()

        APP = wx.App()
        FRAME = NetoolMainFrame()

        feeder = threading.Thread(target=start_feeder)
        feeder.start()

        FRAME.load_status()
        FRAME.Show()

        APP.MainLoop()
        DBG("~~~~~~~~~~~~~~~~~~ die 1 ~~~~~~~~~~~~~~~~~~~")