def launch_client(clients_threads, client_id, client_data, routers_data, routers_threads): arp_table_mac = data.client_arp_table_generator(client_data["gateway_ip"], routers_data) default_gateway = client_data["gateway_ip"] # find the id of the router to which the server will connect for router, router_data in routers_data.items(): if (router_data["client_side"]["ip_address"] == default_gateway): router_id = router break router_thread = routers_threads[router_id] init_params = { "clients_threads": clients_threads, "arp_table_mac": arp_table_mac, "client_data": client_data, "client_id": client_id, "router_thread": router_thread, "router_id": router_id, "sync_event_message": sync_event_message, "sync_event_connection": sync_event_connection } client_thread = ClientThread(init_params) clients_threads[client_id] = client_thread client_thread.start()
def serve(self): worker_thread = Thread(target=self.tick) worker_thread.daemon = True worker_thread.start() while True: connection, address = self.socket_server.accept() connection.settimeout(const.SERVER_CONNECTION_TIMEOUT) log(f"Server - {address} connected") thread = ClientThread(connection, address, self) thread.daemon = True self.client_pool.append(thread) thread.start()
def wait_for_connect(self,client_args={}): (clientsocket, address) = self.serversocket.accept() self.logger.info("Starting client thread %s:%d" % address) commands = self._server_commands() args = dict(client_args) if args.has_key('commands'): args['commands'].update(commands) else: args['commands'] = commands ct = ClientThread(sock=clientsocket, address=address, logger=self.logger, args=args) ct.cleanup_func = self._client_stopped ct.broadcast_func = self._broadcast with self.lock: self.clientthreads.append(ct) ct.start()
def startClient(self): try: # initiate client thread and pass simulation GUI message queue self.mode = ClientThread(self.tcp_sim_queue,self.thread_event) self.mode.daemon = True # thread to close when main thread closes self.mode.start() # disable all buttons except 'Stop' self.btn_start_server.setEnabled(False) self.btn_start_client.setEnabled(False) self.btn_random_ball.setEnabled(False) self.btn_custom_ball.setEnabled(False) except Exception: print "No server available."
def test_gui_channel_window(self): try: from .gui import ChannelWindow from .client import ClientThread except SystemError: from gui import ChannelWindow from client import ClientThread sources = { "123":{"uuid": "123","hop": 3, "username": "******", "velocity": 3, "channel": 1}, "234":{"uuid": "234","hop": 0, "username": "******", "velocity": 3, "channel": 6} } client_thread = ClientThread() channel_window = ChannelWindow(sources, client_thread) test_widget = TestWidget() channel_window.on_change_mode(test_widget, "123", "hop") channel_window.on_change_mode(test_widget, "123", "lock") channel_window.on_change_value(None, "123", "hop") channel_window.on_cancel(None) channel_window.on_apply(None)
if not q.empty(): r = q.get() if isinstance(r, MailDataFrame): print(r.data) else: for i in range(2): if r[-i] in ["\r", "\n"]: r = r[:-i] print(r) HOST = '127.0.0.1' SERVPORT = 42069 DESTPORT = 25 BACKLOG = 5 msg_q = Queue() log_q = Queue() client_thread = ClientThread((HOST, DESTPORT), msg_q, log_q, daemon=True) client_thread.start() log = Thread(target=logger, args=(log_q, ), daemon=True) log.start() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, SERVPORT)) i = 0 while True: s.listen(BACKLOG) cl_skt, addr = s.accept() t = ServerThread(cl_skt, msg_q, log_q, daemon=True) t.start() i = i + 1
def _server_commands(self): return { 'users': ClientThread.make_command( func=self._users, helptext="print list of connected users" )}
from server import ServerThread from settings import THREAD_SERVER, THREAD_CLIENT import sys if __name__ == "__main__": if len(sys.argv) > 1: if sys.argv[1] == "-c" or sys.argv[1] == "--cliente": # Se entrou aqui é porque deve subir um cliente if len(sys.argv) == 3: # Pega argumentos ip:porta da linha de comando server = sys.argv[2] server = server.split(":") # Cria thread cliente para ip:porta informados # na linha de comando server = ClientThread(server[0],server[1]) server.setName(THREAD_CLIENT) server.start() else: print "forneça ip:porta do servidor." elif sys.argv[1] == "-s" or sys.argv[1] == "--servidor": # Se entrou aqui é porque deve subir um servidor if len(sys.argv) == 3: # Pega argumento porta da linha de comando porta = sys.argv[2] # Cria thread servidor para port server = ServerThread(porta) server.setName(THREAD_SERVER) server.start() else:
def test_client(self): try: from .client import Client, ClientThread, encode_cryptset, decode_cryptset except SystemError: from client import Client, ClientThread, encode_cryptset, decode_cryptset class TestClient(Client): def send(self, msg): return test_lines, result_split_line, result_parse_line = get_client_test_data() client = TestClient() client.server = "invalid:xyz" client.start() test_dump_name = "%s%skismet_dump_test-%s.dump" % (tempfile.gettempdir(), os.sep, int(time.time())) test_dump = open(test_dump_name, "w") client = TestClient() client.set_capabilities(["bssid", "ssid"]) pos = 0 errors = 0 for line in test_lines: result = client.split_line(line.split(":", 1)[1]) if result != result_split_line[pos]: print("split_line error %s" % pos) print("%s\n!=\n%s" % (result, result_split_line[pos])) errors += 1 result = client.parse_line(line) if result != result_parse_line[pos]: print("parse_line error %s" % pos) print("%s\n!=\n%s" % (result, result_parse_line[pos])) errors += 1 pos += 1 test_dump.write(line) crypt_test = [ (0, "none"), (2, "WEP"), (226, "WEP,TKIP,WPA,PSK"), (706, "WEP,WPA,PSK,AES_CCM"), (738, "WEP,TKIP,WPA,PSK,AES_CCM"), ] for cryptset, result in crypt_test: crypt_str = decode_cryptset(cryptset, True) if crypt_str != result: print("decode_cryptset error: %s\n%s!=%s" % (cryptset, crypt_str, result)) test_cryptset = encode_cryptset(crypt_str.lower().split(",")) if test_cryptset != cryptset: print("encode_cryptset error: %s\n%s!=%s" % (crypt_str, test_cryptset, cryptset)) if errors != 0: sys.exit("client test failed, %s errors" % errors) test_dump.close() client.load_dump(test_dump_name) client.loop() client_thread = ClientThread() client_thread.client = client client.load_dump(test_dump_name) client_thread.run()
def test_gui_main_window(self): from gi.repository import Gtk try: from .config import Config from .map import Map from .gui import MainWindow from .client import ClientThread from .tracks import Tracks except SystemError: from config import Config from map import Map from gui import MainWindow from client import ClientThread from tracks import Tracks def dummy(server_id): return test_widget = TestWidget() test_config = Config(None).default_config test_map = Map(test_config["map"]) test_networks = networks() test_client_threads = {0: ClientThread()} tmp_tracks_file = "%s%stest-tracks-%s.json" % (tempfile.gettempdir(), os.sep, int(time.time())) test_tracks = Tracks(tmp_tracks_file) main_window = MainWindow(test_config, dummy, dummy, test_map, test_networks, test_tracks, {0: None, 1: None}, test_client_threads) main_window.network_list.crypt_cache = {} main_window.log_list.add("Kismon", "test") main_window.network_list.add_network('11:22:33:44:55:66') main_window.network_list.network_selected = '11:22:33:44:55:66' main_window.network_list.add_network('00:12:2A:03:B9:12') main_window.network_list.add_network('00:12:2A:03:B9:12') main_window.network_list.column_selected = 2 main_window.network_list.on_copy_field(None) main_window.network_list.on_copy_network(None) main_window.network_list.on_comment_editing_done(test_widget) main_window.network_list.remove_network('00:12:2A:03:B9:12') main_window.server_tabs[0].update_info_table({"networks":100, "packets":200} ) main_window.server_tabs[0].update_gps_table({"fix": 3, "lat": 52.0, "lon": 13.0}) sources = {"1": {"uuid": "1", "username": "******", "type": "bla", "channel": 11, "packets": 100}} main_window.server_tabs[0].update_sources_table(sources) main_window.on_configure_event(None, None) main_window.on_config_window(None) main_window.on_config_window(None) main_window.on_signal_graph(None) main_window.on_signal_graph_destroy(None, "11:22:33:44:55:66") main_window.fullscreen() main_window.fullscreen() main_window.on_map_window(None, True) main_window.on_map_window(None, False) main_window.on_map_widget(None, True) main_window.on_map_widget(None, False) #main_window.on_server_disconnect(None, 0) test_event = TestEvent() main_window.on_window_state(None, test_event) config_window = main_window.config_window main_window.on_file_import(None) test_widget.text = "Infrastructure" main_window.on_network_filter_type(test_widget) main_window.on_network_filter_networks(test_widget, "map", "all")
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.run = True self.mode = None # signals 'server'/'client' mode self.input_values = [] # input values retrieve from UI self.io_handlers() # initialize UI components # communication/network variables self.tcp_main_queue = Queue.Queue() self.tcp_sim_queue = Queue.Queue() self.thread_event = threading.Event() self.data = "meaningless" self.custom_data = '' self.cm = SceneManager(self.graphicsView) self.animations = [] self.animator = QTimer() # timer paired with main thread self.animator.timeout.connect(self.update) # timeout callback self.update() # initial call # links buttons to event handlers def io_handlers(self): self.btn_start_server.clicked.connect(self.startServer) self.btn_start_client.clicked.connect(self.startClient) self.btn_stop.clicked.connect(self.stopSimulation) self.btn_random_ball.clicked.connect(self.randomBall) self.btn_custom_ball.clicked.connect(self.customBall) # period callback used to animate 'graphicsView' def update(self): # moves item to location smoothly in one second def config_animate_to(t,item,x,y): # used to animate an item in specific ways animation = QGraphicsItemAnimation() # create a timeline (1 sec here) timeline = QTimeLine(100) timeline.setFrameRange(0,200) # 200 steps #item should at 'x,y' by time 't's animation.setPosAt(t,QPointF(x,y)) animation.setItem(item) # animate this item animation.setTimeLine(timeline) # with this duration/steps return animation if (self.run): # still running # check for items received via tcp if (not self.tcp_sim_queue.empty()): self.cm.deleteItems() # item = self.tcp_sim_queue.get() # retrieve value msg = self.tcp_sim_queue.get() if (type(msg) == type('s')) : # self.cm.addItem(item) # add new item self.cm.addItem(msg) else: self.cm.addItems(msg) elif (self.custom_data != ''): # data received from GUI # print 'self.custom_data is %s' % self.custom_data #DEBUG self.cm.addItem(self.custom_data) self.custom_data = '' if (str(self.mode) == 'SERVER'): del self.animations[:] # empty list of prev animations # retrieve all items in the graphicsView scene_items = self.cm.getItems() for item in scene_items: next_x, next_y = self.cm.next_move(item) # determine next location # create corresponding item animation (given displacement in local coordinates) item_animation = config_animate_to(1,item,next_x,next_y) self.animations.append(item_animation) # store item animation # update location values of item (global coordiantes) item.set_location(next_x+item.x_start,next_y+item.y_start) # signal the start of all animations [ animation.timeLine().start() for animation in self.animations] # send all simulation items to server thread if (len(scene_items) > 0): # retrieve items encoded for TCP tcp_list = self.cm.getItemsForTCP() # print ('Observed: ' + str(tcp_list)) #DEBUG self.tcp_main_queue.put(tcp_list) self.animator.start(ANIMATOR_TIMEOUT) def startServer(self): self.btn_start_client.setEnabled(False) # disable 'client' button # initiate server thread and pass GUI/simulation messgae queues self.mode = ServerThread(self.tcp_main_queue,self.thread_event) self.mode.daemon = True self.mode.start() def startClient(self): try: # initiate client thread and pass simulation GUI message queue self.mode = ClientThread(self.tcp_sim_queue,self.thread_event) self.mode.daemon = True # thread to close when main thread closes self.mode.start() # disable all buttons except 'Stop' self.btn_start_server.setEnabled(False) self.btn_start_client.setEnabled(False) self.btn_random_ball.setEnabled(False) self.btn_custom_ball.setEnabled(False) except Exception: print "No server available." def stopSimulation(self): # disable all buttons self.btn_start_server.setEnabled(False) self.btn_start_client.setEnabled(False) self.btn_stop.setEnabled(False) self.btn_random_ball.setEnabled(False) self.btn_custom_ball.setEnabled(False) self.run = False self.thread_event.set() print 'Main thread stopped' def randomBall(self): # select random radius, mass, x/y velocities mass = random.randint(5, 20) radius = int(mass * 2) x_vel = random.randint(1,30) y_vel = random.randint(1,30) # select x/y positions within graphicsView x_pos = random.randint(0,SCENE_WIDTH-radius) y_pos = random.randint(0,SCENE_HEIGHT-radius) # encode data for TCP transport self.data = 'x' + str(x_pos) + 'y' + str(y_pos) + 'xv' + str(x_vel) + \ 'yv' + str(y_vel) + 'm' + str(mass) + 'r' + str(radius) # self.tcp_main_queue.put(self.data) # self.tcp_sim_queue.put(self.data) self.custom_data = self.data def customBall(self): # create dialog for input dialog = CustomDialog() # retrieve input from dialog if (dialog.exec_()): self.input_values = dialog.results params = ['x','y','xv','yv','m','r'] self.data = '' # encode data for TCP transmission for i in range(0,len(self.input_values)): self.data += params[i] + str(self.input_values[i]) # # input in queue for tcp thread if (len(self.data) > 0): self.custom_data = self.data
def startServer(self): self.btn_start_client.setEnabled(False) # disable 'client' button # initiate server thread and pass GUI/simulation messgae queues self.mode = ServerThread(self.tcp_main_queue,self.thread_event) self.mode.daemon = True self.mode.start()
def join_server(self, ip): ip = self.sender().ip.text() client = ClientThread(ip) client.start()