Skip to main content

eggup_service/
windows_scm.rs

1#[cfg(test)]
2use std::collections::VecDeque;
3use std::fmt;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use crate::{
8    reconcile_config_identity, require_owned, HealthState, LifecycleSnapshot, LifecycleState,
9    ManagerFailureKind, OperationDeadline, Ownership, RegistrationSnapshot, ServiceError,
10    ServiceId, ServiceManager, ServiceOperation, ServiceSpec, TransitionResult,
11    MAX_TRANSITION_TIMEOUT,
12};
13
14const MAX_SCM_NAME_CHARS: usize = 256;
15const MAX_SCM_COMMAND_CHARS: usize = 8192;
16const DEFAULT_SCM_TIMEOUT: Duration = Duration::from_secs(30);
17const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(50);
18const MAX_POLL_INTERVAL: Duration = Duration::from_millis(500);
19
20/// Caller-selected Windows service startup mode.
21///
22/// # Errors
23///
24/// Infallible: this type carries a caller choice and cannot fail. The Service
25/// Control Manager conditions it takes part in — an access denial (OS code
26/// `5`) and a registration that disappeared before the operation — are
27/// reported by [`WindowsScmManager`]'s operations, not by this type.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum WindowsStartType {
30    /// Start automatically when Windows starts.
31    Automatic,
32    /// Start only when requested by an operator or manager.
33    Manual,
34    /// Leave registered but prevent start requests from succeeding.
35    Disabled,
36}
37
38/// Caller-selected SCM error-control setting.
39///
40/// # Errors
41///
42/// Infallible: this type carries a caller choice and cannot fail. The Service
43/// Control Manager conditions it takes part in — an access denial (OS code
44/// `5`) and a registration that disappeared before the operation — are
45/// reported by [`WindowsScmManager`]'s operations, not by this type.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum WindowsErrorControl {
48    /// Log the error and continue startup.
49    Ignore,
50    /// Log the error and continue startup.
51    Normal,
52    /// Log the error; restart using the last-known-good configuration.
53    Severe,
54    /// Log the error; startup fails using the last-known-good configuration.
55    Critical,
56}
57
58/// A caller-selected SCM dependency by service key or load-order group.
59///
60/// # Errors
61///
62/// Infallible: this type carries a caller choice and cannot fail. The Service
63/// Control Manager conditions it takes part in — an access denial (OS code
64/// `5`) and a registration that disappeared before the operation — are
65/// reported by [`WindowsScmManager`]'s operations, not by this type.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum WindowsServiceDependency {
68    /// Require another service to start first.
69    Service(String),
70    /// Require a Windows load-order group to start first.
71    Group(String),
72}
73
74/// Caller-owned settings used when creating or refreshing an SCM registration.
75///
76/// The descriptor intentionally omits failure actions, service descriptions,
77/// dependencies, custom passwords, and service-entrypoint configuration. A
78/// refresh preserves existing fields that this descriptor does not own.
79///
80/// # Errors
81///
82/// The validating builders on this type report
83/// [`ServiceError::InvalidInput`]: an empty, overlong, path-like, or
84/// control-character service name, display name, account name, or dependency
85/// name; a duplicate dependency name; and a zero or overlong transition
86/// timeout. The Service Control Manager's own conditions — an access denial
87/// (OS code `5`) and a registration that disappeared before the operation —
88/// are reported by [`WindowsScmManager`]'s operations, not by this type.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct WindowsScmInstall {
91    service_id: ServiceId,
92    display_name: String,
93    start_type: WindowsStartType,
94    error_control: WindowsErrorControl,
95    account_name: Option<String>,
96    dependencies: Option<Vec<WindowsServiceDependency>>,
97    transition_timeout: Duration,
98}
99
100impl WindowsScmInstall {
101    /// Creates a caller-owned SCM install descriptor.
102    ///
103    /// # Errors
104    ///
105    /// [`ServiceError::InvalidInput`] when the service name is empty,
106    /// overlong (`MAX_SCM_NAME_CHARS` UTF-16 units), path-like, or contains a
107    /// control character; when the display name is empty, overlong, or
108    /// contains a control character; or when the account name is empty,
109    /// overlong, or contains a control character.
110    pub fn new(
111        service_name: impl Into<String>,
112        display_name: impl Into<String>,
113        start_type: WindowsStartType,
114        error_control: WindowsErrorControl,
115        account_name: Option<String>,
116    ) -> Result<Self, ServiceError> {
117        let service_name = service_name.into();
118        validate_service_name(&service_name)?;
119        let display_name = display_name.into();
120        validate_display_name(&display_name)?;
121        if let Some(account) = &account_name {
122            validate_account_name(account)?;
123        }
124        Ok(Self {
125            service_id: ServiceId::new(service_name)?,
126            display_name,
127            start_type,
128            error_control,
129            account_name,
130            dependencies: None,
131            transition_timeout: DEFAULT_SCM_TIMEOUT,
132        })
133    }
134
135    /// Sets caller-owned SCM dependencies. An empty list explicitly clears
136    /// dependencies during refresh; leaving this unset preserves them.
137    ///
138    /// # Errors
139    ///
140    /// [`ServiceError::InvalidInput`] when a dependency name is empty,
141    /// overlong (`MAX_SCM_NAME_CHARS` UTF-16 units), path-like, or contains a
142    /// control character, or when the list names the same service or group
143    /// twice.
144    pub fn with_dependencies(
145        mut self,
146        dependencies: Vec<WindowsServiceDependency>,
147    ) -> Result<Self, ServiceError> {
148        validate_dependencies(&dependencies)?;
149        self.dependencies = Some(dependencies);
150        Ok(self)
151    }
152
153    /// Sets the bounded timeout used by install/uninstall and SCM polling.
154    ///
155    /// # Errors
156    ///
157    /// [`ServiceError::InvalidInput`] when the timeout is zero or exceeds
158    /// [`MAX_TRANSITION_TIMEOUT`].
159    pub fn with_transition_timeout(mut self, timeout: Duration) -> Result<Self, ServiceError> {
160        if timeout.is_zero() || timeout > MAX_TRANSITION_TIMEOUT {
161            return Err(ServiceError::invalid("transition timeout out of range"));
162        }
163        self.transition_timeout = timeout;
164        Ok(self)
165    }
166
167    /// The Windows service key name.
168    pub fn service_id(&self) -> &ServiceId {
169        &self.service_id
170    }
171
172    /// The caller-owned display name.
173    pub fn display_name(&self) -> &str {
174        &self.display_name
175    }
176
177    /// The caller-owned startup mode.
178    pub fn start_type(&self) -> WindowsStartType {
179        self.start_type
180    }
181
182    /// The caller-owned error-control setting.
183    pub fn error_control(&self) -> WindowsErrorControl {
184        self.error_control
185    }
186
187    /// Optional caller-selected account name; no account password is accepted or stored.
188    pub fn account_name(&self) -> Option<&str> {
189        self.account_name.as_deref()
190    }
191
192    /// Optional caller-owned SCM dependencies; `None` preserves them on refresh.
193    pub fn dependencies(&self) -> Option<&[WindowsServiceDependency]> {
194        self.dependencies.as_deref()
195    }
196
197    /// The bounded timeout used by install/uninstall and SCM polling.
198    pub fn transition_timeout(&self) -> Duration {
199        self.transition_timeout
200    }
201}
202
203fn validate_service_name(value: &str) -> Result<(), ServiceError> {
204    if value.is_empty()
205        || value.encode_utf16().count() > MAX_SCM_NAME_CHARS
206        || value.chars().any(|c| c.is_control() || c == '\0')
207        || value.contains(['/', '\\'])
208    {
209        return Err(ServiceError::invalid(
210            "Windows service name is empty, overlong, path-like, or has controls",
211        ));
212    }
213    Ok(())
214}
215
216fn validate_display_name(value: &str) -> Result<(), ServiceError> {
217    if value.is_empty()
218        || value.encode_utf16().count() > MAX_SCM_NAME_CHARS
219        || value.chars().any(|c| c.is_control() || c == '\0')
220    {
221        return Err(ServiceError::invalid(
222            "Windows service display name is empty, overlong, or has controls",
223        ));
224    }
225    Ok(())
226}
227
228fn validate_account_name(value: &str) -> Result<(), ServiceError> {
229    if value.is_empty()
230        || value.encode_utf16().count() > MAX_SCM_NAME_CHARS
231        || value.chars().any(|c| c.is_control() || c == '\0')
232    {
233        return Err(ServiceError::invalid(
234            "Windows service account name is empty, overlong, or has controls",
235        ));
236    }
237    Ok(())
238}
239
240fn validate_dependencies(dependencies: &[WindowsServiceDependency]) -> Result<(), ServiceError> {
241    let mut seen = std::collections::HashSet::new();
242    for dependency in dependencies {
243        let (kind, namespace, name) = match dependency {
244            WindowsServiceDependency::Service(name) => ("service", 's', name),
245            WindowsServiceDependency::Group(name) => ("group", 'g', name),
246        };
247        if name.is_empty()
248            || name.encode_utf16().count() > MAX_SCM_NAME_CHARS
249            || name.chars().any(|c| c.is_control() || c == '\0')
250            || name.contains(['/', '\\'])
251        {
252            return Err(ServiceError::invalid(format!(
253                "Windows SCM {kind} dependency is empty, overlong, path-like, or has controls"
254            )));
255        }
256        let key = (namespace, name.to_ascii_lowercase());
257        if !seen.insert(key) {
258            return Err(ServiceError::invalid(
259                "Windows SCM dependencies contain a duplicate name",
260            ));
261        }
262    }
263    Ok(())
264}
265
266/// Renders the bounded detail for one SCM failure.
267///
268/// The mapping is: OS code `5` becomes the access-denied sentence that names
269/// the remediation and no elevation path; every other code becomes a bounded
270/// generic failure sentence that still carries the raw code.
271///
272/// # Errors
273///
274/// Infallible: this renders a diagnostic, it does not produce an error. The
275/// conditions it encodes — an access denial (OS code `5`) and any other SCM
276/// code, reported as a typed [`ServiceError::Manager`] that keeps the raw OS
277/// code reachable — are produced by [`WindowsBackend::map_error`].
278#[cfg(any(windows, test))]
279fn scm_error_detail(operation: &'static str, code: Option<i32>) -> String {
280    if code == Some(5) {
281        format!("{operation} denied by Windows SCM (code 5); run with an account authorized for this service operation")
282    } else {
283        format!(
284            "{operation} failed in Windows SCM (code {})",
285            code.unwrap_or_default()
286        )
287    }
288}
289
290/// Why an SCM service handle could not be opened.
291///
292/// The two codes that carry a *meaning* about the registration stay distinct
293/// so the mapping is lossless: `1060` (the specified service does not exist)
294/// and `1072` (the service is marked for deletion). Every other SCM code is
295/// carried verbatim in [`OpenFailure::Other`] and surfaces as a typed error,
296/// never as a panic.
297#[cfg(any(windows, test))]
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299enum OpenFailure {
300    /// SCM code `1060`: the specified service does not exist.
301    NotFound,
302    /// SCM code `1072`: the service is marked for deletion.
303    MarkedForDelete,
304    /// Any other SCM failure, carrying the raw OS code when the platform
305    /// supplied one.
306    Other(Option<i32>),
307}
308
309/// Classifies a raw SCM OS code into an [`OpenFailure`].
310///
311/// `1060` and `1072` are the only codes that carry a meaning about the
312/// registration; every other code — and a failure that carried no code at
313/// all — is carried verbatim so nothing is lost.
314#[cfg(any(windows, test))]
315fn classify_open_code(code: Option<i32>) -> OpenFailure {
316    match code {
317        Some(1060) => OpenFailure::NotFound,
318        Some(1072) => OpenFailure::MarkedForDelete,
319        other => OpenFailure::Other(other),
320    }
321}
322
323/// The typed error an unmapped SCM open failure produces.
324///
325/// The raw OS code stays reachable through [`ServiceError::manager_os_code`],
326/// so the mapping is lossless. Code `5` (access denied) becomes
327/// [`ManagerFailureKind::Permission`]; every other code becomes
328/// [`ManagerFailureKind::Protocol`].
329///
330/// # Errors
331///
332/// Always returns a typed [`ServiceError::Manager`]. It never panics and
333/// never degrades into an "absent" or "marked for delete" reading: only the
334/// SCM's `1060` and `1072` codes may take those paths.
335#[cfg(any(windows, test))]
336fn unmapped_open_error(code: Option<i32>) -> ServiceError {
337    ServiceError::manager_with_os_code(
338        ManagerFailureKind::from_scm_os_code(code),
339        scm_error_detail("open service", code),
340        code,
341    )
342}
343
344/// The typed error a mutating SCM operation reports when the handle cannot be
345/// opened.
346///
347/// `1060` and `1072` are the only codes that mean "the service is gone":
348/// they become a conflict naming the operation. Any other code becomes a
349/// typed manager error that keeps the raw OS code.
350///
351/// # Errors
352///
353/// Always returns a typed [`ServiceError`]: [`ServiceError::Conflict`] for the
354/// disappeared case, [`ServiceError::Manager`] for every other code. It never
355/// panics.
356#[cfg(any(windows, test))]
357fn open_failure(operation: &'static str, failure: OpenFailure) -> ServiceError {
358    match failure {
359        OpenFailure::NotFound | OpenFailure::MarkedForDelete => {
360            ServiceError::conflict(format!("service disappeared before {operation}"))
361        }
362        OpenFailure::Other(code) => unmapped_open_error(code),
363    }
364}
365
366/// Native Windows SCM adapter implementing the manager-neutral contract.
367///
368/// `new` is available on Windows. The ownership, command-line parser, and
369/// deterministic backend tests are platform-independent. No `sc.exe`, shell,
370/// ambient `PATH`, or automatic elevation is used.
371///
372/// # Errors
373///
374/// The adapter's operations report the Service Control Manager's conditions as
375/// typed [`ServiceError`]s and never as a panic:
376///
377/// * an access denial (OS code `5`) becomes [`ServiceError::Manager`] with
378///   [`ManagerFailureKind::Permission`] and a bounded remediation detail that
379///   names no elevation path;
380/// * a registration that disappeared before the operation — the SCM's `1060`
381///   (does not exist) and `1072` (marked for deletion) codes — becomes
382///   [`ServiceError::Conflict`];
383/// * any other SCM code becomes [`ServiceError::Manager`] with the raw OS
384///   code still reachable through [`ServiceError::manager_os_code`];
385/// * an observation whose ownership is not `Owned` is denied with
386///   [`ServiceError::OwnershipDenied`].
387#[derive(Debug)]
388pub struct WindowsScmManager {
389    backend: Box<dyn ScmBackend>,
390    install: WindowsScmInstall,
391}
392
393impl WindowsScmManager {
394    /// Creates an adapter using the local Windows Service Control Manager.
395    ///
396    /// # Errors
397    ///
398    /// This constructor is infallible: it does not contact the Service Control
399    /// Manager, and every SCM handle is opened per operation. The conditions
400    /// the adapter reports are the ones named on [`WindowsScmManager`]: an
401    /// access denial (OS code `5`), a registration that disappeared before
402    /// the operation, and any other SCM code carried losslessly.
403    #[cfg(windows)]
404    pub fn new(install: WindowsScmInstall) -> Self {
405        Self {
406            backend: Box::<WindowsBackend>::default(),
407            install,
408        }
409    }
410
411    /// Returns the caller-owned descriptor.
412    pub fn install_config(&self) -> &WindowsScmInstall {
413        &self.install
414    }
415
416    #[cfg(test)]
417    fn with_backend(backend: impl ScmBackend + 'static, install: WindowsScmInstall) -> Self {
418        Self {
419            backend: Box::new(backend),
420            install,
421        }
422    }
423
424    fn validate_spec(&self, spec: &ServiceSpec) -> Result<(), ServiceError> {
425        if spec.id() != &self.install.service_id {
426            return Err(ServiceError::invalid(
427                "service spec id does not match Windows install descriptor",
428            ));
429        }
430        if !is_windows_absolute_path(spec.executable()) {
431            return Err(ServiceError::invalid(
432                "Windows service executable must be an absolute Windows path",
433            ));
434        }
435        let executable = spec.executable().to_str().ok_or_else(|| {
436            ServiceError::invalid("Windows service executable must be representable as UTF-8")
437        })?;
438        if let Some(config) = spec.config() {
439            if config.to_str().is_none() {
440                return Err(ServiceError::invalid(
441                    "Windows service config path must be representable as UTF-8",
442                ));
443            }
444        }
445        let command_budget = executable
446            .encode_utf16()
447            .count()
448            .saturating_mul(2)
449            .saturating_add(2)
450            .saturating_add(
451                spec.args()
452                    .iter()
453                    .map(|arg| {
454                        arg.encode_utf16()
455                            .count()
456                            .saturating_mul(2)
457                            .saturating_add(3)
458                    })
459                    .sum::<usize>(),
460            );
461        if command_budget > MAX_SCM_COMMAND_CHARS {
462            return Err(ServiceError::invalid(
463                "Windows service command line exceeds the supported bound",
464            ));
465        }
466        Ok(())
467    }
468
469    fn observe(
470        &mut self,
471        spec: &ServiceSpec,
472        deadline: OperationDeadline,
473    ) -> Result<(Ownership, ScmLookup), ServiceError> {
474        self.validate_spec(spec)?;
475        let lookup = self.backend.query(spec.id(), deadline.command_timeout()?)?;
476        if deadline.expired() {
477            return Err(ServiceError::manager(
478                ManagerFailureKind::Timeout,
479                "SCM query exceeded transition deadline",
480            ));
481        }
482        let ownership = match &lookup {
483            ScmLookup::Absent => Ownership::Absent,
484            ScmLookup::MarkedForDelete => Ownership::Unknown,
485            ScmLookup::Present(record) => registration_ownership(record, spec),
486        };
487        Ok((ownership, lookup))
488    }
489
490    fn require_owned_observation(
491        &mut self,
492        spec: &ServiceSpec,
493        deadline: OperationDeadline,
494    ) -> Result<ScmRecord, ServiceError> {
495        let (ownership, lookup) = self.observe(spec, deadline)?;
496        require_owned(spec.id(), ownership)?;
497        match lookup {
498            ScmLookup::Present(record) => Ok(record),
499            ScmLookup::Absent | ScmLookup::MarkedForDelete => {
500                Err(ServiceError::denied(spec.id(), ownership))
501            }
502        }
503    }
504
505    fn wait_for_state(
506        &mut self,
507        spec: &ServiceSpec,
508        target: ScmState,
509        deadline: OperationDeadline,
510    ) -> Result<bool, ServiceError> {
511        loop {
512            let record = self.require_owned_observation(spec, deadline)?;
513            if record.state == target {
514                return Ok(!deadline.expired());
515            }
516            if deadline.expired() {
517                return Ok(false);
518            }
519            let wait = if record.wait_hint.is_zero() {
520                DEFAULT_POLL_INTERVAL
521            } else {
522                record.wait_hint.min(MAX_POLL_INTERVAL)
523            };
524            let delay = deadline.remaining().unwrap_or_default().min(wait);
525            if delay.is_zero() {
526                return Ok(false);
527            }
528            self.backend.sleep(delay);
529        }
530    }
531
532    fn stop_phase_for_restart(
533        &mut self,
534        spec: &ServiceSpec,
535        deadline: OperationDeadline,
536    ) -> Result<bool, ServiceError> {
537        loop {
538            let record = self.require_owned_observation(spec, deadline)?;
539            match record.state {
540                ScmState::Stopped => return Ok(!deadline.expired()),
541                ScmState::Running | ScmState::Paused => {
542                    self.backend.stop(spec.id(), deadline.command_timeout()?)?;
543                    return self.wait_for_state(spec, ScmState::Stopped, deadline);
544                }
545                ScmState::Unknown => return Ok(false),
546                ScmState::StartPending
547                | ScmState::StopPending
548                | ScmState::ContinuePending
549                | ScmState::PausePending => {}
550            }
551            if deadline.expired() {
552                return Ok(false);
553            }
554            let wait = if record.wait_hint.is_zero() {
555                DEFAULT_POLL_INTERVAL
556            } else {
557                record.wait_hint.min(MAX_POLL_INTERVAL)
558            };
559            let delay = deadline.remaining().unwrap_or_default().min(wait);
560            if delay.is_zero() {
561                return Ok(false);
562            }
563            self.backend.sleep(delay);
564        }
565    }
566
567    fn transition(
568        operation: ServiceOperation,
569        completed: bool,
570        detail: &'static str,
571    ) -> TransitionResult {
572        TransitionResult {
573            operation,
574            completed,
575            detail: ServiceError::bounded(detail),
576        }
577    }
578}
579
580impl ServiceManager for WindowsScmManager {
581    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
582        self.validate_spec(spec)?;
583        let deadline = OperationDeadline::new(self.install.transition_timeout)?;
584        let lookup = self.backend.query(spec.id(), deadline.command_timeout()?)?;
585        if deadline.expired() {
586            return Err(ServiceError::manager(
587                ManagerFailureKind::Timeout,
588                "SCM inspection exceeded transition deadline",
589            ));
590        }
591        let (ownership, state, present) = match lookup {
592            ScmLookup::Absent => (Ownership::Absent, LifecycleState::Stopped, false),
593            ScmLookup::MarkedForDelete => (Ownership::Unknown, LifecycleState::Transitioning, true),
594            ScmLookup::Present(record) => (
595                registration_ownership(&record, spec),
596                lifecycle_state(record.state),
597                true,
598            ),
599        };
600        Ok(LifecycleSnapshot {
601            id: spec.id().clone(),
602            ownership,
603            state,
604            health: HealthState::Unknown,
605            was_registered: present,
606            was_running: state == LifecycleState::Running,
607        })
608    }
609
610    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
611        self.validate_spec(spec)?;
612        let deadline = OperationDeadline::new(self.install.transition_timeout)?;
613        let (ownership, _) = self.observe(spec, deadline)?;
614        match ownership {
615            Ownership::Absent => {
616                self.backend
617                    .create(&self.install, spec, deadline.command_timeout()?)?;
618                if deadline.expired() {
619                    return Ok(Self::transition(
620                        ServiceOperation::Install,
621                        false,
622                        "create accepted; registration confirmation exceeded deadline",
623                    ));
624                }
625                let (after, _) = self.observe(spec, deadline)?;
626                if after != Ownership::Owned {
627                    return Err(ServiceError::denied(spec.id(), after));
628                }
629                Ok(Self::transition(
630                    ServiceOperation::Install,
631                    true,
632                    "created owned Windows service registration",
633                ))
634            }
635            Ownership::Owned => {
636                let (rechecked, _) = self.observe(spec, deadline)?;
637                if rechecked != Ownership::Owned {
638                    return Err(ServiceError::denied(spec.id(), rechecked));
639                }
640                self.backend
641                    .refresh(&self.install, spec, deadline.command_timeout()?)?;
642                if deadline.expired() {
643                    return Ok(Self::transition(
644                        ServiceOperation::Install,
645                        false,
646                        "refresh accepted; registration confirmation exceeded deadline",
647                    ));
648                }
649                let (after, _) = self.observe(spec, deadline)?;
650                if after != Ownership::Owned {
651                    return Err(ServiceError::denied(spec.id(), after));
652                }
653                Ok(Self::transition(
654                    ServiceOperation::Install,
655                    true,
656                    "refreshed owned Windows service settings",
657                ))
658            }
659            Ownership::Foreign | Ownership::Unknown => {
660                Err(ServiceError::denied(spec.id(), ownership))
661            }
662        }
663    }
664
665    fn start(
666        &mut self,
667        spec: &ServiceSpec,
668        timeout: Duration,
669    ) -> Result<TransitionResult, ServiceError> {
670        self.validate_spec(spec)?;
671        let deadline = OperationDeadline::new(timeout)?;
672        let record = self.require_owned_observation(spec, deadline)?;
673        match record.state {
674            ScmState::Running => Ok(Self::transition(
675                ServiceOperation::Start,
676                !deadline.expired(),
677                "already running",
678            )),
679            ScmState::Stopped => {
680                self.backend.start(spec.id(), deadline.command_timeout()?)?;
681                let completed = self.wait_for_state(spec, ScmState::Running, deadline)?;
682                Ok(Self::transition(
683                    ServiceOperation::Start,
684                    completed,
685                    if completed {
686                        "started"
687                    } else {
688                        "start incomplete; running state unconfirmed"
689                    },
690                ))
691            }
692            ScmState::StartPending | ScmState::ContinuePending => {
693                let completed = self.wait_for_state(spec, ScmState::Running, deadline)?;
694                Ok(Self::transition(
695                    ServiceOperation::Start,
696                    completed,
697                    if completed {
698                        "start transition completed"
699                    } else {
700                        "start incomplete; running state unconfirmed"
701                    },
702                ))
703            }
704            ScmState::StopPending
705            | ScmState::PausePending
706            | ScmState::Paused
707            | ScmState::Unknown => Ok(Self::transition(
708                ServiceOperation::Start,
709                false,
710                "start not issued from an unsupported or conflicting SCM state",
711            )),
712        }
713    }
714
715    fn stop(
716        &mut self,
717        spec: &ServiceSpec,
718        timeout: Duration,
719    ) -> Result<TransitionResult, ServiceError> {
720        self.validate_spec(spec)?;
721        let deadline = OperationDeadline::new(timeout)?;
722        let record = self.require_owned_observation(spec, deadline)?;
723        match record.state {
724            ScmState::Stopped => Ok(Self::transition(
725                ServiceOperation::Stop,
726                !deadline.expired(),
727                "already stopped",
728            )),
729            ScmState::Running | ScmState::Paused => {
730                self.backend.stop(spec.id(), deadline.command_timeout()?)?;
731                let completed = self.wait_for_state(spec, ScmState::Stopped, deadline)?;
732                Ok(Self::transition(
733                    ServiceOperation::Stop,
734                    completed,
735                    if completed {
736                        "stopped"
737                    } else {
738                        "stop incomplete; stopped state unconfirmed"
739                    },
740                ))
741            }
742            ScmState::StopPending => {
743                let completed = self.wait_for_state(spec, ScmState::Stopped, deadline)?;
744                Ok(Self::transition(
745                    ServiceOperation::Stop,
746                    completed,
747                    if completed {
748                        "stop transition completed"
749                    } else {
750                        "stop incomplete; stopped state unconfirmed"
751                    },
752                ))
753            }
754            ScmState::StartPending
755            | ScmState::ContinuePending
756            | ScmState::PausePending
757            | ScmState::Unknown => Ok(Self::transition(
758                ServiceOperation::Stop,
759                false,
760                "stop not issued from an unsupported or conflicting SCM state",
761            )),
762        }
763    }
764
765    fn restart(
766        &mut self,
767        spec: &ServiceSpec,
768        timeout: Duration,
769    ) -> Result<TransitionResult, ServiceError> {
770        self.validate_spec(spec)?;
771        let deadline = OperationDeadline::new(timeout)?;
772        let stopped = self.stop_phase_for_restart(spec, deadline)?;
773        if !stopped || deadline.expired() {
774            return Ok(Self::transition(
775                ServiceOperation::Restart,
776                false,
777                "restart stop phase incomplete; start was not issued",
778            ));
779        }
780        let stopped_record = self.require_owned_observation(spec, deadline)?;
781        if stopped_record.state != ScmState::Stopped {
782            return Ok(Self::transition(
783                ServiceOperation::Restart,
784                false,
785                "restart stop phase changed before start; start was not issued",
786            ));
787        }
788        self.backend.start(spec.id(), deadline.command_timeout()?)?;
789        let completed = self.wait_for_state(spec, ScmState::Running, deadline)?;
790        Ok(Self::transition(
791            ServiceOperation::Restart,
792            completed,
793            if completed {
794                "restarted"
795            } else {
796                "restart start phase incomplete; running state unconfirmed"
797            },
798        ))
799    }
800
801    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
802        self.validate_spec(spec)?;
803        let deadline = OperationDeadline::new(self.install.transition_timeout)?;
804        let record = self.require_owned_observation(spec, deadline)?;
805        match record.state {
806            ScmState::Running | ScmState::Paused => {
807                self.backend.stop(spec.id(), deadline.command_timeout()?)?;
808                if !self.wait_for_state(spec, ScmState::Stopped, deadline)? {
809                    return Ok(Self::transition(
810                        ServiceOperation::Uninstall,
811                        false,
812                        "stop incomplete; service was not deleted",
813                    ));
814                }
815            }
816            ScmState::StopPending => {
817                if !self.wait_for_state(spec, ScmState::Stopped, deadline)? {
818                    return Ok(Self::transition(
819                        ServiceOperation::Uninstall,
820                        false,
821                        "stop incomplete; service was not deleted",
822                    ));
823                }
824            }
825            ScmState::Stopped => {}
826            ScmState::StartPending
827            | ScmState::ContinuePending
828            | ScmState::PausePending
829            | ScmState::Unknown => {
830                return Ok(Self::transition(
831                    ServiceOperation::Uninstall,
832                    false,
833                    "service state is not safely stopped; registration was not deleted",
834                ));
835            }
836        }
837        let final_check = self.require_owned_observation(spec, deadline)?;
838        if final_check.state != ScmState::Stopped {
839            return Ok(Self::transition(
840                ServiceOperation::Uninstall,
841                false,
842                "service changed before delete; registration was not deleted",
843            ));
844        }
845        self.backend
846            .delete(spec.id(), deadline.command_timeout()?)?;
847        loop {
848            if deadline.expired() {
849                return Ok(Self::transition(
850                    ServiceOperation::Uninstall,
851                    false,
852                    "delete accepted; service remains present or marked for deletion",
853                ));
854            }
855            match self.backend.query(spec.id(), deadline.command_timeout()?)? {
856                ScmLookup::Absent => {
857                    return Ok(Self::transition(
858                        ServiceOperation::Uninstall,
859                        !deadline.expired(),
860                        "service deletion confirmed",
861                    ));
862                }
863                ScmLookup::MarkedForDelete => {}
864                ScmLookup::Present(record) => {
865                    let ownership = registration_ownership(&record, spec);
866                    require_owned(spec.id(), ownership)?;
867                }
868            }
869            let delay = deadline
870                .remaining()
871                .unwrap_or_default()
872                .min(DEFAULT_POLL_INTERVAL);
873            if delay.is_zero() {
874                return Ok(Self::transition(
875                    ServiceOperation::Uninstall,
876                    false,
877                    "delete accepted; service remains present or marked for deletion",
878                ));
879            }
880            self.backend.sleep(delay);
881        }
882    }
883}
884
885/// The SCM lifecycle states the adapter observes.
886///
887/// Every variant except `Unknown` is constructed by the `#[cfg(windows)]` SCM
888/// backend, and by the test helpers in test builds. On a non-Windows build
889/// none of them is constructed, so each carries its own `allow(dead_code)`
890/// instead of one enum-wide allowance: a variant added later is not covered by
891/// that allowance and is still reported.
892#[derive(Debug, Clone, Copy, PartialEq, Eq)]
893enum ScmState {
894    /// The service is stopped.
895    #[cfg_attr(not(windows), allow(dead_code))]
896    Stopped,
897    /// The service is starting.
898    #[cfg_attr(not(windows), allow(dead_code))]
899    StartPending,
900    /// The service is stopping.
901    #[cfg_attr(not(windows), allow(dead_code))]
902    StopPending,
903    /// The service is running.
904    #[cfg_attr(not(windows), allow(dead_code))]
905    Running,
906    /// The service is continuing after a pause.
907    #[cfg_attr(not(windows), allow(dead_code))]
908    ContinuePending,
909    /// The service is pausing.
910    #[cfg_attr(not(windows), allow(dead_code))]
911    PausePending,
912    /// The service is paused.
913    #[cfg_attr(not(windows), allow(dead_code))]
914    Paused,
915    /// The SCM reported a state the adapter cannot classify.
916    ///
917    /// No `windows-service` service state maps to this variant, so it is
918    /// constructed by the test helpers only. It is unreachable on every
919    /// platform and therefore needs its allowance unconditionally.
920    #[allow(dead_code)]
921    Unknown,
922}
923
924#[derive(Debug, Clone, PartialEq, Eq)]
925struct ScmRecord {
926    /// `None` means the API returned a command that cannot be represented as UTF-8.
927    command_line: Option<String>,
928    state: ScmState,
929    wait_hint: Duration,
930}
931
932/// The outcome of an SCM lookup.
933///
934/// Every variant is constructed by the `#[cfg(windows)]` SCM backend, and by
935/// the test helpers in test builds. On a non-Windows build none of them is
936/// constructed, so each carries its own `allow(dead_code)` instead of one
937/// enum-wide allowance: a variant added later is not covered by that
938/// allowance and is still reported.
939#[derive(Debug, Clone, PartialEq, Eq)]
940enum ScmLookup {
941    /// The registration does not exist (SCM code `1060`).
942    #[cfg_attr(not(windows), allow(dead_code))]
943    Absent,
944    /// The registration is marked for deletion (SCM code `1072`).
945    #[cfg_attr(not(windows), allow(dead_code))]
946    MarkedForDelete,
947    /// The registration exists and was read.
948    #[cfg_attr(not(windows), allow(dead_code))]
949    Present(ScmRecord),
950}
951
952trait ScmBackend: fmt::Debug {
953    fn query(&self, id: &ServiceId, remaining: Duration) -> Result<ScmLookup, ServiceError>;
954    fn create(
955        &mut self,
956        install: &WindowsScmInstall,
957        spec: &ServiceSpec,
958        remaining: Duration,
959    ) -> Result<(), ServiceError>;
960    fn refresh(
961        &mut self,
962        install: &WindowsScmInstall,
963        spec: &ServiceSpec,
964        remaining: Duration,
965    ) -> Result<(), ServiceError>;
966    fn start(&mut self, id: &ServiceId, remaining: Duration) -> Result<(), ServiceError>;
967    fn stop(&mut self, id: &ServiceId, remaining: Duration) -> Result<(), ServiceError>;
968    fn delete(&mut self, id: &ServiceId, remaining: Duration) -> Result<(), ServiceError>;
969    #[cfg(test)]
970    fn test_calls(&self) -> Vec<&'static str> {
971        Vec::new()
972    }
973    fn sleep(&mut self, delay: Duration) {
974        std::thread::sleep(delay);
975    }
976}
977
978fn registration_ownership(record: &ScmRecord, spec: &ServiceSpec) -> Ownership {
979    let Some(command_line) = record.command_line.as_deref() else {
980        return Ownership::Unknown;
981    };
982    let Some((executable, args)) = parse_service_command(command_line) else {
983        return Ownership::Unknown;
984    };
985    reconcile_config_identity(
986        RegistrationSnapshot {
987            present: true,
988            executable: Some(executable),
989            args,
990            config: None,
991            malformed: false,
992        },
993        spec,
994    )
995    .ownership(spec)
996}
997
998fn lifecycle_state(state: ScmState) -> LifecycleState {
999    match state {
1000        ScmState::Stopped => LifecycleState::Stopped,
1001        ScmState::Running => LifecycleState::Running,
1002        ScmState::StartPending
1003        | ScmState::StopPending
1004        | ScmState::ContinuePending
1005        | ScmState::PausePending => LifecycleState::Transitioning,
1006        ScmState::Paused | ScmState::Unknown => LifecycleState::Unknown,
1007    }
1008}
1009
1010fn parse_service_command(command_line: &str) -> Option<(PathBuf, Vec<String>)> {
1011    if command_line.is_empty()
1012        || command_line.encode_utf16().count() > MAX_SCM_COMMAND_CHARS
1013        || command_line.chars().any(|c| c.is_control() || c == '\0')
1014        || !has_balanced_windows_quotes(command_line)
1015    {
1016        return None;
1017    }
1018    let mut arguments: Vec<String> = windows_args::Args::parse_cmd(command_line).collect();
1019    if arguments.is_empty() || arguments[0].is_empty() || !is_windows_absolute_str(&arguments[0]) {
1020        return None;
1021    }
1022    if arguments[0].chars().any(char::is_whitespace) && !command_line.starts_with('"') {
1023        return None;
1024    }
1025    if !command_line.starts_with('"') {
1026        let first = command_line.split_whitespace().next()?;
1027        if !first.to_ascii_lowercase().ends_with(".exe") {
1028            return None;
1029        }
1030    }
1031    let executable = PathBuf::from(arguments.remove(0));
1032    Some((executable, arguments))
1033}
1034
1035fn has_balanced_windows_quotes(command_line: &str) -> bool {
1036    let mut quoted = false;
1037    let mut backslashes = 0usize;
1038    for ch in command_line.chars() {
1039        match ch {
1040            '\\' => backslashes = backslashes.saturating_add(1),
1041            '"' => {
1042                if backslashes & 1 == 0 {
1043                    quoted = !quoted;
1044                }
1045                backslashes = 0;
1046            }
1047            _ => backslashes = 0,
1048        }
1049    }
1050    !quoted
1051}
1052
1053fn is_windows_absolute_path(path: &Path) -> bool {
1054    path.to_str().is_some_and(is_windows_absolute_str)
1055}
1056
1057fn is_windows_absolute_str(path: &str) -> bool {
1058    let bytes = path.as_bytes();
1059    (bytes.len() >= 3
1060        && bytes[0].is_ascii_alphabetic()
1061        && bytes[1] == b':'
1062        && matches!(bytes[2], b'\\' | b'/'))
1063        || (path.starts_with(r"\\")
1064            && path[2..]
1065                .split(['\\', '/'])
1066                .filter(|part| !part.is_empty())
1067                .count()
1068                >= 2)
1069}
1070
1071#[cfg(windows)]
1072fn start_type(value: WindowsStartType) -> windows_service::service::ServiceStartType {
1073    use windows_service::service::ServiceStartType;
1074    match value {
1075        WindowsStartType::Automatic => ServiceStartType::AutoStart,
1076        WindowsStartType::Manual => ServiceStartType::OnDemand,
1077        WindowsStartType::Disabled => ServiceStartType::Disabled,
1078    }
1079}
1080
1081#[cfg(windows)]
1082fn error_control(value: WindowsErrorControl) -> windows_service::service::ServiceErrorControl {
1083    use windows_service::service::ServiceErrorControl;
1084    match value {
1085        WindowsErrorControl::Ignore => ServiceErrorControl::Ignore,
1086        WindowsErrorControl::Normal => ServiceErrorControl::Normal,
1087        WindowsErrorControl::Severe => ServiceErrorControl::Severe,
1088        WindowsErrorControl::Critical => ServiceErrorControl::Critical,
1089    }
1090}
1091
1092#[cfg(windows)]
1093fn service_dependencies(
1094    dependencies: &[WindowsServiceDependency],
1095) -> Vec<windows_service::service::ServiceDependency> {
1096    use std::ffi::OsString;
1097    use windows_service::service::ServiceDependency;
1098    dependencies
1099        .iter()
1100        .map(|dependency| match dependency {
1101            WindowsServiceDependency::Service(name) => {
1102                ServiceDependency::Service(OsString::from(name))
1103            }
1104            WindowsServiceDependency::Group(name) => ServiceDependency::Group(OsString::from(name)),
1105        })
1106        .collect()
1107}
1108
1109#[cfg(windows)]
1110#[derive(Debug, Default)]
1111struct WindowsBackend;
1112
1113#[cfg(windows)]
1114impl WindowsBackend {
1115    fn map_error(error: windows_service::Error, operation: &'static str) -> ServiceError {
1116        let code = match &error {
1117            windows_service::Error::Winapi(io_error) => io_error.raw_os_error(),
1118            _ => None,
1119        };
1120        // The kind is decided from the raw OS code, and the code itself stays
1121        // reachable programmatically: it is carried in the error's `os_code`
1122        // and is also rendered into the bounded detail.
1123        ServiceError::manager_with_os_code(
1124            ManagerFailureKind::from_scm_os_code(code),
1125            scm_error_detail(operation, code),
1126            code,
1127        )
1128    }
1129
1130    fn manager(
1131        access: windows_service::service_manager::ServiceManagerAccess,
1132        operation: &'static str,
1133    ) -> Result<windows_service::service_manager::ServiceManager, ServiceError> {
1134        windows_service::service_manager::ServiceManager::local_computer(None::<&str>, access)
1135            .map_err(|error| Self::map_error(error, operation))
1136    }
1137
1138    /// Opens a service handle, mapping the SCM's absence codes to
1139    /// [`OpenFailure`] and every other code to a typed error.
1140    ///
1141    /// # Errors
1142    ///
1143    /// [`ServiceError::Manager`] when the Service Control Manager itself
1144    /// cannot be reached, or when the failure carried no OS code at all. The
1145    /// codes that mean something about the registration — `1060` and `1072` —
1146    /// are returned as [`OpenFailure`] so the caller keeps the lossless
1147    /// mapping; every other OS code is returned as [`OpenFailure::Other`] with
1148    /// the raw code attached.
1149    fn open(
1150        id: &ServiceId,
1151        access: windows_service::service::ServiceAccess,
1152    ) -> Result<Result<windows_service::service::Service, OpenFailure>, ServiceError> {
1153        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
1154        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
1155            .map_err(|error| Self::map_error(error, "open SCM"))?;
1156        match manager.open_service(id.as_str(), access) {
1157            Ok(service) => Ok(Ok(service)),
1158            Err(windows_service::Error::Winapi(error)) => {
1159                Ok(Err(classify_open_code(error.raw_os_error())))
1160            }
1161            Err(error) => Err(Self::map_error(error, "open service")),
1162        }
1163    }
1164
1165    fn info(
1166        install: &WindowsScmInstall,
1167        spec: &ServiceSpec,
1168    ) -> windows_service::service::ServiceInfo {
1169        use std::ffi::OsString;
1170        use windows_service::service::ServiceType;
1171        windows_service::service::ServiceInfo {
1172            name: OsString::from(install.service_id.as_str()),
1173            display_name: OsString::from(&install.display_name),
1174            service_type: ServiceType::OWN_PROCESS,
1175            start_type: start_type(install.start_type),
1176            error_control: error_control(install.error_control),
1177            executable_path: spec.executable().to_path_buf(),
1178            launch_arguments: spec.args().iter().map(OsString::from).collect(),
1179            dependencies: service_dependencies(install.dependencies.as_deref().unwrap_or_default()),
1180            account_name: install.account_name.as_deref().map(OsString::from),
1181            account_password: None,
1182        }
1183    }
1184}
1185
1186#[cfg(windows)]
1187impl ScmBackend for WindowsBackend {
1188    fn query(&self, id: &ServiceId, _remaining: Duration) -> Result<ScmLookup, ServiceError> {
1189        use windows_service::service::ServiceAccess;
1190        match Self::open(
1191            id,
1192            ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS,
1193        )? {
1194            Err(OpenFailure::NotFound) => Ok(ScmLookup::Absent),
1195            Err(OpenFailure::MarkedForDelete) => Ok(ScmLookup::MarkedForDelete),
1196            Err(OpenFailure::Other(code)) => Err(unmapped_open_error(code)),
1197            Ok(service) => {
1198                let config = service
1199                    .query_config()
1200                    .map_err(|error| Self::map_error(error, "query service config"))?;
1201                let status = service
1202                    .query_status()
1203                    .map_err(|error| Self::map_error(error, "query service status"))?;
1204                let command_line = config.executable_path.to_str().map(str::to_owned);
1205                Ok(ScmLookup::Present(ScmRecord {
1206                    command_line,
1207                    state: match status.current_state {
1208                        windows_service::service::ServiceState::Stopped => ScmState::Stopped,
1209                        windows_service::service::ServiceState::StartPending => {
1210                            ScmState::StartPending
1211                        }
1212                        windows_service::service::ServiceState::StopPending => {
1213                            ScmState::StopPending
1214                        }
1215                        windows_service::service::ServiceState::Running => ScmState::Running,
1216                        windows_service::service::ServiceState::ContinuePending => {
1217                            ScmState::ContinuePending
1218                        }
1219                        windows_service::service::ServiceState::PausePending => {
1220                            ScmState::PausePending
1221                        }
1222                        windows_service::service::ServiceState::Paused => ScmState::Paused,
1223                    },
1224                    wait_hint: status.wait_hint,
1225                }))
1226            }
1227        }
1228    }
1229
1230    fn create(
1231        &mut self,
1232        install: &WindowsScmInstall,
1233        spec: &ServiceSpec,
1234        _remaining: Duration,
1235    ) -> Result<(), ServiceError> {
1236        use windows_service::service::{ServiceAccess, ServiceType};
1237        use windows_service::service_manager::ServiceManagerAccess;
1238        let manager = Self::manager(ServiceManagerAccess::CREATE_SERVICE, "create service")?;
1239        let mut info = Self::info(install, spec);
1240        info.service_type = ServiceType::OWN_PROCESS;
1241        manager
1242            .create_service(
1243                &info,
1244                ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS,
1245            )
1246            .map(drop)
1247            .map_err(|error| Self::map_error(error, "create service"))
1248    }
1249
1250    fn refresh(
1251        &mut self,
1252        install: &WindowsScmInstall,
1253        spec: &ServiceSpec,
1254        _remaining: Duration,
1255    ) -> Result<(), ServiceError> {
1256        use windows_service::service::ServiceAccess;
1257        let (service, config) = match Self::open(
1258            spec.id(),
1259            ServiceAccess::QUERY_CONFIG | ServiceAccess::CHANGE_CONFIG,
1260        )? {
1261            Ok(service) => {
1262                let config = service
1263                    .query_config()
1264                    .map_err(|error| Self::map_error(error, "query config before refresh"))?;
1265                (service, config)
1266            }
1267            Err(OpenFailure::NotFound | OpenFailure::MarkedForDelete) => {
1268                return Err(ServiceError::conflict("service disappeared before refresh"))
1269            }
1270            Err(failure) => return Err(open_failure("refresh", failure)),
1271        };
1272        let mut info = Self::info(install, spec);
1273        // Preserve fields outside this adapter's ownership. In particular, dependencies and
1274        // service type are queried and carried forward; account None means ChangeServiceConfig
1275        // leaves the existing account unchanged. Load-order group/tag are passed as null by the
1276        // wrapper, which likewise means no change.
1277        info.service_type = config.service_type;
1278        info.dependencies = install
1279            .dependencies
1280            .as_deref()
1281            .map(service_dependencies)
1282            .unwrap_or(config.dependencies);
1283        info.account_name = None;
1284        service
1285            .change_config(&info)
1286            .map_err(|error| Self::map_error(error, "refresh service config"))
1287    }
1288
1289    fn start(&mut self, id: &ServiceId, _remaining: Duration) -> Result<(), ServiceError> {
1290        use windows_service::service::ServiceAccess;
1291        match Self::open(id, ServiceAccess::START)? {
1292            Ok(service) => service
1293                .start::<&std::ffi::OsStr>(&[])
1294                .map_err(|error| Self::map_error(error, "start service")),
1295            Err(OpenFailure::NotFound | OpenFailure::MarkedForDelete) => {
1296                Err(ServiceError::conflict("service disappeared before start"))
1297            }
1298            Err(failure) => Err(open_failure("start", failure)),
1299        }
1300    }
1301
1302    fn stop(&mut self, id: &ServiceId, _remaining: Duration) -> Result<(), ServiceError> {
1303        use windows_service::service::ServiceAccess;
1304        match Self::open(id, ServiceAccess::STOP)? {
1305            Ok(service) => service
1306                .stop()
1307                .map(drop)
1308                .map_err(|error| Self::map_error(error, "stop service")),
1309            Err(OpenFailure::NotFound | OpenFailure::MarkedForDelete) => {
1310                Err(ServiceError::conflict("service disappeared before stop"))
1311            }
1312            Err(failure) => Err(open_failure("stop", failure)),
1313        }
1314    }
1315
1316    fn delete(&mut self, id: &ServiceId, _remaining: Duration) -> Result<(), ServiceError> {
1317        use windows_service::service::ServiceAccess;
1318        match Self::open(id, ServiceAccess::DELETE)? {
1319            Ok(service) => service
1320                .delete()
1321                .map_err(|error| Self::map_error(error, "delete service")),
1322            Err(OpenFailure::NotFound | OpenFailure::MarkedForDelete) => {
1323                Err(ServiceError::conflict("service disappeared before delete"))
1324            }
1325            Err(failure) => Err(open_failure("delete", failure)),
1326        }
1327    }
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use super::*;
1333    use std::cell::RefCell;
1334
1335    #[derive(Debug)]
1336    struct FakeBackend {
1337        lookup: RefCell<VecDeque<ScmLookup>>,
1338        current: RefCell<ScmLookup>,
1339        calls: RefCell<Vec<&'static str>>,
1340    }
1341
1342    impl FakeBackend {
1343        fn new(lookup: ScmLookup) -> Self {
1344            Self {
1345                lookup: RefCell::new(VecDeque::new()),
1346                current: RefCell::new(lookup),
1347                calls: RefCell::new(Vec::new()),
1348            }
1349        }
1350
1351        fn scripted(initial: ScmLookup, states: impl IntoIterator<Item = ScmLookup>) -> Self {
1352            Self {
1353                lookup: RefCell::new(states.into_iter().collect()),
1354                current: RefCell::new(initial),
1355                calls: RefCell::new(Vec::new()),
1356            }
1357        }
1358    }
1359
1360    impl ScmBackend for FakeBackend {
1361        fn query(&self, _id: &ServiceId, _remaining: Duration) -> Result<ScmLookup, ServiceError> {
1362            if let Some(next) = self.lookup.borrow_mut().pop_front() {
1363                *self.current.borrow_mut() = next;
1364            }
1365            Ok(self.current.borrow().clone())
1366        }
1367        fn create(
1368            &mut self,
1369            _: &WindowsScmInstall,
1370            _: &ServiceSpec,
1371            _: Duration,
1372        ) -> Result<(), ServiceError> {
1373            self.calls.borrow_mut().push("create");
1374            *self.current.borrow_mut() = present(
1375                r#""C:\Program Files\Eggup\egg.exe" --service"#,
1376                ScmState::Stopped,
1377            );
1378            Ok(())
1379        }
1380        fn refresh(
1381            &mut self,
1382            _: &WindowsScmInstall,
1383            _: &ServiceSpec,
1384            _: Duration,
1385        ) -> Result<(), ServiceError> {
1386            self.calls.borrow_mut().push("refresh");
1387            Ok(())
1388        }
1389        fn start(&mut self, _: &ServiceId, _: Duration) -> Result<(), ServiceError> {
1390            self.calls.borrow_mut().push("start");
1391            Ok(())
1392        }
1393        fn stop(&mut self, _: &ServiceId, _: Duration) -> Result<(), ServiceError> {
1394            self.calls.borrow_mut().push("stop");
1395            Ok(())
1396        }
1397        fn delete(&mut self, _: &ServiceId, _: Duration) -> Result<(), ServiceError> {
1398            self.calls.borrow_mut().push("delete");
1399            *self.current.borrow_mut() = ScmLookup::MarkedForDelete;
1400            Ok(())
1401        }
1402        fn sleep(&mut self, delay: Duration) {
1403            std::thread::sleep(delay);
1404        }
1405        fn test_calls(&self) -> Vec<&'static str> {
1406            self.calls.borrow().clone()
1407        }
1408    }
1409
1410    fn present(command_line: &str, state: ScmState) -> ScmLookup {
1411        ScmLookup::Present(record(command_line, state))
1412    }
1413
1414    fn record(command_line: &str, state: ScmState) -> ScmRecord {
1415        ScmRecord {
1416            command_line: Some(command_line.to_owned()),
1417            state,
1418            wait_hint: Duration::from_millis(1),
1419        }
1420    }
1421
1422    fn install() -> WindowsScmInstall {
1423        WindowsScmInstall::new(
1424            "EggupTest",
1425            "Eggup Test",
1426            WindowsStartType::Manual,
1427            WindowsErrorControl::Normal,
1428            None,
1429        )
1430        .unwrap()
1431        .with_transition_timeout(Duration::from_secs(1))
1432        .unwrap()
1433    }
1434
1435    #[test]
1436    fn former_panic_sites_report_typed_errors_instead_of_panicking() {
1437        // The five former panic sites all funnel through the seam's
1438        // own open-failure contract. `1060` and `1072` keep their lossless
1439        // meaning; every other code becomes a typed manager error that still
1440        // carries the raw OS code.
1441        assert_eq!(classify_open_code(Some(1060)), OpenFailure::NotFound);
1442        assert_eq!(classify_open_code(Some(1072)), OpenFailure::MarkedForDelete);
1443        assert_eq!(classify_open_code(Some(5)), OpenFailure::Other(Some(5)));
1444        assert_eq!(classify_open_code(None), OpenFailure::Other(None));
1445        assert_eq!(
1446            classify_open_code(Some(4242)),
1447            OpenFailure::Other(Some(4242))
1448        );
1449
1450        // The four mutating operations: refresh, start, stop, delete.
1451        for operation in ["refresh", "start", "stop", "delete"] {
1452            for gone in [OpenFailure::NotFound, OpenFailure::MarkedForDelete] {
1453                let error = open_failure(operation, gone);
1454                assert!(
1455                    matches!(error, ServiceError::Conflict(_)),
1456                    "{operation}: the disappeared case must be a typed conflict, got {error:?}"
1457                );
1458            }
1459            let unmapped = open_failure(operation, OpenFailure::Other(Some(4242)));
1460            assert_eq!(
1461                unmapped.manager_os_code(),
1462                Some(4242),
1463                "{operation}: the raw OS code must stay reachable"
1464            );
1465            assert_eq!(
1466                unmapped.manager_kind(),
1467                Some(ManagerFailureKind::Protocol),
1468                "{operation}: an unmapped code must be a typed manager failure"
1469            );
1470        }
1471
1472        // The inspection path: an unmapped code is a typed manager failure,
1473        // never an "absent" or "marked for delete" reading.
1474        let unmapped = unmapped_open_error(Some(4242));
1475        assert_eq!(unmapped.manager_os_code(), Some(4242));
1476        assert_eq!(unmapped.manager_kind(), Some(ManagerFailureKind::Protocol));
1477
1478        // The access-denied case keeps its kind and its bounded remediation.
1479        let denied = unmapped_open_error(Some(5));
1480        assert_eq!(denied.manager_os_code(), Some(5));
1481        assert_eq!(denied.manager_kind(), Some(ManagerFailureKind::Permission));
1482        assert!(
1483            denied.to_string().contains("account authorized"),
1484            "the access-denied detail must name the remediation: {denied}"
1485        );
1486    }
1487
1488    #[test]
1489    fn install_descriptor_rejects_invalid_scm_names() {
1490        for name in ["", "group/service", "embedded\0nul"] {
1491            assert!(WindowsScmInstall::new(
1492                name,
1493                "Valid display",
1494                WindowsStartType::Manual,
1495                WindowsErrorControl::Normal,
1496                None,
1497            )
1498            .is_err());
1499        }
1500        assert!(WindowsScmInstall::new(
1501            "valid-name",
1502            "",
1503            WindowsStartType::Manual,
1504            WindowsErrorControl::Normal,
1505            None,
1506        )
1507        .is_err());
1508        let dependencies = vec![
1509            WindowsServiceDependency::Service("Tcpip".into()),
1510            WindowsServiceDependency::Group("NetworkProvider".into()),
1511        ];
1512        assert!(validate_dependencies(&dependencies).is_ok());
1513        assert!(validate_dependencies(&[
1514            WindowsServiceDependency::Service("Tcpip".into()),
1515            WindowsServiceDependency::Group("tcpip".into()),
1516        ])
1517        .is_ok());
1518        assert!(validate_dependencies(&[
1519            WindowsServiceDependency::Service("Tcpip".into()),
1520            WindowsServiceDependency::Service("tcpip".into()),
1521        ])
1522        .is_err());
1523        assert!(validate_dependencies(&[WindowsServiceDependency::Service(
1524            "group/service".into(),
1525        )])
1526        .is_err());
1527    }
1528
1529    #[test]
1530    fn access_denied_diagnostic_is_bounded_and_does_not_escalate() {
1531        let detail = scm_error_detail("start service", Some(5));
1532        assert!(detail.contains("account authorized"));
1533        assert!(!detail.to_ascii_lowercase().contains("uac"));
1534        assert!(!detail.to_ascii_lowercase().contains("runas"));
1535        assert!(ServiceError::bounded(detail).len() <= 512);
1536    }
1537
1538    fn spec() -> ServiceSpec {
1539        ServiceSpec {
1540            id: ServiceId::new("EggupTest").unwrap(),
1541            executable: PathBuf::from(r"C:\Program Files\Eggup\egg.exe"),
1542            args: vec!["--service".into()],
1543            config: None,
1544        }
1545    }
1546
1547    fn manager(backend: FakeBackend) -> WindowsScmManager {
1548        WindowsScmManager::with_backend(backend, install())
1549    }
1550
1551    #[test]
1552    fn parser_handles_quoted_executable_arguments_backslashes_and_unicode() {
1553        let parsed = parse_service_command(
1554            r#""C:\Program Files\Eggup\工具.exe" --path "C:\a b\\" --name "é""#,
1555        )
1556        .unwrap();
1557        assert_eq!(parsed.0, PathBuf::from(r"C:\Program Files\Eggup\工具.exe"));
1558        assert_eq!(parsed.1, ["--path", r"C:\a b\", "--name", "é"]);
1559        assert!(parse_service_command(r#"C:\Program Files\Eggup\egg.exe --service"#).is_none());
1560        assert!(parse_service_command(r#""C:\Program Files\egg.exe --service"#).is_none());
1561    }
1562
1563    #[test]
1564    fn parser_rejects_ambiguous_or_relative_command_lines() {
1565        for bad in ["", "egg.exe --service", r#""C:\egg.exe" "unterminated"#] {
1566            assert!(parse_service_command(bad).is_none(), "{bad:?}");
1567        }
1568    }
1569
1570    #[test]
1571    fn config_identity_requires_exactly_one_config_argument() {
1572        let mut configured = spec();
1573        configured.config = Some(PathBuf::from(r"C:\ProgramData\Eggup\cfg.toml"));
1574        configured
1575            .args
1576            .push(r"C:\ProgramData\Eggup\cfg.toml".into());
1577        let first_record = record(
1578            r#""C:\Program Files\Eggup\egg.exe" --service C:\ProgramData\Eggup\cfg.toml"#,
1579            ScmState::Stopped,
1580        );
1581        assert_eq!(
1582            registration_ownership(&first_record, &configured),
1583            Ownership::Owned
1584        );
1585        configured
1586            .args
1587            .push(r"C:\ProgramData\Eggup\cfg.toml".into());
1588        let second_record = record(
1589            r#""C:\Program Files\Eggup\egg.exe" --service C:\ProgramData\Eggup\cfg.toml C:\ProgramData\Eggup\cfg.toml"#,
1590            ScmState::Stopped,
1591        );
1592        assert_eq!(
1593            registration_ownership(&second_record, &configured),
1594            Ownership::Unknown
1595        );
1596    }
1597
1598    #[test]
1599    fn lifecycle_mapping_is_explicit_for_all_scm_states() {
1600        for (scm, neutral) in [
1601            (ScmState::Stopped, LifecycleState::Stopped),
1602            (ScmState::Running, LifecycleState::Running),
1603            (ScmState::StartPending, LifecycleState::Transitioning),
1604            (ScmState::StopPending, LifecycleState::Transitioning),
1605            (ScmState::ContinuePending, LifecycleState::Transitioning),
1606            (ScmState::PausePending, LifecycleState::Transitioning),
1607            (ScmState::Paused, LifecycleState::Unknown),
1608            (ScmState::Unknown, LifecycleState::Unknown),
1609        ] {
1610            assert_eq!(lifecycle_state(scm), neutral);
1611        }
1612    }
1613
1614    #[test]
1615    fn inspect_maps_absent_and_requires_exact_command_identity() {
1616        let absent = manager(FakeBackend::new(ScmLookup::Absent))
1617            .inspect(&spec())
1618            .unwrap();
1619        assert_eq!(absent.ownership, Ownership::Absent);
1620        let owned = manager(FakeBackend::new(present(
1621            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1622            ScmState::Running,
1623        )))
1624        .inspect(&spec())
1625        .unwrap();
1626        assert_eq!(owned.ownership, Ownership::Owned);
1627        let foreign = manager(FakeBackend::new(present(
1628            r#""C:\Other\egg.exe" --service"#,
1629            ScmState::Stopped,
1630        )))
1631        .inspect(&spec())
1632        .unwrap();
1633        assert_eq!(foreign.ownership, Ownership::Foreign);
1634        let argv_foreign = manager(FakeBackend::new(present(
1635            r#""C:\Program Files\Eggup\egg.exe" --other"#,
1636            ScmState::Stopped,
1637        )))
1638        .inspect(&spec())
1639        .unwrap();
1640        assert_eq!(argv_foreign.ownership, Ownership::Foreign);
1641        let unknown = manager(FakeBackend::new(present(
1642            "malformed cmd",
1643            ScmState::Stopped,
1644        )))
1645        .inspect(&spec())
1646        .unwrap();
1647        assert_eq!(unknown.ownership, Ownership::Unknown);
1648    }
1649
1650    #[test]
1651    fn validate_spec_rejects_identity_mismatch_and_oversized_command() {
1652        let manager = manager(FakeBackend::new(ScmLookup::Absent));
1653        let mut wrong_id = spec();
1654        wrong_id.id = ServiceId::new("Different").unwrap();
1655        assert!(manager.validate_spec(&wrong_id).is_err());
1656        let mut oversized = spec();
1657        oversized.args = vec!["x".repeat(MAX_SCM_COMMAND_CHARS)];
1658        assert!(manager.validate_spec(&oversized).is_err());
1659    }
1660
1661    #[test]
1662    fn install_creates_absent_and_denies_foreign() {
1663        let mut m = manager(FakeBackend::new(ScmLookup::Absent));
1664        assert!(m.install(&spec()).unwrap().completed);
1665        assert!(manager(FakeBackend::new(present(
1666            r#""C:\other.exe" --service"#,
1667            ScmState::Stopped
1668        )))
1669        .install(&spec())
1670        .is_err());
1671    }
1672
1673    #[test]
1674    fn refresh_reinspects_owned_registration() {
1675        let owned = present(
1676            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1677            ScmState::Stopped,
1678        );
1679        let mut refresh = manager(FakeBackend::scripted(owned.clone(), [owned.clone(), owned]));
1680        assert!(refresh.install(&spec()).unwrap().completed);
1681        assert!(refresh.backend.test_calls().contains(&"refresh"));
1682
1683        let backend = FakeBackend::scripted(
1684            present(
1685                r#""C:\Program Files\Eggup\egg.exe" --service"#,
1686                ScmState::Stopped,
1687            ),
1688            [
1689                present(
1690                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1691                    ScmState::Stopped,
1692                ),
1693                present(r#""C:\other.exe" --service"#, ScmState::Stopped),
1694            ],
1695        );
1696        assert!(manager(backend).install(&spec()).is_err());
1697    }
1698
1699    #[test]
1700    fn start_stop_restart_use_confirmed_states_and_one_deadline() {
1701        let running = present(
1702            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1703            ScmState::Running,
1704        );
1705        assert!(
1706            manager(FakeBackend::new(running.clone()))
1707                .start(&spec(), Duration::from_secs(1))
1708                .unwrap()
1709                .completed
1710        );
1711
1712        let stopped = present(
1713            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1714            ScmState::Stopped,
1715        );
1716        let start_manager = manager(FakeBackend::scripted(
1717            stopped.clone(),
1718            [
1719                present(
1720                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1721                    ScmState::Stopped,
1722                ),
1723                present(
1724                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1725                    ScmState::StartPending,
1726                ),
1727                present(
1728                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1729                    ScmState::Running,
1730                ),
1731            ],
1732        ));
1733        let mut start_manager = start_manager;
1734        assert!(
1735            start_manager
1736                .start(&spec(), Duration::from_secs(1))
1737                .unwrap()
1738                .completed
1739        );
1740
1741        let restart_manager = manager(FakeBackend::scripted(
1742            running.clone(),
1743            [
1744                present(
1745                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1746                    ScmState::Running,
1747                ),
1748                present(
1749                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1750                    ScmState::Stopped,
1751                ),
1752                present(
1753                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1754                    ScmState::Stopped,
1755                ),
1756                present(
1757                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1758                    ScmState::Stopped,
1759                ),
1760                present(
1761                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1762                    ScmState::Running,
1763                ),
1764            ],
1765        ));
1766        let mut restart_manager = restart_manager;
1767        assert!(
1768            restart_manager
1769                .restart(&spec(), Duration::from_secs(1))
1770                .unwrap()
1771                .completed
1772        );
1773
1774        let stop_backend = FakeBackend::scripted(
1775            running,
1776            [
1777                present(
1778                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1779                    ScmState::Running,
1780                ),
1781                present(
1782                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1783                    ScmState::Stopped,
1784                ),
1785            ],
1786        );
1787        let mut stop_manager = manager(stop_backend);
1788        assert!(
1789            stop_manager
1790                .stop(&spec(), Duration::from_secs(1))
1791                .unwrap()
1792                .completed
1793        );
1794    }
1795
1796    #[test]
1797    fn restart_does_not_start_if_stop_does_not_complete() {
1798        let backend = FakeBackend::scripted(
1799            present(
1800                r#""C:\Program Files\Eggup\egg.exe" --service"#,
1801                ScmState::Running,
1802            ),
1803            std::iter::once(present(
1804                r#""C:\Program Files\Eggup\egg.exe" --service"#,
1805                ScmState::Running,
1806            ))
1807            .chain(std::iter::repeat_n(
1808                present(
1809                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1810                    ScmState::StopPending,
1811                ),
1812                5,
1813            )),
1814        );
1815        let mut manager = manager(backend);
1816        let result = manager.restart(&spec(), Duration::from_millis(20));
1817        assert!(
1818            matches!(&result, Ok(result) if !result.completed)
1819                || matches!(
1820                    &result,
1821                    Err(ServiceError::Manager { kind, .. })
1822                        if *kind == ManagerFailureKind::Timeout
1823                )
1824        );
1825        assert!(!manager.backend.test_calls().contains(&"start"));
1826    }
1827
1828    #[test]
1829    fn uninstall_reports_marked_for_delete_until_absent() {
1830        let backend = FakeBackend::scripted(
1831            present(
1832                r#""C:\Program Files\Eggup\egg.exe" --service"#,
1833                ScmState::Stopped,
1834            ),
1835            [
1836                present(
1837                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1838                    ScmState::Stopped,
1839                ),
1840                present(
1841                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1842                    ScmState::Stopped,
1843                ),
1844                present(
1845                    r#""C:\Program Files\Eggup\egg.exe" --service"#,
1846                    ScmState::Stopped,
1847                ),
1848                ScmLookup::MarkedForDelete,
1849                ScmLookup::Absent,
1850            ],
1851        );
1852        let mut manager = manager(backend);
1853        assert!(manager.uninstall(&spec()).unwrap().completed);
1854    }
1855
1856    #[test]
1857    fn uninstall_does_not_claim_completion_while_marked_for_delete() {
1858        let stopped = present(
1859            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1860            ScmState::Stopped,
1861        );
1862        let backend = FakeBackend::scripted(stopped.clone(), [stopped.clone(), stopped]);
1863        let install = install()
1864            .with_transition_timeout(Duration::from_millis(20))
1865            .unwrap();
1866        let mut manager = WindowsScmManager::with_backend(backend, install);
1867        let result = manager.uninstall(&spec()).unwrap();
1868        assert!(!result.completed);
1869        assert!(manager.backend.test_calls().contains(&"delete"));
1870    }
1871
1872    #[test]
1873    fn stop_of_already_stopped_registration_is_complete_without_a_control() {
1874        let mut manager = manager(FakeBackend::new(present(
1875            r#""C:\Program Files\Eggup\egg.exe" --service"#,
1876            ScmState::Stopped,
1877        )));
1878        assert!(
1879            manager
1880                .stop(&spec(), Duration::from_secs(1))
1881                .unwrap()
1882                .completed
1883        );
1884        assert!(!manager.backend.test_calls().contains(&"stop"));
1885    }
1886}