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 if not args
.system_channel
or not args
.vendor_channel
:
63 logging
.error("ERROR: You must provide 'System OTA' and 'Vendor OTA' URLs.")
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
:
72 "Failed to get system OTA channel: {}, error: {}".format(args
.system_ota
, system_request
[0]))
74 args
.system_ota
= "None"
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
87 if not args
.vendor_type
:
88 if args
.images_path
not in preinstalled_images_paths
:
90 "Failed to get vendor OTA channel: {}".format(vendor_ota
))
92 args
.vendor_ota
= "None"
93 args
.vendor_type
= get_vendor_type(args
)
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"]
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
)
111 if not is_initialized(args
) or args
.force
:
112 initializer_service
= None
114 initializer_service
= tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer")
115 except dbus
.DBusException
:
117 if not setup_config(args
):
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")
125 container
= tools
.helpers
.ipc
.DBusContainerService()
126 args
.session
= container
.GetSession()
127 container
.Stop(False)
128 except Exception as 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
)
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")
151 container
.Start(args
.session
)
152 except Exception as e
:
154 logging
.error("Failed to restart container. Please do so manually.")
156 if "running_init_in_service" not in args
or not args
.running_init_in_service
:
158 if initializer_service
:
159 initializer_service
.Done()
160 except dbus
.DBusException
:
163 logging
.info("Already initialized")
165 def wait_for_init(args
):
166 helpers
.ipc
.create_channel("remote_init_output")
168 mainloop
= GLib
.MainLoop()
169 dbus_obj
= DbusInitializer(mainloop
, dbus
.SystemBus(), '/Initializer', args
)
173 dbus_obj
.remove_from_connection()
175 class DbusInitializer(dbus
.service
.Object
):
176 def __init__(self
, looper
, bus
, object_path
, args
):
179 dbus
.service
.Object
.__init
__(self
, bus
, object_path
)
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()
189 raise PermissionError("Polkit: Authentication failed")
191 @dbus.service.method("id.waydro.Initializer", in_signature
='', out_signature
='')
193 if is_initialized(self
.args
):
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")
201 (is_auth
, _
, _
) = polkit
.CheckAuthorization(
203 "pid": dbus
.UInt32(pid
, variant_level
=1),
204 "start-time": dbus
.UInt64(0, variant_level
=1)}),
205 privilege
, {"AllowUserInteraction": "true"}
,
210 except dbus
.DBusException
:
211 raise PermissionError("Polkit: Authentication timed out")
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
):
217 channel_out
.write(str.encode(s
))
220 def emit(self
, record
):
221 if record
.levelno
>= logging
.INFO
:
222 self
.write(self
.format(record
) + self
.terminator
)
224 out
= StdoutRedirect()
225 sys
.stdout
= sys
.stderr
= out
226 logging
.getLogger().addHandler(out
)
228 ctl_queue
= queue
.Queue()
232 except Exception as e
:
238 poller
= select
.poll()
239 poller
.register(channel_out
, select
.POLLERR
)
241 # When reaching here the client was terminated
244 init_thread
= threading
.Thread(target
=try_init
, args
=(args
,))
245 init_thread
.daemon
= True
248 poll_thread
= threading
.Thread(target
=poll_pipe
)
249 poll_thread
.daemon
= True
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???
257 sys
.stdout
= sys
.__stdout
__
258 sys
.stderr
= sys
.__stderr
__
259 logging
.getLogger().removeHandler(out
)
261 def remote_init_server(args
, params
):
263 args
.images_path
= ""
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
270 p
= multiprocessing
.Process(target
=background_remote_init_process
, args
=(args
,))
275 def remote_init_client(args
):
276 # Local imports cause Gtk is intrusive
278 gi
.require_version("Gtk", "3.0")
279 from gi
.repository
import Gtk
281 bus
= dbus
.SystemBus()
283 if is_initialized(args
):
285 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
286 except dbus
.DBusException
:
290 def notify_and_quit(caller
):
291 if is_initialized(args
):
293 tools
.helpers
.ipc
.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
294 except dbus
.DBusException
:
296 GLib
.idle_add(Gtk
.main_quit
)
298 class WaydroidInitWindow(Gtk
.Window
):
300 super().__init
__(title
="Initialize Waydroid")
301 channels_cfg
= tools
.config
.load_channels()
303 self
.set_default_size(600, 250)
304 self
.set_icon_name("waydroid")
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)
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()
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()
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
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
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
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)
359 self
.open_channel
= None
361 def scroll_to_bottom(self
):
362 self
.outTextView
.scroll_mark_onscreen(self
.outBuffer
.get_mark("end"))
364 def on_download_btn_clicked(self
, widget
):
365 widget
.set_sensitive(False)
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
373 def run_init(self
, systemOta
, vendorOta
, systemType
):
375 if s
.startswith('\r'):
376 last
= self
.outBuffer
.get_iter_at_line(self
.outBuffer
.get_line_count()-1)
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()
382 GLib
.idle_add(draw_sync
, s
)
384 if self
.open_channel
is not None:
385 self
.open_channel
.close()
386 # Wait for other end to reset
389 draw("Waiting for waydroid container service...\n")
392 "system_channel": self
.sysOta
.get_text(),
393 "vendor_channel": self
.vndOta
.get_text(),
394 "system_type": self
.sysType
.get_active_text()
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")
401 draw("The waydroid container service is not listening\n")
402 GLib
.idle_add(self
.downloadBtn
.set_sensitive
, True)
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)
411 data
= channel
.read(1)
425 draw("\nInterrupted\n")
427 if is_initialized(args
):
428 GLib
.idle_add(self
.doneBtn
.show
)
432 GLib
.set_prgname("Waydroid")
433 win
= WaydroidInitWindow()
434 win
.connect("destroy", notify_and_quit
)
437 win
.outTextView
.hide()