def __new_tunnel(self): tunnel = Tunnel() port = tunnel.new_tunnel(self.req_data.get('port', 0), self.req_data.get('client_id')) res = { 'tunnel_port': port, 'client_id': self.req_data.get('client_id'), 'res': 'start_tunnel' } self.protocol.sendString(json.dumps(res).encode('utf8'))
def test_steps(self): tunnel = Tunnel(5, 5, 5, orient=Orientation.right) positions = tunnel.steps() message = 'Positions {}: '.format(len(positions)) for pos in positions: message += str(pos) print(message) self.assertTrue(Position(5, 9) in positions)
def readSettings(self): if os.name == 'nt': settings = QSettings() else: settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat) for name in settings.childGroups(): tunnel = Tunnel(self) tunnel.name = name tunnel.readSettings(settings) self._tunnels.append(tunnel) self.tray.menu.insertAction(self.actionLastSep, tunnel.action) self.tray.menu.removeAction(self.actionNoTun)
def run_game(self) -> None: while True: clock.tick(self.settings.frames_per_second) self._check_events() if self.stats.is_changing_level: if not self.pause_animations: self.ship.hide_ship() self.scripted_ship = ScriptedShip() self.pause_animations.add(self.scripted_ship) self.pause_animations.add(Tunnel()) if self.scripted_ship.has_finished(): self.level_display.update() if self.stats.is_level_changed: self.pause_animations.empty() self._set_stage() self.stats.set_game_mode(Mode.ACTIVE) if self.stats.is_active: self.ship.update() self._update_bullets() self._change_level() self._update_aliens() self._update_screen()
def forward_request(self): uri = self.path cmd = self.command if cmd == "CONNECT": self.send_response(200) # in Python 3.4, end_headers need access _headers_buffer. Invoke send_header # will make sure the field is created self.send_header("Date", self.date_time_string()) self.end_headers() return Tunnel(self.connection, uri).handle() if uri.startswith("https://"): raise NotSupportedError("https not supported yet") elif uri.startswith("http://"): uri = uri[len("http://") :] else: raise InvalidRequest("Invalid uri for proxy: {0}".format(uri)) start_ind = uri.find("/") if start_ind == -1: start_ind = uri.find("?") if start_ind == -1: addr = uri resource = "/" else: addr = uri[:start_ind] resource = uri[start_ind:] if not resource.startswith("/"): resource = "/" + resource conn = HTTPConnection(addr) if cmd not in ["GET", "POST"]: raise NotSupportedError("http method {0} not supported".format(cmd)) headers = {name: self.headers[name] for name in self.headers } if headers.get("Content-Length"): cl = int(headers["Content-Length"]) else: cl = None body = None # get body for post if cmd in ["POST"]: self.handleExpect100(headers) if cl: body = self.rfile.read(cl) else: body = self.rfile.read() print("body is [{0}]".format(body)) if "Proxy-Connection" in headers: del headers["Proxy-Connection"] conn.request(cmd, resource, body, headers) resp = conn.getresponse() self.forward_response(resp)
def add_tunnel(self, dstname, physport, dstvlan): # NOTE: this doesn't check for whether or not this is a valid thing to # do. The user of this function should be confirming with the switch # that a particular VLAN/Port combination is valid. # Make sure there isn't already a 'dstname' in the tunnels list for tunnel in self.tunnels: if tunnel.get_name() == dstname: tunnel_names = [] for t in self.tunnels: tunnel_names.append(t.get_name()) raise Exception("%s already exists as a tunnel name: %s" % (dstname, tunnel_names)) # Find open virtual port number self.current_vport += 1 vport = self.current_vport # Create the Tunnel object tunnel_href = self.href + "/tunnels/" + str(dstname) tunnel = Tunnel(tunnel_href, dstname, physport, dstvlan, vport) # Make REST calls to instantiate this new tunnel self.add_tunnel_REST_helper(physport, vport, dstvlan) # Finally, add it to the local list of tunnels self.tunnels.append(tunnel) return tunnel
def on_btnDuplicateTunnel_clicked(self): cur = self.currentTunnel() if cur is not None: tunnel = Tunnel(self) tunnel.name = cur.name+" (copy)" tunnel.host = cur.host tunnel.localPort = cur.localPort tunnel.port = cur.port tunnel.username = cur.username tunnel.command = cur.command tunnel.autoClose = cur.autoClose self._tunnels.append(tunnel) self.listTunnels.setCurrentItem(tunnel.item) self.tray.menu.insertAction(self.actionLastSep, tunnel.action)
def test_create_horizontal(self): pos_1 = Position(5, 5) pos_2 = Position(7, 7) tunnel = Tunnel.create_horizontal(pos_1, pos_2) self.assertEquals(tunnel.pos.point, pos_1.point) self.assertEquals(tunnel.length, 2) self.assertEquals(tunnel.orient, Orientation.right)
def test_create_vertical(self): pos_1 = Position(5, 5) pos_2 = Position(6, 6) tunnel = Tunnel.create_vertical(pos_1, pos_2) self.assertEquals(tunnel.pos.point, pos_1.point) self.assertEquals(tunnel.length, 1) self.assertEquals(tunnel.orient, Orientation.bottom)
def connect_side_multiplex(tun_device, _, packet): if need_restore(from_addr, packet): restore_dst(packet) if packet.is_rst(): _logger.info('%s has been reset', packet.get_source_ip()) addr_list, id_, domain = try_parse_dns_result(packet) if addr_list is not None: if packet.get_raw_source_ip() == TEST_DNS_SERVER: _logger.error('POISONED DOMAIN: %s', domain) update_poisoned_domain(domain) return True else: normal_address.update(addr_list) try_restore_dns(packet, id_) tun_device.send(packet.get_packet()) return True through_tunnel, dns_query = is_through_tunnel(packet, to_addr) if not through_tunnel: if dns_query is True: test_domain_poisoned(tun_device, packet) change_src(packet) tun_device.send(packet.get_packet()) return True id_ = address2uuid(packet.get_raw_source_ip(), packet.get_source_port()) key = id_.int % TUNNEL_SIZE tunnel = None if key in key_to_tunnels: tunnel = key_to_tunnels[key] if tunnel is None or tunnel.is_closed(): tunnel = Tunnel(connect_to=via) tunnel.set_on_payload(on_tunnel_received) tunnel.initialize() key_to_tunnels[key] = tunnel # if proto == 'tcp': # data = data * 2 tunnel.send_tun_initial_data(id_, packet.get_packet()) return True
def handle(self): StreamRequestHandler.handle(self) t = Tunnel(self._tcp_sock, self._icmp_sock, self._peer, self._id) t.loop()
def server_side_on_accepted(sock, _): tunnel = Tunnel(connection=sock) tunnel.initialize()
def __init__(self): super(QMainWindow, self).__init__() self.setupUi(self) self.connButtonBox.button(QDialogButtonBox.Ok).setText("Connect") self.runButtonBox.button(QDialogButtonBox.Ok).setText("Run") self.tunnelButton.clicked[bool].connect(self.toggle_tunnel) self.tunnelWidget.hide() self.keyFileButton.clicked.connect(self.choose_keyfile) self.clearButton.clicked.connect(self.clear_tunnel) self.keyComboBox.activated[str].connect(self.set_key_type) self.db_engine = DBEngine() self.db_engine.result_signal.connect(self.show_results) self.db_engine.progress_signal.connect(self.set_progress) self.db_engine.error_signal.connect(self.show_error) self.db_engine.msg_signal.connect(self.show_msg) self.stmt_signal.connect(self.db_engine.receive_stmt) self.db_lite = DBLite() self.tunnel = Tunnel() self.tunnel_keyfile = "" self.data_schema = [] self.settings = QSettings() self.restore_settings() history = self.db_lite.history() self.historyMenuBar = QMenuBar(self.sqlWidget) self.historyMenuBar.setNativeMenuBar(False) self.historyMenu = self.historyMenuBar.addMenu(' &History ⇲ ') actions = [ QAction(sql.replace('\n', ' '), self.historyMenu) for sql in history ] for i in range(len(actions)): actions[i].triggered.connect(partial(self.use_history, history[i])) self.historyMenu.addActions(actions) self.history_cache = pylru.lrucache(history_limit, self.remove_action) for i in reversed(range(len(history))): self.history_cache[history[i]] = { KEY_ACTION: actions[i], KEY_RESULTS: [], KEY_COLUMNS: [] } self.historyMenu.setStyleSheet(""" QMenu { max-width: 1000px; font-size: 12px; } """) self.historyMenuBar.setStyleSheet(""" QMenuBar { border: None; } QMenuBar::item { background: #404040; color: #ffffff; border-radius: 4px; } QMenuBar::item:selected { background: rgba(1, 1, 1, 0.2);; color: #404040; border-radius: 4px; } """) self.sqlWidgetLayout.insertWidget(0, self.historyMenuBar) self.connButtonBox.accepted.connect(self.connect) self.connButtonBox.rejected.connect(self.disconnect) self.runButtonBox.accepted.connect(self.run) self.runButtonBox.rejected.connect(self.cancel) self.tablesWidget.itemDoubleClicked.connect(self.get_meta) self.tablesWidget.itemExpanded.connect(self.get_meta) self.progressBar = QProgressBar() self.statusbar.addPermanentWidget(self.progressBar) self.progressBar.setValue(100) QApplication.processEvents() self.highlight = syntax.PrestoHighlighter(self.sqlEdit) self.dataWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.dataWidget.customContextMenuRequested.connect( self.show_table_context_menu) self.dataWidget.horizontalHeader().setStretchLastSection(False) self.dataWidget.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.schemaView.header().setStretchLastSection(False) self.schemaView.header().setSectionResizeMode( QHeaderView.ResizeToContents) self.runButtonBox.button( QDialogButtonBox.Ok).setShortcut("Ctrl+Return") self.completer = SQLCompleter(self) self.sqlEdit.setCompleter(self.completer) self.set_key_type(self.keyComboBox.currentText()) self.sqlEdit.setFocus()
def on_btnAddTunnel_clicked(self): tunnel = Tunnel(self) self._tunnels.append(tunnel) self.listTunnels.setCurrentItem(tunnel.item) self.tray.menu.insertAction(self.actionLastSep, tunnel.action) self.tray.menu.removeAction(self.actionNoTun)
def main(args): mods = dict() #Parse commandline args if len(args) != 4: print "host.py MAC IP IFACE" return mymac = args[1] myip = args[2] myiface = args[3] while True: #Read and Parse Message line = "" msg = None try: line = sys.stdin.readline() except Exception as e: print e print "Exiting" return if len(line) == 0: continue try: msg = eval(line) except Exception as e: continue if not isinstance(msg, dict): continue if not 'module' in msg: continue #Select Module and send command m = None if msg['module'] is "ping": if "ping" in mods: m = mods['ping'] else: m = Ping(mymac, myip, myiface) mods['ping'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "iperf": if "iperf" in mods: m = mods['iperf'] else: m = Iperf(mymac, myip, myiface) mods['iperf'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "http": if "http" in mods: m = mods["http"] else: m = HttpTest(mymac, myip, myiface) mods['http'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "arp": if "arp" in mods: m = mods['arp'] else: m = Arp(mymac, myip, myiface) mods['arp'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "lldp": if "lldp" in mods: m = mods['lldp'] else: m = LLDPAttack(mymac, myip, myiface) mods['lldp'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "tunnel": if "tunnel" in mods: m = mods['tunnel'] else: m = Tunnel(mymac, myip, myiface) mods['tunnel'] = m out = response(m.cmd(msg)) send_response(out) elif msg['module'] is "magic": if "magic" in mods: m = mods["magic"] else: m = Magic(mymac, myip, myiface) mods["magic"] = m out = response(m.cmd(msg)) send_response(out) else: print "Unknown Module"
class WinApp(QMainWindow, Ui_MainWindow): stmt_signal = pyqtSignal(str) def __init__(self): super(QMainWindow, self).__init__() self.setupUi(self) self.connButtonBox.button(QDialogButtonBox.Ok).setText("Connect") self.runButtonBox.button(QDialogButtonBox.Ok).setText("Run") self.tunnelButton.clicked[bool].connect(self.toggle_tunnel) self.tunnelWidget.hide() self.keyFileButton.clicked.connect(self.choose_keyfile) self.clearButton.clicked.connect(self.clear_tunnel) self.keyComboBox.activated[str].connect(self.set_key_type) self.db_engine = DBEngine() self.db_engine.result_signal.connect(self.show_results) self.db_engine.progress_signal.connect(self.set_progress) self.db_engine.error_signal.connect(self.show_error) self.db_engine.msg_signal.connect(self.show_msg) self.stmt_signal.connect(self.db_engine.receive_stmt) self.db_lite = DBLite() self.tunnel = Tunnel() self.tunnel_keyfile = "" self.data_schema = [] self.settings = QSettings() self.restore_settings() history = self.db_lite.history() self.historyMenuBar = QMenuBar(self.sqlWidget) self.historyMenuBar.setNativeMenuBar(False) self.historyMenu = self.historyMenuBar.addMenu(' &History ⇲ ') actions = [ QAction(sql.replace('\n', ' '), self.historyMenu) for sql in history ] for i in range(len(actions)): actions[i].triggered.connect(partial(self.use_history, history[i])) self.historyMenu.addActions(actions) self.history_cache = pylru.lrucache(history_limit, self.remove_action) for i in reversed(range(len(history))): self.history_cache[history[i]] = { KEY_ACTION: actions[i], KEY_RESULTS: [], KEY_COLUMNS: [] } self.historyMenu.setStyleSheet(""" QMenu { max-width: 1000px; font-size: 12px; } """) self.historyMenuBar.setStyleSheet(""" QMenuBar { border: None; } QMenuBar::item { background: #404040; color: #ffffff; border-radius: 4px; } QMenuBar::item:selected { background: rgba(1, 1, 1, 0.2);; color: #404040; border-radius: 4px; } """) self.sqlWidgetLayout.insertWidget(0, self.historyMenuBar) self.connButtonBox.accepted.connect(self.connect) self.connButtonBox.rejected.connect(self.disconnect) self.runButtonBox.accepted.connect(self.run) self.runButtonBox.rejected.connect(self.cancel) self.tablesWidget.itemDoubleClicked.connect(self.get_meta) self.tablesWidget.itemExpanded.connect(self.get_meta) self.progressBar = QProgressBar() self.statusbar.addPermanentWidget(self.progressBar) self.progressBar.setValue(100) QApplication.processEvents() self.highlight = syntax.PrestoHighlighter(self.sqlEdit) self.dataWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.dataWidget.customContextMenuRequested.connect( self.show_table_context_menu) self.dataWidget.horizontalHeader().setStretchLastSection(False) self.dataWidget.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.schemaView.header().setStretchLastSection(False) self.schemaView.header().setSectionResizeMode( QHeaderView.ResizeToContents) self.runButtonBox.button( QDialogButtonBox.Ok).setShortcut("Ctrl+Return") self.completer = SQLCompleter(self) self.sqlEdit.setCompleter(self.completer) self.set_key_type(self.keyComboBox.currentText()) self.sqlEdit.setFocus() def connect(self): self.tablesWidget.clear() self.schemaView.clear() try: if self.serverEdit.text().strip() and self.gatewayEdit.text( ).strip() and self.tunnelUserEdit.text().strip(): self.statusbar.showMessage('Starting tunnel') QApplication.processEvents() self.tunnel.start_tunnel( self.serverEdit.text().strip(), self.gatewayEdit.text().strip(), self.tunnelUserEdit.text().strip(), self.keyComboBox.currentText() == 'KeyFile', self.tunnel_keyfile, self.pwdLineEdit.text(), self.urlEdit.text().strip()) self.statusbar.showMessage('Connecting') QApplication.processEvents() self.db_engine.connect(self.urlEdit.text().strip(), self.userEdit.text().strip()) self.statusbar.showMessage('Fetching db info') QApplication.processEvents() dbs = self.db_engine.dbs() for db in dbs: db_item = QTreeWidgetItem([db]) db_item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator) self.tablesWidget.addTopLevelItem(db_item) self.completer.addItems(dbs) self.statusbar.showMessage('Connected') except Exception as err: QMessageBox.critical(self, "Error", str(err)) self.db_engine.close() self.statusbar.showMessage('Disconnected') def disconnect(self): self.db_engine.close() self.tunnel.stop_tunnel() self.schemaView.clear() self.tablesWidget.clear() self.statusbar.showMessage('Disconnected') def get_meta(self, item): try: if item.parent(): columns = self.db_engine.columns(item.parent().text(0), item.text(0)) self.set_columns(columns) self.completer.addItems([column[0] for column in columns]) else: if item.childCount() <= 0: tables = self.db_engine.tables(item.text(0)) item.addChildren( [QTreeWidgetItem([table]) for table in tables]) self.completer.addTreeItem(item) except Exception as err: QMessageBox.critical(self, "Error", str(err)) def set_columns(self, columns): try: self.schemaView.clear() for column in columns: column_item = self.type_tree(column[0], type_parser.parse(column[1])) self.schemaView.addTopLevelItem(column_item) self.schemaView.expandToDepth(2) for j in range(self.schemaView.columnCount()): self.schemaView.resizeColumnToContents(j) except Exception as err: QMessageBox.critical(self, "Error", str(err)) def run(self): self.dataWidget.setRowCount(0) self.dataWidget.setColumnCount(0) try: self.stmt_signal.emit(self.sqlEdit.toPlainText().strip().replace( ';', '')) self.db_engine.start() except Exception as err: QMessageBox.critical(self, "Error", str(err)) def show_results(self, results, columns, sql, save=True): try: num_cols = len(columns) num_rows = len(results) self.dataWidget.setRowCount(num_rows) self.dataWidget.setColumnCount(num_cols) for i in range(num_rows): for j in range(num_cols): self.dataWidget.setItem( i, j, QTableWidgetItem(str(results[i][j]))) self.dataWidget.resizeColumnsToContents() for j in range(num_cols): header_label = columns[j][0] # header_width = self.fm.width(header_label) # if header_width > self.dataWidget.columnWidth(j): # self.dataWidget.setColumnWidth(j, header_width) self.dataWidget.setHorizontalHeaderItem( j, QTableWidgetItem(header_label)) self.data_schema = [column[1] for column in columns] if not columns and not results: self.dataWidget.setColumnCount(1) self.dataWidget.setHorizontalHeaderItem( 0, QTableWidgetItem("Empty Result")) if save: self.save_history(sql, results, columns) except Exception as err: QMessageBox.critical(self, "Error", str(err)) finally: self.statusbar.showMessage('Finished') def cancel(self): self.db_engine.cancel() def set_progress(self, progress): self.progressBar.setValue(progress) QApplication.processEvents() def save_history(self, sql, results, columns): if sql not in self.history_cache: action = QAction(sql.replace('\n', ' '), self.historyMenu) action.triggered.connect(partial(self.use_history, sql)) self.history_cache[sql] = { KEY_ACTION: action, KEY_RESULTS: results, KEY_COLUMNS: columns } else: action = self.history_cache[sql][KEY_ACTION] self.historyMenu.removeAction(action) if len(results) * len(columns) <= CACHE_LIMIT: self.history_cache[sql][KEY_RESULTS] = results self.history_cache[sql][KEY_COLUMNS] = columns else: self.history_cache[sql][KEY_RESULTS] = [] self.history_cache[sql][KEY_COLUMNS] = [ ("results too large to cache", "varchar") ] self.historyMenu.insertAction( self.historyMenu.actions()[0] if (self.historyMenu.actions()) else None, action) self.db_lite.upsert(sql) def use_history(self, sql): self.sqlEdit.setText(sql) QApplication.processEvents() cached = self.history_cache[sql] self.db_engine.result_signal.emit(cached[KEY_RESULTS], cached[KEY_COLUMNS], sql, False) self.statusbar.showMessage("Loaded cached history") def remove_action(self, sql, cached): self.historyMenu.removeAction(cached[KEY_ACTION]) def show_table_context_menu(self, position): col = self.dataWidget.columnAt(position.x()) dialog = QDialog(self, Qt.Popup) schema_view = QTreeWidget(dialog) schema_view.headerItem().setText(0, "Field") schema_view.headerItem().setText(1, "Type") root = type_parser.parse(self.data_schema[col]) schema_tree = self.type_tree( self.dataWidget.horizontalHeaderItem(col).text(), root) schema_view.addTopLevelItem(schema_tree) schema_view.expandToDepth(2) schema_view.header().setStretchLastSection(False) schema_view.setSizeAdjustPolicy( QAbstractScrollArea.AdjustToContentsOnFirstShow) schema_view.header().setSectionResizeMode(QHeaderView.ResizeToContents) schema_view.setMinimumHeight(30) schema_view.setMaximumHeight(400) schema_view.adjustSize() schema_view.setHeaderHidden(True) dialog.move( self.dataWidget.mapToGlobal(position) + QPoint(dialog.width() / 5 * 2, dialog.height() + 5)) dialog.adjustSize() dialog.show() def type_tree(self, name, root): if root.children[0].data == 'primitive_type': return QTreeWidgetItem([name, root.children[0].children[0].value]) elif root.children[0].data == 'row_type': root_widget = QTreeWidgetItem([name, 'row']) for i in range(len(root.children[0].children) // 2): name = root.children[0].children[i * 2].value child_type = root.children[0].children[i * 2 + 1] root_widget.addChild(self.type_tree(name, child_type)) return root_widget elif root.children[0].data == 'array_type': if root.children[0].children[0].children[ 0].data == 'primitive_type': return QTreeWidgetItem([ name, 'array(' + root.children[0].children[0].children[0].children[0].value + ')' ]) else: root_widget = QTreeWidgetItem([name, 'array(row)']) for i in range( len(root.children[0].children[0].children[0].children) // 2): name = root.children[0].children[0].children[0].children[ i * 2].value child_type = root.children[0].children[0].children[ 0].children[i * 2 + 1] root_widget.addChild(self.type_tree(name, child_type)) return root_widget elif root.children[0].data == 'map_type': root_widget = QTreeWidgetItem([name, 'map']) key = self.type_tree('_key', root.children[0].children[0]) value = self.type_tree('_value', root.children[0].children[1]) root_widget.addChildren([key, value]) return root_widget else: pass def toggle_tunnel(self, pressed): if pressed: self.tunnelWidget.show() self.repaint() else: self.tunnelWidget.hide() def choose_keyfile(self): file_name, _ = QFileDialog.getOpenFileName(self, "Choose Key File", QDir.homePath() + "/.ssh", "All Files (*)") if file_name: self.tunnel_keyfile = file_name self.keyFileButton.setText(file_name.split('/')[-1]) def clear_tunnel(self): self.tunnel_keyfile = None self.keyFileButton.setText("Choose Key File...") self.serverEdit.clear() self.gatewayEdit.clear() self.tunnelUserEdit.clear() self.pwdLineEdit.clear() def close_all(self): self.save_settings() self.db_engine.close() self.tunnel.stop_tunnel() def restore_settings(self): self.urlEdit.setText(self.settings.value(URL, "")) self.userEdit.setText(self.settings.value(USER, "")) self.serverEdit.setText(self.settings.value(SERVER, "")) self.gatewayEdit.setText(self.settings.value(GATEWAY, "")) self.tunnelUserEdit.setText(self.settings.value(TUNNEL_USER, "")) self.tunnel_keyfile = self.settings.value(KEYFILE, "") if self.tunnel_keyfile: self.keyFileButton.setText(self.tunnel_keyfile.split('/')[-1]) self.pwdLineEdit.setText(self.settings.value(TUNNEL_PWD, "")) self.keyComboBox.setCurrentText(self.settings.value( KEYTYPE, "KeyFile")) def save_settings(self): self.settings.setValue(URL, self.urlEdit.text().strip()) self.settings.setValue(USER, self.userEdit.text().strip()) self.settings.setValue(SERVER, self.serverEdit.text().strip()) self.settings.setValue(GATEWAY, self.gatewayEdit.text().strip()) self.settings.setValue(TUNNEL_USER, self.tunnelUserEdit.text().strip()) self.settings.setValue(KEYFILE, self.tunnel_keyfile) self.settings.setValue(KEYTYPE, self.keyComboBox.currentText()) self.settings.setValue(TUNNEL_PWD, self.pwdLineEdit.text()) self.settings.sync() def show_error(self, error): QMessageBox.critical(self, "Error", error) def show_msg(self, msg): self.statusbar.showMessage(msg) def set_key_type(self, key_type): if key_type == 'KeyFile': self.pwdLineEdit.hide() self.keyFileButton.show() else: self.keyFileButton.hide() self.pwdLineEdit.show()
tun_device = None def on_server_side_initialized(tunnel, id_, data): def on_received(_, data_, packet): id__ = address2uuid(packet.get_raw_destination_ip(), packet.get_destination_port()) key_ = id__.int % TUNNEL_SIZE tunnel_ = None if key_ in key_to_tunnels: tunnel_ = key_to_tunnels[key_] if tunnel_ is not None: tunnel_.send_payload(id__, data_) else: _logger.warning('unknown dst %s:%d', packet.get_destination_ip(), packet.get_destination_port()) return True global tun_device if tun_device is None: tun_device = TunDevice('', '', 0) tun_device.set_on_received(on_received) tun_device.start_receiving() key = id_.int % TUNNEL_SIZE key_to_tunnels[key] = tunnel tun_device.send(data) Tunnel.set_tun_initial_handler(on_server_side_initialized)
raise Exception('Already in Connect Mode') server_list = process_accept_side_argument(arg) if cmd == '-C': connect_mode = True if accept_mode is True: raise Exception('Already in Accept Mode') server_list = process_connect_side_argument(arg) if cmd == '-h': print(_helpText) sys.exit(0) if not accept_mode and not connect_mode: print(_helpText) sys.exit(0) Tunnel.set_tcp_fin_received_handler(tcptun.on_stream_fin_received) Tunnel.set_tcp_closed_handler(tcptun.on_stream_closed) Tunnel.set_udp_closed_handler(udptun.on_dgram_closed) if accept_mode: Tunnel.set_tcp_initial_handler(tcptun.on_server_side_initialized) Tunnel.set_udp_initial_handler(udptun.on_server_side_initialized) for addr, port, type_, arg in server_list: if accept_mode: acceptor = Acceptor('TUNNEL') acceptor.bind(addr, port) acceptor.listen() acceptor.set_on_accepted(server_side_on_accepted) acceptor.set_on_closed(acceptor_on_closed) else: via, to = arg
def on_received(endpoint, data, from_): id_ = address2uuid(*from_) tunnel = Delegation.get_tunnel(id_) if tunnel is None: tunnel = Tunnel(connect_to=via) tunnel.set_on_payload(Delegation.on_payload) tunnel.set_on_closed(Delegation.on_closed) tunnel.set_on_ready_to_send(Delegation.set_on_ready_to_send) tunnel.set_on_send_buffer_full(Delegation.set_on_send_buffer_full) tunnel.initialize() if Delegation.query_endpoint(id_) is None: tunnel.send_udp_initial_data(id_, initial_data) Delegation.register(id_, tunnel, endpoint) tunnel.send_payload(id_, data)
player = Player(w, h) # create pellet array pellet_list = [] # list of actual nodes nodeList = [] # create powerPellet array powerPellet_list = [] # create ghostNodes array ghostNodes = [] # create two way tunnel tunnel = Tunnel(10, 290, w-10, 290) # (x1, y1, x2, y2) startTime = 0 # pre load background image pygame.image.load('colourmap.png').convert() image_rect = pygame.image.load('colourmap.png').convert().get_rect() image_surface = pygame.Surface((image_rect.width, image_rect.height)) image_surface.blit(pygame.image.load("colourmap.png"), image_rect) # have the ghost get the path to its target pinky_node = player.findNode(ghostNodes) def get_pinky_node(): global pinky_node # global ghostNodes