1use cpa_core::gostr::GoStr;
6use std::path::{Path, PathBuf};
7
8use super::checksum::{parse_checksums, sha256_hex, verify_checksum};
9use super::client::{Client, Release, StoreError, select_release_assets};
10use super::manifest::{Manifest, release_version};
11use super::registry::{
12 Artifact, INSTALL_TYPE_DIRECT, INSTALL_TYPE_GITHUB_RELEASE, InstallPlan, Plugin, normalize_goarch, normalize_goos,
13 normalize_install_plan, plugin_install_type, valid_plugin_id, valid_plugin_version, validate_install_plan,
14 validate_plugin,
15};
16use super::version::normalize_version;
17use super::zip::{Archive, ReadError};
18
19pub const MAX_LIBRARY_BYTES: u64 = 256 << 20;
22
23pub const LOADED_PLUGIN_LOCKED: &str = "loaded plugin library cannot be overwritten while the server is running";
25
26#[derive(Default)]
28pub struct InstallOptions {
29 pub plugins_dir: String,
30 pub goos: String,
31 pub goarch: String,
32 pub plugin_loaded: Option<Box<dyn Fn() -> bool + Send + Sync>>,
35 pub before_write: Option<Box<dyn Fn() -> Result<(), String> + Send + Sync>>,
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
41pub struct InstallResult {
42 pub id: String,
43 pub version: String,
44 pub release_tag: String,
45 pub install_type: String,
46 pub path: String,
47 pub overwritten: bool,
48 pub skipped: bool,
49}
50
51fn normalize_options(options: &mut InstallOptions) {
54 options.plugins_dir = match options.plugins_dir.trim() {
55 "" => "plugins".into(),
56 d => d.into(),
57 };
58 let goos = match options.goos.trim() {
59 "" => crate::platform::goos(),
60 g => g,
61 };
62 let goarch = match options.goarch.trim() {
63 "" => crate::platform::goarch(),
64 g => g,
65 };
66 options.goos = normalize_goos(goos);
67 options.goarch = normalize_goarch(goarch);
68}
69
70fn other(e: impl Into<String>) -> StoreError {
71 StoreError::Other(e.into())
72}
73
74impl Client {
75 pub async fn install(&self, mut plugin: Plugin, mut options: InstallOptions) -> Result<InstallResult, StoreError> {
77 validate_plugin(&plugin)?;
78 normalize_options(&mut options);
79 if plugin_install_type(&plugin) == INSTALL_TYPE_DIRECT {
80 plugin.version = normalize_version(&plugin.version);
81 let plan = plugin.install.clone();
82 return self.install_direct(plugin, plan, options).await;
83 }
84 let release = self.fetch_latest_release(&plugin).await?;
85 let latest = release_version(&release)?;
86 plugin.version = latest.clone();
87 self.install_release(plugin, &release, &latest, options).await
88 }
89
90 pub async fn install_manifest(
92 &self,
93 manifest: &Manifest,
94 mut options: InstallOptions,
95 ) -> Result<InstallResult, StoreError> {
96 manifest.validate()?;
97 normalize_options(&mut options);
98 match manifest.install_type().as_str() {
99 INSTALL_TYPE_DIRECT => {
100 let plugin = self.direct_plugin_from_manifest(manifest).await?;
101 let plan = plugin.install.clone();
102 self.install_direct(plugin, plan, options).await
103 }
104 INSTALL_TYPE_GITHUB_RELEASE => {
105 self.install_version(manifest.plugin(), &manifest.release_tag, &manifest.version, options)
106 .await
107 }
108 _ => Err(other(format!(
109 "unsupported install type {}",
110 cpa_common::gostr::quote(&manifest.install.install_type)
111 ))),
112 }
113 }
114
115 pub async fn install_version(
117 &self,
118 mut plugin: Plugin,
119 release_tag: &str,
120 version: &str,
121 mut options: InstallOptions,
122 ) -> Result<InstallResult, StoreError> {
123 validate_plugin(&plugin)?;
124 normalize_options(&mut options);
125 let version = normalize_version(version);
126 if !valid_plugin_version(&version) {
127 return Err(other(format!(
128 "invalid plugin version {}",
129 cpa_common::gostr::quote(&version)
130 )));
131 }
132 let release_tag = match release_tag.trim() {
133 "" => version.clone(),
134 t => t.to_owned(),
135 };
136 let release = self.fetch_release_by_tag(&plugin, &release_tag).await?;
137 let resolved = release_version(&release)?;
138 if resolved != version {
139 return Err(other(format!(
140 "release tag {} resolved version {}, want {}",
141 cpa_common::gostr::quote(&release_tag),
142 cpa_common::gostr::quote(&resolved),
143 cpa_common::gostr::quote(&version)
144 )));
145 }
146 plugin.version = version.clone();
147 self.install_release(plugin, &release, &version, options).await
148 }
149
150 async fn install_release(
151 &self,
152 mut plugin: Plugin,
153 release: &Release,
154 version: &str,
155 options: InstallOptions,
156 ) -> Result<InstallResult, StoreError> {
157 let (archive, checksums) =
158 select_release_assets(release, &plugin.id, &plugin.version, &options.goos, &options.goarch)?;
159 let archive_data = self
160 .download_asset(&archive)
161 .await
162 .map_err(|e| e.context(&format!("download {}", archive.name)))?;
163 let checksum_data = self
164 .download_asset(&checksums)
165 .await
166 .map_err(|e| e.context("download checksums.txt"))?;
167 let sums = parse_checksums(&checksum_data)?;
168 verify_checksum(&archive.name, &archive_data, &sums)?;
169 plugin.version = version.to_owned();
170 let mut result = install_archive(&archive_data, &plugin, options)?;
171 result.install_type = INSTALL_TYPE_GITHUB_RELEASE.into();
172 result.release_tag = release.tag_name.trim().to_owned();
173 Ok(result)
174 }
175
176 pub async fn install_direct(
178 &self,
179 mut plugin: Plugin,
180 plan: InstallPlan,
181 mut options: InstallOptions,
182 ) -> Result<InstallResult, StoreError> {
183 plugin.id = plugin.id.trim().to_owned();
184 plugin.version = normalize_version(&plugin.version);
185 if !valid_plugin_id(&plugin.id) {
186 return Err(other(format!(
187 "invalid plugin id {}",
188 cpa_common::gostr::quote(&plugin.id)
189 )));
190 }
191 if !valid_plugin_version(&plugin.version) {
192 return Err(other(format!(
193 "invalid plugin version {}",
194 cpa_common::gostr::quote(&plugin.version)
195 )));
196 }
197 let mut plan = normalize_install_plan(&plan);
198 plan.install_type = INSTALL_TYPE_DIRECT.into();
199 validate_install_plan(&plan)?;
200 normalize_options(&mut options);
201 let artifact = select_artifact(&plan, &options.goos, &options.goarch)?;
202 let data = self
203 .download_artifact(&artifact)
204 .await
205 .map_err(|e| e.context("download artifact"))?;
206 verify_artifact_checksum(&artifact, &data)?;
207 let mut result = install_archive(&data, &plugin, options)?;
208 result.install_type = INSTALL_TYPE_DIRECT.into();
209 Ok(result)
210 }
211
212 async fn direct_plugin_from_manifest(&self, manifest: &Manifest) -> Result<Plugin, StoreError> {
215 let mut plugin = manifest.plugin();
216 plugin.version = normalize_version(&manifest.version);
217 plugin.install = normalize_install_plan(&plugin.install);
218 plugin.install.install_type = INSTALL_TYPE_DIRECT.into();
219 if !plugin.install.artifacts.is_empty() {
220 return Ok(plugin);
221 }
222 let source_url = match manifest.source_url.trim() {
223 "" => self.registry_url.trim().to_owned(),
224 u => u.to_owned(),
225 };
226 if source_url.is_empty() {
227 return Err(other("direct install manifest missing source-url"));
228 }
229 let mut source_client = self.clone();
230 source_client.registry_url = source_url;
231 let registry = source_client
232 .fetch_registry()
233 .await
234 .map_err(|e| e.context("fetch direct install source"))?;
235 let id = manifest.id.trim();
236 let resolved = registry.plugin_by_id(id).ok_or_else(|| {
237 other(format!(
238 "direct install plugin {} not found in source",
239 cpa_common::gostr::quote(id)
240 ))
241 })?;
242 let install_type = plugin_install_type(resolved);
243 if install_type != INSTALL_TYPE_DIRECT {
244 return Err(other(format!(
245 "direct install plugin {} resolved as {}",
246 cpa_common::gostr::quote(id),
247 cpa_common::gostr::quote(&install_type)
248 )));
249 }
250 Ok(direct_plugin_version(resolved.clone(), id, &manifest.version)?)
251 }
252}
253
254fn direct_plugin_version(mut plugin: Plugin, id: &str, version: &str) -> Result<Plugin, String> {
256 let version = normalize_version(version);
257 let q = cpa_common::gostr::quote;
258 if normalize_version(&plugin.version) == version {
259 plugin.version = version.clone();
260 plugin.install = normalize_install_plan(&plugin.install);
261 plugin.install.install_type = INSTALL_TYPE_DIRECT.into();
262 validate_install_plan(&plugin.install)
263 .map_err(|e| format!("direct install plugin {} version {}: {e}", q(id), q(&version)))?;
264 return Ok(plugin);
265 }
266 let candidate = plugin
267 .versions
268 .iter()
269 .find(|c| normalize_version(&c.version) == version)
270 .cloned()
271 .ok_or_else(|| {
272 format!(
273 "direct install plugin {} version {} not found in source",
274 q(id),
275 q(&version)
276 )
277 })?;
278 plugin.version = version.clone();
279 plugin.install = normalize_install_plan(&candidate.install);
280 if plugin.install.install_type.is_empty() {
281 plugin.install.install_type = INSTALL_TYPE_DIRECT.into();
282 }
283 if plugin.install.install_type != INSTALL_TYPE_DIRECT {
284 return Err(format!(
285 "direct install plugin {} version {} resolved as {}",
286 q(id),
287 q(&version),
288 q(&plugin.install.install_type)
289 ));
290 }
291 validate_install_plan(&plugin.install)
292 .map_err(|e| format!("direct install plugin {} version {}: {e}", q(id), q(&version)))?;
293 Ok(plugin)
294}
295
296pub fn select_artifact(plan: &InstallPlan, goos: &str, goarch: &str) -> Result<Artifact, String> {
298 let plan = normalize_install_plan(plan);
299 let (goos, goarch) = (normalize_goos(goos), normalize_goarch(goarch));
300 if plan.install_type != INSTALL_TYPE_DIRECT {
301 return Err(format!(
302 "install type {} is not direct",
303 cpa_common::gostr::quote(&plan.install_type)
304 ));
305 }
306 plan.artifacts
307 .into_iter()
308 .find(|a| a.goos == goos && a.goarch == goarch)
309 .ok_or_else(|| format!("artifact not found for {goos}/{goarch}"))
310}
311
312pub fn verify_artifact_checksum(artifact: &Artifact, data: &[u8]) -> Result<(), String> {
314 let expected = artifact.sha256.trim().go_lower();
315 if expected.is_empty() {
316 return Err("artifact checksum missing".into());
317 }
318 if sha256_hex(data) != expected {
319 return Err("artifact checksum mismatch".into());
320 }
321 Ok(())
322}
323
324pub fn install_archive(data: &[u8], plugin: &Plugin, options: InstallOptions) -> Result<InstallResult, StoreError> {
327 let mut options = options;
328 normalize_options(&mut options);
329 let options = &options;
330 let q = cpa_common::gostr::quote;
331 let id = plugin.id.trim();
332 if !valid_plugin_id(id) {
333 return Err(format!("invalid plugin id {}", q(&plugin.id)).into());
334 }
335 let version = normalize_version(&plugin.version);
336 if !valid_plugin_version(&version) {
337 return Err(format!("invalid plugin version {}", q(&plugin.version)).into());
338 }
339 let archive = Archive::new(data).map_err(|e| format!("open zip: {e}"))?;
340 let (library, mode) = read_target_library(&archive, id, &version, &options.goos)?;
341 let target = install_target_path(options, id, &version)?;
342 let overwritten = match std::fs::metadata(&target) {
343 Ok(_) => true,
344 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
345 Err(e) => return Err(format!("stat target plugin: {}", go_path_error("stat", &target, &e)).into()),
346 };
347 let result = |overwritten: bool, skipped: bool| InstallResult {
348 id: id.to_owned(),
349 version: version.clone(),
350 path: target.to_string_lossy().into_owned(),
351 overwritten,
352 skipped,
353 ..Default::default()
354 };
355 if overwritten {
356 let existing = std::fs::read(&target)
357 .map_err(|e| format!("read target plugin: {}", go_path_error("open", &target, &e)))?;
358 if existing == library {
359 return Ok(result(true, true));
360 }
361 if let Some(before_write) = &options.before_write {
362 before_write().map_err(|e| format!("prepare plugin write: {e}"))?;
363 }
364 if options.goos.eq_ignore_ascii_case("windows") && options.plugin_loaded.as_ref().is_some_and(|f| f()) {
366 return Err(StoreError::LoadedPluginLocked);
367 }
368 }
369 write_file_atomic(&target, &library, mode)?;
370 Ok(result(overwritten, false))
371}
372
373fn install_target_path(options: &InstallOptions, id: &str, version: &str) -> Result<PathBuf, String> {
374 let version = normalize_version(version);
375 if !valid_plugin_version(&version) {
376 return Err(format!("invalid plugin version {}", cpa_common::gostr::quote(&version)));
377 }
378 Ok(Path::new(&options.plugins_dir)
379 .join(&options.goos)
380 .join(&options.goarch)
381 .join(versioned_file_name(id, &version, &options.goos)))
382}
383
384fn read_target_library(archive: &Archive<'_>, id: &str, version: &str, goos: &str) -> Result<(Vec<u8>, u32), String> {
387 let target_name = format!("{}{}", id.trim(), extension(goos));
388 let versioned = versioned_file_name(id, version, goos);
389 let mut target = None;
390 for entry in &archive.entries {
391 let cleaned = clean_zip_name(&entry.name)?;
392 if entry.is_dir() {
393 continue;
394 }
395 if !entry.is_regular() {
396 return Err(format!("zip entry {} is not a regular file", entry.name));
397 }
398 let lower = cleaned.go_lower();
399 if !(lower.ends_with(".dylib") || lower.ends_with(".so") || lower.ends_with(".dll")) {
400 continue;
401 }
402 if cleaned != target_name && cleaned != versioned {
403 let base = cleaned.rsplit('/').next().unwrap_or_default();
404 if base == target_name || base == versioned {
405 return Err("target dynamic library must be at zip root".into());
406 }
407 return Err(format!("dynamic library filename must be {target_name} or {versioned}"));
408 }
409 if target.is_some() {
410 return Err("zip contains multiple target dynamic libraries".into());
411 }
412 target = Some(entry);
413 }
414 let entry = target.ok_or_else(|| format!("zip does not contain {target_name}"))?;
415 if entry.size() > MAX_LIBRARY_BYTES {
417 return Err(format!(
418 "{target_name} exceeds maximum allowed size of {MAX_LIBRARY_BYTES} bytes"
419 ));
420 }
421 let data = archive.read(entry).map_err(|e| match e {
422 ReadError::Open(e) => format!("open {target_name}: {e}"),
423 ReadError::Read(e) => format!("read {target_name}: {e}"),
424 })?;
425 let mode = match entry.perm() {
426 0 => 0o755,
427 m => m,
428 };
429 Ok((data, mode))
430}
431
432fn versioned_file_name(id: &str, version: &str, goos: &str) -> String {
433 format!("{}-v{}{}", id.trim(), normalize_version(version), extension(goos))
434}
435
436fn extension(goos: &str) -> &'static str {
438 match goos.trim().go_lower().as_str() {
439 "darwin" | "mac" | "macos" | "osx" => ".dylib",
440 "windows" => ".dll",
441 _ => ".so",
442 }
443}
444
445fn clean_zip_name(name: &str) -> Result<String, String> {
447 if name.trim().is_empty() {
448 return Err("zip entry has empty name".into());
449 }
450 if name.contains('\\') {
451 return Err(format!("zip entry {name} uses backslash path separators"));
452 }
453 if name.starts_with('/') {
454 return Err(format!("zip entry {name} is absolute"));
455 }
456 let cleaned = clean_path(name);
457 if cleaned == "." || cleaned == ".." || cleaned.starts_with("../") {
458 return Err(format!("zip entry {name} escapes archive root"));
459 }
460 Ok(cleaned)
461}
462
463fn clean_path(name: &str) -> String {
465 let mut out: Vec<&str> = Vec::new();
466 for segment in name.split('/') {
467 match segment {
468 "" | "." => {}
469 ".." => {
470 if out.last().is_some_and(|s| *s != "..") {
471 out.pop();
472 } else {
473 out.push("..");
474 }
475 }
476 s => out.push(s),
477 }
478 }
479 if out.is_empty() { ".".into() } else { out.join("/") }
480}
481
482fn write_file_atomic(target: &Path, data: &[u8], mode: u32) -> Result<(), String> {
484 use std::io::Write as _;
485 let dir = target.parent().unwrap_or(Path::new("."));
486 let mut builder = std::fs::DirBuilder::new();
488 builder.recursive(true);
489 #[cfg(unix)]
490 std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o755);
491 builder
492 .create(dir)
493 .map_err(|e| format!("create plugin directory: {}", go_path_error("mkdir", dir, &e)))?;
494 let base = target
495 .file_name()
496 .map(|n| n.to_string_lossy().into_owned())
497 .unwrap_or_default();
498 let (mut temp, temp_path) = create_temp(dir, &base)?;
499 let cleanup = |e: String| {
500 let _ = std::fs::remove_file(&temp_path);
501 e
502 };
503 #[cfg(unix)]
504 {
505 use std::os::unix::fs::PermissionsExt as _;
506 temp.set_permissions(std::fs::Permissions::from_mode(mode))
507 .map_err(|e| {
508 cleanup(format!(
509 "chmod temp plugin file: {}",
510 go_path_error("chmod", &temp_path, &e)
511 ))
512 })?;
513 }
514 #[cfg(not(unix))]
515 let _ = mode;
516 temp.write_all(data).map_err(|e| {
517 cleanup(format!(
518 "write temp plugin file: {}",
519 go_path_error("write", &temp_path, &e)
520 ))
521 })?;
522 temp.sync_all().map_err(|e| {
523 cleanup(format!(
524 "sync temp plugin file: {}",
525 go_path_error("sync", &temp_path, &e)
526 ))
527 })?;
528 drop(temp);
529 if let Err(e) = std::fs::rename(&temp_path, target) {
530 if cfg!(windows) {
531 if let Err(e) = std::fs::remove_file(target)
532 && e.kind() != std::io::ErrorKind::NotFound
533 {
534 return Err(cleanup(format!(
535 "remove old plugin file: {}",
536 go_path_error("remove", target, &e)
537 )));
538 }
539 return std::fs::rename(&temp_path, target).map_err(|e| {
540 cleanup(format!(
541 "install plugin file: {}",
542 go_link_error(&temp_path, target, &e)
543 ))
544 });
545 }
546 return Err(cleanup(format!(
547 "install plugin file: {}",
548 go_link_error(&temp_path, target, &e)
549 )));
550 }
551 Ok(())
552}
553
554pub(crate) fn create_temp(dir: &Path, base: &str) -> Result<(std::fs::File, PathBuf), String> {
556 use std::time::{SystemTime, UNIX_EPOCH};
557 let seed = SystemTime::now()
558 .duration_since(UNIX_EPOCH)
559 .map(|d| d.as_nanos())
560 .unwrap_or_default();
561 for attempt in 0..10_000u128 {
562 let suffix = (seed.wrapping_add(attempt * 7919) % 4_294_967_296) as u32;
563 let path = dir.join(format!(".{base}.tmp-{suffix}"));
564 let mut options = std::fs::OpenOptions::new();
565 options.write(true).create_new(true);
566 #[cfg(unix)]
567 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
568 match options.open(&path) {
569 Ok(file) => return Ok((file, path)),
570 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
571 Err(e) => {
572 return Err(format!(
573 "create temp plugin file: {}",
574 go_path_error("open", &dir.join(format!(".{base}.tmp-*")), &e)
575 ));
576 }
577 }
578 }
579 Err("create temp plugin file: too many attempts".into())
580}
581
582fn go_path_error(op: &str, path: &Path, e: &std::io::Error) -> String {
584 format!("{op} {}: {}", path.display(), errno_text(e))
585}
586
587fn go_link_error(from: &Path, to: &Path, e: &std::io::Error) -> String {
589 format!("rename {} {}: {}", from.display(), to.display(), errno_text(e))
590}
591
592fn errno_text(e: &std::io::Error) -> String {
593 let text = e.to_string();
594 let text = text.split(" (os error").next().unwrap_or_default();
595 let mut chars = text.chars();
596 chars
597 .next()
598 .map_or_else(String::new, |c| c.to_lowercase().chain(chars).collect())
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn zip_names_follow_go() {
607 assert_eq!(clean_zip_name("a/./b.so"), Ok("a/b.so".into()));
608 assert_eq!(clean_zip_name("a/../b.so"), Ok("b.so".into()));
609 assert!(clean_zip_name("../b.so").is_err());
610 assert!(clean_zip_name("a/../../b.so").is_err());
611 assert!(clean_zip_name("/b.so").is_err());
612 assert!(clean_zip_name("a\\b.so").is_err());
613 assert_eq!(versioned_file_name("p", "v1.2", "darwin"), "p-v1.2.dylib");
614 }
615
616 #[test]
619 fn library_size_is_bounded() {
620 let mut data = crate::testing::stored_zip(&[("p.so", b"lib", 0o755)]);
621 assert_eq!(
622 read_target_library(&Archive::new(&data).unwrap(), "p", "1.0.0", "linux")
623 .unwrap()
624 .0,
625 b"lib"
626 );
627 let eocd = data.len() - 22;
629 let central = u32::from_le_bytes(data[eocd + 16..eocd + 20].try_into().unwrap()) as usize;
630 let declared = (MAX_LIBRARY_BYTES + 1) as u32;
631 data[central + 24..central + 28].copy_from_slice(&declared.to_le_bytes());
632 let err = read_target_library(&Archive::new(&data).unwrap(), "p", "1.0.0", "linux").unwrap_err();
633 assert_eq!(
634 err,
635 format!("p.so exceeds maximum allowed size of {MAX_LIBRARY_BYTES} bytes")
636 );
637 }
638}