Debian Codegraph @

src/client/cockpit-client

raw
1 #!/usr/bin/env python3
2
3 #
4 # Copyright (C) 2018-2021 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 import configparser
9 import ctypes
10 import logging
11 import os
12 import signal
13 import subprocess
14 import sys
15 import tempfile
16 import textwrap
17
18 import gi
19
20 gi.require_version("Gtk", "4.0")
21 from gi.repository import GLib, Gio, Gtk # ruff: ignore[unsorted-imports, module-import-not-at-top-of-file]
22
23 gi.require_version("WebKit", "6.0")
24 from gi.repository import WebKit # ruff: ignore[module-import-not-at-top-of-file]
25
26 gi.require_version("Adw", "1")
27 from gi.repository import Adw # ruff: ignore[module-import-not-at-top-of-file]
28
29 libexecdir = os.path.realpath(__file__ + '/..')
30
31 sys_prctl = ctypes.CDLL(None).prctl
32
33
34 def prctl(*args):
35 if sys_prctl(*args) != 0:
36 raise Exception('prctl() failed')
37
38
39 def get_user_state_dir():
40 try:
41 # GLib ≥ 2.72
42 return GLib.get_user_state_dir()
43 except AttributeError:
44 try:
45 return os.environ["XDG_STATE_HOME"]
46 except KeyError:
47 return os.path.expanduser("~/.local/share")
48
49
50 SET_PDEATHSIG = 1
51
52
53 @Gtk.Template(filename=f'{libexecdir}/cockpit-client.ui')
54 class CockpitClientWindow(Gtk.ApplicationWindow):
55 __gtype_name__ = 'CockpitClientWindow'
56 webview_container = Gtk.Template.Child()
57 title = Gtk.Template.Child()
58
59 def __init__(self, app, uri):
60 super().__init__(application=app)
61
62 self.webview = WebKit.WebView(network_session=app.network_session, vexpand=True, hexpand=True)
63 self.webview_container.append(self.webview)
64
65 self.add_action_entries([
66 ('reload', self.reload),
67 ('reload-bypass-cache', self.reload_bypass_cache),
68 ('go-back', self.go_back),
69 ('go-forward', self.go_forward),
70 ('zoom', self.zoom, 's'),
71 ('open-inspector', self.open_inspector),
72 ('run-js', self.run_js, 's', '""'),
73 ])
74 self.lookup_action('run-js').set_enabled(app.enable_run_js)
75
76 self.webview.get_settings().set_enable_developer_extras(enabled=True)
77 self.webview.connect('decide-policy', self.decide_policy)
78 self.webview.load_uri(uri)
79
80 history = self.webview.get_back_forward_list()
81 history.connect('changed', self.history_changed)
82 self.history_changed()
83
84 self.webview.connect('notify::title', self.update_subtitle)
85
86 if app.no_ui:
87 self.set_titlebar(None)
88 self.webview.bind_property('title', self, 'title')
89
90 def history_changed(self, *args):
91 self.lookup_action('go-back').set_enabled(self.webview.can_go_back())
92 self.lookup_action('go-forward').set_enabled(self.webview.can_go_forward())
93
94 def update_subtitle(self, webview, *args):
95 title = webview.get_title() or "Loading..."
96 self.title.set_label(title)
97
98 def reload(self, *args):
99 self.webview.reload()
100
101 def reload_bypass_cache(self, *args):
102 self.webview.reload_bypass_cache()
103
104 def go_back(self, *args):
105 self.webview.go_back()
106
107 def go_forward(self, *args):
108 self.webview.go_forward()
109
110 def decide_policy(self, _view, decision, decision_type):
111 if decision_type == WebKit.PolicyDecisionType.NEW_WINDOW_ACTION:
112 uri = decision.get_navigation_action().get_request().get_uri()
113 if uri.startswith('http://127'):
114 logging.error('warning: no support for pop-ups')
115 else:
116 launcher = Gtk.UriLauncher.new(uri)
117 launcher.launch(self, None, None, None)
118
119 decision.ignore()
120 return True
121
122 return False
123
124 def zoom(self, _action, parameter, *_unused):
125 current = self.webview.get_zoom_level()
126 factors = {'in': current * 1.1, 'default': 1.0, 'out': current * 0.9}
127 self.webview.set_zoom_level(factors[parameter.get_string()])
128
129 def open_inspector(self, *_unused):
130 self.webview.get_inspector().show()
131
132 def run_js(self, action, parameter, *_unused):
133 """Run given JavaScript code in the current page/context
134
135 The JS code has to return a scalar value immediately. To process asynchronous
136 actions, this function installs signal handlers to wait until the code calls
137
138 window.webkit.messageHandlers.result.postMessage("some string")
139
140 or a page load happens.
141
142 This is because a page load (as reaction to clicking a link or other action)
143 impredictably and immediately stops the current context and execution of the
144 given JS code, with no reliable way of returning a result value.
145
146 The postMessage() string is returned via the action state.
147 If a page load happens instead, the action state will be "page-load".
148 If the JS code throws an error, the action state gets set to the error message.
149 """
150 def set_result(result):
151 action.set_state(GLib.Variant.new_string(result))
152 print(f"run-js async result: {result}")
153 self.webview.disconnect(on_load_handler)
154 uc_manager.disconnect(on_result_handler)
155 uc_manager.unregister_script_message_handler("result")
156
157 def run_js_ready(webview, result, _user_data):
158 try:
159 js_res = webview.evaluate_javascript_finish(result)
160 print(f"run-js return value: {js_res.to_json(2)}")
161 except GLib.GError as e:
162 sys.stderr.write(f"run-js error: {e.message}\n")
163 set_result(str(e))
164
165 # zero the current state, to ensure that the result triggers an Actions.Changed signal
166 action.set_state(GLib.Variant.new_string(""))
167
168 uc_manager = self.webview.get_user_content_manager()
169 on_result_handler = uc_manager.connect(
170 "script-message-received::result",
171 lambda _mgr, result: set_result(result.to_string()))
172 uc_manager.register_script_message_handler("result")
173
174 # wait for loads to complete, to avoid races and ensure that it did not fail
175 on_load_handler = self.webview.connect(
176 "load-changed",
177 lambda webview, event: set_result("page-load") if event == WebKit.LoadEvent.FINISHED else None)
178
179 self.webview.evaluate_javascript(parameter.get_string(), len(parameter.get_string()),
180 None, None, None, run_js_ready, None)
181
182
183 class CockpitClient(Gtk.Application):
184 def __init__(self):
185 super().__init__(application_id='org.cockpit_project.CockpitClient')
186
187 self.add_main_option('no-ui', 0, GLib.OptionFlags.NONE, GLib.OptionArg.NONE,
188 'Show only a window with a webview')
189 self.add_main_option('external-ws', 0, GLib.OptionFlags.NONE, GLib.OptionArg.STRING,
190 'Connect to existing cockpit-ws on the given URL')
191 self.add_main_option('disable-uniqueness', 0, GLib.OptionFlags.NONE, GLib.OptionArg.NONE,
192 'Disable GApplication single-instance mode')
193 self.add_main_option('enable-run-js', 0, GLib.OptionFlags.HIDDEN, GLib.OptionArg.NONE,
194 'Enable run-js action for testing')
195 self.add_main_option('wildly-insecure', 0, GLib.OptionFlags.HIDDEN, GLib.OptionArg.NONE,
196 '***DANGEROUS*** Allow anyone to use your ssh credentials')
197
198 def do_startup(self):
199 Gtk.Application.do_startup(self)
200
201 Adw.StyleManager.get_default().set_color_scheme(Adw.ColorScheme.PREFER_LIGHT)
202
203 # .add_action_entries() binding is broken for GApplication
204 # https://gitlab.gnome.org/GNOME/pygobject/-/issues/426
205 Gio.ActionMap.add_action_entries(self, [
206 ('new-window', self.new_window),
207 ('quit', self.quit_action),
208 ('open-path', self.open_path, 's'),
209 ])
210
211 self.set_accels_for_action("app.new-window", ["<Ctrl>N"])
212 self.set_accels_for_action("win.reload", ["<Primary>r"])
213 self.set_accels_for_action("win.reload-bypass-cache", ["<Primary><Shift>r"])
214 self.set_accels_for_action("win.go-back", ["<Alt>Left"])
215 self.set_accels_for_action("win.go-forward", ["<Alt>Right"])
216 self.set_accels_for_action("win.zoom::in", ["<Primary>equal"])
217 self.set_accels_for_action("win.zoom::out", ["<Primary>minus"])
218 self.set_accels_for_action("win.zoom::default", ["<Primary>0"])
219 self.set_accels_for_action("win.open-inspector", ["<Primary><Shift>i", "F12"])
220
221 self.network_session = WebKit.NetworkSession.get_default()
222 self.network_session.set_proxy_settings(WebKit.NetworkProxyMode.NO_PROXY)
223
224 cookiesFile = os.path.join(get_user_state_dir(), "cockpit-client", "cookies.txt")
225 cookie_manager = self.network_session.get_cookie_manager()
226 cookie_manager.set_persistent_storage(cookiesFile, WebKit.CookiePersistentStorage.TEXT)
227
228 self.uri = self.ws.start()
229
230 def new_window(self, *args):
231 self.activate()
232
233 def quit_action(self, *args):
234 self.quit()
235
236 def open_path(self, action, parameter, *args):
237 CockpitClientWindow(self, self.uri + parameter.get_string()).present()
238
239 def do_activate(self):
240 CockpitClientWindow(self, self.uri).present()
241
242 def do_shutdown(self):
243 self.ws.stop()
244
245 Gtk.Application.do_shutdown(self)
246
247 def do_handle_local_options(self, options):
248 self.no_ui = options.lookup_value('no-ui') is not None
249
250 if options.lookup_value('disable-uniqueness'):
251 self.set_flags(Gio.ApplicationFlags.NON_UNIQUE)
252
253 self.enable_run_js = bool(options.lookup_value('enable-run-js'))
254
255 if flatpak_id := os.getenv('FLATPAK_ID'):
256 self.set_application_id(flatpak_id)
257
258 if external_ws := options.lookup_value('external-ws'):
259 self.ws = ExternalCockpitWs(external_ws.get_string())
260
261 elif self.safely_sandboxed() or options.lookup_value('wildly-insecure'):
262 self.ws = InternalCockpitWs()
263
264 else:
265 logging.error('Unable to detect any sandboxing: refusing to spawn cockpit-ws')
266 return 1
267
268 return -1
269
270 def safely_sandboxed(self):
271 flatpak_info = configparser.ConfigParser()
272
273 if not flatpak_info.read('/.flatpak-info'):
274 return False
275
276 shared = flatpak_info.get('Context', 'Shared', fallback='').lower().split(';')
277 if 'network' in shared:
278 return False
279
280 return True
281
282
283 class ExternalCockpitWs:
284 def __init__(self, uri):
285 self.uri = uri
286
287 def start(self):
288 return self.uri
289
290 def stop(self):
291 pass
292
293
294 class InternalCockpitWs:
295 def start(self):
296 self.write_config()
297 host = '127.0.0.90'
298 port = '9090'
299 self.ws = subprocess.Popen(
300 [f'{libexecdir}/cockpit-ws', f'--address={host}', f'--port={port}'],
301 preexec_fn=self.preexec_fn
302 )
303
304 return f'http://{host}:{port}/'
305
306 def preexec_fn(self):
307 os.environ['XDG_CONFIG_DIRS'] = self.config_dir.name
308 prctl(SET_PDEATHSIG, signal.SIGKILL)
309
310 def stop(self):
311 self.ws.kill()
312 self.config_dir.cleanup()
313
314 def write_config(self):
315 self.config_dir = tempfile.TemporaryDirectory(prefix='cockpit-client-', suffix='-etc')
316 os.mkdir(f'{self.config_dir.name}/cockpit')
317 with open(f'{self.config_dir.name}/cockpit/cockpit.conf', 'x') as cockpit_conf:
318 # avoid putting strings here that ought to be translated
319 config = """
320 # dynamically generated by cockpit-client
321 [WebService]
322 X-For-CockpitClient = true
323 LoginTo = true
324
325 [Ssh-Login]
326 Command = /usr/bin/env python3 -m cockpit.beiboot
327 """
328
329 cockpit_conf.write(textwrap.dedent(config))
330
331
332 if __name__ == "__main__":
333 app = CockpitClient()
334 app.run(sys.argv)