Background
Alright, so there's a lot of voodoo and undocumented stuff going on here but hopefully somebody can help me out. I've reverse engineered how stuff might work based on:
https://opensource.apple.com/source/launchd/launchd-442.21/support/launchctl.c.auto.html
I've got a launchdaemon running that spawns another process in the /dev/console bootstrap context in order to act as a remote desktop server. What I'm trying to accomplish here, is to run one of my processes as root in the current gui bootstrap context which is attached to the console.
There are several guesswork states in MacOS (11.6, M1) that I've discovered. When you boot a machine, the loginwindow process is run in the bootstrap context of 88 (_windowserver). This makes sense because this process is created by WindowServer. The current console UID is discoverable by running:
echo "show State:/Users/ConsoleUser" | scutil
You can also introspect loginwindow using launchctl procinfo and friends.
Note that, this is before any login has ever happened on the machine.
In this state I can do anything in the gui bootstrap context by running this from the launchdaemon: launchctl asuser 88 myprogram
In my case, I'm taking a screenshot using AppKit/CoreGraphics and checking some permissions.
Once a user logs in, that loginwindow gets blessed by the OS and ownership is transferred to the logged in user. If you lock the machine, you're still in the same bootstrap context and everything works as expected. You can also log out and log into another user and everything works as I expect it to in terms of who controls loginwindow.
However, as soon as you hit the "Switch user" button from the lock screen the following happens:
- A new loginwindow is spawned with the bootstrap context of root (UID of 0)
- launchctl asuser 0 myprog seems not to properly execute within the bootstrap context of root.
My guess is that: 1 is a bug(?), the fast user switching bootstrap context should probably run as 88 rather than 0.
A "fix" is running pkill loginwindow which nukes all gui sessions and restarts one loginwindow running in the bootstrap context of 88. This is of course not an acceptable solution.
Doing the same thing using launchctl bootstrap gui/0 doesn't work either. I understand that the concept of "bootstrap gui/0" and "asuser 0" sounds nonsensical and it probably is. I'm just trying to find a working solution here.
Is there a more proper way of being able run as root in the bootstrap context of a logged in/not yet logged in loginwindow?
In case anyone is curious, I'm porting this to MacOS: https://fleetdeck.io