Windows services 101 (2004)


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Windows services 101 (2004)

  1. 1. Windows Services 101 Vatroslav Mihalj 2004.
  2. 2. What is Windows Service? <ul><li>application that conforms to the interface rules of SCM </li></ul><ul><li>can be started automatically at system boot, by a user through the Services control panel applet, or by an app that uses service functions </li></ul><ul><li>can execute even when no user is logged on to the system. </li></ul>
  3. 3. <ul><li>driver service </li></ul><ul><ul><li>conforms to the device driver protocols </li></ul></ul><ul><ul><li>similar to a service app, but it does not interact with the SCM </li></ul></ul><ul><li>filename extension is .EXE for services and .SYS for driver services </li></ul>
  4. 4. Operating Windows Services <ul><li>3 types of programs use functions provided by SCM, i.e. are neccessary to operate a WS: </li></ul><ul><ul><li>s ervice program </li></ul></ul><ul><ul><li>s ervice configuration program </li></ul></ul><ul><ul><li>s ervice control program </li></ul></ul>
  5. 5. <ul><li>s ervice program </li></ul><ul><ul><li>provides the actual functionality we are looking for (for one or more services) </li></ul></ul><ul><ul><li>use functions that connect to the SCM and send status information to the SCM </li></ul></ul><ul><li>s ervice configuration program </li></ul><ul><ul><li>queries/modifies services DB (install or delete services, query/modify config and security params) </li></ul></ul><ul><li>s ervice control program </li></ul><ul><ul><li>sending control requests to SCM (start, stop, pause/continue) - which carries out the request </li></ul></ul><ul><ul><li>net.exe , sc.exe , VS.NET Server Explorer </li></ul></ul>
  6. 6. What is SMC ( Service Control Manager ) <ul><li>maintains a database of installed services and driver services (&quot;services&quot; from now on) </li></ul><ul><ul><li>database includes information on how each service or driver service should be started </li></ul></ul><ul><li>provides a unified and secure means of controlling them </li></ul><ul><ul><li>RPC server, so service configuration and service control programs can manipulate services on remote machines </li></ul></ul><ul><li>enables admins to customize security requirements for each service and thereby control access to the service </li></ul>
  7. 7. Service database <ul><li>used by the SCM and programs that add, modify, or configure services </li></ul><ul><li>HKEY_LOCAL_MACHINESYSTEM </li></ul><ul><li>CurrentControlSetServices </li></ul><ul><li>subkey for each installed service </li></ul><ul><ul><li>name of the subkey is service name </li></ul></ul><ul><ul><ul><li>specified by CreateService function when service was installed by a service configuration program </li></ul></ul></ul>
  8. 8. <ul><li>database includes: </li></ul><ul><ul><li>service type (own process or shares a process with other services, kernel driver or a file system driver) </li></ul></ul>
  9. 9. <ul><ul><li>start type (automatic, manual, disabled) </li></ul></ul><ul><ul><li>error control level </li></ul></ul><ul><ul><ul><li>severity of error if svc fails to start, determines action that startup program will take </li></ul></ul></ul><ul><ul><li>fully qualified path of the executable </li></ul></ul><ul><ul><li>optional dependency info </li></ul></ul><ul><ul><ul><li>list of services that SCM must start before it can start the specified service </li></ul></ul></ul><ul><ul><li>optional account name and password </li></ul></ul><ul><ul><ul><li>no account specified: executes in context of LocalSystem account </li></ul></ul></ul><ul><ul><li>for driver svc, optional driver object name, used by the I/O system to load the device driver </li></ul></ul>
  10. 10. <ul><li>after successful boot, system saves a clone of the database in the last-known-good (LKG) configuration </li></ul><ul><ul><li>If an auto-start service with a SERVICE_ERROR_CRITICAL error control level fails to start, the SCM reboots the machine using the LKG configuration </li></ul></ul>
  11. 11. Stopping the service <ul><li>with the Services control panel utility </li></ul><ul><li>ControlService function </li></ul><ul><ul><li>SERVICE_CONTROL_STOP request to the service through SCM </li></ul></ul><ul><ul><li>if other running services are dependent on this one, SCM doesn't forward stop request </li></ul></ul><ul><ul><ul><li>instead, it returns ERROR_DEPENDENT_SERVICES_RUNNING </li></ul></ul></ul><ul><ul><ul><li>you need to enumerate and stop dependent services </li></ul></ul></ul>
  12. 12. &quot;Common&quot; apps as services <ul><li>no need to recode all apps as services </li></ul><ul><li>Windows 2000/2003 Resource Kit tools: srvany.exe , instsrv.exe </li></ul><ul><li>NO INTERACTION! </li></ul><ul><li>instsrv ServiceAnyApp <path> srvany.exe </li></ul><ul><li>instsrv ServiceAnyApp <path> srvany.exe </li></ul><ul><li>-a MYDOMAINauser -p My1Password </li></ul><ul><li>( instsrv MyService Remove ) </li></ul>
  13. 13. <ul><li>Some Registry keys need to be added: </li></ul><ul><ul><li>Open HKLM SYSTEMCurrentControlSetServices < service name > </li></ul></ul><ul><ul><li>a dd k ey </li></ul></ul><ul><ul><ul><li>K ey Name: &quot; Parameters &quot; </li></ul></ul></ul><ul><ul><ul><li>Class : <leave blank> </li></ul></ul></ul><ul><ul><li>Select the Parameters key , Add Value </li></ul></ul><ul><ul><ul><li>Value Name: Application </li></ul></ul></ul><ul><ul><ul><li>Data Type : REG_SZ </li></ul></ul></ul><ul><ul><ul><li>String : <path><application.ext> </li></ul></ul></ul><ul><ul><ul><li>optional &quot;AppParameters&quot; and &quot;AppDirectory&quot; (REG_SZ) </li></ul></ul></ul>
  14. 14. srvany / instsrv info <ul><li>MS: </li></ul><ul><li>;en-us;137890 </li></ul><ul><li>info & help (in German), will create .BAT and .REG file with neccessary params: </li></ul><ul><li> </li></ul><ul><li>/pc/sys/srvany/index.php </li></ul>
  15. 15. Service programs <ul><li>when service control program requests the service to run, SCM starts the service: </li></ul><ul><ul><li>sends start request to control dispatcher </li></ul></ul><ul><ul><ul><li>CD - special function executed by a separate thread which needs to initialize the service structures </li></ul></ul></ul><ul><ul><ul><li>does not return until there is an error or all of the services in the process have terminated </li></ul></ul></ul><ul><ul><ul><li>when all svcs in a process have terminated, SCM sends a control request to dispatcher thread to shut down </li></ul></ul></ul><ul><ul><li>control dispatcher creates a new thread to execute ServiceMain </li></ul></ul><ul><ul><li>ServiceMain - starting place for the job the service needs to do </li></ul></ul>
  16. 17. Starting a service <ul><li>Perform initialization (if <1 sec can be done within ServiceMain ) </li></ul><ul><li>init time (&quot;pending&quot; state) <=30s total! </li></ul><ul><ul><li>use SetServiceStatus function , with SERVICE_START_PENDING </li></ul></ul><ul><ul><li>as init continues, service should make additional calls to SetServiceStatus to report progress </li></ul></ul><ul><li>init complete: call SetServiceStatus , with SERVICE_RUNNING </li></ul>
  17. 18. Service Control Handler <ul><li>invoked by the control dispatcher when the service process receives a control request from a service control program </li></ul><ul><li>whenever SCH invoked, service must call SetServiceStatus to report status to SCM, regardless of whether the status changed </li></ul>
  18. 19. <ul><li>service control program can send control requests using ControlService </li></ul><ul><li>control handler must return within 30 sec, or SCM will return an error </li></ul><ul><ul><li>lengthy processing: create a secondary thread to perform processing, then return </li></ul></ul><ul><li>service name != display name (in the Service control panel) </li></ul>
  19. 20. System s hutdown <ul><li>by default, after received SERVICE_CONTROL_SHUTDOWN, ~20 sec to perform cleanup task s </li></ul><ul><li>after this expires, shutdown proceeds regardless of whether service shutdown is complete </li></ul>
  20. 21. <ul><li>need more time to clean up? </li></ul><ul><ul><li>send STOP_PENDING status messages, along with a wait hint </li></ul></ul><ul><ul><ul><li>so service controller knows how long to wait before reporting that svc shutdown is complete </li></ul></ul></ul><ul><ul><li>there is a limit to how long the service controller will wait </li></ul></ul><ul><ul><ul><li>To change this time limit, modify WaitToKillServiceTimeout in HKLMSYSTEMCurrentControlSetControl </li></ul></ul></ul>
  21. 22. Service User Accounts <ul><li>LocalService Account </li></ul><ul><ul><li>minimum privileges on the local computer, anonymous credentials on the network </li></ul></ul><ul><ul><li>does not have a password </li></ul></ul><ul><li>NetworkService Account </li></ul><ul><ul><li>minimum privileges on the local computer and acts as the computer on the network </li></ul></ul><ul><ul><li>does not have a password </li></ul></ul><ul><ul><li>remote token contains SIDs for the Everyone and Authenticated Users groups </li></ul></ul>
  22. 23. <ul><li>LocalSystem Account </li></ul><ul><ul><li>extensive privileges on the local computer, acts as the computer on the network </li></ul></ul><ul><ul><li>does not have a password </li></ul></ul><ul><ul><li>inherits the security context of the SCM </li></ul></ul>
  23. 24. Interactive Services <ul><li>each service has an associated “ window station ” and “ desktop ” </li></ul><ul><li>only one window station, Winsta0 can be an interactive </li></ul><ul><li>by default, window station the service uses is not interactive, so the service cannot display a user interface </li></ul>
  24. 25. <ul><li>interactive service </li></ul><ul><ul><li>running in the context of the LocalSystem account and has SERVICE_INTERACTIVE_PROCESS attribute </li></ul></ul><ul><ul><ul><li>can be set by choosing Properties in Service control panel and checking “Allow service to interact with desktop” </li></ul></ul></ul>
  25. 26. <ul><li>dangerous practice!!!! </li></ul><ul><ul><li>never open dialogs for services running on a server-nobody will answer this dialog </li></ul></ul><ul><li>better solution: separate GUI application running within the context of the user session, IPC communication </li></ul><ul><ul><li>for hazarders: to display a msg box from a service, even if not running as LocalSystem or not configured to run interactively - call MessageBox using MB_SERVICE_NOTIFICATION </li></ul></ul><ul><ul><ul><li>“ displays a message box on the current active desktop, even if there is no user logged on to the computer.” </li></ul></ul></ul>
  26. 27. Worker threads <ul><li>start worker threads from the main thread and leave the main thread free to answer the requests </li></ul><ul><li>use Events to notify the main thread when worker thread starts and finishes </li></ul><ul><li>job processing functions in worker threads can be started by firing custom message which are handled by their message handlers </li></ul>
  27. 28. <ul><li>when starting, SCM needs a certain amout of time to query status and stuff </li></ul><ul><ul><li>if an error occurs or the service can’t connect to a server, don’t stop it immediately after it starts (i.e. exits start pending state) - let the main thread sleep for a while (1 sec is enough) </li></ul></ul><ul><ul><ul><li>otherwise, an error will occur because SCM might not detect that thread was started and immediately stopped and will write an error in Event Log saying that the thread did not enter the desired (&quot;started&quot;) state - i.e. it didn't detect it because it was too “quick” </li></ul></ul></ul>
  28. 29. <ul><li>when creating/opening a custom log file, beware - the service starts in %windir%system32 by default </li></ul><ul><li>don’t set service control level too high and startup type to auto unless you're absolutly sure – system might get block while booting </li></ul><ul><li>using Unicode is a good thing to consider </li></ul><ul><ul><li>but do not insist if it’s not neccessary </li></ul></ul>
  29. 30. .NET <ul><li>System.ServiceProcess namespace </li></ul><ul><li>inherit from ServiceBase class to implement a service </li></ul><ul><ul><li>registers the service and answers to start and stop requests </li></ul></ul><ul><li>ServiceController class is used to implement a service control program </li></ul><ul><ul><li>sends requests to services </li></ul></ul><ul><ul><li>ServiceProcessInstaller and ServiceInstaller classes install and configure service programs </li></ul></ul><ul><li>good sample: , &quot; Professional C# &quot; code samples, ISBN 1861007043 </li></ul>
  30. 31. WMI <ul><li>service status can be obtained and controlled through WMI </li></ul><ul><ul><li>Win32_BaseService , Win32_Service </li></ul></ul><ul><li>Restart any automatic service that is stopped: </li></ul><ul><li>Set colListOfServices = GetObject(&quot;winmgmts:&quot;).ExecQuery </li></ul><ul><li>(&quot;Select * from Win32_Service Where </li></ul><ul><li>State = 'Stopped' and StartMode = 'Automatic'&quot;) </li></ul><ul><li>For Each strService in colListOfServices </li></ul><ul><li>strService.StartService() </li></ul><ul><li>Next </li></ul>
  31. 33. Debugging a Service <ul><li>debug the service by attach to process </li></ul><ul><li>or call DebugBreak to invoke JIT dbg </li></ul><ul><li>or specify a debugger to use when starting a program </li></ul>
  32. 34. <ul><li>specifying a debugger to use when starting a program: </li></ul><ul><ul><li>create key Image File Execution Option in HKLMSOFTWAREMicrosoftWindows NTCurrentVersion create a subkey with the same name as your service </li></ul></ul><ul><ul><li>to this subkey, add a value of type REG_SZ, named Debugger </li></ul></ul><ul><ul><li>use full path to debugger as string value </li></ul></ul><ul><ul><li>In the Services control panel applet, select your service, click Startup and check Allow Service to Interact with Desktop </li></ul></ul>
  33. 35. <ul><li>to keep it simple: </li></ul><ul><ul><li>develop (or use) a robust general-purpose service framework </li></ul></ul><ul><ul><li>develop your code as a normal (or better, console) application, keeping in mid that it will be added on top of the service framework </li></ul></ul><ul><ul><li>when you’re sure that your code is OK, put it in a separate working thread, so that service framework and the job are separated </li></ul></ul><ul><ul><ul><li>don’t use worker function threads, but create a class for the thread (CWinThread base class) </li></ul></ul></ul>
  34. 36. Event Log <ul><li>service write to Application </li></ul><ul><li>SCM writes to System </li></ul><ul><li>to enter a message to the event log, it is not enought just to call a particular function </li></ul><ul><ul><li>messages are not entered as “normal” records – they need to be compiled by the message compiler </li></ul></ul>
  35. 37. Message compiler <ul><li>input: < >), messages which are to be written to Event Log </li></ul><ul><li>processed by message compiler ( mc.exe ) </li></ul><ul><ul><li>output: compiled messages (bin file) </li></ul></ul><ul><li>needed because messages (each with an ID) can be in different languages </li></ul><ul><li>usually a message DLL is created from the output and registered as an even source </li></ul><ul><ul><li>if you move or delete this DLL, Even Log will not be able to find and display the strings </li></ul></ul>
  36. 38. <ul><li>MessageId =0x1 </li></ul><ul><li>Severity =Error </li></ul><ul><li>Facility =Runtime </li></ul><ul><li>SymbolicName =MSG_BAD_COMMAND </li></ul><ul><li>Language =English </li></ul><ul><li>All your base are belong to us. </li></ul><ul><li>Language =Japanese </li></ul><ul><li>正しくないコマンド選択がされました。 </li></ul><ul><li>. </li></ul>
  37. 39. <ul><li>runtime messages can be included in Event Log records ( %1 within message string) </li></ul><ul><li>MessageID =1 </li></ul><ul><li>Severity =Informational </li></ul><ul><li>Facility =Application </li></ul><ul><li>SymbolicName =CNTS_MSG_SERVICE_STARTED </li></ul><ul><li>Language =English </li></ul><ul><li>&quot;%1&quot; started successfully. </li></ul><ul><li>. </li></ul>
  38. 40. Useful links & books <ul><li>Platform SDK docs (MSDN) </li></ul><ul><li> - CNTService framework </li></ul><ul><li>Jeffrey Richter : &quot; Programming Server-Side Applications for Microsoft Windows 2000 “ </li></ul><ul><li>links to dev. sites at www. mscommunity .net FAQ/Tips page  </li></ul>