1use crate::state::SecureString;
4use crate::state::{PackageItem, modal::CascadeMode};
5
6#[derive(Debug, Clone)]
17pub enum ExecutorRequest {
18 Install {
20 items: Vec<PackageItem>,
22 password: Option<SecureString>,
24 dry_run: bool,
26 },
27 Remove {
29 names: Vec<String>,
31 password: Option<SecureString>,
33 cascade: CascadeMode,
35 dry_run: bool,
37 },
38 Downgrade {
40 names: Vec<String>,
42 password: Option<SecureString>,
44 dry_run: bool,
46 },
47 CustomCommand {
49 command: String,
51 password: Option<SecureString>,
53 dry_run: bool,
55 },
56 Update {
58 commands: Vec<String>,
60 password: Option<SecureString>,
62 dry_run: bool,
64 },
65 Scan {
67 package: String,
69 do_clamav: bool,
71 do_trivy: bool,
73 do_semgrep: bool,
75 do_shellcheck: bool,
77 do_virustotal: bool,
79 do_custom: bool,
81 dry_run: bool,
83 },
84}
85
86#[derive(Debug, Clone)]
97pub enum ExecutorOutput {
98 Line(String),
100 ReplaceLastLine(String),
102 Finished {
104 success: bool,
106 exit_code: Option<i32>,
108 failed_command: Option<String>,
110 },
111 Error(String),
113}
114
115pub fn build_install_command_for_executor(
135 items: &[PackageItem],
136 password: Option<&str>,
137 dry_run: bool,
138) -> Result<String, String> {
139 use crate::state::Source;
140
141 let mut official = Vec::new();
142 let mut aur = Vec::new();
143 for item in items {
144 match item.source {
145 Source::Official { .. } => official.push(item.name.clone()),
146 Source::Aur => aur.push(item.name.clone()),
147 }
148 }
149 let installed = crate::logic::deps::get_installed_packages();
150 let provided = crate::logic::deps::get_provided_packages(&installed);
151 let official_reinstall = official.iter().any(|name| {
152 crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
153 });
154 let aur_reinstall = aur.iter().any(|name| {
155 crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
156 });
157 let (official_plan, aur_plan) = crate::integrations::arch_toolkit::install::batch_install(
158 &official,
159 &aur,
160 official_reinstall,
161 aur_reinstall,
162 )?;
163
164 let official_command = match official_plan {
165 Some(plan) if dry_run => Some(privilege_command(&plan, None)?),
166 Some(plan) => {
167 let sync = privilege_command("pacman -Sy", password)?;
168 let install = privilege_command(&plan, password)?;
169 Some(format!("{sync} && {install}"))
170 }
171 None => None,
172 };
173 let body = match (official_command, aur_plan) {
174 (Some(official), Some(aur)) => format!("{official} && {aur}"),
175 (Some(official), None) => official,
176 (None, Some(aur)) => aur,
177 (None, None) => "echo nothing to install".to_string(),
178 };
179 if dry_run {
180 Ok(format!(
181 "echo DRY RUN: {}",
182 super::utils::shell_single_quote(&body)
183 ))
184 } else {
185 Ok(body)
186 }
187}
188
189fn privilege_command(command: &str, password: Option<&str>) -> Result<String, String> {
201 let tool = crate::logic::privilege::active_tool()?;
202 Ok(password.filter(|value| !value.is_empty()).map_or_else(
203 || crate::logic::privilege::build_privilege_command(tool, command),
204 |value| {
205 crate::logic::privilege::build_password_pipe(tool, value, command)
206 .unwrap_or_else(|| crate::logic::privilege::build_privilege_command(tool, command))
207 },
208 ))
209}
210
211pub fn build_remove_command_for_executor(
232 names: &[String],
233 password: Option<&str>,
234 cascade: crate::state::modal::CascadeMode,
235 dry_run: bool,
236) -> Result<String, String> {
237 use super::utils::shell_single_quote;
238
239 if names.is_empty() {
240 return Ok(if dry_run {
241 "echo DRY RUN: nothing to remove".to_string()
242 } else {
243 "echo nothing to remove".to_string()
244 });
245 }
246
247 let base_cmd = crate::integrations::arch_toolkit::install::remove(names, cascade)?;
248 if dry_run {
249 let command = privilege_command(&base_cmd, None)?;
250 Ok(format!("echo DRY RUN: {}", shell_single_quote(&command)))
251 } else {
252 privilege_command(&base_cmd, password)
253 }
254}
255
256pub fn build_downgrade_command_for_executor(
276 names: &[String],
277 _password: Option<&str>,
278 dry_run: bool,
279) -> Result<String, String> {
280 use super::utils::shell_single_quote;
281 if names.is_empty() {
282 return Ok(if dry_run {
283 "echo DRY RUN: nothing to downgrade".to_string()
284 } else {
285 "echo nothing to downgrade".to_string()
286 });
287 }
288
289 let names_str = names.join(" ");
290
291 let tool = crate::logic::privilege::active_tool()?;
292 let bin = tool.binary_name();
293
294 if dry_run {
295 let cmd = crate::logic::privilege::build_privilege_command(
296 tool,
297 &format!("downgrade {names_str}"),
298 );
299 let quoted = shell_single_quote(&cmd);
300 Ok(format!("echo DRY RUN: {quoted}"))
301 } else {
302 Ok(format!(
303 "if (command -v downgrade >/dev/null 2>&1) || pacman -Qi downgrade >/dev/null 2>&1; then {bin} downgrade {names_str}; else echo 'downgrade tool not found. Install \"downgrade\" package.'; fi"
304 ))
305 }
306}
307
308pub fn build_update_command_for_executor(
329 commands: &[String],
330 password: Option<&str>,
331 dry_run: bool,
332) -> Result<String, String> {
333 use super::utils::shell_single_quote;
334
335 if commands.is_empty() {
336 return Ok(if dry_run {
337 "echo DRY RUN: nothing to update".to_string()
338 } else {
339 "echo nothing to update".to_string()
340 });
341 }
342
343 let processed_commands: Vec<String> = if dry_run {
344 let simulate_failure = std::env::var("PACSEA_TEST_SIMULATE_PACMAN_FAILURE").is_ok()
346 && !commands.is_empty()
347 && commands[0].contains("pacman");
348
349 if simulate_failure {
350 tracing::info!(
351 "[DRY-RUN] Simulating pacman failure for testing - first command will fail with exit code 1"
352 );
353 }
354
355 commands
356 .iter()
357 .enumerate()
358 .map(|(idx, c)| {
359 let quoted = shell_single_quote(c);
361 if simulate_failure && idx == 0 {
362 format!("echo DRY RUN: {quoted} && false")
366 } else {
367 format!("echo DRY RUN: {quoted}")
368 }
369 })
370 .collect()
371 } else {
372 let tool = crate::logic::privilege::active_tool()?;
373 let prefix = format!("{} ", tool.binary_name());
374 commands
375 .iter()
376 .map(|cmd| {
377 password.map_or_else(
378 || cmd.clone(),
379 |pass| {
380 cmd.strip_prefix(&prefix).map_or_else(
381 || cmd.clone(),
382 |base_cmd| {
383 crate::logic::privilege::build_password_pipe(tool, pass, base_cmd)
384 .unwrap_or_else(|| cmd.clone())
385 },
386 )
387 },
388 )
389 })
390 .collect()
391 };
392
393 let joined = processed_commands.join(" && ");
394
395 if let Some(pass) = password {
397 let tool = crate::logic::privilege::active_tool()?;
398 if let Some(warmup) = crate::logic::privilege::build_credential_warmup(tool, pass) {
399 return Ok(format!("{warmup} ; {joined}"));
400 }
401 }
402
403 Ok(joined)
404}
405
406#[cfg(not(target_os = "windows"))]
421#[must_use]
422#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
423pub fn build_scan_command_for_executor(
424 package: &str,
425 do_clamav: bool,
426 do_trivy: bool,
427 do_semgrep: bool,
428 do_shellcheck: bool,
429 do_virustotal: bool,
430 do_custom: bool,
431 dry_run: bool,
432) -> String {
433 use super::utils::shell_single_quote;
434 use crate::install::scan::pkg::build_scan_cmds_for_pkg_without_sleuth;
435
436 let mut cmds: Vec<String> = Vec::new();
438 cmds.push(format!(
439 "export PACSEA_SCAN_DO_CLAMAV={}",
440 if do_clamav { "1" } else { "0" }
441 ));
442 cmds.push(format!(
443 "export PACSEA_SCAN_DO_TRIVY={}",
444 if do_trivy { "1" } else { "0" }
445 ));
446 cmds.push(format!(
447 "export PACSEA_SCAN_DO_SEMGREP={}",
448 if do_semgrep { "1" } else { "0" }
449 ));
450 cmds.push(format!(
451 "export PACSEA_SCAN_DO_SHELLCHECK={}",
452 if do_shellcheck { "1" } else { "0" }
453 ));
454 cmds.push(format!(
455 "export PACSEA_SCAN_DO_VIRUSTOTAL={}",
456 if do_virustotal { "1" } else { "0" }
457 ));
458 cmds.push(format!(
459 "export PACSEA_SCAN_DO_CUSTOM={}",
460 if do_custom { "1" } else { "0" }
461 ));
462 cmds.push("export PACSEA_PATTERNS_CRIT='/dev/(tcp|udp)/|bash -i *>& *[^ ]*/dev/(tcp|udp)/[0-9]+|exec [0-9]{2,}<>/dev/(tcp|udp)/|rm -rf[[:space:]]+/|dd if=/dev/zero of=/dev/sd[a-z]|[>]{1,2}[[:space:]]*/dev/sd[a-z]|: *\\(\\) *\\{ *: *\\| *: *& *\\};:|/etc/sudoers([[:space:]>]|$)|echo .*[>]{2}.*(/etc/sudoers|/root/.ssh/authorized_keys)|/etc/ld\\.so\\.preload|LD_PRELOAD=|authorized_keys.*[>]{2}|ssh-rsa [A-Za-z0-9+/=]+.*[>]{2}.*authorized_keys|curl .*(169\\.254\\.169\\.254)'".to_string());
464 cmds.push("export PACSEA_PATTERNS_HIGH='eval|base64 -d|wget .*(sh|bash|dash|ksh|zsh)([^A-Za-z]|$)|curl .*(sh|bash|dash|ksh|zsh)([^A-Za-z]|$)|sudo[[:space:]]|chattr[[:space:]]|useradd|adduser|groupadd|systemctl|service[[:space:]]|crontab|/etc/cron\\.|[>]{2}.*(\\.bashrc|\\.bash_profile|/etc/profile|\\.zshrc)|cat[[:space:]]+/etc/shadow|cat[[:space:]]+~/.ssh/id_rsa|cat[[:space:]]+~/.bash_history|systemctl stop (auditd|rsyslog)|service (auditd|rsyslog) stop|scp .*@|curl -F|nc[[:space:]].*<|tar -czv?f|zip -r'".to_string());
465 cmds.push("export PACSEA_PATTERNS_MEDIUM='whoami|uname -a|hostname|id|groups|nmap|netstat -anp|ss -anp|ifconfig|ip addr|arp -a|grep -ri .*secret|find .*-name.*(password|\\.key)|env[[:space:]]*\\|[[:space:]]*grep -i pass|wget https?://|curl https?://'".to_string());
466 cmds.push("export PACSEA_PATTERNS_LOW='http_proxy=|https_proxy=|ALL_PROXY=|yes[[:space:]]+> */dev/null *&|ulimit -n [0-9]{5,}'".to_string());
467
468 cmds.extend(build_scan_cmds_for_pkg_without_sleuth(package));
470
471 let full_cmd = cmds.join(" && ");
472
473 if dry_run {
474 let quoted = shell_single_quote(&full_cmd);
475 format!("echo DRY RUN: {quoted}")
476 } else {
477 full_cmd
478 }
479}
480
481#[cfg(test)]
482mod tests {
483 use super::*;
484 use crate::state::Source;
485
486 fn create_test_package(name: &str, source: Source) -> PackageItem {
498 PackageItem {
499 name: name.into(),
500 version: "1.0.0".into(),
501 description: String::new(),
502 source,
503 popularity: None,
504 out_of_date: None,
505 orphaned: false,
506 }
507 }
508
509 #[test]
510 fn executor_build_install_command_variants() {
524 let tool = crate::logic::privilege::active_tool().expect("privilege tool");
525 let bin = tool.binary_name();
526
527 let official_pkg = create_test_package(
528 "ripgrep",
529 Source::Official {
530 repo: "extra".into(),
531 arch: "x86_64".into(),
532 },
533 );
534
535 let aur_pkg = create_test_package("yay-bin", Source::Aur);
536
537 let installed_set = crate::logic::deps::get_installed_packages();
538 let provided_set = crate::logic::deps::get_provided_packages(&installed_set);
539 let is_installed = crate::logic::deps::is_package_installed_or_provided(
540 "ripgrep",
541 &installed_set,
542 &provided_set,
543 );
544 let cmd1 =
545 build_install_command_for_executor(std::slice::from_ref(&official_pkg), None, false)
546 .expect("build install");
547 if is_installed {
548 assert!(
549 cmd1.contains("pacman -S --noconfirm -- ripgrep"),
550 "expected validated package operand in: {cmd1}"
551 );
552 assert!(!cmd1.contains("--needed"));
553 } else {
554 assert!(
555 cmd1.contains("pacman -S --needed --noconfirm -- ripgrep"),
556 "expected validated package operand in: {cmd1}"
557 );
558 }
559 assert!(!cmd1.contains("Press any key to close"));
560
561 let cmd2 = build_install_command_for_executor(
563 std::slice::from_ref(&official_pkg),
564 Some("pass"),
565 false,
566 )
567 .expect("build install");
568 if tool.capabilities().supports_stdin_password {
569 assert!(cmd2.contains("printf "), "expected printf in: {cmd2}");
570 if is_installed {
571 assert!(
572 cmd2.contains("pacman -S --noconfirm -- ripgrep"),
573 "expected validated package operand in password command: {cmd2}"
574 );
575 } else {
576 assert!(
577 cmd2.contains("pacman -S --needed --noconfirm -- ripgrep"),
578 "expected validated package operand in password command: {cmd2}"
579 );
580 }
581 } else {
582 assert!(
583 cmd2.contains(&format!("{bin} pacman")),
584 "doas fallback should use plain command: {cmd2}"
585 );
586 }
587
588 let cmd3 = build_install_command_for_executor(std::slice::from_ref(&aur_pkg), None, false)
590 .expect("build install");
591 assert!(cmd3.contains("command -v paru"));
592 assert!(cmd3.contains("paru -S --aur"));
593 assert!(!cmd3.contains("Press any key to close"));
594
595 let cmd4 =
597 build_install_command_for_executor(&[official_pkg], None, true).expect("build install");
598 assert!(cmd4.starts_with("echo DRY RUN:"));
599 }
600
601 #[test]
602 fn executor_build_mixed_packages() {
613 let tool = crate::logic::privilege::active_tool().expect("privilege tool");
614 let bin = tool.binary_name();
615
616 let official_pkg = create_test_package(
617 "ripgrep",
618 Source::Official {
619 repo: "extra".into(),
620 arch: "x86_64".into(),
621 },
622 );
623 let aur_pkg = create_test_package("yay-bin", Source::Aur);
624
625 let cmd = build_install_command_for_executor(&[official_pkg, aur_pkg], None, false)
626 .expect("build install");
627 assert!(
628 cmd.contains(&format!("{bin} pacman")),
629 "expected privileged pacman in mixed install: {cmd}"
630 );
631 assert!(
632 cmd.contains("ripgrep"),
633 "expected official pkg in cmd: {cmd}"
634 );
635 assert!(
636 cmd.contains("paru -S --aur") || cmd.contains("yay -S --aur"),
637 "expected helper --aur for AUR targets: {cmd}"
638 );
639 assert!(
640 cmd.contains("yay-bin"),
641 "expected AUR pkg name in helper invocation: {cmd}"
642 );
643 }
644
645 #[test]
646 fn executor_build_empty_list() {
657 let cmd = build_install_command_for_executor(&[], None, false).expect("build install");
658 assert!(cmd.contains("nothing to install") || cmd.is_empty());
659 }
660
661 #[test]
662 fn executor_build_multiple_official() {
673 let pkg1 = create_test_package(
674 "ripgrep",
675 Source::Official {
676 repo: "extra".into(),
677 arch: "x86_64".into(),
678 },
679 );
680 let pkg2 = create_test_package(
681 "fd",
682 Source::Official {
683 repo: "extra".into(),
684 arch: "x86_64".into(),
685 },
686 );
687
688 let installed_set = crate::logic::deps::get_installed_packages();
689 let provided_set = crate::logic::deps::get_provided_packages(&installed_set);
690 let ripgrep_installed = crate::logic::deps::is_package_installed_or_provided(
691 "ripgrep",
692 &installed_set,
693 &provided_set,
694 );
695 let fd_installed = crate::logic::deps::is_package_installed_or_provided(
696 "fd",
697 &installed_set,
698 &provided_set,
699 );
700 let has_reinstall = ripgrep_installed || fd_installed;
701
702 let cmd =
703 build_install_command_for_executor(&[pkg1, pkg2], None, false).expect("build install");
704 assert!(cmd.contains("ripgrep"));
705 assert!(cmd.contains("fd"));
706 let bin = crate::logic::privilege::active_tool()
707 .expect("privilege tool")
708 .binary_name();
709 if has_reinstall {
710 assert!(
711 cmd.contains(&format!("{bin} pacman -S --noconfirm")),
712 "expected '{bin} pacman -S --noconfirm' in: {cmd}"
713 );
714 assert!(!cmd.contains("--needed"));
715 } else {
716 assert!(
717 cmd.contains(&format!("{bin} pacman -S --needed --noconfirm")),
718 "expected '{bin} pacman -S --needed --noconfirm' in: {cmd}"
719 );
720 }
721 }
722
723 #[test]
724 fn executor_build_dry_run() {
735 let pkg = create_test_package(
736 "ripgrep",
737 Source::Official {
738 repo: "extra".into(),
739 arch: "x86_64".into(),
740 },
741 );
742
743 let cmd = build_install_command_for_executor(&[pkg], None, true).expect("build install");
744 assert!(cmd.starts_with("echo DRY RUN:"));
745 }
748
749 #[test]
750 fn executor_build_password_escaping() {
761 let tool = crate::logic::privilege::active_tool().expect("privilege tool");
762 let pkg = create_test_package(
763 "ripgrep",
764 Source::Official {
765 repo: "extra".into(),
766 arch: "x86_64".into(),
767 },
768 );
769
770 let password = "pass'word\"with$special";
771 let cmd = build_install_command_for_executor(&[pkg], Some(password), false)
772 .expect("build install");
773 if tool.capabilities().supports_stdin_password {
774 assert!(cmd.contains("printf"), "expected printf in: {cmd}");
775 assert!(
776 cmd.contains(&format!("{} -S", tool.binary_name())),
777 "expected '{} -S' in: {cmd}",
778 tool.binary_name()
779 );
780 assert!(
782 cmd.contains('\'') || cmd.contains('"'),
783 "password must be shell-escaped in: {cmd}"
784 );
785 } else {
786 assert!(
788 !cmd.contains(password),
789 "password must not be embedded for non-stdin tools: {cmd}"
790 );
791 }
792 }
793
794 #[test]
795 fn executor_build_remove_command_variants() {
806 use crate::state::modal::CascadeMode;
807
808 let tool = crate::logic::privilege::active_tool().expect("privilege tool");
809 let bin = tool.binary_name();
810 let names = vec!["test-pkg1".to_string(), "test-pkg2".to_string()];
811
812 let cmd1 = build_remove_command_for_executor(&names, None, CascadeMode::Basic, false)
814 .expect("build remove");
815 assert!(
816 cmd1.contains(&format!("{bin} pacman -R --noconfirm")),
817 "expected '{bin} pacman -R --noconfirm' in: {cmd1}"
818 );
819 assert!(cmd1.contains("test-pkg1"));
820 assert!(cmd1.contains("test-pkg2"));
821 assert!(!cmd1.contains("Press any key to close"));
822
823 let cmd2 =
825 build_remove_command_for_executor(&names, Some("pass"), CascadeMode::Cascade, false)
826 .expect("build remove");
827 if tool.capabilities().supports_stdin_password {
828 assert!(cmd2.contains("printf "), "expected printf in: {cmd2}");
829 assert!(
830 cmd2.contains(&format!("{bin} -S pacman -Rs --noconfirm")),
831 "expected '{bin} -S pacman -Rs --noconfirm' in: {cmd2}"
832 );
833 } else {
834 assert!(
835 cmd2.contains(&format!("{bin} pacman -Rs --noconfirm")),
836 "expected '{bin} pacman -Rs --noconfirm' in: {cmd2}"
837 );
838 }
839
840 let cmd3 =
842 build_remove_command_for_executor(&names, None, CascadeMode::CascadeWithConfigs, false)
843 .expect("build remove");
844 assert!(
845 cmd3.contains(&format!("{bin} pacman -Rns --noconfirm")),
846 "expected '{bin} pacman -Rns --noconfirm' in: {cmd3}"
847 );
848
849 let cmd4 = build_remove_command_for_executor(&names, None, CascadeMode::Basic, true)
851 .expect("build remove");
852 assert!(cmd4.starts_with("echo DRY RUN:"));
853 assert!(cmd4.contains("pacman -R --noconfirm"));
854
855 let cmd5 = build_remove_command_for_executor(&[], None, CascadeMode::Basic, false)
857 .expect("build remove");
858 assert_eq!(cmd5, "echo nothing to remove");
859 }
860
861 #[test]
862 fn executor_build_downgrade_command_uses_unprivileged_qi_check() {
875 let names = vec!["linux".to_string(), "linux-headers".to_string()];
876 let tool = crate::logic::privilege::active_tool().expect("privilege tool");
877 let bin = tool.binary_name();
878
879 let live =
880 build_downgrade_command_for_executor(&names, None, false).expect("build downgrade");
881 assert!(
882 live.contains("pacman -Qi downgrade"),
883 "expected unprivileged pacman -Qi check in: {live}"
884 );
885 assert!(
886 live.contains(&format!("{bin} downgrade linux linux-headers")),
887 "expected tool-aware downgrade command in: {live}"
888 );
889
890 let dry =
891 build_downgrade_command_for_executor(&names, None, true).expect("build downgrade");
892 assert!(dry.starts_with("echo DRY RUN:"));
893 assert!(dry.contains(&format!("{bin} downgrade linux linux-headers")));
894 }
895}