Skip to main content

windows_services/
lib.rs

1#![doc = include_str!("../readme.md")]
2#![cfg(windows)]
3
4#[expect(non_camel_case_types, non_snake_case, clippy::upper_case_acronyms)]
5mod bindings;
6use bindings::*;
7use std::boxed::Box;
8use std::ffi::c_void;
9use std::sync::RwLock;
10
11/// A command sent by the service control manager.
12#[derive(Debug, Copy, Clone, PartialEq, Eq)]
13pub enum Command {
14    /// Starts the service.
15    Start,
16
17    /// Stops the service before process termination.
18    ///
19    /// This command will only be sent if the `can_stop` method is called as part of construction.
20    Stop,
21
22    /// Pauses the service.
23    ///
24    /// This command will only be sent if the `can_pause` method is called as part of construction.
25    Pause,
26
27    /// Resumes the service.
28    ///
29    /// This command will only be sent if the `can_pause` method is called as part of construction.
30    Resume,
31
32    /// An extended command.
33    ///
34    /// The service receives only controls enabled with [`Service::can_accept`].
35    Extended(ExtendedCommand),
36}
37
38/// A command not specifically covered by the `Command` enum.
39#[derive(Debug, Copy, Clone, PartialEq, Eq)]
40pub struct ExtendedCommand {
41    /// The control code for the command.
42    pub control: u32,
43
44    /// The event type, if any.
45    pub ty: u32,
46
47    /// The event data, if any.
48    pub data: *const c_void,
49}
50
51unsafe impl Send for ExtendedCommand {}
52unsafe impl Sync for ExtendedCommand {}
53
54/// A service state, including transitional states.
55#[derive(Debug, Copy, Clone, PartialEq, Eq)]
56pub enum State {
57    /// Resume is pending.
58    ContinuePending,
59    /// The service is paused.
60    Paused,
61    /// Pause is pending.
62    PausePending,
63    /// The service is running.
64    Running,
65    /// Start is pending.
66    StartPending,
67    /// The service is stopped.
68    Stopped,
69    /// Stop is pending.
70    StopPending,
71}
72
73/// Configures and runs a Windows service.
74pub struct Service<'a> {
75    accept: u32,
76    fallback: Option<Box<dyn FnOnce(&Service) + 'a>>,
77    handle: RwLock<SERVICE_STATUS_HANDLE>,
78    callback: RwLock<Option<Box<dyn FnMut(&Service, Command) + Send + Sync + 'a>>>,
79    status: RwLock<SERVICE_STATUS>,
80}
81
82impl Default for Service<'_> {
83    fn default() -> Self {
84        Self::new()
85    }
86}
87
88unsafe impl Send for Service<'_> {}
89unsafe impl Sync for Service<'_> {}
90
91impl<'a> Service<'a> {
92    /// Creates a service that accepts only the start command.
93    pub fn new() -> Self {
94        Self {
95            accept: 0,
96            fallback: None,
97            handle: RwLock::new(std::ptr::null_mut()),
98            callback: RwLock::new(None),
99            status: RwLock::new(SERVICE_STATUS {
100                dwServiceType: SERVICE_WIN32_OWN_PROCESS as u32,
101                dwCurrentState: SERVICE_STOPPED as u32,
102                dwControlsAccepted: 0,
103                dwWin32ExitCode: 0,
104                dwServiceSpecificExitCode: 0,
105                dwCheckPoint: 0,
106                dwWaitHint: 0,
107            }),
108        }
109    }
110
111    /// The service accepts stop and shutdown commands.
112    pub fn can_stop(&mut self) -> &mut Self {
113        self.accept |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN) as u32;
114        self
115    }
116
117    /// The service accepts pause and resume commands.
118    pub fn can_pause(&mut self) -> &mut Self {
119        self.accept |= SERVICE_ACCEPT_PAUSE_CONTINUE as u32;
120        self
121    }
122
123    /// The service accepts other specified commands.
124    pub fn can_accept(&mut self, accept: u32) -> &mut Self {
125        self.accept |= accept;
126        self
127    }
128
129    /// Runs the fallback closure if the service is not started by the Service Control Manager.
130    pub fn can_fallback<F: FnOnce(&Service) + Send + 'a>(&mut self, f: F) -> &mut Self {
131        self.fallback = Some(Box::new(f));
132        self
133    }
134
135    /// Runs the service with the given callback closure to receive commands sent by the service
136    /// control manager.
137    ///
138    /// Blocks while the service dispatcher runs. Returns after the service stops or the fallback
139    /// closure completes.
140    pub fn run<F: FnMut(&Service, Command) + Send + Sync + 'a>(
141        &mut self,
142        callback: F,
143    ) -> Result<(), &'static str> {
144        debug_assert!(self.status.read().unwrap().dwCurrentState == SERVICE_STOPPED as u32);
145        self.status.write().unwrap().dwControlsAccepted = self.accept;
146
147        {
148            let mut write = self.callback.write().unwrap();
149
150            assert!(!write.is_some(), "`run` was already called");
151
152            *write = Some(Box::new(callback));
153        }
154
155        let table = [
156            SERVICE_TABLE_ENTRYW {
157                lpServiceName: &mut 0,
158                lpServiceProc: Some(service_main),
159            },
160            SERVICE_TABLE_ENTRYW::default(),
161        ];
162
163        SERVICE_CONTEXT.write().unwrap().0 = self as *const _ as _;
164
165        let fallback = unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) == 0 };
166
167        if fallback {
168            if let Some(fallback) = self.fallback.take() {
169                self.set_state(State::StartPending);
170                self.command(Command::Start);
171                self.set_state(State::Running);
172                fallback(self);
173                self.set_state(State::StopPending);
174                self.command(Command::Stop);
175            } else {
176                return Err("Use service control manager to start service");
177            }
178        }
179
180        Ok(())
181    }
182
183    /// Sets the current state of the service.
184    ///
185    /// In most cases, the service state is updated automatically and does not need to be set
186    /// directly.
187    pub fn set_state(&self, state: State) {
188        let mut writer = self.status.write().unwrap();
189        writer.dwCurrentState = match state {
190            State::ContinuePending => SERVICE_CONTINUE_PENDING,
191            State::Paused => SERVICE_PAUSED,
192            State::PausePending => SERVICE_PAUSE_PENDING,
193            State::Running => SERVICE_RUNNING,
194            State::StartPending => SERVICE_START_PENDING,
195            State::Stopped => SERVICE_STOPPED,
196            State::StopPending => SERVICE_STOP_PENDING,
197        } as u32;
198
199        // Makes a copy to avoid holding a lock while calling `SetServiceStatus`.
200        let status: SERVICE_STATUS = *writer;
201        drop(writer);
202
203        unsafe {
204            SetServiceStatus(self.handle(), &status);
205        }
206    }
207
208    /// The raw handle representing the service.
209    pub fn handle(&self) -> *mut c_void {
210        *self.handle.read().unwrap()
211    }
212
213    /// Returns the current state of the service.
214    pub fn state(&self) -> State {
215        let reader = self.status.read().unwrap();
216
217        match reader.dwCurrentState as i32 {
218            SERVICE_CONTINUE_PENDING => State::ContinuePending,
219            SERVICE_PAUSED => State::Paused,
220            SERVICE_PAUSE_PENDING => State::PausePending,
221            SERVICE_RUNNING => State::Running,
222            SERVICE_START_PENDING => State::StartPending,
223            SERVICE_STOPPED => State::Stopped,
224            SERVICE_STOP_PENDING => State::StopPending,
225            _ => panic!("unexpected state"),
226        }
227    }
228
229    /// Sends the command to the service callback.
230    pub fn command(&self, command: Command) {
231        let mut write = self.callback.write().unwrap();
232        (write.as_deref_mut().unwrap())(self, command);
233    }
234
235    /// Low-level dispatcher to send control commands directly to the service.
236    pub fn handler(&self, control: u32, event_type: u32, event_data: *const c_void) -> u32 {
237        handler(
238            control,
239            event_type,
240            event_data as *mut _,
241            self as *const _ as _,
242        )
243    }
244}
245
246extern "system" fn service_main(_len: u32, _args: *mut PWSTR) {
247    let service: &Service = unsafe { &*(SERVICE_CONTEXT.read().unwrap().0 as *const Service) };
248
249    *service.handle.write().unwrap() = unsafe {
250        RegisterServiceCtrlHandlerExW(std::ptr::null(), Some(handler), service as *const _ as _)
251    };
252
253    service.set_state(State::StartPending);
254    service.command(Command::Start);
255    service.set_state(State::Running);
256}
257
258extern "system" fn handler(control: u32, ty: u32, data: *mut c_void, context: *mut c_void) -> u32 {
259    let service = unsafe { &*(context as *const Service) };
260
261    match control as i32 {
262        SERVICE_CONTROL_CONTINUE if service.state() == State::Paused => {
263            service.set_state(State::ContinuePending);
264            service.command(Command::Resume);
265            service.set_state(State::Running);
266        }
267        SERVICE_CONTROL_PAUSE if service.state() == State::Running => {
268            service.set_state(State::PausePending);
269            service.command(Command::Pause);
270            service.set_state(State::Paused);
271        }
272        SERVICE_CONTROL_SHUTDOWN | SERVICE_CONTROL_STOP => {
273            service.set_state(State::StopPending);
274            service.command(Command::Stop);
275            service.set_state(State::Stopped);
276        }
277        _ => service.command(Command::Extended(ExtendedCommand { control, ty, data })),
278    }
279
280    NO_ERROR as u32
281}
282
283// The dispatcher callback has no user-defined context parameter.
284// This lock allows us to safely retrieve the service instance from the service callback.
285#[derive(Debug)]
286struct ServiceContext(*const c_void);
287static SERVICE_CONTEXT: RwLock<ServiceContext> = RwLock::new(ServiceContext(std::ptr::null()));
288unsafe impl Send for ServiceContext {}
289unsafe impl Sync for ServiceContext {}