veloren_common_state/plugin/
mod.rs1pub mod errors;
2pub mod memory_manager;
3pub mod module;
4
5use bincode::error::DecodeError;
6use common::{assets::ASSETS_PATH, event::PluginHash, uid::Uid};
7use serde::{Deserialize, Serialize};
8use std::{
9 collections::{HashMap, HashSet},
10 fs,
11 io::{Read, Write},
12 path::{Path, PathBuf},
13};
14use tracing::{error, info};
15
16use self::{
17 errors::{PluginError, PluginModuleError},
18 memory_manager::EcsWorld,
19 module::PluginModule,
20};
21
22use sha2::Digest;
23use specs::WorldExt;
24
25#[derive(Clone, Debug, Serialize, Deserialize)]
26pub struct PluginData {
27 name: String,
28 modules: HashSet<PathBuf>,
29 dependencies: HashSet<String>,
30}
31
32fn compute_hash(data: &[u8]) -> PluginHash {
33 let shasum = sha2::Sha256::digest(data);
34 let mut shasum_iter = shasum.iter();
35 let shasum: PluginHash = std::array::from_fn(|_| *shasum_iter.next().unwrap());
37 shasum
38}
39
40fn cache_file_name(
41 mut base_dir: PathBuf,
42 hash: &PluginHash,
43 create_dir: bool,
44) -> Result<PathBuf, std::io::Error> {
45 base_dir.push("server-plugins");
46 if create_dir {
47 std::fs::create_dir_all(base_dir.as_path())?;
48 }
49 let name = hex::encode(hash);
50 base_dir.push(name);
51 base_dir.set_extension("plugin.tar");
52 Ok(base_dir)
53}
54
55pub fn store_server_plugin(base_dir: &Path, data: Vec<u8>) -> Result<PathBuf, std::io::Error> {
57 let shasum = compute_hash(data.as_slice());
58 let result = cache_file_name(base_dir.to_path_buf(), &shasum, true)?;
59 let mut file = std::fs::File::create(result.as_path())?;
60 file.write_all(data.as_slice())?;
61 Ok(result)
62}
63
64pub fn find_cached(base_dir: &Path, hash: &PluginHash) -> Result<PathBuf, std::io::Error> {
65 let local_path = cache_file_name(base_dir.to_path_buf(), hash, false)?;
66 if local_path.as_path().exists() {
67 Ok(local_path)
68 } else {
69 Err(std::io::Error::from(std::io::ErrorKind::NotFound))
70 }
71}
72
73pub struct Plugin {
74 data: PluginData,
75 modules: Vec<PluginModule>,
76 hash: PluginHash,
77 path: PathBuf,
78 data_buf: Vec<u8>,
79}
80
81impl Plugin {
82 pub fn from_path(path_buf: PathBuf) -> Result<Self, PluginError> {
83 let mut reader = fs::File::open(path_buf.as_path()).map_err(PluginError::Io)?;
84 let mut buf = Vec::new();
85 reader.read_to_end(&mut buf).map_err(PluginError::Io)?;
86 let shasum = compute_hash(buf.as_slice());
87
88 let mut files = tar::Archive::new(&*buf)
89 .entries()
90 .map_err(PluginError::Io)?
91 .map(|e| {
92 e.and_then(|e| {
93 Ok((e.path()?.into_owned(), {
94 let offset = e.raw_file_position() as usize;
95 buf[offset..offset + e.size() as usize].to_vec()
96 }))
97 })
98 })
99 .collect::<Result<HashMap<_, _>, _>>()
100 .map_err(PluginError::Io)?;
101
102 let data = toml::de::from_str::<PluginData>(
103 std::str::from_utf8(
104 files
105 .get(Path::new("plugin.toml"))
106 .ok_or(PluginError::NoConfig)?,
107 )
108 .map_err(|inner| PluginError::Encoding(Box::new(DecodeError::Utf8 { inner })))?,
109 )
110 .map_err(PluginError::Toml)?;
111
112 let modules = data
113 .modules
114 .iter()
115 .map(|path| {
116 let wasm_data = files.remove(path).ok_or(PluginError::NoSuchModule)?;
117 PluginModule::new(data.name.to_owned(), &wasm_data).map_err(|e| {
118 PluginError::PluginModuleError(data.name.to_owned(), "<init>".to_owned(), e)
119 })
120 })
121 .collect::<Result<_, _>>()?;
122
123 let data_buf = fs::read(&path_buf).map_err(PluginError::Io)?;
124
125 Ok(Plugin {
126 data,
127 modules,
128 hash: shasum,
129 path: path_buf,
130 data_buf,
131 })
132 }
133
134 pub fn load_event(
135 &mut self,
136 ecs: &EcsWorld,
137 mode: common::resources::GameMode,
138 ) -> Result<(), PluginModuleError> {
139 self.modules
140 .iter_mut()
141 .try_for_each(|module| module.load_event(ecs, mode))
142 }
143
144 pub fn command_event(
145 &mut self,
146 ecs: &EcsWorld,
147 name: &str,
148 args: &[String],
149 player: common::uid::Uid,
150 ) -> Result<Vec<String>, CommandResults> {
151 let mut result = Err(CommandResults::UnknownCommand);
152 self.modules.iter_mut().for_each(|module| {
153 match module.command_event(ecs, name, args, player) {
154 Ok(res) => result = Ok(res),
155 Err(CommandResults::UnknownCommand) => (),
156 Err(err) => {
157 if result.is_err() {
158 result = Err(err)
159 }
160 },
161 }
162 });
163 result
164 }
165
166 pub fn path(&self) -> &Path { self.path.as_path() }
168
169 pub fn data_buf(&self) -> &[u8] { &self.data_buf }
171
172 pub fn skeleton(
174 &mut self,
175 species: &str,
176 dep: &module::Dependency,
177 time: f32,
178 ) -> Option<module::Skeleton> {
179 self.modules
180 .iter_mut()
181 .find_map(|module| module.skeleton(species, dep, time))
182 }
183}
184
185#[derive(Default)]
186pub struct PluginMgr {
187 plugins: Vec<Plugin>,
188}
189
190impl PluginMgr {
191 pub fn from_asset_or_default() -> Self {
192 let mut path = (*ASSETS_PATH).clone();
193 path.push("plugins");
194 info!("Searching {:?} for plugins...", path);
195
196 match Self::from_dir(&path) {
197 Ok(plugin_mgr) => {
198 info!("{} plugin(s) loaded", plugin_mgr.plugins.len());
199 plugin_mgr
200 },
201 Err(e) => {
202 if let PluginError::FromDirDoesNotExist = e {
203 info!("{:?} does not exist, no plugins loaded", path);
204 } else {
205 error!(?e, "Failed to read plugins from assets");
206 };
207 PluginMgr::default()
208 },
209 }
210 }
211
212 fn from_dir(path: &Path) -> Result<Self, PluginError> {
213 let plugins = fs::read_dir(path)
214 .map_err(|e| {
215 if e.kind() == std::io::ErrorKind::NotFound {
216 PluginError::FromDirDoesNotExist
217 } else {
218 PluginError::Io(e)
219 }
220 })?
221 .filter_map(|e| e.ok())
222 .map(|entry| {
223 if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
224 && entry
225 .path()
226 .file_name()
227 .and_then(|n| n.to_str())
228 .map(|s| s.ends_with(".plugin.tar"))
229 .unwrap_or(false)
230 {
231 info!("Loading plugin at {:?}", entry.path());
232 Plugin::from_path(entry.path()).map(|plugin| {
233 if let Err(e) = common::assets::register_tar(entry.path()) {
234 error!("Plugin {:?} tar error {e:?}", entry.path());
235 }
236 Some(plugin)
237 })
238 } else {
239 Ok(None)
240 }
241 })
242 .filter_map(Result::transpose)
243 .inspect(|p| {
244 let _ = p.as_ref().map_err(|e| error!(?e, "Failed to load plugin"));
245 })
246 .collect::<Result<Vec<_>, _>>()?;
247
248 for plugin in &plugins {
249 info!(
250 "Loaded plugin '{}' with {} module(s)",
251 plugin.data.name,
252 plugin.modules.len()
253 );
254 }
255
256 Ok(Self { plugins })
257 }
258
259 pub fn load_server_plugin(
261 &mut self,
262 path: PathBuf,
263 ecs: &specs::World,
264 ) -> Result<PluginHash, PluginError> {
265 Plugin::from_path(path.clone()).map(|mut plugin| {
266 if let Err(e) = common::assets::register_tar(path.clone()) {
267 error!("Plugin {:?} tar error {e:?}", path.as_path());
268 }
269 let ecs_world = EcsWorld {
272 entities: &ecs.entities(),
273 health: ecs.read_component().into(),
274 uid: ecs.read_component().into(),
275 id_maps: &ecs.read_resource::<common::uid::IdMaps>().into(),
276 player: ecs.read_component().into(),
277 };
278 let mode = *ecs.read_resource::<common::resources::GameMode>();
279 if let Err(e) = plugin.load_event(&ecs_world, mode) {
280 error!(?e, "Failed to run server plugin init");
281 }
282 let hash = plugin.hash;
283 self.plugins.push(plugin);
284 hash
285 })
286 }
287
288 pub fn cache_server_plugin(
289 &mut self,
290 base_dir: &Path,
291 data: Vec<u8>,
292 ecs: &specs::World,
293 ) -> Result<PluginHash, PluginError> {
294 let path = store_server_plugin(base_dir, data).map_err(PluginError::Io)?;
295 self.load_server_plugin(path, ecs)
296 }
297
298 pub fn plugin_list(&self) -> Vec<PluginHash> {
300 self.plugins.iter().map(|plugin| plugin.hash).collect()
301 }
302
303 pub fn find(&self, hash: &PluginHash) -> Option<&Plugin> {
305 self.plugins.iter().find(|plugin| &plugin.hash == hash)
306 }
307
308 pub fn load_event(
309 &mut self,
310 ecs: &EcsWorld,
311 mode: common::resources::GameMode,
312 ) -> Result<(), PluginModuleError> {
313 self.plugins
314 .iter_mut()
315 .try_for_each(|plugin| plugin.load_event(ecs, mode))
316 }
317
318 pub fn command_event(
319 &mut self,
320 ecs: &EcsWorld,
321 name: &str,
322 args: &[String],
323 player: Uid,
324 ) -> Result<Vec<String>, CommandResults> {
325 let mut result = Err(CommandResults::UnknownCommand);
327 self.plugins.iter_mut().for_each(|plugin| {
328 match plugin.command_event(ecs, name, args, player) {
329 Ok(val) => result = Ok(val),
330 Err(CommandResults::UnknownCommand) => (),
331 Err(err) => {
332 if result.is_err() {
333 result = Err(err);
334 }
335 },
336 }
337 });
338 result
339 }
340
341 pub fn skeleton(
342 &mut self,
343 species: &str,
344 dep: &module::Dependency,
345 time: f32,
346 ) -> Option<module::Skeleton> {
347 self.plugins
348 .iter_mut()
349 .find_map(|plugin| plugin.skeleton(species, dep, time))
350 }
351}
352
353pub enum CommandResults {
355 UnknownCommand,
356 HostError(wasmtime::Error),
357 PluginError(String),
358}