]> glassweightruler.freedombox.rocks Git - waydroid.git/blob - tools/actions/initializer.py
debian: Use new polkitd package
[waydroid.git] / tools / actions / initializer.py
1 # Copyright 2021 Erfan Abdi
2 # SPDX-License-Identifier: GPL-3.0-or-later
3 import logging
4 import os
5 from tools import helpers
6 import tools.config
7
8 import sys
9 import threading
10 import multiprocessing
11 import select
12 import queue
13 import time
14 import dbus
15 import dbus.service
16 from gi.repository import GLib
17
18 def is_initialized(args):
19 return os.path.isfile(args.config) and os.path.isdir(tools.config.defaults["rootfs"])
20
21 def get_vendor_type(args):
22 vndk_str = helpers.props.host_get(args, "ro.vndk.version")
23 ret = "MAINLINE"
24 if vndk_str != "":
25 vndk = int(vndk_str)
26 if vndk > 31:
27 vndk -= 1 # 12L -> Halium 12
28 if vndk > 19:
29 ret = "HALIUM_" + str(vndk - 19)
30
31 return ret
32
33 def setup_config(args):
34 cfg = tools.config.load(args)
35 args.arch = helpers.arch.host()
36 cfg["waydroid"]["arch"] = args.arch
37
38 preinstalled_images_paths = tools.config.defaults["preinstalled_images_paths"]
39 if not args.images_path:
40 for preinstalled_images in preinstalled_images_paths:
41 if os.path.isdir(preinstalled_images):
42 if os.path.isfile(preinstalled_images + "/system.img") and os.path.isfile(preinstalled_images + "/vendor.img"):
43 args.images_path = preinstalled_images
44 break
45 else:
46 logging.warning("Found directory {} but missing system or vendor image, ignoring...".format(preinstalled_images))
47
48 if not args.images_path:
49 args.images_path = tools.config.defaults["images_path"]
50 cfg["waydroid"]["images_path"] = args.images_path
51
52 channels_cfg = tools.config.load_channels()
53 if not args.system_channel:
54 args.system_channel = channels_cfg["channels"]["system_channel"]
55 if not args.vendor_channel:
56 args.vendor_channel = channels_cfg["channels"]["vendor_channel"]
57 if not args.rom_type:
58 args.rom_type = channels_cfg["channels"]["rom_type"]
59 if not args.system_type:
60 args.system_type = channels_cfg["channels"]["system_type"]
61
62 if not args.system_channel or not args.vendor_channel:
63 logging.error("ERROR: You must provide 'System OTA' and 'Vendor OTA' URLs.")
64 return False
65
66 args.system_ota = args.system_channel + "/" + args.rom_type + \
67 "/waydroid_" + args.arch + "/" + args.system_type + ".json"
68 system_request = helpers.http.retrieve(args.system_ota)
69 if system_request[0] != 200:
70 if args.images_path not in preinstalled_images_paths:
71 raise ValueError(
72 "Failed to get system OTA channel: {}, error: {}".format(args.system_ota, system_request[0]))
73 else:
74 args.system_ota = "None"
75
76 device_codename = helpers.props.host_get(args, "ro.product.device")
77 args.vendor_type = None
78 for vendor in [device_codename, get_vendor_type(args)]:
79 vendor_ota = args.vendor_channel + "/waydroid_" + \
80 args.arch + "/" + vendor.replace(" ", "_") + ".json"
81 vendor_request = helpers.http.retrieve(vendor_ota)
82 if vendor_request[0] == 200:
83 args.vendor_type = vendor
84 args.vendor_ota = vendor_ota
85 break
86
87 if not args.vendor_type:
88 if args.images_path not in preinstalled_images_paths:
89 raise ValueError(
90 "Failed to get vendor OTA channel: {}".format(vendor_ota))
91 else:
92 args.vendor_ota = "None"
93 args.vendor_type = get_vendor_type(args)
94
95 if args.system_ota != cfg["waydroid"].get("system_ota"):
96 cfg["waydroid"]["system_datetime"] = tools.config.defaults["system_datetime"]
97 if args.vendor_ota != cfg["waydroid"].get("vendor_ota"):
98 cfg["waydroid"]["vendor_datetime"] = tools.config.defaults["vendor_datetime"]
99
100 cfg["waydroid"]["vendor_type"] = args.vendor_type
101 cfg["waydroid"]["system_ota"] = args.system_ota
102 cfg["waydroid"]["vendor_ota"] = args.vendor_ota
103 helpers.drivers.setupBinderNodes(args)
104 cfg["waydroid"]["binder"] = args.BINDER_DRIVER
105 cfg["waydroid"]["vndbinder"] = args.VNDBINDER_DRIVER
106 cfg["waydroid"]["hwbinder"] = args.HWBINDER_DRIVER
107 tools.config.save(args, cfg)
108 return True
109
110 def init(args):
111 if not is_initialized(args) or args.force:
112 initializer_service = None
113 try:
114 initializer_service = tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer")
115 except dbus.DBusException:
116 pass
117 if not setup_config(args):
118 return
119 status = "STOPPED"
120 if os.path.exists(tools.config.defaults["lxc"] + "/waydroid"):
121 status = helpers.lxc.status(args)
122 if status != "STOPPED":
123 logging.info("Stopping container")
124 try:
125 container = tools.helpers.ipc.DBusContainerService()
126 args.session = container.GetSession()
127 container.Stop(False)
128 except Exception as e:
129 logging.debug(e)
130 tools.actions.container_manager.stop(args)
131 if args.images_path not in tools.config.defaults["preinstalled_images_paths"]:
132 helpers.images.get(args)
133 else:
134 helpers.images.remove_overlay(args)
135 if not os.path.isdir(tools.config.defaults["rootfs"]):
136 os.mkdir(tools.config.defaults["rootfs"])
137 if not os.path.isdir(tools.config.defaults["overlay"]):
138 os.mkdir(tools.config.defaults["overlay"])
139 os.mkdir(tools.config.defaults["overlay"]+"/vendor")
140 if not os.path.isdir(tools.config.defaults["overlay_rw"]):
141 os.mkdir(tools.config.defaults["overlay_rw"])
142 os.mkdir(tools.config.defaults["overlay_rw"]+"/system")
143 os.mkdir(tools.config.defaults["overlay_rw"]+"/vendor")
144 helpers.drivers.probeAshmemDriver(args)
145 helpers.lxc.setup_host_perms(args)
146 helpers.lxc.set_lxc_config(args)
147 helpers.lxc.make_base_props(args)
148 if status != "STOPPED":
149 logging.info("Starting container")
150 try:
151 container.Start(args.session)
152 except Exception as e:
153 logging.debug(e)
154 logging.error("Failed to restart container. Please do so manually.")
155
156 if "running_init_in_service" not in args or not args.running_init_in_service:
157 try:
158 if initializer_service:
159 initializer_service.Done()
160 except dbus.DBusException:
161 pass
162 else:
163 logging.info("Already initialized")
164
165 def wait_for_init(args):
166 helpers.ipc.create_channel("remote_init_output")
167
168 mainloop = GLib.MainLoop()
169 dbus_obj = DbusInitializer(mainloop, dbus.SystemBus(), '/Initializer', args)
170 mainloop.run()
171
172 # After init
173 dbus_obj.remove_from_connection()
174
175 class DbusInitializer(dbus.service.Object):
176 def __init__(self, looper, bus, object_path, args):
177 self.args = args
178 self.looper = looper
179 dbus.service.Object.__init__(self, bus, object_path)
180
181 @dbus.service.method("id.waydro.Initializer", in_signature='a{ss}', out_signature='', sender_keyword="sender", connection_keyword="conn")
182 def Init(self, params, sender=None, conn=None):
183 channels_cfg = tools.config.load_channels()
184 no_auth = params["system_channel"] == channels_cfg["channels"]["system_channel"] and \
185 params["vendor_channel"] == channels_cfg["channels"]["vendor_channel"]
186 if no_auth or ensure_polkit_auth(sender, conn, "id.waydro.Initializer.Init"):
187 threading.Thread(target=remote_init_server, args=(self.args, params)).start()
188 else:
189 raise PermissionError("Polkit: Authentication failed")
190
191 @dbus.service.method("id.waydro.Initializer", in_signature='', out_signature='')
192 def Done(self):
193 if is_initialized(self.args):
194 self.looper.quit()
195
196 def ensure_polkit_auth(sender, conn, privilege):
197 dbus_info = dbus.Interface(conn.get_object("org.freedesktop.DBus", "/org/freedesktop/DBus/Bus", False), "org.freedesktop.DBus")
198 pid = dbus_info.GetConnectionUnixProcessID(sender)
199 polkit = dbus.Interface(dbus.SystemBus().get_object("org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", False), "org.freedesktop.PolicyKit1.Authority")
200 try:
201 (is_auth, _, _) = polkit.CheckAuthorization(
202 ("unix-process", {
203 "pid": dbus.UInt32(pid, variant_level=1),
204 "start-time": dbus.UInt64(0, variant_level=1)}),
205 privilege, {"AllowUserInteraction": "true"},
206 dbus.UInt32(1),
207 "",
208 timeout=300)
209 return is_auth
210 except dbus.DBusException:
211 raise PermissionError("Polkit: Authentication timed out")
212
213 def background_remote_init_process(args):
214 with helpers.ipc.open_channel("remote_init_output", "wb") as channel_out:
215 class StdoutRedirect(logging.StreamHandler):
216 def write(self, s):
217 channel_out.write(str.encode(s))
218 def flush(self):
219 pass
220 def emit(self, record):
221 if record.levelno >= logging.INFO:
222 self.write(self.format(record) + self.terminator)
223
224 out = StdoutRedirect()
225 sys.stdout = sys.stderr = out
226 logging.getLogger().addHandler(out)
227
228 ctl_queue = queue.Queue()
229 def try_init(args):
230 try:
231 init(args)
232 except Exception as e:
233 print(str(e))
234 finally:
235 ctl_queue.put(0)
236
237 def poll_pipe():
238 poller = select.poll()
239 poller.register(channel_out, select.POLLERR)
240 poller.poll()
241 # When reaching here the client was terminated
242 ctl_queue.put(0)
243
244 init_thread = threading.Thread(target=try_init, args=(args,))
245 init_thread.daemon = True
246 init_thread.start()
247
248 poll_thread = threading.Thread(target=poll_pipe)
249 poll_thread.daemon = True
250 poll_thread.start()
251
252 # Join any one of the two threads
253 # Then exit the subprocess to kill the remaining thread.
254 # Can you believe this is the only way to kill a thread in python???
255 ctl_queue.get()
256
257 sys.stdout = sys.__stdout__
258 sys.stderr = sys.__stderr__
259 logging.getLogger().removeHandler(out)
260
261 def remote_init_server(args, params):
262 args.force = True
263 args.images_path = ""
264 args.rom_type = ""
265 args.system_channel = params["system_channel"]
266 args.vendor_channel = params["vendor_channel"]
267 args.system_type = params["system_type"]
268 args.running_init_in_service = True
269
270 p = multiprocessing.Process(target=background_remote_init_process, args=(args,))
271 p.daemon = True
272 p.start()
273 p.join()
274
275 def remote_init_client(args):
276 # Local imports cause Gtk is intrusive
277 import gi
278 gi.require_version("Gtk", "3.0")
279 from gi.repository import Gtk
280
281 bus = dbus.SystemBus()
282
283 if is_initialized(args):
284 try:
285 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
286 except dbus.DBusException:
287 pass
288 return
289
290 def notify_and_quit(caller):
291 if is_initialized(args):
292 try:
293 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
294 except dbus.DBusException:
295 pass
296 GLib.idle_add(Gtk.main_quit)
297
298 class WaydroidInitWindow(Gtk.Window):
299 def __init__(self):
300 super().__init__(title="Initialize Waydroid")
301 channels_cfg = tools.config.load_channels()
302
303 self.set_default_size(600, 250)
304 self.set_icon_name("waydroid")
305
306 grid = Gtk.Grid(row_spacing=6, column_spacing=6, margin=10, column_homogeneous=True)
307 grid.set_hexpand(True)
308 grid.set_vexpand(True)
309 self.add(grid)
310
311 sysOtaLabel = Gtk.Label("System OTA")
312 sysOtaEntry = Gtk.Entry()
313 sysOtaEntry.set_text(channels_cfg["channels"]["system_channel"])
314 grid.attach(sysOtaLabel, 0, 0, 1, 1)
315 grid.attach_next_to(sysOtaEntry ,sysOtaLabel, Gtk.PositionType.RIGHT, 2, 1)
316 self.sysOta = sysOtaEntry.get_buffer()
317
318 vndOtaLabel = Gtk.Label("Vendor OTA")
319 vndOtaEntry = Gtk.Entry()
320 vndOtaEntry.set_text(channels_cfg["channels"]["vendor_channel"])
321 grid.attach(vndOtaLabel, 0, 1, 1, 1)
322 grid.attach_next_to(vndOtaEntry, vndOtaLabel, Gtk.PositionType.RIGHT, 2, 1)
323 self.vndOta = vndOtaEntry.get_buffer()
324
325 sysTypeLabel = Gtk.Label("Android Type")
326 sysTypeCombo = Gtk.ComboBoxText()
327 sysTypeCombo.set_entry_text_column(0)
328 for t in ["VANILLA", "GAPPS"]:
329 sysTypeCombo.append_text(t)
330 sysTypeCombo.set_active(0)
331 grid.attach(sysTypeLabel, 0, 2, 1, 1)
332 grid.attach_next_to(sysTypeCombo, sysTypeLabel, Gtk.PositionType.RIGHT, 2, 1)
333 self.sysType = sysTypeCombo
334
335 downloadBtn = Gtk.Button("Download")
336 downloadBtn.connect("clicked", self.on_download_btn_clicked)
337 grid.attach(downloadBtn, 1,3,1,1)
338 self.downloadBtn = downloadBtn
339
340 doneBtn = Gtk.Button("Done")
341 doneBtn.connect("clicked", lambda x: self.destroy())
342 doneBtn.get_style_context().add_class('suggested-action')
343 grid.attach_next_to(doneBtn, downloadBtn, Gtk.PositionType.RIGHT, 1, 1)
344 self.doneBtn = doneBtn
345
346 outScrolledWindow = Gtk.ScrolledWindow()
347 outScrolledWindow.set_hexpand(True)
348 outScrolledWindow.set_vexpand(True)
349 outTextView = Gtk.TextView()
350 outTextView.set_property('editable', False)
351 outTextView.set_property('cursor-visible', False)
352 outScrolledWindow.add(outTextView)
353 grid.attach(outScrolledWindow, 0, 4, 3, 1)
354 self.outScrolledWindow = outScrolledWindow
355 self.outTextView = outTextView
356 self.outBuffer = outTextView.get_buffer()
357 self.outBuffer.create_mark("end", self.outBuffer.get_end_iter(), False)
358
359 self.open_channel = None
360
361 def scroll_to_bottom(self):
362 self.outTextView.scroll_mark_onscreen(self.outBuffer.get_mark("end"))
363
364 def on_download_btn_clicked(self, widget):
365 widget.set_sensitive(False)
366 self.doneBtn.hide()
367 self.outTextView.show()
368 init_params = (self.sysOta.get_text(), self.vndOta.get_text(), self.sysType.get_active_text())
369 init_runner = threading.Thread(target=self.run_init, args=init_params)
370 init_runner.daemon = True
371 init_runner.start()
372
373 def run_init(self, systemOta, vendorOta, systemType):
374 def draw_sync(s):
375 if s.startswith('\r'):
376 last = self.outBuffer.get_iter_at_line(self.outBuffer.get_line_count()-1)
377 last.backward_char()
378 self.outBuffer.delete(last, self.outBuffer.get_end_iter())
379 self.outBuffer.insert(self.outBuffer.get_end_iter(), s)
380 self.scroll_to_bottom()
381 def draw(s):
382 GLib.idle_add(draw_sync, s)
383
384 if self.open_channel is not None:
385 self.open_channel.close()
386 # Wait for other end to reset
387 time.sleep(1)
388
389 draw("Waiting for waydroid container service...\n")
390 try:
391 params = {
392 "system_channel": self.sysOta.get_text(),
393 "vendor_channel": self.vndOta.get_text(),
394 "system_type": self.sysType.get_active_text()
395 }
396 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Init(params, timeout=310)
397 except dbus.DBusException as e:
398 if e.get_dbus_name() == "org.freedesktop.DBus.Python.PermissionError":
399 draw(e.get_dbus_message().splitlines()[-1] + "\n")
400 else:
401 draw("The waydroid container service is not listening\n")
402 GLib.idle_add(self.downloadBtn.set_sensitive, True)
403 return
404
405 with helpers.ipc.open_channel("remote_init_output", "rb") as channel:
406 self.open_channel = channel
407 GLib.idle_add(self.downloadBtn.set_sensitive, True)
408 line = ""
409 try:
410 while True:
411 data = channel.read(1)
412 if len(data) == 0:
413 draw(line)
414 break
415 c = data.decode()
416 if c == '\r':
417 draw(line)
418 line = c
419 else:
420 line += c
421 if c == '\n':
422 draw(line)
423 line = ""
424 except:
425 draw("\nInterrupted\n")
426
427 if is_initialized(args):
428 GLib.idle_add(self.doneBtn.show)
429 draw("Done\n")
430
431
432 GLib.set_prgname("Waydroid")
433 win = WaydroidInitWindow()
434 win.connect("destroy", notify_and_quit)
435
436 win.show_all()
437 win.outTextView.hide()
438 win.doneBtn.hide()
439
440 Gtk.main()