tentacli 15.2.2

Framework for building extensible network protocol clients via modular plugins.
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
use anyhow::Context;
use async_broadcast::broadcast;
use cfg_if::cfg_if;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use serde::de::DeserializeOwned;
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio::sync::mpsc::{self, Sender};
use tokio_util::sync::CancellationToken;

pub mod packet;
pub mod plugin;
pub mod prelude;
mod transport;
pub mod types;

pub use prelude::*;

inventory::collect!(PluginLoader<dyn NetworkPlugin>);
inventory::collect!(PluginLoader<dyn CorePlugin>);
inventory::collect!(PluginLoader<dyn ProcessorPlugin>);

#[macro_export]
macro_rules! register_plugin {
    ($plugin_type:ty, $trait_obj:ty) => {
        $crate::__inventory::submit! {
            $crate::client::PluginLoader::<$trait_obj> {
                load: || {
                    ::std::sync::Arc::new(<$plugin_type>::default()) as ::std::sync::Arc<$trait_obj>
                },
                name: stringify!($plugin_type),
            }
        }
    };
}

cfg_if! {
    if #[cfg(feature = "wow-wotlk")] {
        #[cfg(not(feature = "replay"))]
        use crate::plugins::wow::wotlk::login;
        #[cfg(not(feature = "replay"))]
        use crate::plugins::wow::logger::Logger;
        use crate::plugins::wow::wotlk::realm;

        // network plugins
        #[cfg(not(feature = "replay"))]
        register_plugin!(login::LoginPlugin, dyn NetworkPlugin);
        #[cfg(feature = "replay")]
        register_plugin!(OutgoingPolicy<realm::RealmPlugin, false>, dyn NetworkPlugin);

        #[cfg(not(feature = "replay"))]
        register_plugin!(realm::RealmPlugin, dyn NetworkPlugin);

        // processor plugins
        #[cfg(not(feature = "replay"))]
        register_plugin!(login::Processors, dyn ProcessorPlugin);
        register_plugin!(realm::Processors, dyn ProcessorPlugin);
        #[cfg(not(feature = "replay"))]
        register_plugin!(Logger, dyn CorePlugin);
    }
}

cfg_if! {
    if #[cfg(feature = "replay")] {
        use crate::plugins::replay::Replay;
        register_plugin!(Replay, dyn CorePlugin);
    }
}

// core plugins
cfg_if! {
    if #[cfg(feature = "tui")] {
        use crate::plugins::tui::TUIPlugin;

        register_plugin!(TUIPlugin, dyn CorePlugin);
    } else if #[cfg(feature = "dbg-ui")] {
        use crate::plugins::dbg_ui::DbgUI;

        register_plugin!(DbgUI, dyn CorePlugin);
    }
}

cfg_if! {
    if #[cfg(feature = "websocket")] {
        use crate::plugins::websocket::WebSocket;
        register_plugin!(WebSocket, dyn CorePlugin);
    }
}

register_plugin!(crate::plugins::core::Core, dyn CorePlugin);

pub struct Client;
impl Client {
    fn collect_labels() -> (Vec<ServerLabel>, Vec<ServerLabel>) {
        let network_labels: Vec<ServerLabel> = inventory::iter::<PluginLoader<dyn NetworkPlugin>>
            .into_iter()
            .map(|loader| (loader.load)().label())
            .collect();

        let processor_labels: Vec<ServerLabel> =
            inventory::iter::<PluginLoader<dyn ProcessorPlugin>>
                .into_iter()
                .map(|loader| (loader.load)().label())
                .collect();

        (network_labels, processor_labels)
    }

    fn validate_labels(
        network_labels: &[ServerLabel],
        processor_labels: &[ServerLabel],
    ) -> Result<(), ValidationError> {
        let mut network_set = HashSet::with_capacity(network_labels.len());

        // Check duplicates and build set
        for &label in network_labels {
            if !network_set.insert(label) {
                return Err(ValidationError::DuplicateNetworkLabel(label));
            }
        }

        // Check processors are wired to a network
        for &label in processor_labels {
            if !network_set.contains(&label) {
                return Err(ValidationError::MissingNetworkForProcessor(label));
            }
        }

        Ok(())
    }

