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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
|
#![allow(dead_code)]
use std::collections::HashSet;
use std::fs;
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Once, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
static PID_REGISTRY: OnceLock<Mutex<HashSet<u32>>> = OnceLock::new();
static RUNTIME_DIR_REGISTRY: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
static INIT: Once = Once::new();
static CLEANUP_GUARD: OnceLock<CleanupGuard> = OnceLock::new();
const WATCHDOG_SCAN_INTERVAL: Duration = Duration::from_secs(1);
const RUNTIME_OWNER_MARKER: &str = ".herdr-test-owner-pid";
pub fn register_spawned_herdr_pid(pid: Option<u32>) {
let Some(pid) = pid else {
return;
};
ensure_cleanup_hooks();
let mut registry = pid_registry_lock();
registry.insert(pid);
}
pub fn unregister_spawned_herdr_pid(pid: Option<u32>) {
let Some(pid) = pid else {
return;
};
if let Some(registry) = PID_REGISTRY.get() {
let mut guard = registry
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.remove(&pid);
}
}
pub fn register_runtime_dir(path: &Path) {
ensure_cleanup_hooks();
let _ = fs::create_dir_all(path);
let _ = fs::write(
path.join(RUNTIME_OWNER_MARKER),
std::process::id().to_string(),
);
let mut runtime_dirs = runtime_dir_registry_lock();
runtime_dirs.insert(path.to_path_buf());
}
pub fn unregister_runtime_dir(path: &Path) {
if let Some(registry) = RUNTIME_DIR_REGISTRY.get() {
let mut guard = registry
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.remove(path);
}
}
#[cfg(target_os = "linux")]
pub fn herdr_server_pids_for_runtime_dir(runtime_dir: &Path) -> std::io::Result<Vec<u32>> {
let mut pids = Vec::new();
for pid in iter_worktree_server_pids()? {
let Some(process_runtime_dir) = process_runtime_dir(pid)? else {
continue;
};
if process_runtime_dir == runtime_dir {
pids.push(pid);
}
}
pids.sort_unstable();
Ok(pids)
}
pub fn cleanup_test_base(base: &Path) {
let runtime_dir = base.join("runtime");
let runtime_dirs = HashSet::from([runtime_dir.clone()]);
terminate_servers_for_runtime_dirs(&runtime_dirs);
unregister_runtime_dir(&runtime_dir);
let _ = fs::remove_dir_all(base);
}
pub fn wait_for_socket(path: &Path, timeout: Duration) {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if path.exists() && UnixStream::connect(path).is_ok() {
return;
}
thread::sleep(Duration::from_millis(25));
}
panic!("socket did not appear at {}", path.display());
}
pub fn wait_for_file(path: &Path, timeout: Duration) {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if path.exists() {
return;
}
thread::sleep(Duration::from_millis(25));
}
panic!("file did not appear at {}", path.display());
}
pub fn encode_varint_u32(v: u32) -> Vec<u8> {
if v < 251 {
vec![v as u8]
} else if v < 65536 {
let mut buf = vec![251u8];
buf.extend_from_slice(&(v as u16).to_le_bytes());
buf
} else {
let mut buf = vec![252u8];
buf.extend_from_slice(&v.to_le_bytes());
buf
}
}
pub fn encode_varint_u16(v: u16) -> Vec<u8> {
if v < 251 {
vec![v as u8]
} else {
let mut buf = vec![251u8];
buf.extend_from_slice(&v.to_le_bytes());
buf
}
}
pub fn frame_message(payload: &[u8]) -> Vec<u8> {
let len = payload.len() as u32;
let mut framed = len.to_le_bytes().to_vec();
framed.extend_from_slice(payload);
framed
}
pub fn decode_varint_u32(payload: &[u8], offset: usize) -> Result<(u32, usize), String> {
if offset >= payload.len() {
return Err("payload too short for varint".into());
}
let first_byte = payload[offset];
match first_byte {
0..=250 => Ok((first_byte as u32, 1)),
251 => {
if offset + 3 > payload.len() {
return Err("payload too short for u16 varint".into());
}
let v = u16::from_le_bytes(
payload[offset + 1..offset + 3]
.try_into()
.map_err(|e: std::array::TryFromSliceError| e.to_string())?,
);
Ok((v as u32, 3))
}
252 => {
if offset + 5 > payload.len() {
return Err("payload too short for u32 varint".into());
}
let v = u32::from_le_bytes(
payload[offset + 1..offset + 5]
.try_into()
.map_err(|e: std::array::TryFromSliceError| e.to_string())?,
);
Ok((v, 5))
}
_ => Err(format!("unsupported varint tag: {first_byte}")),
}
}
fn encode_varint_enum(variant_idx: u32, fields: &[&[u8]]) -> Vec<u8> {
let mut buf = encode_varint_u32(variant_idx);
for field in fields {
buf.extend_from_slice(field);
}
buf
}
fn decode_welcome(payload: &[u8]) -> Result<(u32, Option<String>), String> {
let mut offset = 0;
let (variant, consumed) = decode_varint_u32(payload, offset)?;
offset += consumed;
if variant != 0 {
return Err(format!(
"expected Welcome (variant 0), got variant {variant}"
));
}
let (version, consumed) = decode_varint_u32(payload, offset)?;
offset += consumed;
let (_encoding, consumed) = decode_varint_u32(payload, offset)?;
offset += consumed;
if offset >= payload.len() {
return Err("payload too short for Option tag".into());
}
let option_tag = payload[offset];
offset += 1;
let error = if option_tag == 1 {
let (str_len, consumed) = decode_varint_u32(payload, offset)?;
offset += consumed;
let str_len = str_len as usize;
if offset + str_len > payload.len() {
return Err("payload too short for string content".into());
}
Some(
String::from_utf8(payload[offset..offset + str_len].to_vec())
.map_err(|e| e.to_string())?,
)
} else {
None
};
Ok((version, error))
}
pub fn client_handshake(
stream: &mut UnixStream,
version: u32,
cols: u16,
rows: u16,
) -> Result<(u32, Option<String>), String> {
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.map_err(|e| e.to_string())?;
let hello_payload = encode_varint_enum(
0,
&[
&encode_varint_u32(version),
&encode_varint_u16(cols),
&encode_varint_u16(rows),
&encode_varint_u32(8), // cell_width_px
&encode_varint_u32(16), // cell_height_px
&encode_varint_u32(0), // RenderEncoding::SemanticFrame
&encode_varint_u32(0), // ClientKeybindings::Server
&encode_varint_u32(0), // ClientLaunchMode::App
],
);
let framed = frame_message(&hello_payload);
stream.write_all(&framed).map_err(|e| e.to_string())?;
stream.flush().map_err(|e| e.to_string())?;
let mut len_buf = [0u8; 4];
stream.read_exact(&mut len_buf).map_err(|e| e.to_string())?;
let len = u32::from_le_bytes(len_buf) as usize;
if len > 2 * 1024 * 1024 {
return Err(format!("oversized response: {len}"));
}
let mut payload = vec![0u8; len];
stream.read_exact(&mut payload).map_err(|e| e.to_string())?;
decode_welcome(&payload)
}
pub fn read_server_message(stream: &mut UnixStream) -> Result<(u32, Vec<u8>), String> {
let mut len_buf = [0u8; 4];
stream
.read_exact(&mut len_buf)
.map_err(|e| format!("read length prefix: {e}"))?;
let len = u32::from_le_bytes(len_buf) as usize;
if len > 2 * 1024 * 1024 {
return Err(format!("oversized frame: {len} bytes"));
}
if len == 0 {
return Err("zero-length frame".into());
}
let mut payload = vec![0u8; len];
stream
.read_exact(&mut payload)
.map_err(|e| format!("read payload: {e}"))?;
let (variant, consumed) = decode_varint_u32(&payload, 0)?;
Ok((variant, payload[consumed..].to_vec()))
}
pub fn send_input(stream: &mut UnixStream, data: &[u8]) -> Result<(), String> {
let mut buf = encode_varint_u32(1);
buf.extend_from_slice(&encode_varint_u32(data.len() as u32));
buf.extend_from_slice(data);
let framed = frame_message(&buf);
stream
.write_all(&framed)
.map_err(|e| format!("write input: {e}"))?;
stream.flush().map_err(|e| format!("flush input: {e}"))?;
Ok(())
}
pub fn send_detach(stream: &mut UnixStream) -> Result<(), String> {
let detach_payload = encode_varint_u32(4);
let framed = frame_message(&detach_payload);
stream
.write_all(&framed)
.map_err(|e| format!("write detach: {e}"))?;
stream.flush().map_err(|e| format!("flush detach: {e}"))?;
Ok(())
}
pub fn drain_messages(stream: &mut UnixStream) {
stream
.set_read_timeout(Some(Duration::from_millis(200)))
.unwrap();
while read_server_message(stream).is_ok() {}
stream.set_read_timeout(None).unwrap();
}
pub fn wait_until<F>(timeout: Duration, interval: Duration, mut predicate: F) -> bool
where
F: FnMut() -> bool,
{
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if predicate() {
return true;
}
thread::sleep(interval);
}
predicate()
}
pub fn wait_for_message_variant(
stream: &mut UnixStream,
timeout: Duration,
variant: u32,
) -> Result<bool, String> {
stream
.set_read_timeout(Some(Duration::from_millis(200)))
.map_err(|e| e.to_string())?;
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
match read_server_message(stream) {
Ok((got, _)) if got == variant => return Ok(true),
Ok(_) => continue,
Err(_) => continue,
}
}
Ok(false)
}
pub fn wait_for_disconnect(stream: &mut UnixStream, timeout: Duration) -> Result<bool, String> {
stream.set_nonblocking(true).map_err(|e| e.to_string())?;
let deadline = Instant::now() + timeout;
let mut idle_since = None;
let result = loop {
match read_server_message(stream) {
Ok(_) => idle_since = None,
Err(err)
if err.to_ascii_lowercase().contains("would block")
|| err.contains("Resource temporarily unavailable") =>
{
let idle_started = *idle_since.get_or_insert_with(Instant::now);
if idle_started.elapsed() >= Duration::from_millis(200) {
break Ok(true);
}
}
Err(_) => break Ok(true),
}
if Instant::now() >= deadline {
break Ok(false);
}
thread::sleep(Duration::from_millis(25));
};
let _ = stream.set_nonblocking(false);
result
}
pub fn cleanup_registered_herdr_pids() {
let pids: Vec<u32> = {
let mut registry = pid_registry_lock();
registry.drain().collect()
};
for pid in pids {
terminate_pid(pid);
}
let runtime_dirs: HashSet<PathBuf> = {
let mut runtime_dirs = runtime_dir_registry_lock();
runtime_dirs.drain().collect()
};
terminate_servers_for_runtime_dirs(&runtime_dirs);
let _ = cleanup_servers_with_missing_runtime_dir();
}
fn ensure_cleanup_hooks() {
INIT.call_once(|| {
let _ = cleanup_servers_with_missing_runtime_dir();
start_global_watchdog();
let _ = CLEANUP_GUARD.set(CleanupGuard);
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
cleanup_registered_herdr_pids();
previous_hook(panic_info);
}));
let _ = ctrlc::set_handler(|| {
cleanup_registered_herdr_pids();
std::process::exit(130);
});
unsafe {
libc::atexit(run_atexit_cleanup);
}
});
}
fn pid_registry_lock() -> std::sync::MutexGuard<'static, HashSet<u32>> {
PID_REGISTRY
.get_or_init(|| Mutex::new(HashSet::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn runtime_dir_registry_lock() -> std::sync::MutexGuard<'static, HashSet<PathBuf>> {
RUNTIME_DIR_REGISTRY
.get_or_init(|| Mutex::new(HashSet::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn registered_runtime_dirs_snapshot() -> HashSet<PathBuf> {
if let Some(runtime_dirs) = RUNTIME_DIR_REGISTRY.get() {
runtime_dirs
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
} else {
HashSet::new()
}
}
fn should_terminate_runtime_dir(
runtime_dir: &Path,
registered_runtime_dirs: &HashSet<PathBuf>,
) -> bool {
if !registered_runtime_dirs.contains(runtime_dir) {
return false;
}
if !runtime_dir.exists() {
return true;
}
!runtime_dir_owner_alive(runtime_dir)
}
fn start_global_watchdog() {
thread::spawn(|| loop {
thread::sleep(WATCHDOG_SCAN_INTERVAL);
if let Err(err) = cleanup_servers_with_missing_runtime_dir() {
eprintln!("herdr test cleanup watchdog error: {err}");
}
});
}
fn cleanup_servers_with_missing_runtime_dir() -> std::io::Result<()> {
let registered_runtime_dirs = registered_runtime_dirs_snapshot();
if registered_runtime_dirs.is_empty() {
return Ok(());
}
for pid in iter_worktree_server_pids()? {
let Some(runtime_dir) = process_runtime_dir(pid)? else {
continue;
};
if should_terminate_runtime_dir(&runtime_dir, ®istered_runtime_dirs) {
terminate_pid(pid);
}
}
Ok(())
}
fn terminate_servers_for_runtime_dirs(runtime_dirs: &HashSet<PathBuf>) {
if runtime_dirs.is_empty() {
return;
}
let Ok(pids) = iter_worktree_server_pids() else {
return;
};
for pid in pids {
let Ok(runtime_dir) = process_runtime_dir(pid) else {
continue;
};
let Some(runtime_dir) = runtime_dir else {
continue;
};
if runtime_dirs.contains(&runtime_dir) {
terminate_pid(pid);
}
}
}
fn iter_worktree_server_pids() -> std::io::Result<Vec<u32>> {
let own_pid = std::process::id();
let mut pids = Vec::new();
let proc_entries = match fs::read_dir("/proc") {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => return Err(err),
};
for entry in proc_entries {
let entry = entry?;
let file_name = entry.file_name();
let Some(pid) = file_name.to_str().and_then(|name| name.parse::<u32>().ok()) else {
continue;
};
if pid == own_pid {
continue;
}
if is_test_herdr_server_process(pid) {
pids.push(pid);
}
}
Ok(pids)
}
fn is_test_herdr_server_process(pid: u32) -> bool {
let Some(exe_path) = proc_link_target(pid, "exe") else {
return false;
};
if !is_test_herdr_binary(&exe_path) {
return false;
}
let Ok(cmdline) = read_cmdline(pid) else {
return false;
};
cmdline.iter().any(|arg| arg == "server")
}
fn proc_link_target(pid: u32, link: &str) -> Option<PathBuf> {
fs::read_link(format!("/proc/{pid}/{link}")).ok()
}
fn read_cmdline(pid: u32) -> std::io::Result<Vec<String>> {
let cmdline = fs::read(format!("/proc/{pid}/cmdline"))?;
Ok(cmdline
.split(|byte| *byte == 0)
.filter(|chunk| !chunk.is_empty())
.map(|chunk| String::from_utf8_lossy(chunk).to_string())
.collect())
}
fn process_runtime_dir(pid: u32) -> std::io::Result<Option<PathBuf>> {
let environ = fs::read(format!("/proc/{pid}/environ"))?;
let mut socket_path: Option<PathBuf> = None;
for entry in environ.split(|byte| *byte == 0) {
if entry.is_empty() {
continue;
}
let kv = String::from_utf8_lossy(entry);
if let Some(value) = kv.strip_prefix("XDG_RUNTIME_DIR=") {
return Ok(Some(PathBuf::from(value)));
}
if let Some(value) = kv.strip_prefix("HERDR_SOCKET_PATH=") {
socket_path = Some(PathBuf::from(value));
}
}
Ok(socket_path.and_then(|path| path.parent().map(Path::to_path_buf)))
}
fn runtime_dir_owner_alive(runtime_dir: &Path) -> bool {
let marker = runtime_dir.join(RUNTIME_OWNER_MARKER);
let Ok(contents) = fs::read_to_string(marker) else {
return false;
};
let Ok(owner_pid) = contents.trim().parse::<libc::pid_t>() else {
return false;
};
process_exists(owner_pid)
}
fn current_checkout_root() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
}
fn is_test_herdr_binary(path: &Path) -> bool {
path.ends_with("target/debug/herdr") && path.starts_with(current_checkout_root())
}
extern "C" fn run_atexit_cleanup() {
cleanup_registered_herdr_pids();
}
struct CleanupGuard;
impl Drop for CleanupGuard {
fn drop(&mut self) {
cleanup_registered_herdr_pids();
}
}
fn terminate_pid(pid: u32) {
let pid_t = pid as libc::pid_t;
if process_exists(pid_t) {
unsafe {
libc::kill(pid_t, libc::SIGTERM);
}
}
if wait_for_pid_exit(pid_t, Duration::from_millis(400)) {
return;
}
if process_exists(pid_t) {
unsafe {
libc::kill(pid_t, libc::SIGKILL);
}
}
let _ = wait_for_pid_exit(pid_t, Duration::from_secs(2));
}
fn wait_for_pid_exit(pid: libc::pid_t, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if !process_exists(pid) {
return true;
}
let mut status = 0;
let result = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
if result == pid {
return true;
}
if result == -1 {
match std::io::Error::last_os_error().raw_os_error() {
Some(libc::ECHILD) => {
// Not our child (or already reaped elsewhere). Poll /proc existence
// until the process is truly gone.
if !process_exists(pid) {
return true;
}
}
Some(libc::ESRCH) => return true,
_ => {
if !process_exists(pid) {
return true;
}
}
}
}
thread::sleep(Duration::from_millis(20));
}
!process_exists(pid)
}
fn process_exists(pid: libc::pid_t) -> bool {
let result = unsafe { libc::kill(pid, 0) };
if result == 0 {
true
} else {
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unique_missing_runtime_dir(label: &str) -> PathBuf {
let unique = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
std::env::temp_dir().join(format!(
"herdr-watchdog-scoping-{label}-{}-{unique}",
std::process::id()
))
}
#[test]
fn watchdog_scoping_does_not_terminate_missing_unregistered_runtime_dir() {
let runtime_dir = unique_missing_runtime_dir("unregistered");
let registered_runtime_dirs = HashSet::new();
assert!(
!should_terminate_runtime_dir(&runtime_dir, ®istered_runtime_dirs),
"missing runtime dirs must not be killable until they are proven session-owned"
);
}
#[test]
fn watchdog_scoping_terminates_missing_registered_runtime_dir() {
let runtime_dir = unique_missing_runtime_dir("registered");
let mut registered_runtime_dirs = HashSet::new();
registered_runtime_dirs.insert(runtime_dir.clone());
assert!(
should_terminate_runtime_dir(&runtime_dir, ®istered_runtime_dirs),
"missing runtime dirs that are session-owned should be considered killable"
);
}
#[test]
fn test_binary_matcher_accepts_current_checkout_debug_binary() {
let binary = current_checkout_root().join("target/debug/herdr");
assert!(
is_test_herdr_binary(&binary),
"current checkout debug binary should be considered test-owned"
);
}
#[test]
fn test_binary_matcher_rejects_installed_binary() {
assert!(
!is_test_herdr_binary(Path::new("/home/can/.local/bin/herdr")),
"installed binaries must not be considered test-owned"
);
}
}
|