lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! NFS export management.
//!
//! This module handles the configuration and management of NFS exports,
//! including access control, security settings, and client tracking.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use lazy_static::lazy_static;
use spin::Mutex;

use super::error::{NfsError, NfsResult, NfsStatus};
use super::types::{ClientId, FileHandle, SessionId};

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORT CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Export options for an NFS share.
#[derive(Debug, Clone)]
pub struct ExportOptions {
    /// Read-only export.
    pub read_only: bool,
    /// Allow root access (no_root_squash).
    pub no_root_squash: bool,
    /// All users treated as anonymous.
    pub all_squash: bool,
    /// Anonymous UID.
    pub anon_uid: u32,
    /// Anonymous GID.
    pub anon_gid: u32,
    /// Sync writes immediately.
    pub sync: bool,
    /// Allow subtree checking.
    pub subtree_check: bool,
    /// Security flavors allowed.
    pub security: Vec<SecurityFlavor>,
    /// Maximum allowed clients (0 = unlimited).
    pub max_clients: usize,
}

impl Default for ExportOptions {
    fn default() -> Self {
        Self {
            read_only: false,
            no_root_squash: false,
            all_squash: false,
            anon_uid: 65534, // nobody
            anon_gid: 65534, // nogroup
            sync: true,
            subtree_check: false,
            security: vec![SecurityFlavor::Sys],
            max_clients: 0,
        }
    }
}

impl ExportOptions {
    /// Create read-only export options.
    pub fn read_only() -> Self {
        Self {
            read_only: true,
            ..Self::default()
        }
    }

    /// Create read-write export options.
    pub fn read_write() -> Self {
        Self::default()
    }

    /// Allow root access.
    pub fn with_no_root_squash(mut self) -> Self {
        self.no_root_squash = true;
        self
    }

    /// Set security flavors.
    pub fn with_security(mut self, flavors: Vec<SecurityFlavor>) -> Self {
        self.security = flavors;
        self
    }

    /// Set async mode.
    pub fn with_async(mut self) -> Self {
        self.sync = false;
        self
    }
}

/// Security flavors for NFS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum SecurityFlavor {
    /// No authentication (AUTH_NONE).
    None = 0,
    /// Unix authentication (AUTH_SYS).
    Sys = 1,
    /// Kerberos 5.
    Krb5 = 390003,
    /// Kerberos 5 with integrity.
    Krb5i = 390004,
    /// Kerberos 5 with privacy.
    Krb5p = 390005,
}

impl SecurityFlavor {
    /// Convert from raw u32.
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            0 => Some(Self::None),
            1 => Some(Self::Sys),
            390003 => Some(Self::Krb5),
            390004 => Some(Self::Krb5i),
            390005 => Some(Self::Krb5p),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CLIENT ACCESS RULES
// ═══════════════════════════════════════════════════════════════════════════════

/// Access rule for a client.
#[derive(Debug, Clone)]
pub struct AccessRule {
    /// Client specification (IP, hostname, or wildcard).
    pub client: ClientSpec,
    /// Options for this client.
    pub options: ExportOptions,
}

/// Client specification.
#[derive(Debug, Clone)]
pub enum ClientSpec {
    /// Single IP address.
    Ip([u8; 4]),
    /// IP network with mask.
    Network {
        /// IP address.
        ip: [u8; 4],
        /// Network mask.
        mask: [u8; 4],
    },
    /// Hostname.
    Host(String),
    /// Wildcard (all clients).
    All,
}

impl ClientSpec {
    /// Parse from string (e.g., "192.168.1.0/24", "*.example.com", "*").
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();

        if s == "*" {
            return Some(Self::All);
        }

        // Check for CIDR notation
        if let Some((ip_str, mask_str)) = s.split_once('/') {
            let ip = Self::parse_ip(ip_str)?;
            let prefix_len: u8 = mask_str.parse().ok()?;
            if prefix_len > 32 {
                return None;
            }
            let mask = Self::prefix_to_mask(prefix_len);
            return Some(Self::Network { ip, mask });
        }

        // Try as IP address
        if let Some(ip) = Self::parse_ip(s) {
            return Some(Self::Ip(ip));
        }

        // Treat as hostname
        Some(Self::Host(s.into()))
    }

    /// Parse IP address.
    fn parse_ip(s: &str) -> Option<[u8; 4]> {
        let parts: Vec<_> = s.split('.').collect();
        if parts.len() != 4 {
            return None;
        }

        let mut ip = [0u8; 4];
        for (i, part) in parts.iter().enumerate() {
            ip[i] = part.parse().ok()?;
        }
        Some(ip)
    }