    pub async fn run(context: Option<SharedContext>) -> anyhow::Result<()> {
        let context = context.unwrap_or_else(|| Arc::new(RwLock::new(CtxMap::default())));

        // Root cancellation token for the whole system
        let shutdown = CancellationToken::new();

        let mut echo_senders: HashMap<ServerLabel, Sender<Echo>> = HashMap::new();
        let (broadcast_tx, mut broadcast_rx) = broadcast::<OrderedOutput>(100);
        broadcast_rx.set_overflow(true);

        let mut tasks: Vec<Task> = vec![];

        // Collect and validate plugin labels
        let (network_labels, processor_labels) = Client::collect_labels();

        Client::validate_labels(&network_labels, &processor_labels).map_err(|err| match err {
            ValidationError::DuplicateNetworkLabel(label) => {
                anyhow::anyhow!("Duplicate NetworkPlugin label \"{}\"", label)
            }
            ValidationError::MissingNetworkForProcessor(label) => {
                anyhow::anyhow!("No NetworkPlugin was registered with label \"{}\"", label)
            }
        })?;

        // Start network plugins
        for loader in inventory::iter::<PluginLoader<dyn NetworkPlugin>> {
            let plugin: Arc<dyn NetworkPlugin> = (loader.load)();

            let (echo_tx, echo_rx) = mpsc::channel::<Echo>(100);
            let (packet_sender, packet_receiver) = mpsc::channel::<Vec<Packet>>(100);

            echo_senders.insert(plugin.label(), echo_tx.clone());

            let task = plugin.connect(
                echo_rx,
                echo_tx,
                packet_sender,
                packet_receiver,
                broadcast_tx.clone(),
                shutdown.clone(),
                context.clone(),
            );

            tasks.push(task);
        }

        let echo_senders = Arc::new(echo_senders);

        // Start core plugins
        for loader in inventory::iter::<PluginLoader<dyn CorePlugin>> {
            let plugin = (loader.load)();
            tasks.extend(plugin.get_tasks(
                broadcast_rx.clone(),
                echo_senders.clone(),
                shutdown.clone(),
                context.clone(),
            )?);
        }

        // Drive all tasks and broadcast errors
        let mut futures: FuturesUnordered<_> = tasks.into_iter().collect();

        while let Some(result) = futures.next().await {
            let err_message = match result {
                Ok(Err(err)) => Some(err.to_string()),
                Err(err) => Some(err.to_string()),
                _ => None,
            };

            if let Some(message) = err_message {
                let payload = Arc::new(vec![HandlerOutput::Messages(vec![Message {
                    msg_type: MsgType::Error,
                    text: message,
                }])]);

                for label in network_labels.iter().copied() {
                    broadcast_tx
                        .broadcast(OrderedOutput::new(label, payload.clone()))
                        .await?;
                }
            }
        }

        Ok(())
    }

    fn snapshot_plugins() -> PluginSnapshot {
        let networks = inventory::iter::<PluginLoader<dyn NetworkPlugin>>
            .into_iter()
            .map(|l| {
                let plugin = (l.load)();
                (plugin.label(), l.name)
            })
            .collect::<Vec<_>>();

        let processors = inventory::iter::<PluginLoader<dyn ProcessorPlugin>>
            .into_iter()
            .map(|l| {
                let plugin = (l.load)();
                (plugin.label(), l.name)
            })
            .collect::<Vec<_>>();

        let cores = inventory::iter::<PluginLoader<dyn CorePlugin>>
            .into_iter()
            .map(|l| l.name)
            .collect::<Vec<_>>();

        PluginSnapshot {
            networks,
            processors,
            cores,
        }
    }

