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 vndk
-= 1 # 12L -> Halium 12
29 ret
= "HALIUM_" + str(vndk
- 19)
33 def setup_config(args
):
34 cfg
= tools
.config
.load(args
)
35 args
.arch
= helpers
.arch
.host()
36 cfg
["waydroid"]["arch"] = args
.arch
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
46 logging
.warning("Found directory {} but missing system or vendor image, ignoring...".format(preinstalled_images
))
48 if not args
.images_path
:
49 args
.images_path
= tools
.config
.defaults
["images_path"]
50 cfg
["waydroid"]["images_path"] = args
.images_path
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"]
58 args
.rom_type
= channels_cfg
["channels"]["rom_type"]
59 if not args
.system_type
:
60 args
.system_type
= channels_cfg
["channels"]["system_type"]
62 args
.system_ota
= args
.system_channel
+ "/" + args
.rom_type
+ \
63 "/waydroid_" + args
.arch
+ "/" + args
.system_type
+ ".json"
64 system_request
= helpers
.http
.retrieve(args
.system_ota
)
65 if system_request
[0] != 200:
66 if args
.images_path
not in preinstalled_images_paths
:
68 "Failed to get system OTA channel: {}, error: {}".format(args
.system_ota
, system_request
[0]))
70 args
.system_ota
= "None"
72 device_codename
= helpers
.props
.host_get(args
, "ro.product.device")
73 args
.vendor_type
= None
74 for vendor
in [device_codename
, get_vendor_type(args
)]:
75 vendor_ota
= args
.vendor_channel
+ "/waydroid_" + \
76 args
.arch
+ "/" + vendor
.replace(" ", "_") + ".json"
77 vendor_request
= helpers
.http
.retrieve(vendor_ota
)
78 if vendor_request
[0] == 200:
79 args
.vendor_type
= vendor
80 args
.vendor_ota
= vendor_ota
83 if not args
.vendor_type
:
84 if args
.images_path
not in preinstalled_images_paths
:
86 "Failed to get vendor OTA channel: {}".format(vendor_ota
))
88 args
.vendor_ota
= "None"
89 args
.vendor_type
= get_vendor_type(args
)
91 if args
.system_ota
!= cfg
["waydroid"].get("system_ota"):
92 cfg
["waydroid"]["system_datetime"] = tools
.config
.defaults
["system_datetime"]
93 if args
.vendor_ota
!= cfg
["waydroid"].get("vendor_ota"):
94 cfg
["waydroid"]["vendor_datetime"] = tools
.config
.defaults
["vendor_datetime"]
96 cfg
["waydroid"]["vendor_type"] = args
.vendor_type
97 cfg
["waydroid"]["system_ota"] = args
.system_ota
98 cfg
["waydroid"]["vendor_ota"] = args
.vendor_ota
99 helpers
.drivers
.setupBinderNodes(args
)
100 cfg
["waydroid"]["binder"] = args
.BINDER_DRIVER
101 cfg
["waydroid"]["vndbinder"] = args
.VNDBINDER_DRIVER
102 cfg
["waydroid"]["hwbinder"] = args
.HWBINDER_DRIVER
103 tools
.config
.save(args
, cfg
)
106 if not is_initialized(args
) or args
.force
:
107 initializer_service
= None
109 initializer_service
= tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer")
110 except dbus
.DBusException
:
114 if os
.path
.exists(tools
.config
.defaults
["lxc"] + "/waydroid"):
115 status
= helpers
.lxc
.status(args
)
116 if status
!= "STOPPED":
117 logging
.info("Stopping container")
119 container
= tools
.helpers
.ipc
.DBusContainerService()
120 args
.session
= container
.GetSession()
121 container
.Stop(False)
122 except Exception as e
:
124 tools
.actions
.container_manager
.stop(args
)
125 if args
.images_path
not in tools
.config
.defaults
["preinstalled_images_paths"]:
126 helpers
.images
.get(args
)
128 helpers
.images
.remove_overlay(args
)
129 if not os
.path
.isdir(tools
.config
.defaults
["rootfs"]):
130 os
.mkdir(tools
.config
.defaults
["rootfs"])
131 if not os
.path
.isdir(tools
.config
.defaults
["overlay"]):
132 os
.mkdir(tools
.config
.defaults
["overlay"])
133 os
.mkdir(tools
.config
.defaults
["overlay"]+"/vendor")
134 if not os
.path
.isdir(tools
.config
.defaults
["overlay_rw"]):
135 os
.mkdir(tools
.config
.defaults
["overlay_rw"])
136 os
.mkdir(tools
.config
.defaults
["overlay_rw"]+"/system")
137 os
.mkdir(tools
.config
.defaults
["overlay_rw"]+"/vendor")
138 helpers
.drivers
.probeAshmemDriver(args
)
139 helpers
.lxc
.setup_host_perms(args
)
140 helpers
.lxc
.set_lxc_config(args
)
141 helpers
.lxc
.make_base_props(args
)
142 if status
!= "STOPPED":
143 logging
.info("Starting container")
145 container
.Start(args
.session
)
146 except Exception as e
:
148 logging
.error("Failed to restart container. Please do so manually.")
150 if "running_init_in_service" not in args
or not args
.running_init_in_service
:
152 if initializer_service
:
153 initializer_service
.Done()
154 except dbus
.DBusException
:
157 logging
.info("Already initialized")
159 def wait_for_init(args
):
160 helpers
.ipc
.create_channel("remote_init_output")
162 mainloop
= GLib
.MainLoop()
163 dbus_obj
= DbusInitializer(mainloop
, dbus
.SystemBus(), '/Initializer', args
)
167 dbus_obj
.remove_from_connection()
169 class DbusInitializer(dbus
.service
.Object
):
170 def __init__(self
, looper
, bus
, object_path
, args
):
173 dbus
.service
.Object
.__init
__(self
, bus
, object_path
)
175 @dbus.service.method("id.waydro.Initializer", in_signature
='a{ss}', out_signature
='', sender_keyword
="sender", connection_keyword
="conn")
176 def Init(self
, params
, sender
=None, conn
=None):
177 channels_cfg
= tools
.config
.load_channels()
178 no_auth
= params
["system_channel"] == channels_cfg
["channels"]["system_channel"] and \
179 params
["vendor_channel"] == channels_cfg
["channels"]["vendor_channel"]
180 if no_auth
or ensure_polkit_auth(sender
, conn
, "id.waydro.Initializer.Init"):
181 threading
.Thread(target
=remote_init_server
, args
=(self
.args
, params
)).start()
183 raise PermissionError("Polkit: Authentication failed")
185 @dbus.service.method("id.waydro.Initializer", in_signature
='', out_signature
='')
187 if is_initialized(self
.args
):
190 def ensure_polkit_auth(sender
, conn
, privilege
):
191 dbus_info
= dbus
.Interface(conn
.get_object("org.freedesktop.DBus", "/org/freedesktop/DBus/Bus", False), "org.freedesktop.DBus")
192 pid
= dbus_info
.GetConnectionUnixProcessID(sender
)
193 polkit
= dbus
.Interface(dbus
.SystemBus().get_object("org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", False), "org.freedesktop.PolicyKit1.Authority")
195 (is_auth
, _
, _
) = polkit
.CheckAuthorization(
197 "pid": dbus
.UInt32(pid
, variant_level
=1),
198 "start-time": dbus
.UInt64(0, variant_level
=1)}),
199 privilege
, {"AllowUserInteraction": "true"}
,
204 except dbus
.DBusException
:
205 raise PermissionError("Polkit: Authentication timed out")
207 def background_remote_init_process(args
):
208 with helpers
.ipc
.open_channel("remote_init_output", "wb") as channel_out
:
209 class StdoutRedirect(logging
.StreamHandler
):
211 channel_out
.write(str.encode(s
))
214 def emit(self
, record
):
215 if record
.levelno
>= logging
.INFO
:
216 self
.write(self
.format(record
) + self
.terminator
)
218 out
= StdoutRedirect()
219 sys
.stdout
= sys
.stderr
= out
220 logging
.getLogger().addHandler(out
)
222 ctl_queue
= queue
.Queue()
226 except Exception as e
:
232 poller
= select
.poll()
233 poller
.register(channel_out
, select
.POLLERR
)
235 # When reaching here the client was terminated
238 init_thread
= threading
.Thread(target
=try_init
, args
=(args
,))
239 init_thread
.daemon
= True
242 poll_thread
= threading
.Thread(target
=poll_pipe
)
243 poll_thread
.daemon
= True
246 # Join any one of the two threads
247 # Then exit the subprocess to kill the remaining thread.
248 # Can you believe this is the only way to kill a thread in python???
251 sys
.stdout
= sys
.__stdout
__
252 sys
.stderr
= sys
.__stderr
__
253 logging
.getLogger().removeHandler(out
)
255 def remote_init_server(args
, params
):
257 args
.images_path
= ""
259 args
.system_channel
= params
["system_channel"]
260 args
.vendor_channel
= params
["vendor_channel"]
261 args
.system_type
= params
["system_type"]
262 args
.running_init_in_service
= True
264 p
= multiprocessing
.Process(target
=background_remote_init_process
, args
=(args
,))
269 def remote_init_client(args
):
270 # Local imports cause Gtk is intrusive
272 gi
.require_version("Gtk", "3.0")
273 from gi
.repository
import Gtk
275 bus
= dbus
.SystemBus()
277 if is_initialized(args
):
279 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
280 except dbus
.DBusException
:
284 def notify_and_quit(caller
):
285 if is_initialized(args
):
287 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
288 except dbus
.DBusException
:
290 GLib
.idle_add(Gtk
.main_quit
)
292 class WaydroidInitWindow(Gtk
.Window
):
294 super().__init
__(title
="Initialize Waydroid")
295 channels_cfg
= tools
.config
.load_channels()
297 self
.set_default_size(600, 250)
298 self
.set_icon_name("waydroid")
300 grid
= Gtk
.Grid(row_spacing
=6, column_spacing
=6, margin
=10, column_homogeneous
=True)
301 grid
.set_hexpand(True)
302 grid
.set_vexpand(True)
305 sysOtaLabel
= Gtk
.Label("System OTA")
306 sysOtaEntry
= Gtk
.Entry()
307 sysOtaEntry
.set_text(channels_cfg
["channels"]["system_channel"])
308 grid
.attach(sysOtaLabel
, 0, 0, 1, 1)
309 grid
.attach_next_to(sysOtaEntry
,sysOtaLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
310 self
.sysOta
= sysOtaEntry
.get_buffer()
312 vndOtaLabel
= Gtk
.Label("Vendor OTA")
313 vndOtaEntry
= Gtk
.Entry()
314 vndOtaEntry
.set_text(channels_cfg
["channels"]["vendor_channel"])
315 grid
.attach(vndOtaLabel
, 0, 1, 1, 1)
316 grid
.attach_next_to(vndOtaEntry
, vndOtaLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
317 self
.vndOta
= vndOtaEntry
.get_buffer()
319 sysTypeLabel
= Gtk
.Label("Android Type")
320 sysTypeCombo
= Gtk
.ComboBoxText()
321 sysTypeCombo
.set_entry_text_column(0)
322 for t
in ["VANILLA", "GAPPS"]:
323 sysTypeCombo
.append_text(t
)
324 sysTypeCombo
.set_active(0)
325 grid
.attach(sysTypeLabel
, 0, 2, 1, 1)
326 grid
.attach_next_to(sysTypeCombo
, sysTypeLabel
, Gtk
.PositionType
.RIGHT
, 2, 1)
327 self
.sysType
= sysTypeCombo
329 downloadBtn
= Gtk
.Button("Download")
330 downloadBtn
.connect("clicked", self
.on_download_btn_clicked
)
331 grid
.attach(downloadBtn
, 1,3,1,1)
332 self
.downloadBtn
= downloadBtn
334 doneBtn
= Gtk
.Button("Done")
335 doneBtn
.connect("clicked", lambda x
: self
.destroy())
336 doneBtn
.get_style_context().add_class('suggested-action')
337 grid
.attach_next_to(doneBtn
, downloadBtn
, Gtk
.PositionType
.RIGHT
, 1, 1)
338 self
.doneBtn
= doneBtn
340 outScrolledWindow
= Gtk
.ScrolledWindow()
341 outScrolledWindow
.set_hexpand(True)
342 outScrolledWindow
.set_vexpand(True)
343 outTextView
= Gtk
.TextView()
344 outTextView
.set_property('editable', False)
345 outTextView
.set_property('cursor-visible', False)
346 outScrolledWindow
.add(outTextView
)
347 grid
.attach(outScrolledWindow
, 0, 4, 3, 1)
348 self
.outScrolledWindow
= outScrolledWindow
349 self
.outTextView
= outTextView
350 self
.outBuffer
= outTextView
.get_buffer()
351 self
.outBuffer
.create_mark("end", self
.outBuffer
.get_end_iter(), False)
353 self
.open_channel
= None
355 def scroll_to_bottom(self
):
356 self
.outTextView
.scroll_mark_onscreen(self
.outBuffer
.get_mark("end"))
358 def on_download_btn_clicked(self
, widget
):
359 widget
.set_sensitive(False)
361 self
.outTextView
.show()
362 init_params
= (self
.sysOta
.get_text(), self
.vndOta
.get_text(), self
.sysType
.get_active_text())
363 init_runner
= threading
.Thread(target
=self
.run_init
, args
=init_params
)
364 init_runner
.daemon
= True
367 def run_init(self
, systemOta
, vendorOta
, systemType
):
369 if s
.startswith('\r'):
370 last
= self
.outBuffer
.get_iter_at_line(self
.outBuffer
.get_line_count()-1)
372 self
.outBuffer
.delete(last
, self
.outBuffer
.get_end_iter())
373 self
.outBuffer
.insert(self
.outBuffer
.get_end_iter(), s
)
374 self
.scroll_to_bottom()
376 GLib
.idle_add(draw_sync
, s
)
378 if self
.open_channel
is not None:
379 self
.open_channel
.close()
380 # Wait for other end to reset
383 draw("Waiting for waydroid container service...\n")
386 "system_channel": self
.sysOta
.get_text(),
387 "vendor_channel": self
.vndOta
.get_text(),
388 "system_type": self
.sysType
.get_active_text()
390 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Init(params
, timeout
=310)
391 except dbus
.DBusException
as e
:
392 if e
.get_dbus_name() == "org.freedesktop.DBus.Python.PermissionError":
393 draw(e
.get_dbus_message().splitlines()[-1] + "\n")
395 draw("The waydroid container service is not listening\n")
396 GLib
.idle_add(self
.downloadBtn
.set_sensitive
, True)
399 with helpers
.ipc
.open_channel("remote_init_output", "rb") as channel
:
400 self
.open_channel
= channel
401 GLib
.idle_add(self
.downloadBtn
.set_sensitive
, True)
405 data
= channel
.read(1)
419 draw("\nInterrupted\n")
421 if is_initialized(args
):
422 GLib
.idle_add(self
.doneBtn
.show
)
426 GLib
.set_prgname("Waydroid")
427 win
= WaydroidInitWindow()
428 win
.connect("destroy", notify_and_quit
)
431 win
.outTextView
.hide()