Winlogon: How to run app after explorer terminates during logoff? - hook

Windows XP/VISTA/7
How might it be possible to run an application during the logoff procedure of a user, after explorer.exe terminates?
The purpose is to block shutdown but with an application that runs after explorer has terminated.
It is of course possible to temporararily block shutdown in vista with ShutdownBlockReasonCreate, or to cancel it in XP via WM_QUERYENDSESSION. However both of those methods occur during the user session before Explorer terminates. The question is how to get an app to run after explorer terminates AND to block shutdown.
This is not possible from a service because in VISTA/7 if the user has selected Shutdown/Restart, the service seems to have no way to block shutdown after the user has been logged-off. (The kernel seems to terminate the service and the service itself cannot block shutdown like a user app can ?)
How and when exactly does WinLogon terminate explorer.exe? It seems that it waits until all/any other applications have terminated and have ceased blocking shutdown, then it terminates explorer?
Does WinLogon wait for explorer.exe to close before it will finally close the desktop / session?
I have considered, for example attempting to hook NTDLL for the APIs that terminate a process and intercept the termination of explorer but it is unclear how or why Winlogon would then wait rather than continue the shutdown.
The purpose of all this is to find a way to run an executable during Vista/7 shutdown, which is able to block shutdown for as long as it pleases, only AFTER explorer has exited and all files and resources have been released by explorer and all other apps running as that user.
In XP this is possible by simply cancelling the shutdown in WM_QUERYENDSESSION then re-issuing ExitWindowsEx (LOGOFF) then doing the tasks in a system service. It however leaves the user at a logon screen with no progress indication.
If it was possible to inject a process after explorer terminated, the process would be able (in my theory) to show UI on the same user's desktop and effectively act as a second-time-around custom shell during the logoff procedure.
It is believed/suspected that Windows performs something similar when it installs updates during shutdown (but this behaviour has not been noted on Vista so far)
In summary there seems to be no obvious way in Vista to block shutdown after explorer closes during a user's logout?

Related

why did Windows 10 kill my worker thread in my Windows Service?

I have implemented a Windows Service in .NET 4 and C# using Visual Studio 2015. In the OnStart method, my service creates a "Worker Thread" which loops, blocking on an AutoResetEvent (connected to a Timer). The "Worker Thread" also has a CancellationTokenSource that it manually polls to check whether it should stop working. The OnStop method first Cancels with the CancellationTokenSource and then signals with the AutoResetEvent, waking up the Worker thread which notices that "cancel" has happened, and which then exits.
This Windows Service works fine on Win7. I've installed it on Win10 a few times and it worked fine - until yesterday where I saw a logfile which said the Worker Thread had, as expected, blocked on the AutoResetEvent, but: that worker Thread never got to the next statement in my program. It never woke up, didn't execute another statement. 94 seconds after it blocked, the service ended.
Note that in this scenario my OnStop method was not called.
The process as a whole had not been killed - there's a thread which comes in (threadID 1) presumably from the SCM or the OS, and which blocks until my service dies - that thread logged a few messages on the way out.
Here's my question: are there conditions where the Windows Service Control Manager (SCM) feels it necessary to actually kill off application threads? Can anyone explain why my thread died?
Short Answer to the Original Question
I discovered that restarting the machine caused my thread to die (interesting that the Windows-allocated thread didn't die, it just exited - I guess that's how the SCM cleans up services when it is told to shut down).
Longer Answer - Now I have a New Question
I didn't realize that I was barking up the wrong tree. My client app was saying the service was unavailable and I assumed it was because of what I described above - because it was getting killed off.
Not the problem - the problem was that once the service was stopped (because of shutdown), it was not getting restarted again!
So why didn't my .NET 4 Automatic service get automatically started, in Win10? That's a different question.
The New Answer
I have since posting my original question, found several postings that answer the new question:
Automatic Windows 10 service doesn't start up
Automatic Services don't start automatically after windows restart
Automatic Services not starting on Win10 upgrade machine
So the diagnosis was that Win10 was doing some kind of combination of slowing down the startup of my .NET 4 service, and then punishing the service for its slow startup by killing it before it can start executing my code.
I did find System Event log entries that support this.
The solution for me turned out to be changing my "start type" from "Automatic" to "Automatic (Delayed)".
Some relevant links for me:
Automatic vs Automatic Delayed Start
Set service StartType in WiX
I hope all this helps someone else out there.

ExtendedExecutionSession in Windows 10 UAP