    /// Convert prefix length to mask.
    fn prefix_to_mask(prefix: u8) -> [u8; 4] {
        if prefix == 0 {
            return [0, 0, 0, 0];
        }
        let mask_u32 = !((1u32 << (32 - prefix)) - 1);
        mask_u32.to_be_bytes()
    }

    /// Check if a client IP matches this specification.
    pub fn matches(&self, client_ip: [u8; 4]) -> bool {
        match self {
            Self::All => true,
            Self::Ip(ip) => client_ip == *ip,
            Self::Network { ip, mask } => {
                for i in 0..4 {
                    if (client_ip[i] & mask[i]) != (ip[i] & mask[i]) {
                        return false;
                    }
                }
                true
            }
            Self::Host(_) => {
                // Would need DNS resolution
                false
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORT ENTRY
// ═══════════════════════════════════════════════════════════════════════════════

/// An NFS export entry.
#[derive(Debug, Clone)]
pub struct Export {
    /// Unique export ID.
    pub id: u64,
    /// Dataset being exported.
    pub dataset: String,
    /// Path within the dataset (empty = root).
    pub path: String,
    /// Access rules (first match wins).
    pub access_rules: Vec<AccessRule>,
    /// Default options if no rule matches.
    pub default_options: Option<ExportOptions>,
    /// Whether export is active.
    pub active: bool,
}

impl Export {
    /// Create a new export.
    pub fn new(dataset: impl Into<String>, path: impl Into<String>) -> Self {
        static NEXT_ID: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(1);

        Self {
            id: NEXT_ID.fetch_add(1, core::sync::atomic::Ordering::SeqCst),
            dataset: dataset.into(),
            path: path.into(),
            access_rules: Vec::new(),
            default_options: Some(ExportOptions::read_only()),
            active: true,
        }
    }

    /// Add an access rule.
    pub fn with_rule(mut self, client: ClientSpec, options: ExportOptions) -> Self {
        self.access_rules.push(AccessRule { client, options });
        self
    }

    /// Set default options.
    pub fn with_default(mut self, options: ExportOptions) -> Self {
        self.default_options = Some(options);
        self
    }

    /// Allow all clients.
    pub fn allow_all(mut self, options: ExportOptions) -> Self {
        self.access_rules.push(AccessRule {
            client: ClientSpec::All,
            options,
        });
        self
    }

    /// Get the root file handle for this export.
    pub fn root_handle(&self) -> FileHandle {
        FileHandle::new(self.id, 0, 0)
    }

    /// Check if client can access this export.
    pub fn check_access(&self, client_ip: [u8; 4]) -> Option<&ExportOptions> {
        // Check access rules in order
        for rule in &self.access_rules {
            if rule.client.matches(client_ip) {
                return Some(&rule.options);
            }
        }

        // Return default options if no rule matched
        self.default_options.as_ref()
    }

    /// Get the export path.
    pub fn export_path(&self) -> String {
        if self.path.is_empty() {
            alloc::format!("/{}", self.dataset)
        } else {
            alloc::format!("/{}{}", self.dataset, self.path)
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORT REGISTRY
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global export registry.
    static ref EXPORTS: Mutex<ExportRegistry> = Mutex::new(ExportRegistry::new());
}

/// Registry of NFS exports.
#[derive(Debug)]
struct ExportRegistry {
    /// Exports by ID.
    exports: BTreeMap<u64, Export>,
    /// Index by dataset name.
    by_dataset: BTreeMap<String, Vec<u64>>,
}

impl ExportRegistry {
    /// Create a new registry.
    fn new() -> Self {
        Self {
            exports: BTreeMap::new(),
            by_dataset: BTreeMap::new(),
        }
    }
}

/// Add an export.
pub fn add_export(export: Export) -> u64 {
    let mut reg = EXPORTS.lock();
    let id = export.id;
    let dataset = export.dataset.clone();

    reg.exports.insert(id, export);
    reg.by_dataset.entry(dataset).or_default().push(id);

    id
}

/// Remove an export.
pub fn remove_export(id: u64) -> Option<Export> {
    let mut reg = EXPORTS.lock();

    if let Some(export) = reg.exports.remove(&id) {
        if let Some(ids) = reg.by_dataset.get_mut(&export.dataset) {
            ids.retain(|&x| x != id);
        }
        Some(export)
    } else {
        None
    }
}

/// Get an export by ID.
pub fn get_export(id: u64) -> Option<Export> {
    EXPORTS.lock().exports.get(&id).cloned()
}

/// Get exports for a dataset.
pub fn get_exports_for_dataset(dataset: &str) -> Vec<Export> {
    let reg = EXPORTS.lock();
    reg.by_dataset
        .get(dataset)
        .map(|ids| {
            ids.iter()
                .filter_map(|id| reg.exports.get(id).cloned())
                .collect()
        })
        .unwrap_or_default()
}

/// List all exports.
pub fn list_exports() -> Vec<Export> {
    EXPORTS.lock().exports.values().cloned().collect()
}

/// Get export count.
pub fn export_count() -> usize {
    EXPORTS.lock().exports.len()
}

/// Find export by file handle.
pub fn find_export_by_handle(fh: &FileHandle) -> Option<Export> {
    get_export(fh.dataset_id())
}

/// Clear all exports.
pub fn clear_exports() {
    let mut reg = EXPORTS.lock();
    reg.exports.clear();
    reg.by_dataset.clear();
}

// ═══════════════════════════════════════════════════════════════════════════════
// CLIENT STATE MANAGEMENT
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global client registry.
    static ref CLIENTS: Mutex<ClientRegistry> = Mutex::new(ClientRegistry::new());
}

/// NFSv4 client state.
#[derive(Debug, Clone)]
pub struct ClientState {
    /// Client ID.
    pub id: ClientId,
    /// Client verifier.
    pub verifier: [u8; 8],
    /// Client owner identifier.
    pub owner_id: Vec<u8>,
    /// Client address.
    pub address: [u8; 4],
    /// Lease expiration time.
    pub lease_expires: u64,
    /// Sessions (NFSv4.1).
    pub sessions: Vec<SessionId>,
    /// Is confirmed.
    pub confirmed: bool,
    /// Creation timestamp.
    pub created_at: u64,
    /// Last activity timestamp.
    pub last_activity: u64,
}

impl ClientState {
    /// Create a new client state.
    pub fn new(owner_id: Vec<u8>, verifier: [u8; 8], address: [u8; 4]) -> Self {
        Self {
            id: ClientId::generate(),
            verifier,
            owner_id,
            address,
            lease_expires: 0,
            sessions: Vec::new(),
            confirmed: false,
            created_at: 0,
            last_activity: 0,
        }
    }

    /// Check if lease has expired.
    pub fn is_lease_expired(&self, now: u64) -> bool {
        now > self.lease_expires
    }

    /// Renew the lease.
    pub fn renew_lease(&mut self, duration: u64, now: u64) {
        self.lease_expires = now + duration;
        self.last_activity = now;
    }
}

/// Registry of NFS clients.
#[derive(Debug)]
struct ClientRegistry {
    /// Clients by ID.
    clients: BTreeMap<u64, ClientState>,
    /// Index by owner ID.
    by_owner: BTreeMap<Vec<u8>, u64>,
    /// Default lease duration (seconds).
    lease_duration: u64,
}

impl ClientRegistry {
    /// Create a new registry.
    fn new() -> Self {
        Self {
            clients: BTreeMap::new(),
            by_owner: BTreeMap::new(),
            lease_duration: 90, // 90 seconds default
        }
    }
}

/// Register a new client.
pub fn register_client(state: ClientState) -> ClientId {
    let mut reg = CLIENTS.lock();
    let id = state.id;
    let owner_id = state.owner_id.clone();

    reg.clients.insert(id.id, state);
    reg.by_owner.insert(owner_id, id.id);

    id
}

/// Get client state.
pub fn get_client(id: ClientId) -> Option<ClientState> {
    CLIENTS.lock().clients.get(&id.id).cloned()
}

/// Find client by owner ID.
pub fn find_client_by_owner(owner_id: &[u8]) -> Option<ClientState> {
    let reg = CLIENTS.lock();
    reg.by_owner
        .get(owner_id)
        .and_then(|id| reg.clients.get(id).cloned())
}

/// Confirm a client.
pub fn confirm_client(id: ClientId) -> NfsResult<()> {
    let mut reg = CLIENTS.lock();

    if let Some(client) = reg.clients.get_mut(&id.id) {
        client.confirmed = true;
        Ok(())
    } else {
        Err(NfsError::new(NfsStatus::Stale))
    }
}

/// Renew client lease.
pub fn renew_client_lease(id: ClientId, now: u64) -> NfsResult<()> {
    let mut reg = CLIENTS.lock();
    let duration = reg.lease_duration;

    if let Some(client) = reg.clients.get_mut(&id.id) {
        client.renew_lease(duration, now);
        Ok(())
    } else {
        Err(NfsError::new(NfsStatus::Stale))
    }
}

/// Remove expired clients.
pub fn cleanup_expired_clients(now: u64) -> Vec<ClientId> {
    let mut reg = CLIENTS.lock();
    let expired: Vec<_> = reg
        .clients
        .iter()
        .filter(|(_, c)| c.is_lease_expired(now))
        .map(|(id, c)| (*id, c.owner_id.clone()))
        .collect();

    for (id, owner_id) in &expired {
        reg.clients.remove(id);
        reg.by_owner.remove(owner_id);
    }

    expired
        .into_iter()
        .map(|(id, _)| ClientId::new(id))
        .collect()
}

/// Get client count.
pub fn client_count() -> usize {
    CLIENTS.lock().clients.len()
}

/// Set lease duration.
pub fn set_lease_duration(seconds: u64) {
    CLIENTS.lock().lease_duration = seconds;
}

/// Get lease duration.
pub fn get_lease_duration() -> u64 {
    CLIENTS.lock().lease_duration
}

/// Clear all clients.
pub fn clear_clients() {
    let mut reg = CLIENTS.lock();
    reg.clients.clear();
    reg.by_owner.clear();
}

// ═══════════════════════════════════════════════════════════════════════════════
// SESSION MANAGEMENT (NFSv4.1)
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global session registry.
    static ref SESSIONS: Mutex<SessionRegistry> = Mutex::new(SessionRegistry::new());
}

/// NFSv4.1 session state.
#[derive(Debug, Clone)]
pub struct SessionState {
    /// Session ID.
    pub id: SessionId,
    /// Associated client ID.
    pub client_id: ClientId,
    /// Sequence ID.
    pub sequence_id: u32,
    /// Fore channel slots.
    pub fore_slots: u32,
    /// Back channel slots.
    pub back_slots: u32,
    /// Creation timestamp.
    pub created_at: u64,
    /// Is active.
    pub active: bool,
}

impl SessionState {
    /// Create a new session.
    pub fn new(client_id: ClientId) -> Self {
        Self {
            id: SessionId::generate(),
            client_id,
            sequence_id: 1,
            fore_slots: 16,
            back_slots: 4,
            created_at: 0,
            active: true,
        }
    }
}

/// Registry of NFS sessions.
#[derive(Debug)]
struct SessionRegistry {
    /// Sessions by ID.
    sessions: BTreeMap<[u8; 16], SessionState>,
    /// Index by client ID.
    by_client: BTreeMap<u64, Vec<[u8; 16]>>,
}

impl SessionRegistry {
    /// Create a new registry.
    fn new() -> Self {
        Self {
            sessions: BTreeMap::new(),
            by_client: BTreeMap::new(),
        }
    }
}

/// Create a session.
pub fn create_session(client_id: ClientId) -> SessionState {
    let mut reg = SESSIONS.lock();
    let session = SessionState::new(client_id);
    let session_id = session.id.id;

    reg.sessions.insert(session_id, session.clone());
    reg.by_client
        .entry(client_id.id)
        .or_default()
        .push(session_id);

    session
}

/// Get session.
pub fn get_session(id: SessionId) -> Option<SessionState> {
    SESSIONS.lock().sessions.get(&id.id).cloned()
}

/// Get sessions for a client.
pub fn get_client_sessions(client_id: ClientId) -> Vec<SessionState> {
    let reg = SESSIONS.lock();
    reg.by_client
        .get(&client_id.id)
        .map(|ids| {
            ids.iter()
                .filter_map(|id| reg.sessions.get(id).cloned())
                .collect()
        })
        .unwrap_or_default()
}

/// Destroy a session.
pub fn destroy_session(id: SessionId) -> Option<SessionState> {
    let mut reg = SESSIONS.lock();

    if let Some(session) = reg.sessions.remove(&id.id) {
        if let Some(ids) = reg.by_client.get_mut(&session.client_id.id) {
            ids.retain(|sid| sid != &id.id);
        }
        Some(session)
    } else {
        None
    }
}

/// Get session count.
pub fn session_count() -> usize {
    SESSIONS.lock().sessions.len()
}

/// Clear all sessions.
pub fn clear_sessions() {
    let mut reg = SESSIONS.lock();
    reg.sessions.clear();
    reg.by_client.clear();
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    fn setup() {
        clear_exports();
        clear_clients();
        clear_sessions();
    }

    #[test]
    fn test_export_options_default() {
        let opts = ExportOptions::default();
        assert!(!opts.read_only);
        assert!(!opts.no_root_squash);
        assert!(opts.sync);
    }

    #[test]
    fn test_export_options_builder() {
        let opts = ExportOptions::read_only()
            .with_no_root_squash()
            .with_async();
        assert!(opts.read_only);
        assert!(opts.no_root_squash);
        assert!(!opts.sync);
    }

    #[test]
    fn test_client_spec_parse() {
        let all = ClientSpec::parse("*").unwrap();
        assert!(matches!(all, ClientSpec::All));

        let ip = ClientSpec::parse("192.168.1.1").unwrap();
        assert!(matches!(ip, ClientSpec::Ip([192, 168, 1, 1])));

        let net = ClientSpec::parse("10.0.0.0/8").unwrap();
        assert!(matches!(
            net,
            ClientSpec::Network {
                ip: [10, 0, 0, 0],
                ..
            }
        ));

        let host = ClientSpec::parse("server.example.com").unwrap();
        assert!(matches!(host, ClientSpec::Host(_)));
    }

    #[test]
    fn test_client_spec_matches() {
        let all = ClientSpec::All;
        assert!(all.matches([1, 2, 3, 4]));

        let ip = ClientSpec::Ip([192, 168, 1, 1]);
        assert!(ip.matches([192, 168, 1, 1]));
        assert!(!ip.matches([192, 168, 1, 2]));

        let net = ClientSpec::Network {
            ip: [192, 168, 1, 0],
            mask: [255, 255, 255, 0],
        };
        assert!(net.matches([192, 168, 1, 100]));
        assert!(!net.matches([192, 168, 2, 1]));
    }

    #[test]
    fn test_export_creation() {
        let export = Export::new("tank/data", "/shared").allow_all(ExportOptions::read_write());

        assert_eq!(export.dataset, "tank/data");
        assert_eq!(export.path, "/shared");
        assert_eq!(export.access_rules.len(), 1);
    }

    #[test]
    fn test_export_check_access() {
        let export = Export::new("tank", "")
            .with_rule(
                ClientSpec::Ip([192, 168, 1, 100]),
                ExportOptions::read_write(),
            )
            .with_default(ExportOptions::read_only());

        // Specific client gets read-write
        let opts = export.check_access([192, 168, 1, 100]).unwrap();
        assert!(!opts.read_only);

        // Other clients get read-only
        let opts = export.check_access([192, 168, 1, 200]).unwrap();
        assert!(opts.read_only);
    }

    #[test]
    fn test_export_registry() {
        setup();

        let export = Export::new("pool/test", "");
        let id = add_export(export);

        assert!(get_export(id).is_some());
        assert_eq!(export_count(), 1);

        let exports = get_exports_for_dataset("pool/test");
        assert_eq!(exports.len(), 1);

        remove_export(id);
        assert!(get_export(id).is_none());
    }

    #[test]
    fn test_client_registration() {
        setup();

        let state = ClientState::new(b"test-client".to_vec(), [1; 8], [127, 0, 0, 1]);
        let id = register_client(state);

        let client = get_client(id).unwrap();
        assert_eq!(client.owner_id, b"test-client");

        let found = find_client_by_owner(b"test-client").unwrap();
        assert_eq!(found.id, id);
    }

    #[test]
    fn test_client_lease() {
        setup();

        let mut state = ClientState::new(b"lease-test".to_vec(), [2; 8], [127, 0, 0, 1]);
        state.lease_expires = 100;

        assert!(!state.is_lease_expired(50));
        assert!(state.is_lease_expired(150));

        state.renew_lease(60, 100);
        assert_eq!(state.lease_expires, 160);
    }

    #[test]
    fn test_session_creation() {
        setup();

        let client_id = ClientId::generate();
        let session = create_session(client_id);

        assert_eq!(session.client_id, client_id);
        assert!(session.active);

        let retrieved = get_session(session.id).unwrap();
        assert_eq!(retrieved.id, session.id);

        let sessions = get_client_sessions(client_id);
        assert_eq!(sessions.len(), 1);

        destroy_session(session.id);
        assert!(get_session(session.id).is_none());
    }

    #[test]
    fn test_security_flavor() {
        assert_eq!(SecurityFlavor::from_u32(0), Some(SecurityFlavor::None));
        assert_eq!(SecurityFlavor::from_u32(1), Some(SecurityFlavor::Sys));
        assert_eq!(SecurityFlavor::from_u32(390003), Some(SecurityFlavor::Krb5));
    }

    #[test]
    fn test_export_path() {
        let e1 = Export::new("tank", "");
        assert_eq!(e1.export_path(), "/tank");

        let e2 = Export::new("tank/data", "/shared");
        assert_eq!(e2.export_path(), "/tank/data/shared");
    }
}