1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#[cfg(windows)]
fn main() -> windows_service::Result<()> {
ping_service::run()
}
#[cfg(not(windows))]
fn main() {
panic!("This program is only intended to run on Windows.");
}
#[cfg(windows)]
mod ping_service {
use std::{
ffi::OsString,
net::{IpAddr, SocketAddr, UdpSocket},
sync::mpsc,
time::Duration,
};
use windows_service::{
define_windows_service,
service::{
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus,
ServiceType,
},
service_control_handler::{self, ServiceControlHandlerResult},
service_dispatcher, Result,
};
const SERVICE_NAME: &str = "ping_service";
const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
const LOOPBACK_ADDR: [u8; 4] = [127, 0, 0, 1];
const RECEIVER_PORT: u16 = 1234;
const PING_MESSAGE: &str = "ping\n";
pub fn run() -> Result<()> {
service_dispatcher::start(SERVICE_NAME, ffi_service_main)
}
define_windows_service!(ffi_service_main, my_service_main);
pub fn my_service_main(_arguments: Vec<OsString>) {
if let Err(_e) = run_service() {
}
}
pub fn run_service() -> Result<()> {
let (shutdown_tx, shutdown_rx) = mpsc::channel();
let event_handler = move |control_event| -> ServiceControlHandlerResult {
match control_event {
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
ServiceControl::Stop => {
shutdown_tx.send(()).unwrap();
ServiceControlHandlerResult::NoError
}
_ => ServiceControlHandlerResult::NotImplemented,
}
};
let status_handle = service_control_handler::register(SERVICE_NAME, event_handler)?;
status_handle.set_service_status(ServiceStatus {
service_type: SERVICE_TYPE,
current_state: ServiceState::Running,
controls_accepted: ServiceControlAccept::STOP,
exit_code: ServiceExitCode::Win32(0),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: None,
})?;
let loopback_ip = IpAddr::from(LOOPBACK_ADDR);
let sender_addr = SocketAddr::new(loopback_ip, 0);
let receiver_addr = SocketAddr::new(loopback_ip, RECEIVER_PORT);
let msg = PING_MESSAGE.as_bytes();
let socket = UdpSocket::bind(sender_addr).unwrap();
loop {
let _ = socket.send_to(msg, receiver_addr);
match shutdown_rx.recv_timeout(Duration::from_secs(1)) {
Ok(_) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => (),
};
}
status_handle.set_service_status(ServiceStatus {
service_type: SERVICE_TYPE,
current_state: ServiceState::Stopped,
controls_accepted: ServiceControlAccept::empty(),
exit_code: ServiceExitCode::Win32(0),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: None,
})?;
Ok(())
}
}