1 # Copyright 2021 Erfan Abdi
2 # SPDX-License-Identifier: GPL-3.0-or-later
5 from tools
import helpers
10 import multiprocessing
16 from gi
.repository
import GLib
18 def is_initialized(args
):
19 return os
.path
.isfile(args
.config
) and os
.path
.isdir(tools
.config
.defaults
["rootfs"])
21 def get_vendor_type(args
):
22 vndk_str
= helpers
.props
.host_get(args
, "ro.vndk.version")
27 ret
= "HALIUM_" + str(vndk
- 19)
31 def setup_config(args
):
32 cfg
= tools
.config
.load(args
)
33 args
.arch
= helpers
.arch
.host()
34 cfg
["waydroid"]["arch"] = args
.arch
36 preinstalled_images_paths
= tools
.config
.defaults
["preinstalled_images_paths"]
37 if not args
.images_path
:
38 for preinstalled_images
in preinstalled_images_paths
:
39 if os
.path
.isdir(preinstalled_images
):
40 if os
.path
.isfile(preinstalled_images
+ "/system.img") and os
.path
.isfile(preinstalled_images
+ "/vendor.img"):
41 args
.images_path
= preinstalled_images
44 logging
.warning("Found directory {} but missing system or vendor image, ignoring...".format(preinstalled_images
))
46 if not args
.images_path
:
47 args
.images_path
= tools
.config
.defaults
["images_path"]
48 cfg
["waydroid"]["images_path"] = args
.images_path
50 channels_cfg
= tools
.config
.load_channels()
51 if not args
.system_channel
:
52 args
.system_channel
= channels_cfg
["channels"]["system_channel"]
53 if not args
.vendor_channel
:
54 args
.vendor_channel
= channels_cfg
["channels"]["vendor_channel"]
56 args
.rom_type
= channels_cfg
["channels"]["rom_type"]
57 if not args
.system_type
:
58 args
.system_type
= channels_cfg
["channels"]["system_type"]
60 args
.system_ota
= args
.system_channel
+ "/" + args
.rom_type
+ \
61 "/waydroid_" + args
.arch
+ "/" + args
.system_type
+ ".json"
62 system_request
= helpers
.http
.retrieve(args
.system_ota
)
63 if system_request
[0] != 200:
64 if args
.images_path
not in preinstalled_images_paths
:
66 "Failed to get system OTA channel: {}, error: {}".format(args
.system_ota
, system_request
[0]))
68 args
.system_ota
= "None"
70 device_codename
= helpers
.props
.host_get(args
, "ro.product.device")
71 args
.vendor_type
= None
72 for vendor
in [device_codename
, get_vendor_type(args
)]:
73 vendor_ota
= args
.vendor_channel
+ "/waydroid_" + \
74 args
.arch
+ "/" + vendor
.replace(" ", "_") + ".json"
75 vendor_request
= helpers
.http
.retrieve(vendor_ota
)
76 if vendor_request
[0] == 200:
77 args
.vendor_type
= vendor
78 args
.vendor_ota
= vendor_ota
81 if not args
.vendor_type
:
82 if args
.images_path
not in preinstalled_images_paths
:
84 "Failed to get vendor OTA channel: {}".format(vendor_ota
))
86 args
.vendor_ota
= "None"
87 args
.vendor_type
= get_vendor_type(args
)
89 if args
.system_ota
!= cfg
["waydroid"].get("system_ota"):
90 cfg
["waydroid"]["system_datetime"] = tools
.config
.defaults
["system_datetime"]
91 if args
.vendor_ota
!= cfg
["waydroid"].get("vendor_ota"):
92 cfg
["waydroid"]["vendor_datetime"] = tools
.config
.defaults
["vendor_datetime"]
94 cfg
["waydroid"]["vendor_type"] = args
.vendor_type
95 cfg
["waydroid"]["system_ota"] = args
.system_ota
96 cfg
["waydroid"]["vendor_ota"] = args
.vendor_ota
97 helpers
.drivers
.setupBinderNodes(args
)
98 cfg
["waydroid"]["binder"] = args
.BINDER_DRIVER
99 cfg
["waydroid"]["vndbinder"] = args
.VNDBINDER_DRIVER
100 cfg
["waydroid"]["hwbinder"] = args
.HWBINDER_DRIVER
101 tools
.config
.save(args
, cfg
)
104 if not is_initialized(args
) or args
.force
:
105 initializer_service
= None
107 initializer_service
= tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer")
108 except dbus
.DBusException
:
112 if os
.path
.exists(tools
.config
.defaults
["lxc"] + "/waydroid"):
113 status
= helpers
.lxc
.status(args
)
114 if status
!= "STOPPED":
115 logging
.info("Stopping container")
117 container
= tools
.helpers
.ipc
.DBusContainerService()
118 args
.session
= container
.GetSession()
119 container
.Stop(False)
120 except Exception as e
:
122 tools
.actions
.container_manager
.stop(args
)
123 if args
.images_path
not in tools
.config
.defaults
["preinstalled_images_paths"]:
124 helpers
.images
.get(args
)
126 helpers
.images
.remove_overlay(args
)
127 if not os
.path
.isdir(tools
.config
.defaults
["rootfs"]):
128 os
.mkdir(tools
.config
.defaults
["rootfs"])
129 if not os
.path
.isdir(tools
.config
.defaults
["overlay"]):
130 os
.mkdir(tools
.config
.defaults
["overlay"])
131 os
.mkdir(tools
.config
.defaults
["overlay"]+"/vendor")
132 if not os
.path
.isdir(tools
.config
.defaults
["overlay_rw"]):
133 os
.mkdir(tools
.config
.defaults
["overlay_rw"])
134 os
.mkdir(tools
.config
.defaults
["overlay_rw"]+"/system")
135 os
.mkdir(tools
.config
.defaults
["overlay_rw"]+"/vendor")
136 helpers
.drivers
.probeAshmemDriver(args
)
137 helpers
.lxc
.setup_host_perms(args
)
138 helpers
.lxc
.set_lxc_config(args
)
139 helpers
.lxc
.make_base_props(args
)
140 if status
!= "STOPPED":
141 logging
.info("Starting container")
143 container
.Start(args
.session
)
144 except Exception as e
:
146 logging
.error("Failed to restart container. Please do so manually.")
148 if "running_init_in_service" not in args
or not args
.running_init_in_service
:
150 if initializer_service
:
151 initializer_service
.Done()
152 except dbus
.DBusException
:
155 logging
.info("Already initialized")
157 def wait_for_init(args
):
158 helpers
.ipc
.create_channel("remote_init_output")
160 mainloop
= GLib
.MainLoop()
161 dbus_obj
= DbusInitializer(mainloop
, dbus
.SystemBus(), '/Initializer', args
)
165 dbus_obj
.remove_from_connection()
167 class DbusInitializer(dbus
.service
.Object
):
168 def __init__(self
, looper
, bus
, object_path
, args
):
171 dbus
.service
.Object
.__init
__(self
, bus
, object_path
)
173 @dbus.service.method("id.waydro.Initializer", in_signature
='a{ss}', out_signature
='', sender_keyword
="sender", connection_keyword
="conn")
174 def Init(self
, params
, sender
=None, conn
=None):
175 channels_cfg
= tools
.config
.load_channels()
176 no_auth
= params
["system_channel"] == channels_cfg
["channels"]["system_channel"] and \
177 params
["vendor_channel"] == channels_cfg
["channels"]["vendor_channel"]
178 if no_auth
or ensure_polkit_auth(sender
, conn
, "id.waydro.Initializer.Init"):
179 threading
.Thread(target
=remote_init_server
, args
=(self
.args
, params
)).start()
181 raise PermissionError("Polkit: Authentication failed")
183 @dbus.service.method("id.waydro.Initializer", in_signature
='', out_signature
='')
185 if is_initialized(self
.args
):
188 def ensure_polkit_auth(sender
, conn
, privilege
):
189 dbus_info
= dbus
.Interface(conn
.get_object("org.freedesktop.DBus", "/org/freedesktop/DBus/Bus", False), "org.freedesktop.DBus")
190 pid
= dbus_info
.GetConnectionUnixProcessID(sender
)
191 polkit
= dbus
.Interface(dbus
.SystemBus().get_object("org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", False), "org.freedesktop.PolicyKit1.Authority")
193 (is_auth
, _
, _
) = polkit
.CheckAuthorization(
195 "pid": dbus
.UInt32(pid
, variant_level
=1),
196 "start-time": dbus
.UInt64(0, variant_level
=1)}),
197 privilege
, {"AllowUserInteraction": "true"}
,
202 except dbus
.DBusException
:
203 raise PermissionError("Polkit: Authentication timed out")
205 def background_remote_init_process(args
):
206 with helpers
.ipc
.open_channel("remote_init_output", "wb") as channel_out
:
207 class StdoutRedirect(logging
.StreamHandler
):
209 channel_out
.write(str.encode(s
))
212 def emit(self
, record
):
213 if record
.levelno
>= logging
.INFO
:
214 self
.write(self
.format(record
) + self
.terminator
)
216 out
= StdoutRedirect()
217 sys
.stdout
= sys
.stderr
= out
218 logging
.getLogger().addHandler(out
)
220 ctl_queue
= queue
.Queue()
224 except Exception as e
:
230 poller
= select
.poll()
231 poller
.register(channel_out
, select
.POLLERR
)
233 # When reaching here the client was terminated
236 init_thread
= threading
.Thread(target
=try_init
, args
=(args
,))
237 init_thread
.daemon
= True
240 poll_thread
= threading
.Thread(target
=poll_pipe
)
241 poll_thread
.daemon
= True
244 # Join any one of the two threads
245 # Then exit the subprocess to kill the remaining thread.
246 # Can you believe this is the only way to kill a thread in python???
249 sys
.stdout
= sys
.__stdout
__
250 sys
.stderr
= sys
.__stderr
__
251 logging
.getLogger().removeHandler(out
)
253 def remote_init_server(args
, params
):
255 args
.images_path
= ""
257 args
.system_channel
= params
["system_channel"]
258 args
.vendor_channel
= params
["vendor_channel"]
259 args
.system_type
= params
["system_type"]
260 args
.running_init_in_service
= True
262 p
= multiprocessing
.Process(target
=background_remote_init_process
, args
=(args
,))
267 def remote_init_client(args
):
268 # Local imports cause Gtk is intrusive
270 gi
.require_version("Gtk", "3.0")
271 from gi
.repository
import Gtk
273 bus
= dbus
.SystemBus()
275 if is_initialized(args
):
277 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
278 except dbus
.DBusException
:
282 def notify_and_quit(caller
):
283 if is_initialized(args
):
285 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
286 except dbus
.DBusException
:
288 GLib
.idle_add(Gtk
.main_quit
)
290 class WaydroidInitWindow(Gtk
.Window
):
292 super().__init
__(title
="Initialize Waydroid")
293 channels_cfg
= tools
.config
.load_channels()
295 self
.set_default_size(600, 250)
296 self
.set_icon_name("waydroid")
298 grid
= Gtk
.Grid(row_spacing
=6, column_spacing
=6, margin
=10, column_homogeneous
=True)
299 grid
.set_hexpand(True)
300 grid
.set_vexpand(True)
303 sysOtaLabel
= Gtk
.Label("System OTA")
304 sysOtaEntry
= Gtk
.Entry()
305 sysOtaEntry
.set_text(channels_cfg
["channels"]["system_channel"])
306 grid
.attach(sysOtaLabel
, 0, 0, 1, 1)
307 grid
.attach_next_to(sysOtaEntry
,sysOtaLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
308 self
.sysOta
= sysOtaEntry
.get_buffer()
310 vndOtaLabel
= Gtk
.Label("Vendor OTA")
311 vndOtaEntry
= Gtk
.Entry()
312 vndOtaEntry
.set_text(channels_cfg
["channels"]["vendor_channel"])
313 grid
.attach(vndOtaLabel
, 0, 1, 1, 1)
314 grid
.attach_next_to(vndOtaEntry
, vndOtaLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
315 self
.vndOta
= vndOtaEntry
.get_buffer()
317 sysTypeLabel
= Gtk
.Label("Android Type")
318 sysTypeCombo
= Gtk
.ComboBoxText()
319 sysTypeCombo
.set_entry_text_column(0)
320 for t
in ["VANILLA", "GAPPS"]:
321 sysTypeCombo
.append_text(t
)
322 sysTypeCombo
.set_active(0)
323 grid
.attach(sysTypeLabel
, 0, 2, 1, 1)
324 grid
.attach_next_to(sysTypeCombo
, sysTypeLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
325 self
.sysType
= sysTypeCombo
327 downloadBtn
= Gtk
.Button("Download")
328 downloadBtn
.connect("clicked", self
.on_download_btn_clicked
)
329 grid
.attach(downloadBtn
, 1,3,1,1)
330 self
.downloadBtn
= downloadBtn
332 doneBtn
= Gtk
.Button("Done")
333 doneBtn
.connect("clicked", lambda x
: self
.destroy())
334 doneBtn
.get_style_context().add_class('suggested-action')
335 grid
.attach_next_to(doneBtn
, downloadBtn
, Gtk
.PositionType
.RIGHT
, 1, 1)
336 self
.doneBtn
= doneBtn
338 outScrolledWindow
= Gtk
.ScrolledWindow()
339 outScrolledWindow
.set_hexpand(True)
340 outScrolledWindow
.set_vexpand(True)
341 outTextView
= Gtk
.TextView()
342 outTextView
.set_property('editable', False)
343 outTextView
.set_property('cursor-visible', False)
344 outScrolledWindow
.add(outTextView
)
345 grid
.attach(outScrolledWindow
, 0, 4, 3, 1)
346 self
.outScrolledWindow
= outScrolledWindow
347 self
.outTextView
= outTextView
348 self
.outBuffer
= outTextView
.get_buffer()
349 self
.outBuffer
.create_mark("end", self
.outBuffer
.get_end_iter(), False)
351 self
.open_channel
= None
353 def scroll_to_bottom(self
):
354 self
.outTextView
.scroll_mark_onscreen(self
.outBuffer
.get_mark("end"))
356 def on_download_btn_clicked(self
, widget
):
357 widget
.set_sensitive(False)
359 self
.outTextView
.show()
360 init_params
= (self
.sysOta
.get_text(), self
.vndOta
.get_text(), self
.sysType
.get_active_text())
361 init_runner
= threading
.Thread(target
=self
.run_init
, args
=init_params
)
362 init_runner
.daemon
= True
365 def run_init(self
, systemOta
, vendorOta
, systemType
):
367 if s
.startswith('\r'):
368 last
= self
.outBuffer
.get_iter_at_line(self
.outBuffer
.get_line_count()-1)
370 self
.outBuffer
.delete(last
, self
.outBuffer
.get_end_iter())
371 self
.outBuffer
.insert(self
.outBuffer
.get_end_iter(), s
)
372 self
.scroll_to_bottom()
374 GLib
.idle_add(draw_sync
, s
)
376 if self
.open_channel
is not None:
377 self
.open_channel
.close()
378 # Wait for other end to reset
381 draw("Waiting for waydroid container service...\n")
384 "system_channel": self
.sysOta
.get_text(),
385 "vendor_channel": self
.vndOta
.get_text(),
386 "system_type": self
.sysType
.get_active_text()
388 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Init(params
, timeout
=310)
389 except dbus
.DBusException
as e
:
390 if e
.get_dbus_name() == "org.freedesktop.DBus.Python.PermissionError":
391 draw(e
.get_dbus_message().splitlines()[-1] + "\n")
393 draw("The waydroid container service is not listening\n")
394 GLib
.idle_add(self
.downloadBtn
.set_sensitive
, True)
397 with helpers
.ipc
.open_channel("remote_init_output", "rb") as channel
:
398 self
.open_channel
= channel
399 GLib
.idle_add(self
.downloadBtn
.set_sensitive
, True)
403 data
= channel
.read(1)
417 draw("\nInterrupted\n")
419 if is_initialized(args
):
420 GLib
.idle_add(self
.doneBtn
.show
)
424 GLib
.set_prgname("Waydroid")
425 win
= WaydroidInitWindow()
426 win
.connect("destroy", notify_and_quit
)
429 win
.outTextView
.hide()