    pub fn doctor() -> anyhow::Result<()> {
        println!("Tentacli Doctor\n");

        println!("[OK] Build features");
        println!("  - tui        : {}", cfg!(feature = "tui"));
        println!("  - dbg-ui     : {}", cfg!(feature = "dbg-ui"));
        println!("  - wow-wotlk  : {}", cfg!(feature = "wow-wotlk"));
        println!("  - replay     : {}", cfg!(feature = "replay"));

        let snapshot = Client::snapshot_plugins();

        println!("\n[OK] Plugins");

        println!("  - Network:");
        if snapshot.networks.is_empty() {
            println!("      <none>");
        } else {
            for (label, name) in &snapshot.networks {
                println!("      {}  ({})", label, name);
            }
        }

        println!("  - Processor:");
        if snapshot.processors.is_empty() {
            println!("      <none>");
        } else {
            for (label, name) in &snapshot.processors {
                println!("      {}  ({})", label, name);
            }
        }

        println!("  - Core:");
        if snapshot.cores.is_empty() {
            println!("      <none>");
        } else {
            for name in &snapshot.cores {
                println!("      {}", name);
            }
        }

        let network_labels: Vec<ServerLabel> = snapshot.networks.iter().map(|(l, _)| *l).collect();

        let processor_labels: Vec<ServerLabel> =
            snapshot.processors.iter().map(|(l, _)| *l).collect();

        Client::validate_labels(&network_labels, &processor_labels)
            .map_err(|e| anyhow::anyhow!("Wiring error: {:?}", e))?;

        println!("\n[OK] Wiring");
        println!("  - All processor plugins are bound to a network plugin");

        println!("\n[INFO] Config lookup order");

        if let Some(dir) = env::var_os("TENTACLI_CONFIG_DIR") {
            println!("  - TENTACLI_CONFIG_DIR = {:?}", dir);
        } else {
            println!("  - TENTACLI_CONFIG_DIR = <not set>");
        }

        if let Some(dir) = dirs_next::config_dir() {
            println!("  - OS config dir       = {:?}", dir);
        } else {
            println!("  - OS config dir       = <not available>");
        }

        if let Ok(cwd) = env::current_dir() {
            println!("  - Current dir        = {:?}", cwd);
        }

        println!("\n[OK] Doctor finished");
        Ok(())
    }
}

struct PluginSnapshot {
    networks: Vec<(ServerLabel, &'static str)>,
    processors: Vec<(ServerLabel, &'static str)>,
    cores: Vec<&'static str>,
}

#[derive(Debug, PartialEq, Eq)]
enum ValidationError {
    DuplicateNetworkLabel(ServerLabel),
    MissingNetworkForProcessor(ServerLabel),
}

pub struct ConfigParser;
impl ConfigParser {
    pub fn parse_from_file<T, P>(path: P) -> anyhow::Result<T>
    where
        T: DeserializeOwned,
        P: AsRef<Path>,
    {
        let path = Self::get_cfg_path(path.as_ref())?;
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read config at {}", path.display()))?;

        Self::parse_from_string(text)
    }

    pub fn parse_from_string<T: DeserializeOwned>(cfg_string: String) -> anyhow::Result<T> {
        toml::from_str(&cfg_string).with_context(|| "Failed to parse TOML")
    }

    fn get_cfg_path(relative_path: &Path) -> anyhow::Result<PathBuf> {
        // Looking for configs with TENTACLI_CONFIG_DIR as the config dir
        if let Some(root_dir) = env::var_os("TENTACLI_CONFIG_DIR") {
            let candidate = PathBuf::from(root_dir).join(relative_path);
            if candidate.is_file() {
                return Ok(candidate);
            }
        }

        // Check the default per-user configuration directory provided by the OS:
        //
        // - Linux / BSD:   $XDG_CONFIG_HOME or $HOME/.config
        // - Windows:       %APPDATA% (e.g. C:\Users\<User>\AppData\Roaming)
        // - macOS:         $HOME/Library/Application Support
        //
        // Append the Cargo package name to keep configs isolated per application.
        if let Some(root_dir) = dirs_next::config_dir() {
            let candidate = root_dir.join(env!("CARGO_PKG_NAME")).join(relative_path);
            if candidate.is_file() {
                return Ok(candidate);
            }
        }

        // Current working directory: ./<path>
        // This makes it convenient to run the binary in a project folder
        // and have configs resolved relative to it.
        if let Ok(cwd) = env::current_dir() {
            let candidate = cwd.join(relative_path);
            if candidate.is_file() {
                return Ok(candidate);
            }
        }

        // Development fallback: <CARGO_MANIFEST_DIR>/plugins/<path>
        // This covers `cargo run`, when configs are stored in the project root
        // under "plugins/". It uses the compile-time env var injected by Cargo.
        let candidate = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("src/plugins")
            .join(relative_path);

        if candidate.is_file() {
            return Ok(candidate);
        }

        anyhow::bail!("Config file not found for {:?}", relative_path);
    }
}

pub struct PluginLoader<T: ?Sized + 'static> {
    pub load: fn() -> Arc<T>,
    pub name: &'static str,
}

pub type SharedContext = Arc<RwLock<CtxMap>>;

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::fs;
    use tempfile::TempDir;