I have troubles using ExtendedExecutionSession in Windows 10 UAP.
First, it seems that ExtendedExecutionSession.RequestExtensionAsync only returns Allowed if it is called from the app Suspending event handler. If it is called outside this event handler the method returns Denied.
Second, most critical problem. My app executes downloads. If any download is in progress I request ExtendedExecutionSession to allow downloads to complete. What I found at least on Windows 10 mobile though is ExtendedExecutionSession is allowed in app on suspend but downloads seem to freeze. Nothing is downloaded while app is in background and when app is resumed downloads appear frozen with no data transferred.
Here is the MSDN guidance for Extended Execution: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/run-minimized-with-extended-execution
SavingData is the only type of Extended Execution Reason that can be used in the Suspending state. Note that this is specifically for saving critical user data locally that will be lost once the process is removed from memory.
It sounds like you should use the Unspecified Extended Execution if you need to accomplish something when your app is running and in the foreground. It will be revoked if the user decides to close the app before the download operation completes. Like was previously suggested, a background transfer or use of the ApplicationTrigger or MaintenanceTrigger may be better options for these downloads if you want them to continue after your app has been closed.

Intercepting Alt+F4 in UAP

I'm writing a UAP C#/XAML application, for the time being I'm interested in case when user runs my app in desktop environment (case when keyobard and mouse are available, the machine is running some version of Windows 10 not Windows 10 Mobile).
I want to intercept ALT+F4 in order to ask user a few important questions before they quit, like in for example notepad - when you have unsaved file and the notepad notifies you about this fact and asks if you want to save your work, quit without saving or go back to working with your file.
Is such a behaviour possible in Windows 10 UAP? I tried to play with Application.Suspending event and ExtendedExecutionSession, but it seems like before this event is fired the GUI thread is dead, and all I can do in this event's handler are operations not requiring user interaction.
There is no way to intercept and stop events like this.
By the time your app is told it is suspending following a close event (alt+f4, cross clicked) you have 10 seconds (on desktop) to clear up and save state before you are completely terminated.
With universal apps, you shouldn't need a dialog asking them to save or not, just save state so next time they reopen you refresh the view to how it was before, or, think mail client, save their typings as a draft. The guidance on Microsoft is, however, that if the user closes your app, assume they want you gone so don't restore state.
The only thing you can do for some extra processing is ask the OS for extended execution, though this isn't guaranteed and even if granted can be revoked with 1s notice to termination. It's important to note that, even with extended execution granted, you app is not allowed any UI.
For more information on Windows 10 universal application lifecycle, I'd recommend watching the Application Lifecycle session on Microsoft Virtual Academy.

Process Service Thread

We know about relation between Process and Thread.
Thread comes under Process, we can say Process is a container and Thread is an element of a container.
But what about Service ?
I can say Process and Thread having same genre.
Can we say the same thing for Services?
I found Window Services and Android Services having similarity, say in Android if we want to play Media then we have to get getSystemService(Context.AUDIO_SERVICE) likewise in Windows (8) if you stop Windows Audio (audiosrv.dll) services from services.msc then Media will not play.
What is Service?
Windows
A service is an application type that runs in the system background without a user interface and is similar to a UNIX daemon process.
Android A service is a component which runs in the background, without direct interaction with the user.
A service runs by default in the same process in the main thread as the application.
Services which run in the process of the application are sometimes called local services.
With above definition we can say apparently that Service is also a Process (i am not sure, please make me correct)
Let me start with the statement - Service is not a process. It is an activity without GUI
If you start a thread, it runs parallel with your main activity thread. But a Service is not guaranteed to always run in a new thread. So, you cannot call a service similar to Thread.
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
So When to use of a service in your application ?
If your application tells the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
Reason - Your application together with all its global variables will not be wiped out as long as there is a Service still running. So if the user is not interacting with your application and some other application in foreground needs more memory and if the OS triggers a low memory warning and your activity is destroyed, still your application is not completely lost as the service is running.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.
How the Application priority is defined based on service ?
If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.
If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible.
If there are clients bound to the service, then the service's hosting process is never less important than the most important client.
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory.

Linux daemon vs foreground application

What are the advantages of "daemonizing" a server application over running the program in console mode?
Having it run as a daemon means you can
log out without loosing the service (which saves some resources)
do not risk loosing the service from an accidental ctrl-c
does not offer a minor security risk from someone accessing the terminal, hitting ctrl-c and taking your session
Essentially all 'real' services that are running 'in production' (as opposed to debug mode) run that way.
I think it is preventing from accidentally closing an app and you have one more terminal free.
But I personally don't see big difference between "screen" program and "daemonizing"
The main point would be to detach the process from the terminal so that the process does not terminate when the user logs out from the terminal. If you run a program in console mode, it will terminate when you log out, because this is the default behavior for a process when it receives a SIGHUP signal.
Note that there is more to writing a daemon than just calling daemon(3). See How to write a unix daemon for more information.

Resources