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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
13pub enum Command {
14 Start,
16
17 Stop,
21
22 Pause,
26
27 Resume,
31
32 Extended(ExtendedCommand),
36}
37
38#[derive(Debug, Copy, Clone, PartialEq, Eq)]
40pub struct ExtendedCommand {
41 pub control: u32,
43
44 pub ty: u32,
46
47 pub data: *const c_void,
49}
50
51unsafe impl Send for ExtendedCommand {}
52unsafe impl Sync for ExtendedCommand {}
53
54#[derive(Debug, Copy, Clone, PartialEq, Eq)]
56pub enum State {
57 ContinuePending,
59 Paused,
61 PausePending,
63 Running,
65 StartPending,
67 Stopped,
69 StopPending,
71}
72
73pub 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 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 pub fn can_stop(&mut self) -> &mut Self {
113 self.accept |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN) as u32;
114 self
115 }
116
117 pub fn can_pause(&mut self) -> &mut Self {
119 self.accept |= SERVICE_ACCEPT_PAUSE_CONTINUE as u32;
120 self
121 }
122
123 pub fn can_accept(&mut self, accept: u32) -> &mut Self {
125 self.accept |= accept;
126 self
127 }
128
129 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 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 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 let status: SERVICE_STATUS = *writer;
201 drop(writer);
202
203 unsafe {
204 SetServiceStatus(self.handle(), &status);
205 }
206 }
207
208 pub fn handle(&self) -> *mut c_void {
210 *self.handle.read().unwrap()
211 }
212
213 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 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 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#[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 {}