    struct EnvGuard {
        key: &'static str,
        old: Option<std::ffi::OsString>,
    }

    impl EnvGuard {
        fn set(key: &'static str, value: &Path) -> Self {
            let old = env::var_os(key);
            unsafe {
                env::set_var(key, value);
            }
            Self { key, old }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            unsafe {
                if let Some(ref v) = self.old {
                    env::set_var(self.key, v);
                } else {
                    env::remove_var(self.key);
                }
            }
        }
    }

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct TestConfig {
        server: ServerConfig,
    }

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct ServerConfig {
        host: String,
        port: u16,
    }

    #[test]
    fn parses_from_env_config_dir_with_sectioned_toml() {
        let temp_dir = TempDir::new().expect("failed to create temp dir");

        let config_path = temp_dir.path().join("test.toml");

        let toml = r#"
[server]
host = "localhost"
port = 8080
"#;

        fs::write(&config_path, toml).expect("failed to write test config");

        let _guard = EnvGuard::set("TENTACLI_CONFIG_DIR", temp_dir.path());

        let result: TestConfig = ConfigParser::parse_from_file("test.toml").expect("parse failed");

        assert_eq!(
            result,
            TestConfig {
                server: ServerConfig {
                    host: "localhost".into(),
                    port: 8080
                }
            }
        );
    }

    #[test]
    fn valid_configuration_passes() {
        let networks: Vec<ServerLabel> = vec!["login", "realm"];
        let processors: Vec<ServerLabel> = vec!["login", "realm"];

        let result = Client::validate_labels(&networks, &processors);

        assert!(result.is_ok());
    }

    #[test]
    fn duplicate_network_label_is_detected() {
        let networks: Vec<ServerLabel> = vec!["login", "login"];
        let processors: Vec<ServerLabel> = vec!["login"];

        let result = Client::validate_labels(&networks, &processors);

        assert_eq!(result, Err(ValidationError::DuplicateNetworkLabel("login")));
    }

    #[test]
    fn missing_network_for_processor_is_detected() {
        let networks: Vec<ServerLabel> = vec!["login"];
        let processors: Vec<ServerLabel> = vec!["realm"];

        let result = Client::validate_labels(&networks, &processors);

        assert_eq!(
            result,
            Err(ValidationError::MissingNetworkForProcessor("realm"))
        );
    }

    #[test]
    fn allows_no_processors() {
        let networks: Vec<ServerLabel> = vec!["login"];
        let processors: Vec<ServerLabel> = Vec::new();

        let result = Client::validate_labels(&networks, &processors);

        assert!(result.is_ok());
    }

    #[test]
    fn empty_networks_rejects_any_processor() {
        let networks: Vec<ServerLabel> = Vec::new();
        let processors: Vec<ServerLabel> = vec!["login"];

        let result = Client::validate_labels(&networks, &processors);

        assert_eq!(
            result,
            Err(ValidationError::MissingNetworkForProcessor("login"))
        );
    }
}