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()
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'}
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)
def start_command_server(): DBG("start_command_server") from netool_conn import NetoolCommandServer try: NetoolCommandServer(':62223').serve_forever() except: DBG_TRACE()
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)
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()
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()
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()
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()
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()
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()
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()
def __init__(self, command_server_address=COMMAND_SERVER_ADDRESS): MainFrame.__init__(self, None) self.pages = {} self.nodes = {} self.servers = {} self.command_server_address = command_server_address root = self.connection_tree.AddRoot("root") self.connection_node = self.connection_tree.AppendItem( root, 'connection') self.server_node = self.connection_tree.AppendItem(root, 'server') self.nodes['connection'] = self.connection_node self.nodes['server'] = self.server_node self.connection_tree.ExpandAll() try: self.command_sender = socket.socket(type=socket.SOCK_DGRAM) except: DBG_TRACE() self.alert("NetoolMainFrame __init__ error") self.node_menu = wx.Menu() menu_item = wx.MenuItem(self.node_menu, wx.ID_DELETE_NODE, 'Close') self.node_menu.AppendItem(menu_item) self.Bind(wx.EVT_MENU, self.on_popup_close_node, menu_item) self.stash_menu = wx.Menu() menu_item = wx.MenuItem(self.stash_menu, wx.ID_STASH_ADD, 'Add') self.stash_menu.AppendItem(menu_item) self.Bind(wx.EVT_MENU, self.on_popup_stash_add, menu_item) menu_item = wx.MenuItem(self.stash_menu, wx.ID_STASH_MODIFY, 'Modify') self.stash_menu.AppendItem(menu_item) self.Bind(wx.EVT_MENU, self.on_popup_stash_modify, menu_item) menu_item = wx.MenuItem(self.stash_menu, wx.ID_STASH_DELETE, 'Delete') self.stash_menu.AppendItem(menu_item) self.Bind(wx.EVT_MENU, self.on_popup_stash_delete, menu_item) menu_item = wx.MenuItem(self.stash_menu, wx.ID_STASH_TAKE, 'Take') self.stash_menu.AppendItem(menu_item) self.Bind(wx.EVT_MENU, self.on_popup_stash_take, menu_item) self.list_stash.AppendTextColumn('Name', width=80) self.list_stash.AppendTextColumn('Data', width=150)
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)
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)
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)
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()
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'}
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()
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)
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()
def close_node( self, name ): # close a initiative connection or an accepted connection or a server(with its all accepted connections) DBG('close_node %s' % name) if name == 'root' or name == 'connection' or name == 'server': return False try: if name in self.pages: #a connection page = self.pages[name] result = page.on_close() if result['result'] == 'ok': for i in range(0, self.connection_notebook.GetPageCount()): if name == self.connection_notebook.GetPageText(i): self.connection_notebook.DeletePage(i) del self.pages[name] self.connection_tree.Delete(self.nodes[name]) del self.nodes[name] return True else: return False else: #a server node = self.nodes[name] DBG('close children') accepted_node = self.connection_tree.GetFirstChild(node)[0] DBG(accepted_node) while accepted_node.IsOk(): accepted_name = self.connection_tree.GetItemText( accepted_node) accepted_node = self.connection_tree.GetNextSibling( accepted_node) if not self.close_node(accepted_name): return False query = { "name": name, "type": self.servers[name]['type'], "op": "stop" } 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['error'])) return False else: self.connection_tree.Delete(self.nodes[name]) del self.nodes[name] del self.servers[name] return True except: DBG_TRACE() return False
def save_status(self): file = None config = None try: file = open('netool.config', 'r+') config = file.read() except IOError: try: file = open('netool.config', 'w') config = { 'stash': [], 'config': { 'udp_recv_buffer_len': 65535 }, 'connections': [], 'servers': [] } except: DBG_TRACE() except: DBG_TRACE() try: config = json.loads(config) except: config = { 'stash': [], 'config': { 'udp_recv_buffer_len': 65535 }, 'connections': [], 'servers': [] } # save connections connections = [] node = self.nodes['connection'] node = self.connection_tree.GetFirstChild(node)[0] while node.IsOk(): name = self.connection_tree.GetItemText(node) page = self.pages[name] conn_type = 'udpconn' if page.radio_tcp.GetValue(): conn_type = 'tcpconn' connections.append({ "name": page.name, "type": conn_type, "remote_ip": page.remote_ip.GetValue(), "remote_port": int(page.remote_port.GetValue()), "random_port": page.radio_random_port.GetValue(), "specific_port": int(page.specific_port.GetValue()) }) node = self.connection_tree.GetNextSibling(node) # save servers servers = [] node = self.nodes['server'] node = self.connection_tree.GetFirstChild(node)[0] while node.IsOk(): name = self.connection_tree.GetItemText(node) server = self.servers[name] servers.append({ "name": server['name'], "type": server['type'], "specific_port": server['specific_port'] }) node = self.connection_tree.GetNextSibling(node) config['connections'] = connections config['servers'] = servers # save stash stash = [] for i in xrange(0, self.list_stash.GetStore().GetCount()): stash.append({ 'name': self.list_stash.GetTextValue(i, 0), 'data': self.list_stash.GetTextValue(i, 1) }) config['stash'] = stash try: DBG(json.dumps(config)) file.truncate(0) file.seek(0, 0) file.write(json.dumps(config)) file.close() return True except: DBG_TRACE() return False
def load_status(self): DBG("load_status") file = None data = None try: file = open('netool.config', 'r+') data = file.read() data = json.loads(data) except IOError: DBG_TRACE() file = open('netool.config', 'w') file.write(json.dumps(DEFAULT_CONFIG)) file.close() data = DEFAULT_CONFIG self.alert('Wrong config file, using default!') except: DBG_TRACE() file.truncate(0) file.seek(0, 0) file.write(json.dumps(DEFAULT_CONFIG)) file.close() data = DEFAULT_CONFIG self.alert('Wrong config file, using default!') DBG(data) try: for conn in data['connections']: name = conn['name'] 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) page.remote_ip.SetValue(conn['remote_ip']) page.remote_port.SetValue(str(conn['remote_port'])) if conn['type'] == 'udpconn': page.radio_udp.SetValue(True) else: page.radio_tcp.SetValue(True) if conn['random_port']: page.radio_random_port.SetValue(True) else: page.radio_specific_port.SetValue(True) page.specific_port.SetValue(str(conn['specific_port'])) 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() for item in data['stash']: self.list_stash.AppendItem((item['name'], item['data'])) except: DBG_TRACE()
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 ~~~~~~~~~~~~~~~~~~~") command_process.join() feeder.join() DBG("~~~~~~~~~~~~~~~~~~ die 2 ~~~~~~~~~~~~~~~~~~~") except: if command_process: command_process.join() if feeder: feeder.join() DBG_TRACE()
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()
def tcp_handler(socket, address, conn_data, accept_count): need_to_close = False need_to_send_data = False accepted_name = conn_data['name'] + '-%d' % accept_count conn_greenlets[accepted_name] = { 'greenlet': Greenlet.getcurrent(), 'result': None, 'data': None } DBG('new tcp accepted from %s:%s conn_data = %r' % (address[0], address[1], conn_data)) data_pack = dict(name=conn_data['name'], accepted_name=accepted_name, op="accepted", remote_ip=address[0], remote_port=address[1], local_port=conn_data['specific_port'], type='tcpserver') re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) while True: try: if need_to_close: DBG('tcp_handler need_to_close') socket.close() conn_greenlets[accepted_name]['result'].set({'result': 'ok'}) return if need_to_send_data: try: re = socket.send( base64.b64decode( conn_greenlets[accepted_name]['data'])) conn_greenlets[accepted_name]['result'].set('ok') DBG("sent to remote %r" % re) need_to_send_data = False except: DBG_TRACE() conn_greenlets[accepted_name]['result'].set('error') data = socket.recv(8012) if not data: # closed by remote DBG('tcp_handler got nothing') socket.close() data_pack = {"name": accepted_name, "op": "disconnected"} re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) del conn_greenlets[accepted_name] DBG("sent to gui feeder %r" % re) return # die else: DBG(type(data)) DBG('tcp_handler %s got %r' % (time.ctime(), bytearray(data))) data_pack = { "name": accepted_name, "op": "recvdata", "text": base64.b64encode(bytearray(data)) } # socket.send('hi') re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) except CloseSocket: DBG("tcp_handler CloseSocket") need_to_close = True except SendData: DBG("tcp_handler SendData") need_to_send_data = True except: DBG_TRACE() data_pack = { "name": conn_data['name'], 'type': conn_data['type'], "op": "error", 'msg': base64.b64encode(str(sys.exc_info()[1])) } socket.close() del conn_greenlets[conn_data['name']] re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) return
def run_connection(conn_data): DBG('run_connection %r' % conn_data) need_to_close = False need_to_send_data = False conn_socket = None try: if conn_data['type'] == 'udpconn': conn_socket = socket.socket(type=socket.SOCK_DGRAM) elif conn_data['type'] == 'tcpconn': conn_socket = socket.socket(type=socket.SOCK_STREAM) if not conn_data['random_port']: conn_socket.bind(("192.168.0.100", conn_data['specific_port'])) conn_socket.connect( (conn_data['remote_ip'], int(conn_data['remote_port']))) conn_greenlets[conn_data['name']]['result'].set({ 'result': 'ok', 'port': conn_socket.getsockname()[1] }) # new connection ok except: DBG_TRACE() conn_greenlets[conn_data['name']]['result'].set({ 'result': 'error', 'error': base64.b64encode(str(sys.exc_info()[1])) }) # new connection failed return while True: if need_to_close: DBG('run_connection need_to_close') conn_socket.close() conn_greenlets[conn_data['name']]['result'].set({'result': 'ok'}) return if need_to_send_data: try: conn_socket.sendall( base64.b64decode( conn_greenlets[conn_data['name']]['data'])) conn_greenlets[conn_data['name']]['result'].set('ok') need_to_send_data = False except: DBG_TRACE() conn_greenlets[conn_data['name']]['result'].set('error') try: data = conn_socket.recv(4096) if not data: # closed by remote DBG('run_connection got nothing') conn_socket.close() data_pack = {"name": conn_data['name'], "op": "disconnected"} re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) return # die else: DBG(type(data)) DBG('run_connection %s got %r' % (time.ctime(), bytearray(data))) data_pack = { "name": conn_data['name'], "op": "recvdata", "text": base64.b64encode(bytearray(data)) } re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) except CloseSocket: DBG("run_connection CloseSocket") need_to_close = True except SendData: DBG("run_connection SendData") need_to_send_data = True except: DBG_TRACE() data_pack = { "name": conn_data['name'], 'type': conn_data['type'], "op": "error", 'msg': base64.b64encode(str(sys.exc_info()[1])) } conn_socket.close() del conn_greenlets[conn_data['name']] re = guifeeder_socket.sendto(json.dumps(data_pack), GUIFEEDER_ADDRESS) DBG("sent to gui feeder %r" % re) return '''