forked from jlcodes99/cockpit-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocess.rs
More file actions
8000 lines (7385 loc) · 264 KB
/
process.rs
File metadata and controls
8000 lines (7385 loc) · 264 KB
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::modules::config;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
#[cfg(not(target_os = "macos"))]
use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind};
#[cfg(any(target_os = "macos", target_os = "windows"))]
const OPENCODE_APP_NAME: &str = "OpenCode";
#[cfg(target_os = "macos")]
const TRAE_APP_NAME: &str = "Trae";
#[cfg(target_os = "macos")]
const CODEX_APP_PATH: &str = "/Applications/Codex.app/Contents/MacOS/Codex";
#[cfg(target_os = "macos")]
const ANTIGRAVITY_APP_PATH: &str = "/Applications/Antigravity.app/Contents/MacOS/Electron";
#[cfg(target_os = "macos")]
const VSCODE_APP_PATH: &str = "/Applications/Visual Studio Code.app/Contents/MacOS/Electron";
#[cfg(target_os = "windows")]
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
#[cfg(target_os = "windows")]
const DETACHED_PROCESS: u32 = 0x0000_0008;
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[cfg(target_os = "windows")]
const WINDOWS_PROCESS_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// On macOS, extract the executable path from a `ps` command line output.
/// Handles paths with spaces in .app bundles (e.g., "Visual Studio Code.app").
#[cfg(target_os = "macos")]
fn extract_macos_exe_from_cmdline(cmdline: &str) -> Option<String> {
let lower = cmdline.to_lowercase();
// For .app bundles: find the binary after Contents/MacOS/
if let Some(contents_pos) = lower.find(".app/contents/macos/") {
let after_macos = contents_pos + ".app/contents/macos/".len();
// Binary name goes until next whitespace or end
let rest = &cmdline[after_macos..];
let end = rest.find(|c: char| c.is_whitespace()).unwrap_or(rest.len());
return Some(cmdline[..after_macos + end].to_string());
}
// For non-.app executables: first whitespace-delimited token
cmdline.split_whitespace().next().map(|s| s.to_string())
}
fn strict_process_detect_enabled() -> bool {
std::env::var("AG_STRICT_PROCESS_DETECT")
.ok()
.map(|value| {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
})
.unwrap_or(false)
}
fn parse_env_bool(value: &str) -> Option<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Some(true),
"0" | "false" | "no" | "off" => Some(false),
_ => None,
}
}
fn command_trace_enabled() -> bool {
if let Ok(value) = std::env::var("COCKPIT_COMMAND_TRACE") {
if let Some(enabled) = parse_env_bool(&value) {
return enabled;
}
}
false
}
fn quote_command_part(part: &str) -> String {
if part.is_empty() {
return "\"\"".to_string();
}
let needs_quote = part.chars().any(|ch| {
ch.is_whitespace() || matches!(ch, '"' | '\'' | '$' | '`' | '|' | '&' | ';' | '(' | ')')
});
if !needs_quote {
return part.to_string();
}
format!("{:?}", part)
}
fn format_command_preview(command: &Command) -> String {
let program = quote_command_part(command.get_program().to_string_lossy().as_ref());
let args = command
.get_args()
.map(|arg| quote_command_part(arg.to_string_lossy().as_ref()))
.collect::<Vec<String>>();
if args.is_empty() {
program
} else {
format!("{} {}", program, args.join(" "))
}
}
#[cfg(target_os = "windows")]
fn escape_powershell_single_quoted(value: &str) -> String {
value.replace('\'', "''")
}
#[cfg(target_os = "windows")]
fn build_windows_path_filtered_process_probe_script(
process_name: &str,
expected_exe_path: &str,
) -> String {
let process = escape_powershell_single_quoted(process_name);
let expected = escape_powershell_single_quoted(expected_exe_path);
format!(
r#"$processName='{process}';
$expectedRaw='{expected}';
function Normalize-ExePath([string]$path) {{
if ([string]::IsNullOrWhiteSpace($path)) {{ return $null }}
$value = $path.Trim().Trim('"')
$value = [Environment]::ExpandEnvironmentVariables($value)
if ($value.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {{
$value = '\\' + $value.Substring(8)
}} elseif ($value.StartsWith('\\?\', [System.StringComparison]::OrdinalIgnoreCase)) {{
$value = $value.Substring(4)
}}
$value = $value -replace '/', '\'
try {{ $value = [System.IO.Path]::GetFullPath($value) }} catch {{}}
if ($value.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {{
$value = '\\' + $value.Substring(8)
}} elseif ($value.StartsWith('\\?\', [System.StringComparison]::OrdinalIgnoreCase)) {{
$value = $value.Substring(4)
}}
return $value.ToLowerInvariant()
}}
function Get-ExePathFromCmdLine([string]$cmdline) {{
if ([string]::IsNullOrWhiteSpace($cmdline)) {{ return $null }}
$value = $cmdline.Trim()
if ($value.StartsWith('"')) {{
$end = $value.IndexOf('"', 1)
if ($end -gt 1) {{ return $value.Substring(1, $end - 1) }}
}}
$exeMatch = [regex]::Match($value, '^[^""]+?\.exe', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($exeMatch.Success) {{ return $exeMatch.Value.Trim() }}
$space = $value.IndexOf(' ')
if ($space -gt 0) {{ return $value.Substring(0, $space) }}
return $value
}}
$expected = Normalize-ExePath $expectedRaw
if ([string]::IsNullOrWhiteSpace($expected)) {{ exit 0 }}
Get-CimInstance Win32_Process -Filter ("Name='" + $processName + "'") |
Where-Object {{
$exe = Normalize-ExePath $_.ExecutablePath
if (-not $exe) {{ $exe = Normalize-ExePath (Get-ExePathFromCmdLine $_.CommandLine) }}
$exe -eq $expected
}} |
ForEach-Object {{ "$($_.ProcessId)|$($_.CommandLine)" }}"#
)
}
#[cfg(target_os = "windows")]
fn truncate_for_trace(text: &str, max_chars: usize) -> String {
let mut iter = text.chars();
let mut current = String::new();
for _ in 0..max_chars {
let Some(ch) = iter.next() else {
return text.to_string();
};
current.push(ch);
}
if iter.next().is_none() {
text.to_string()
} else {
format!("{}...(truncated)", current)
}
}
#[cfg(target_os = "windows")]
fn output_bytes_for_trace(bytes: &[u8]) -> String {
let value = String::from_utf8_lossy(bytes);
let trimmed = value.trim();
if trimmed.is_empty() {
"<empty>".to_string()
} else {
truncate_for_trace(trimmed, 4000)
}
}
fn log_command_trace_exec(command_preview: &str) {
if !command_trace_enabled() {
return;
}
crate::modules::logger::log_info(&format!("[CmdTrace] EXEC {}", command_preview));
}
#[cfg(target_os = "windows")]
fn log_command_trace_result(
command_preview: &str,
result: &std::io::Result<std::process::Output>,
elapsed: Duration,
) {
if !command_trace_enabled() {
return;
}
match result {
Ok(output) => {
crate::modules::logger::log_info(&format!(
"[CmdTrace] RESULT elapsed={}ms status={} cmd={}",
elapsed.as_millis(),
output.status,
command_preview
));
crate::modules::logger::log_info(&format!(
"[CmdTrace] STDOUT cmd={} => {}",
command_preview,
output_bytes_for_trace(&output.stdout)
));
crate::modules::logger::log_info(&format!(
"[CmdTrace] STDERR cmd={} => {}",
command_preview,
output_bytes_for_trace(&output.stderr)
));
}
Err(err) => {
crate::modules::logger::log_warn(&format!(
"[CmdTrace] ERROR elapsed={}ms cmd={} err={}",
elapsed.as_millis(),
command_preview,
err
));
}
}
}
fn log_command_trace_spawn_result(
command_preview: &str,
result: &std::io::Result<Child>,
elapsed: Duration,
) {
if !command_trace_enabled() {
return;
}
match result {
Ok(child) => crate::modules::logger::log_info(&format!(
"[CmdTrace] SPAWN elapsed={}ms pid={} cmd={}",
elapsed.as_millis(),
child.id(),
command_preview
)),
Err(err) => crate::modules::logger::log_warn(&format!(
"[CmdTrace] SPAWN_ERROR elapsed={}ms cmd={} err={}",
elapsed.as_millis(),
command_preview,
err
)),
}
}
fn spawn_command_with_trace(cmd: &mut Command) -> std::io::Result<Child> {
let preview = format_command_preview(cmd);
log_command_trace_exec(&preview);
let start = Instant::now();
let result = cmd.spawn();
log_command_trace_spawn_result(&preview, &result, start.elapsed());
result
}
#[cfg(target_os = "windows")]
fn build_powershell_command(args: &[&str]) -> Command {
use std::os::windows::process::CommandExt;
let mut final_args: Vec<String> = vec![
"-WindowStyle".to_string(),
"Hidden".to_string(),
"-NonInteractive".to_string(),
"-NoProfile".to_string(),
];
let mut index = 0;
while index < args.len() {
let arg = args[index];
if arg.eq_ignore_ascii_case("-NoProfile") || arg.eq_ignore_ascii_case("-NonInteractive") {
index += 1;
continue;
}
if arg.eq_ignore_ascii_case("-WindowStyle") {
index += if index + 1 < args.len() { 2 } else { 1 };
continue;
}
if arg.eq_ignore_ascii_case("-Command") {
let script = args.get(index + 1).copied().unwrap_or("");
let wrapped = format!(
"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; $OutputEncoding=[System.Text.Encoding]::UTF8; {}",
script
);
final_args.push("-Command".to_string());
final_args.push(wrapped);
index += if index + 1 < args.len() { 2 } else { 1 };
continue;
}
final_args.push(arg.to_string());
index += 1;
}
let mut command = Command::new("powershell");
command.creation_flags(CREATE_NO_WINDOW).args(final_args);
command
}
#[cfg(target_os = "windows")]
fn powershell_output(args: &[&str]) -> std::io::Result<std::process::Output> {
let mut command = build_powershell_command(args);
let preview = format_command_preview(&command);
log_command_trace_exec(&preview);
let start = Instant::now();
let result = command.output();
log_command_trace_result(&preview, &result, start.elapsed());
result
}
#[cfg(target_os = "windows")]
fn powershell_output_with_timeout(
args: &[&str],
timeout: Duration,
) -> std::io::Result<std::process::Output> {
use std::io::{Error, ErrorKind, Read};
let mut command = build_powershell_command(args);
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let preview = format_command_preview(&command);
log_command_trace_exec(&preview);
let mut child = match command.spawn() {
Ok(child) => child,
Err(err) => {
if command_trace_enabled() {
crate::modules::logger::log_warn(&format!(
"[CmdTrace] SPAWN_ERROR elapsed=0ms cmd={} err={}",
preview, err
));
}
return Err(err);
}
};
let start = Instant::now();
loop {
if let Some(status) = child.try_wait()? {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
if let Some(mut out) = child.stdout.take() {
let _ = out.read_to_end(&mut stdout);
}
if let Some(mut err) = child.stderr.take() {
let _ = err.read_to_end(&mut stderr);
}
let result = Ok(std::process::Output {
status,
stdout,
stderr,
});
log_command_trace_result(&preview, &result, start.elapsed());
return result;
}
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
let result = Err(Error::new(
ErrorKind::TimedOut,
format!("PowerShell 进程探测超时({}ms)", timeout.as_millis()),
));
log_command_trace_result(&preview, &result, start.elapsed());
return result;
}
thread::sleep(Duration::from_millis(100));
}
}
#[cfg(target_os = "windows")]
fn cmd_output(args: &[&str]) -> std::io::Result<std::process::Output> {
use std::os::windows::process::CommandExt;
let mut command = Command::new("cmd");
command.creation_flags(CREATE_NO_WINDOW).args(args);
let preview = format_command_preview(&command);
log_command_trace_exec(&preview);
let start = Instant::now();
let result = command.output();
log_command_trace_result(&preview, &result, start.elapsed());
result
}
#[cfg(target_os = "windows")]
fn powershell_output_file(script: &str) -> std::io::Result<std::process::Output> {
use std::os::windows::process::CommandExt;
use std::time::{SystemTime, UNIX_EPOCH};
let mut path = std::env::temp_dir();
let unique = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
path.push(format!("cockpit_ps_{}_{}.ps1", std::process::id(), unique));
let file_script = format!(
"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; $OutputEncoding=[System.Text.Encoding]::UTF8; {}\n",
script
);
std::fs::write(&path, file_script)?;
let mut command = Command::new("powershell");
command.creation_flags(CREATE_NO_WINDOW).args([
"-WindowStyle",
"Hidden",
"-NonInteractive",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
&path.to_string_lossy(),
]);
let preview = format_command_preview(&command);
log_command_trace_exec(&preview);
let start = Instant::now();
let output = command.output();
log_command_trace_result(&preview, &output, start.elapsed());
let _ = std::fs::remove_file(&path);
output
}
#[cfg(target_os = "windows")]
fn powershell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
#[cfg(target_os = "windows")]
fn powershell_array_literal(values: &[&str]) -> String {
values
.iter()
.map(|value| powershell_quote(value))
.collect::<Vec<String>>()
.join(",")
}
#[cfg(target_os = "windows")]
fn normalize_windows_candidate_path(raw: &str) -> Option<std::path::PathBuf> {
let text = raw.trim();
if text.is_empty() {
return None;
}
let mut normalized = text.trim_matches('"').trim_matches('\'').trim().to_string();
let lowered = normalized.to_lowercase();
if let Some(index) = lowered.find(".exe") {
normalized.truncate(index + 4);
}
let normalized = normalized
.trim()
.trim_matches('"')
.trim_matches('\'')
.trim_end_matches(',')
.trim()
.to_string();
if normalized.is_empty() {
return None;
}
let path = std::path::PathBuf::from(normalized);
if path.exists() && path.is_file() {
Some(path)
} else {
None
}
}
#[cfg(target_os = "windows")]
fn score_windows_candidate(
path: &std::path::Path,
exe_names_lower: &HashSet<String>,
keywords_lower: &[String],
) -> Option<i32> {
let file_name = path
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("")
.to_lowercase();
if file_name.is_empty() {
return None;
}
let path_lower = path.to_string_lossy().to_lowercase();
let has_keyword = keywords_lower
.iter()
.any(|keyword| !keyword.is_empty() && path_lower.contains(keyword));
if exe_names_lower.contains(&file_name) {
if file_name == "electron.exe" && !has_keyword {
return None;
}
let mut score = if file_name == "electron.exe" { 60 } else { 100 };
if has_keyword {
score += 5;
}
return Some(score);
}
let is_exe = path
.extension()
.and_then(|value| value.to_str())
.map(|value| value.eq_ignore_ascii_case("exe"))
.unwrap_or(false);
if is_exe && has_keyword {
return Some(50);
}
None
}
#[cfg(target_os = "windows")]
fn parse_windows_exec_candidates(
app_label: &str,
exe_names: &[&str],
display_keywords: &[&str],
output: std::process::Output,
) -> Option<std::path::PathBuf> {
let exe_names_lower: HashSet<String> =
exe_names.iter().map(|value| value.to_lowercase()).collect();
let keywords_lower: Vec<String> = display_keywords
.iter()
.map(|value| value.trim().to_lowercase())
.filter(|value| !value.is_empty())
.collect();
let mut seen: HashSet<String> = HashSet::new();
let mut best: Option<(std::path::PathBuf, i32)> = None;
let mut raw_lines = 0usize;
let mut scored_candidates = 0usize;
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let trimmed_line = line.trim();
if trimmed_line.is_empty() || trimmed_line.starts_with("STAGE:") {
continue;
}
raw_lines += 1;
let Some(path) = normalize_windows_candidate_path(line) else {
continue;
};
let dedupe_key = path.to_string_lossy().to_lowercase();
if !seen.insert(dedupe_key) {
continue;
}
let Some(score) = score_windows_candidate(&path, &exe_names_lower, &keywords_lower) else {
continue;
};
scored_candidates += 1;
match best.as_ref() {
Some((_, current_score)) if *current_score >= score => {}
_ => best = Some((path, score)),
}
}
if let Some((path, score)) = best {
crate::modules::logger::log_info(&format!(
"[Path Detect] {} auto detect hit: {}, score={}",
app_label,
path.to_string_lossy(),
score
));
return Some(path);
}
let local_appdata = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| "<unset>".to_string());
let program_files = std::env::var("PROGRAMFILES").unwrap_or_else(|_| "<unset>".to_string());
let program_files_x86 =
std::env::var("PROGRAMFILES(X86)").unwrap_or_else(|_| "<unset>".to_string());
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} Windows multi-source detect miss: raw_lines={}, unique_candidates={}, scored_candidates={}, local_appdata={}, program_files={}, program_files_x86={}",
app_label,
raw_lines,
seen.len(),
scored_candidates,
local_appdata,
program_files,
program_files_x86
));
None
}
#[cfg(target_os = "windows")]
fn decode_utf16le(bytes: &[u8]) -> String {
// Skip UTF-16 LE BOM if present
let bytes = if bytes.starts_with(&[0xFF, 0xFE]) {
&bytes[2..]
} else {
bytes
};
let mut words = Vec::with_capacity(bytes.len() / 2);
let mut iter = bytes.iter().copied();
while let Some(lo) = iter.next() {
let hi = iter.next().unwrap_or(0);
words.push(u16::from_le_bytes([lo, hi]));
}
String::from_utf16_lossy(&words)
}
#[cfg(target_os = "windows")]
fn reg_query_value(key: &str, value_name: &str) -> Option<String> {
let cmd = if value_name == "(Default)" {
format!("reg query \"{}\" /ve", key)
} else {
format!("reg query \"{}\" /v {}", key, value_name)
};
let output = cmd_output(&["/u", "/c", &cmd]).ok()?;
if !output.status.success() {
return None;
}
let stdout = decode_utf16le(&output.stdout);
let value_name_lower = value_name.to_lowercase();
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let matches_name = if value_name == "(Default)" {
trimmed.starts_with("(Default)")
} else {
trimmed.to_lowercase().starts_with(&value_name_lower)
};
if !matches_name {
continue;
}
if let Some(pos) = trimmed.find("REG_") {
let after = &trimmed[pos..];
if let Some(ws_idx) = after.find(char::is_whitespace) {
let value = after[ws_idx..].trim();
if !value.is_empty() {
return Some(value.to_string());
}
}
}
}
None
}
#[cfg(target_os = "windows")]
fn detect_vscode_exec_path_by_registry() -> Option<std::path::PathBuf> {
let exe_names = ["Code.exe", "Code - Insiders.exe"];
let app_path_roots = [
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths",
"HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths",
"HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths",
];
for root in app_path_roots {
for exe in exe_names {
let key = format!("{}\\{}", root, exe);
if let Some(value) = reg_query_value(&key, "(Default)") {
if let Some(path) = normalize_windows_candidate_path(&value) {
crate::modules::logger::log_info(&format!(
"[Path Detect] vscode registry hit: {}",
path.to_string_lossy()
));
return Some(path);
}
}
if let Some(path_root) = reg_query_value(&key, "Path") {
let candidate = std::path::PathBuf::from(path_root).join(exe);
if candidate.exists() {
crate::modules::logger::log_info(&format!(
"[Path Detect] vscode registry hit: {}",
candidate.to_string_lossy()
));
return Some(candidate);
}
}
}
}
let uninstall_roots = [
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
];
let keywords = ["visual studio code", "vs code", "vscode"];
for root in uninstall_roots {
let cmd = format!("reg query \"{}\" /s /v DisplayName", root);
let output = match cmd_output(&["/u", "/c", &cmd]) {
Ok(o) => o,
Err(_) => continue,
};
if !output.status.success() {
continue;
}
let stdout = decode_utf16le(&output.stdout);
let mut current_key: Option<String> = None;
let mut matched_keys: Vec<String> = Vec::new();
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.starts_with("HKEY_") {
current_key = Some(trimmed.to_string());
continue;
}
if !trimmed.to_lowercase().starts_with("displayname") {
continue;
}
if let Some(pos) = trimmed.find("REG_") {
let after = &trimmed[pos..];
if let Some(ws_idx) = after.find(char::is_whitespace) {
let value = after[ws_idx..].trim().to_lowercase();
if keywords.iter().any(|kw| value.contains(kw)) {
if let Some(key) = current_key.as_ref() {
matched_keys.push(key.clone());
}
}
}
}
}
for key in matched_keys {
for value_name in ["DisplayIcon", "UninstallString"] {
if let Some(value) = reg_query_value(&key, value_name) {
if let Some(path) = normalize_windows_candidate_path(&value) {
crate::modules::logger::log_info(&format!(
"[Path Detect] vscode registry hit: {}",
path.to_string_lossy()
));
return Some(path);
}
}
}
if let Some(install_root) = reg_query_value(&key, "InstallLocation") {
for exe in exe_names {
let candidate = std::path::PathBuf::from(&install_root).join(exe);
if candidate.exists() {
crate::modules::logger::log_info(&format!(
"[Path Detect] vscode registry hit: {}",
candidate.to_string_lossy()
));
return Some(candidate);
}
}
}
}
}
None
}
#[cfg(target_os = "windows")]
pub fn detect_windows_exec_path_by_signatures(
app_label: &str,
exe_names: &[&str],
command_names: &[&str],
protocol_names: &[&str],
display_keywords: &[&str],
) -> Option<std::path::PathBuf> {
if exe_names.is_empty() {
return None;
}
let exe_array = powershell_array_literal(exe_names);
let command_array = powershell_array_literal(command_names);
let protocol_array = powershell_array_literal(protocol_names);
let keyword_array = powershell_array_literal(display_keywords);
let script = format!(
r#"$ErrorActionPreference='SilentlyContinue'
Write-Output 'STAGE:BEGIN'
$exeNames=@({exe_array})
$commandNames=@({command_array})
$protocolNames=@({protocol_array})
$keywords=@({keyword_array})
function Normalize-Candidate([string]$raw) {{
if ([string]::IsNullOrWhiteSpace($raw)) {{ return $null }}
$text = $raw.Trim()
if ($text -match '(?i)(?<p>[A-Za-z]:\\.+?\.exe)') {{
$text = $matches['p']
}}
$text = $text.Trim().Trim('"').Trim("'")
if ([string]::IsNullOrWhiteSpace($text)) {{ return $null }}
return $text
}}
function Emit-Candidate([string]$raw) {{
$candidate = Normalize-Candidate $raw
if ([string]::IsNullOrWhiteSpace($candidate)) {{ return }}
if (Test-Path -LiteralPath $candidate) {{ Write-Output $candidate }}
}}
Write-Output 'STAGE:APP_PATHS'
$appPathRoots=@(
'HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths',
'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths'
)
foreach ($root in $appPathRoots) {{
foreach ($exe in $exeNames) {{
$keyPath = Join-Path $root $exe
$entry = Get-ItemProperty -Path $keyPath -ErrorAction SilentlyContinue
if ($entry) {{
Emit-Candidate $entry.'(default)'
if ($entry.Path) {{
Emit-Candidate (Join-Path $entry.Path $exe)
}}
}}
}}
}}
Write-Output 'STAGE:UNINSTALL'
$uninstallRoots=@(
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
foreach ($root in $uninstallRoots) {{
Get-ItemProperty -Path $root -ErrorAction SilentlyContinue | ForEach-Object {{
$display = [string]$_.DisplayName
$displayLower = $display.ToLowerInvariant()
$hit = $false
foreach ($kw in $keywords) {{
if ([string]::IsNullOrWhiteSpace($kw)) {{ continue }}
if ($displayLower.Contains($kw.ToLowerInvariant())) {{
$hit = $true
break
}}
}}
if (-not $hit) {{ return }}
Emit-Candidate $_.DisplayIcon
Emit-Candidate $_.UninstallString
$install = [string]$_.InstallLocation
if (-not [string]::IsNullOrWhiteSpace($install)) {{
foreach ($exe in $exeNames) {{
Emit-Candidate (Join-Path $install $exe)
}}
}}
}}
}}
Write-Output 'STAGE:CLASSES'
$classRoots=@('HKCU:\Software\Classes','HKLM:\Software\Classes')
foreach ($protocol in $protocolNames) {{
if ([string]::IsNullOrWhiteSpace($protocol)) {{ continue }}
foreach ($classRoot in $classRoots) {{
$commandPath = Join-Path (Join-Path $classRoot $protocol) 'shell\open\command'
Emit-Candidate ((Get-ItemProperty -Path $commandPath -ErrorAction SilentlyContinue).'(default)')
}}
}}
Write-Output 'STAGE:SHORTCUTS'
$shortcutRoots=@(
"$env:ProgramData\Microsoft\Windows\Start Menu\Programs",
"$env:APPDATA\Microsoft\Windows\Start Menu\Programs",
"$env:USERPROFILE\Desktop",
"$env:PUBLIC\Desktop"
)
$shell = $null
try {{ $shell = New-Object -ComObject WScript.Shell }} catch {{}}
if ($shell) {{
foreach ($root in $shortcutRoots) {{
if (-not (Test-Path -LiteralPath $root)) {{ continue }}
Get-ChildItem -Path $root -Filter *.lnk -Recurse -ErrorAction SilentlyContinue | ForEach-Object {{
try {{
$shortcut = $shell.CreateShortcut($_.FullName)
Emit-Candidate $shortcut.TargetPath
}} catch {{}}
}}
}}
}}
Write-Output 'STAGE:COMMANDS'
foreach ($commandName in $commandNames) {{
if ([string]::IsNullOrWhiteSpace($commandName)) {{ continue }}
$command = Get-Command $commandName -ErrorAction SilentlyContinue | Select-Object -First 1
if ($command) {{
Emit-Candidate $command.Source
Emit-Candidate $command.Definition
}}
}}
Write-Output 'STAGE:END'
exit 0
"#
);
let output = match powershell_output(&["-Command", &script]) {
Ok(value) => value,
Err(err) => {
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} PowerShell detect failed: {}",
app_label, err
));
return None;
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} PowerShell command failed(-Command): status={}, stdout_head={}, stderr_head={}",
app_label,
output.status,
stdout.chars().take(400).collect::<String>(),
stderr.chars().take(400).collect::<String>()
));
if strict_process_detect_enabled() {
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} strict mode enabled, skip -File fallback",
app_label
));
return None;
}
let retry = match powershell_output_file(&script) {
Ok(value) => value,
Err(err) => {
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} PowerShell -File detect failed: {}",
app_label, err
));
return None;
}
};
if !retry.status.success() {
let retry_stderr = String::from_utf8_lossy(&retry.stderr);
let retry_stdout = String::from_utf8_lossy(&retry.stdout);
crate::modules::logger::log_warn(&format!(
"[Path Detect] {} PowerShell command failed(-File): status={}, stdout_head={}, stderr_head={}",
app_label,
retry.status,
retry_stdout.chars().take(400).collect::<String>(),
retry_stderr.chars().take(400).collect::<String>()
));
return None;
}
crate::modules::logger::log_info(&format!(
"[Path Detect] {} PowerShell -File fallback succeeded after -Command failure",
app_label
));
return parse_windows_exec_candidates(app_label, exe_names, display_keywords, retry);
}
parse_windows_exec_candidates(app_label, exe_names, display_keywords, output)
}
fn should_detach_child() -> bool {
if let Ok(value) = std::env::var("COCKPIT_CHILD_LOGS") {
let lowered = value.trim().to_lowercase();
if matches!(lowered.as_str(), "1" | "true" | "yes" | "on") {
return false;
}
}
if let Ok(value) = std::env::var("COCKPIT_CHILD_DETACH") {
let lowered = value.trim().to_lowercase();
if matches!(lowered.as_str(), "0" | "false" | "no" | "off") {
return false;
}
}
true
}
#[cfg(target_os = "macos")]
fn sanitize_macos_gui_launch_env(cmd: &mut Command) {
// Avoid inheriting Cockpit bundle identity into child GUI apps.
cmd.env_remove("__CFBundleIdentifier");
cmd.env_remove("XPC_SERVICE_NAME");
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn spawn_detached_unix(cmd: &mut Command) -> Result<Child, String> {
use std::os::unix::process::CommandExt;
if !should_detach_child() {
return spawn_command_with_trace(cmd).map_err(|e| format!("启动失败: {}", e));
}
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
spawn_command_with_trace(cmd).map_err(|e| format!("启动失败: {}", e))
}
fn normalize_custom_path(value: Option<&str>) -> Option<String> {
let trimmed = value.unwrap_or("").trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
const APP_PATH_NOT_FOUND_PREFIX: &str = "APP_PATH_NOT_FOUND:";
fn app_path_missing_error(app: &str) -> String {
format!("{}{}", APP_PATH_NOT_FOUND_PREFIX, app)
}