def sigkill(self): if sys.platform == "win32": self.sendSignal(signal.SIGABRT) else: self.sendSignal(signal.SIGKILL) if self.pid != 0: GLib.spawn_close_pid(self.pid)
def sigkill (self): if sys.platform == "win32": self.sendSignal(signal.SIGABRT) else: self.sendSignal(signal.SIGKILL) if self.pid != 0: GLib.spawn_close_pid(self.pid)
def __on_kid3_result(self, pid, status): """ Set state @param pid as int @param status as bool """ if pid is not None: GLib.spawn_close_pid(pid) self.__kid3_available = status == 0
def child_watch(pid, status): """Handle child termination.""" # pylint: disable=E1103 GLib.spawn_close_pid(pid) # pylint: enable=E1103 if os.WIFEXITED(status): status = os.WEXITSTATUS(status) reply_handler(status) else: msg = "Child terminated abnormally, " "status from waitpid is %r" % status error_handler(msg=msg, failed_to_start=False)
def _checkisoEndsCB(self, pid, status): doneButton = self.builder.get_object("doneButton") verifyLabel = self.builder.get_object("verifyLabel") if status == 0: verifyLabel.set_text(_("This media is good to install from.")) else: verifyLabel.set_text(_("This media is not good to install from.")) self.progressBar.set_fraction(1.0) doneButton.set_sensitive(True) GLib.spawn_close_pid(pid)
def child_watch(pid, status): """Handle child termination.""" # pylint: disable=E1103 GLib.spawn_close_pid(pid) # pylint: enable=E1103 if os.WIFEXITED(status): status = os.WEXITSTATUS(status) reply_handler(status) else: msg = 'Child terminated abnormally, '\ 'status from waitpid is %r' % status error_handler(msg=msg, failed_to_start=False)
def closure_func(pid, status, data): """ Close function by PID :param pid: Process PID to kill it :param status: Process status to kill it :param data: return Process data to kill it GLib.child_watch_add(...) : Sets a function to be called when the child indicated by pid exits, at the priority priority """ GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.progress.set_fraction(0.0) self.pid = 0
def __on_tag_editor_result(self, pid, status, editor, editors): """ Set editor @param pid as int @param status as bool @param editor as str @param editors as [str] """ if pid is not None: GLib.spawn_close_pid(pid) if status == 0: self.__tag_editor = editor else: self.__tag_editor_search(editors)
def __set_popularity(self, pop): """ Set popularity with kid3-cli @param pop as int """ if pop == 0: value = 0 elif pop == 1: value = 1 elif pop == 2: value = 64 elif pop == 3: value = 128 elif pop == 4: value = 196 else: value = 255 f = Gio.File.new_for_uri(self.__object.uri) if f.query_exists(): path = f.get_path() arguments = [["kid3-cli", "-c", "set POPM %s" % value, path], [ "flatpak-spawn", "--host", "kid3-cli", "-c", "set POPM %s" % value, path ]] if App().scanner.inotify is not None: App().scanner.inotify.disable() worked = False for argv in arguments: try: (pid, stdin, stdout, stderr) = GLib.spawn_async( argv, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.STDOUT_TO_DEV_NULL, standard_input=False, standard_output=False, standard_error=False) GLib.spawn_close_pid(pid) # Force mtime update to not run a collection update App().tracks.set_mtime(self.__object.id, int(time()) + 10) worked = True break except Exception as e: Logger.error( "RatingWidget::__on_can_set_popularity(): %s" % e) if not worked: App().notify.send("Lollypop", _("You need to install kid3-cli"))
def _checkisoEndsCB(self, pid, status): doneButton = self.builder.get_object("doneButton") verifyLabel = self.builder.get_object("verifyLabel") if os.WIFSIGNALED(status): pass elif status == 0: verifyLabel.set_text(_("This media is good to install from.")) else: verifyLabel.set_text(_("This media is not good to install from.")) self.progressBar.set_fraction(1.0) doneButton.set_sensitive(True) GLib.spawn_close_pid(pid) self._pid = None
def update(self): """ Update database """ if not Gio.NetworkMonitor.get_default().get_network_available(): return # Update adblock_js repo git = GLib.find_program_in_path("git") if git is None: Logger.info(_("For stronger ad blocking, install git command")) else: if GLib.file_test(ADBLOCK_JS, GLib.FileTest.IS_DIR): argv = [git, "-C", ADBLOCK_JS, "pull", "https://gitlab.gnome.org/gnumdk/eolie-adblock.git"] else: argv = [git, "clone", "https://gitlab.gnome.org/gnumdk/eolie-adblock.git", ADBLOCK_JS] (pid, a1, a2, a3) = GLib.spawn_async( argv, flags=GLib.SpawnFlags.STDOUT_TO_DEV_NULL) GLib.spawn_close_pid(pid) # DB version is last successful sync mtime try: version = load(open(EOLIE_DATA_PATH + "/adblock.bin", "rb")) except: version = 0 self.__cancellable.reset() if self.__adblock_mtime - version > self.__UPDATE: # Update host rules uris = list(self.__URIS) locales = GLib.get_language_names() user_locale = locales[0].split("_")[0] try: uris += self.__CSS_URIS +\ [self.__CSS_LOCALIZED_URIS[user_locale]] except: uris += self.__CSS_URIS uri = uris.pop(0) self.__task_helper.load_uri_content(uri, self.__cancellable, self.__on_load_uri_content, uris)
def test_spawn_async_with_pipes(self): res, pid, stdin, stdout, stderr = GLib.spawn_async_with_pipes( working_directory=None, argv=['cat'], envp=None, flags=GLib.SpawnFlags.SEARCH_PATH) os.write(stdin, b'hello world!\n') os.close(stdin) out = os.read(stdout, 50) os.close(stdout) err = os.read(stderr, 50) os.close(stderr) GLib.spawn_close_pid(pid) self.assertEqual(out, b'hello world!\n') self.assertEqual(err, b'')
def _vmDownOperation(self, inException=False, dbusObj=None): if not inException: dbusObj = dbus.SystemBus().get_object('org.fpemud.VirtService', '/org/fpemud/VirtService') else: assert dbusObj is not None self.peripheralDict.clear() if self.qmpObj is not None: self.qmpObj.close() self.qmpObj = None if self.vmPidWatch is not None: self.vmPidWatch = GLib.source_remove(self.vmPidWatch) if self.vmPid is not None: GLib.spawn_close_pid(self.vmPid) self.vmPid = None self.qmpPort = -1 self.spicePort = -1 self.vsIpAddr = None self.vsMacAddr = None self.vsTapIfName = None if self.vsVmId is not None: dbusObj.DetachVm(self.vsVmId, dbus_interface='org.fpemud.VirtService') self.vsVmId = None if self.vsVmResSetId is not None: dbusObj.DeleteVmResSet(self.vsVmResSetId, dbus_interface='org.fpemud.VirtService') self.vsVmResSetId = None if self.vmTmpDir is not None: shutil.rmtree(self.vmTmpDir) self.vmTmpDir = None self.maxDriveId = 0 if not inException: self.state = FvpVmObject.STATE_POWER_OFF self.notify("state")
def update(self): """ Update database """ if not Gio.NetworkMonitor.get_default().get_network_available(): return # Update adblock_js repo git = GLib.find_program_in_path("git") if git is None: print(_("For stronger ad blocking, install git command")) else: if GLib.file_test(ADBLOCK_JS, GLib.FileTest.IS_DIR): argv = [git, "-C", ADBLOCK_JS, "pull"] else: argv = [ git, "clone", "https://gitlab.gnome.org/gnumdk/eolie-adblock.git", ADBLOCK_JS ] (pid, a1, a2, a3) = GLib.spawn_async(argv, flags=GLib.SpawnFlags.STDOUT_TO_DEV_NULL) GLib.spawn_close_pid(pid) # Check entries in DB, do we need to update? mtime = 0 with SqlCursor(self) as sql: result = sql.execute("SELECT mtime FROM adblock\ ORDER BY mtime LIMIT 1") v = result.fetchone() if v is not None: mtime = v[0] self.__cancellable.reset() if self.__adblock_mtime - mtime > self.__UPDATE: # Update host rules uris = list(self.__URIS) uri = uris.pop(0) self.__task_helper.load_uri_content(uri, self.__cancellable, self.__on_load_uri_content, uris) else: self.__on_save_rules()
def _child_cb(self, pid, status, data=None): """Called when the child process exists.""" # Empty stdout and stderr for f in (self._process[2], self._process[3]): while True: buf = os.read(f, 256).decode('utf-8') if buf == '': break if f == self._process[3]: # stderr self._errors += buf # Check exit status of child try: GLib.spawn_check_exit_status(status) except GLib.GError: self.emit('error-occured', self._errors) GLib.spawn_close_pid(self._process[0]) self.emit('stopped')
def show(self): self.dialog.show_all() self.running = True self.error = False try: self.generate_avi() except GLib.GError as err: #pylint: disable=catching-non-exception error_dlg = Gtk.MessageDialog( transient_for=self.dialog, title=_("Error executing video converter"), modal=True, destroy_with_parent=True, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text=str(err)) error_dlg.run() error_dlg.destroy() self.dialog.destroy() return -1 result = 0 response = self.dialog.run() if response == Gtk.ResponseType.CANCEL: # cancel pressed result = 1 else: if self.running is True: # destroy by user GLib.spawn_close_pid(self.pid) os.kill(self.pid, signal.SIGTERM) result = 1 elif self.error is True: # error result = -1 if self.error_watch is not None: GLib.source_remove(self.error_watch) if self.fh_err: self.fh_err.close() self.dialog.destroy() return result
def __write_image_to_tags(self, path, album): """ Save album at path to album tags @param path as str @param album as Album """ files = [] for track in album.tracks: App().tracks.set_mtime(track.id, int(time()) + 10) f = Gio.File.new_for_uri(track.uri) if f.query_exists(): files.append(f.get_path()) worked = False cover = "%s/lollypop_cover_tags.jpg" % CACHE_PATH arguments = [["kid3-cli", "-c", "set picture:'%s' ''" % cover], [ "flatpak-spawn", "--host", "kid3-cli", "-c", "set picture:'%s' ''" % cover ]] for argv in arguments: argv += files try: (pid, stdin, stdout, stderr) = GLib.spawn_async( argv, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.STDOUT_TO_DEV_NULL, standard_input=False, standard_output=False, standard_error=False) GLib.spawn_close_pid(pid) worked = True break except Exception as e: Logger.error("AlbumArt::__write_image_to_tags(): %s" % e) if worked: self.clean_album_cache(album) GLib.timeout_add(2000, self.album_artwork_update, album.id) else: App().notify.send("Lollypop", _("You need to install kid3-cli"))
def update(self): """ Update database """ if not Gio.NetworkMonitor.get_default().get_network_available(): return # Update adblock_js repo git = GLib.find_program_in_path("git") if git is None: print(_("For stronger ad blocking, install git command")) else: d = Gio.File.new_for_path(ADBLOCK_JS) if d.query_exists(): argv = [git, "-C", ADBLOCK_JS, "pull"] else: argv = [ git, "clone", "https://github.com/gnumdk/eolie-adblock.git", ADBLOCK_JS ] (pid, a1, a2, a3) = GLib.spawn_async(argv, flags=GLib.SpawnFlags.STDOUT_TO_DEV_NULL) GLib.spawn_close_pid(pid) # Get in db mtime # Only update if filters older than one week mtime = 0 with SqlCursor(self) as sql: result = sql.execute("SELECT mtime FROM adblock LIMIT 1") v = result.fetchone() if v is not None: mtime = v[0] self.__mtime = int(time()) if self.__mtime - mtime < 604800: return # Update adblock db thread = Thread(target=self.__update) thread.daemon = True thread.start()
def on_child_process_exit(self, pid, status, callback): print_func = None wexitstatus = os.WEXITSTATUS(status) if wexitstatus == 0: state = ArchiveState.READY elif wexitstatus == 1: state = ArchiveState.READY print_func = logging.warning else: state = ArchiveState.FAILED print_func = logging.error if print_func: print_func("7z returned %s, printing full output:" % wexitstatus) line = self.out_7z.readline() while line: sys.stdout.write(" | " + line) line = self.out_7z.readline() GLib.spawn_close_pid(pid) self.out_7z = None callback(state)
def __on_pacmd_result(self, pid, status, stdout, combo): """ Read output and set combobox @param pid as int @param status as bool @param stdout as int @param combo as Gtk.ComboBox """ from re import findall, DOTALL GLib.spawn_close_pid(pid) io = GLib.IOChannel.unix_new(stdout) [status, data] = io.read_to_end() if data: string = data.decode("utf-8") current = App().settings.get_value("preview-output").get_string() devices = findall('name: <([^>]*)>', string, DOTALL) names = findall('device.description = "([^"]*)"', string, DOTALL) if names: for i in range(0, len(names)): combo.append(devices[i], names[i]) if devices[i] == current: combo.set_active_id(devices[i]) else: combo.set_sensitive(False)
def launch_app(commandline, f): if f.query_exists(): args = [] for item in commandline.split(): if item in ["%U", "%u"]: args.append(f.get_uri()) elif item in ["%F", "%f"]: args.append(f.get_path()) else: args.append(item) commands = [args, ["flatpak-spawn", "--host"] + args] for cmd in commands: try: (pid, stdin, stdout, stderr) = GLib.spawn_async( cmd, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.STDOUT_TO_DEV_NULL, standard_input=False, standard_output=False, standard_error=False) GLib.spawn_close_pid(pid) break except Exception as e: Logger.error("ActionsMenu::launch_app(): %s", e)
def status_icon_activate(sender, *args): app = args[-1] if not app.current: return if app.password_dialog: app.password_dialog.present() return app.password_dialog = create_password_dialog( app.status_icon.get_property('tooltip_text'), app.status_icon.get_property('icon_name')) result = app.password_dialog.run() password = app.password_dialog.entry.get_text() app.password_dialog.destroy() app.password_dialog = None if result in [Gtk.ResponseType.REJECT, Gtk.ResponseType.DELETE_EVENT, Gtk.ResponseType.CANCEL]: return reply_argv = ['/usr/bin/pkexec', '/lib/systemd/systemd-reply-password', '1' if result == Gtk.ResponseType.OK else '0', app.socket] try: child = GLib.spawn_async_with_pipes(None, reply_argv, None, GLib.SpawnFlags.DO_NOT_REAP_CHILD) GLib.child_watch_add(child.child_pid, lambda pid, status: GLib.spawn_close_pid(pid)) with os.fdopen(child.standard_input, 'w') as child_stdin: child_stdin.write(password) except Exception as e: log('error replying password: {}', e)
def __init__(self, application): """ :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ utilities.assert_arg_type(application, Gtk.Application, arg_pos=1) self.application = application self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) if not has_vte: gui_utilities.show_dialog_error('RPC Terminal Is Unavailable', self.application.get_active_window(), 'VTE is not installed') return config = application.config self.terminal = Vte.Terminal() self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application) rpc = self.application.rpc config = { 'campaign_id': config['campaign_id'], 'campaign_name': config['campaign_name'], 'rpc_data': { 'address': (rpc.host, rpc.port), 'use_ssl': rpc.use_ssl, 'username': rpc.username, 'uri_base': rpc.uri_base, 'headers': rpc.headers } } module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + '..') * client_rpc.__name__.count('.')) module_path = os.path.normpath(module_path) python_command = [ "import {0}".format(client_rpc.__name__), "{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json_ex.dumps(config, pretty=False)) ] python_command = '; '.join(python_command) if hasattr(self.terminal, 'pty_new_sync'): # Vte._version >= 2.91 vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT) self.terminal.set_pty(vte_pty) self.terminal.connect('child-exited', lambda vt, status: self.rpc_window.window.destroy()) else: # Vte._version <= 2.90 vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT) self.terminal.set_pty_object(vte_pty) self.terminal.connect('child-exited', lambda vt: self.rpc_window.window.destroy()) child_pid, _, _, _ = GLib.spawn_async( working_directory=os.getcwd(), argv=[sys.executable, '-c', python_command], envp=[ 'PATH=' + os.environ['PATH'], 'PYTHONPATH=' + module_path, find.ENV_VAR + '=' + os.environ[find.ENV_VAR] ], flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD), child_setup=self._child_setup, user_data=vte_pty ) self.logger.info("vte spawned child process with pid: {0}".format(child_pid)) self.child_pid = child_pid self.terminal.watch_child(child_pid) GLib.spawn_close_pid(child_pid) self.rpc_window.window.show_all() self.rpc_window.child_pid = child_pid return
def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.builder('spinner1').stop() self.pid = None
def transmission_closed(pid, status, data): logging.info("Transmission exited with status %d, exiting.", status) GLib.spawn_close_pid(pid) loop.quit()
def qbittorrent_closed(pid, status, data): logging.info("Qbittorrent exited with status %d, exiting.", status) GLib.spawn_close_pid(pid) loop.quit()
def __init__(self, config, parent, application): """ :param dict config: The King Phisher client configuration. :param parent: The parent window for this object. :type parent: :py:class:`Gtk.Window` :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ assert isinstance(application, Gtk.Application) self.config = config self.parent = parent self.application = application self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) if not has_vte: gui_utilities.show_dialog_error('RPC Terminal Is Unavailable', parent, 'VTE is not installed') return self.terminal = Vte.Terminal() self.terminal.set_property('rewrap-on-resize', True) self.terminal.set_scroll_on_keystroke(True) self.rpc_window = RPCTerminalWindow(self.terminal, config, parent) rpc = self.parent.rpc config = { 'campaign_id': self.config['campaign_id'], 'campaign_name': self.config['campaign_name'], 'rpc_data': { 'address': (rpc.host, rpc.port), 'use_ssl': rpc.use_ssl, 'username': rpc.username, 'uri_base': rpc.uri_base, 'hmac_key': rpc.hmac_key } } module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + '..') * client_rpc.__name__.count('.')) module_path = os.path.normpath(module_path) python_command = [ "import {0}".format(client_rpc.__name__), "{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json.dumps(config)) ] python_command = '; '.join(python_command) if hasattr(self.terminal, 'pty_new_sync'): # Vte._version >= 2.91 vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT) self.terminal.set_pty(vte_pty) self.terminal.connect('child-exited', lambda vt, status: self.rpc_window.window.destroy()) else: # Vte._version <= 2.90 vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT) self.terminal.set_pty_object(vte_pty) self.terminal.connect('child-exited', lambda vt: self.rpc_window.window.destroy()) child_pid, _, _, _ = GLib.spawn_async( working_directory=os.getcwd(), argv=[utilities.which('python'), '-c', python_command], envp=['PYTHONPATH=' + module_path], flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD), child_setup=self._child_setup, user_data=vte_pty ) self.logger.info("vte spawned child process with pid: {0}".format(child_pid)) self.child_pid = child_pid self.terminal.watch_child(child_pid) GLib.spawn_close_pid(child_pid) self.rpc_window.window.show_all() self.rpc_window.child_pid = child_pid # automatically enter the password vte_pty_fd = vte_pty.get_fd() if len(select.select([vte_pty_fd], [], [], 1)[0]): os.write(vte_pty_fd, rpc.password + '\n') return
def __init__(self, config, parent, application): """ :param dict config: The King Phisher client configuration. :param parent: The parent window for this object. :type parent: :py:class:`Gtk.Window` :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ assert isinstance(application, Gtk.Application) self.config = config self.parent = parent self.application = application self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) if not has_vte: gui_utilities.show_dialog_error('RPC Terminal Is Unavailable', parent, 'VTE is not installed') return self.window = Gtk.ApplicationWindow(application=application) self.window.set_property('title', 'King Phisher RPC') self.window.set_transient_for(parent) self.window.set_destroy_with_parent(True) self.window.connect('destroy', self.signal_window_destroy) self.terminal = Vte.Terminal() self.terminal.set_property('rewrap-on-resize', True) self.terminal.set_scroll_on_keystroke(True) vbox = Gtk.VBox() self.window.add(vbox) vbox.pack_end(self.terminal, True, True, 0) action_group = Gtk.ActionGroup("rpc_terminal_window_actions") self._add_menu_actions(action_group) uimanager = self._create_ui_manager() uimanager.insert_action_group(action_group) menubar = uimanager.get_widget("/MenuBar") vbox.pack_start(menubar, False, False, 0) rpc = self.parent.rpc config = {} config['campaign_id'] = self.config['campaign_id'] config['campaign_name'] = self.config['campaign_name'] config['rpc_data'] = { 'address': (rpc.host, rpc.port), 'use_ssl': rpc.use_ssl, 'username': rpc.username, 'uri_base': rpc.uri_base, 'hmac_key': rpc.hmac_key, } module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + '..') * client_rpc.__name__.count('.')) module_path = os.path.normpath(module_path) python_command = [ "import {0}".format(client_rpc.__name__), "{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json.dumps(config)) ] python_command = '; '.join(python_command) if hasattr(self.terminal, 'pty_new_sync'): # Vte._version >= 2.91 vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT) self.terminal.set_pty(vte_pty) self.terminal.connect('child-exited', lambda vt, status: self.window.destroy()) else: # Vte._version <= 2.90 vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT) self.terminal.set_pty_object(vte_pty) self.terminal.connect('child-exited', lambda vt: self.window.destroy()) child_pid, _, _, _ = GLib.spawn_async( working_directory=os.getcwd(), argv=[utilities.which('python'), '-c', python_command], envp=['PYTHONPATH=' + module_path], flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD), child_setup=self._child_setup, user_data=vte_pty ) self.logger.info("vte spawned child process with pid: {0}".format(child_pid)) self.child_pid = child_pid self.terminal.watch_child(child_pid) GLib.spawn_close_pid(child_pid) self.window.show_all() # automatically enter the password vte_pty_fd = vte_pty.get_fd() if len(select.select([vte_pty_fd], [], [], 1)[0]): os.write(vte_pty_fd, rpc.password + '\n') return
def __init__(self, application): """ :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ utilities.assert_arg_type(application, Gtk.Application, arg_pos=1) self.application = application self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__) if not has_vte: gui_utilities.show_dialog_error( 'RPC Terminal Is Unavailable', self.application.get_active_window(), 'VTE is not installed') return config = application.config self.terminal = Vte.Terminal() self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application) rpc = self.application.rpc config = { 'campaign_id': config['campaign_id'], 'campaign_name': config['campaign_name'], 'rpc_data': { 'address': (rpc.host, rpc.port), 'use_ssl': rpc.use_ssl, 'username': rpc.username, 'uri_base': rpc.uri_base, 'headers': rpc.headers } } module_path = os.path.dirname(client_rpc.__file__) + ( (os.path.sep + '..') * client_rpc.__name__.count('.')) module_path = os.path.normpath(module_path) python_command = [ "import {0}".format(client_rpc.__name__), "{0}.vte_child_routine('{1}')".format( client_rpc.__name__, serializers.JSON.dumps(config, pretty=False)) ] python_command = '; '.join(python_command) if hasattr(self.terminal, 'pty_new_sync'): # Vte._version >= 2.91 vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT) self.terminal.set_pty(vte_pty) self.terminal.connect( 'child-exited', lambda vt, status: self.rpc_window.window.destroy()) else: # Vte._version <= 2.90 vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT) self.terminal.set_pty_object(vte_pty) self.terminal.connect('child-exited', lambda vt: self.rpc_window.window.destroy()) child_pid, _, _, _ = GLib.spawn_async( working_directory=os.getcwd(), argv=[sys.executable, '-c', python_command], envp=[ 'DISPLAY=' + os.environ['DISPLAY'], 'PATH=' + os.environ['PATH'], 'PYTHONPATH=' + module_path, find.ENV_VAR + '=' + os.environ[find.ENV_VAR] ], flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD), child_setup=self._child_setup, user_data=vte_pty) self.logger.info( "vte spawned child process with pid: {0}".format(child_pid)) self.child_pid = child_pid self.terminal.watch_child(child_pid) GLib.spawn_close_pid(child_pid) self.rpc_window.window.show_all() self.rpc_window.child_pid = child_pid return
def __init__(self, application): """ :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ assert isinstance(application, Gtk.Application) self.application = application self.logger = logging.getLogger("KingPhisher.Client." + self.__class__.__name__) if not has_vte: gui_utilities.show_dialog_error( "RPC Terminal Is Unavailable", self.application.get_active_window(), "VTE is not installed" ) return config = application.config self.terminal = Vte.Terminal() self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application) rpc = self.application.rpc config = { "campaign_id": config["campaign_id"], "campaign_name": config["campaign_name"], "rpc_data": { "address": (rpc.host, rpc.port), "use_ssl": rpc.use_ssl, "username": rpc.username, "uri_base": rpc.uri_base, "headers": rpc.headers, "hmac_key": rpc.hmac_key, }, } module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + "..") * client_rpc.__name__.count(".")) module_path = os.path.normpath(module_path) python_command = [ "import {0}".format(client_rpc.__name__), "{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json_ex.dumps(config, pretty=False)), ] python_command = "; ".join(python_command) if hasattr(self.terminal, "pty_new_sync"): # Vte._version >= 2.91 vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT) self.terminal.set_pty(vte_pty) self.terminal.connect("child-exited", lambda vt, status: self.rpc_window.window.destroy()) else: # Vte._version <= 2.90 vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT) self.terminal.set_pty_object(vte_pty) self.terminal.connect("child-exited", lambda vt: self.rpc_window.window.destroy()) child_pid, _, _, _ = GLib.spawn_async( working_directory=os.getcwd(), argv=[sys.executable, "-c", python_command], envp=[ "PATH=" + os.environ["PATH"], "PYTHONPATH=" + module_path, find.ENV_VAR + "=" + os.environ[find.ENV_VAR], ], flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD), child_setup=self._child_setup, user_data=vte_pty, ) self.logger.info("vte spawned child process with pid: {0}".format(child_pid)) self.child_pid = child_pid self.terminal.watch_child(child_pid) GLib.spawn_close_pid(child_pid) self.rpc_window.window.show_all() self.rpc_window.child_pid = child_pid return
def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.progress.set_fraction(0.0)