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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//
// libsyd: Rust-based C library for SydB☮x interaction via /dev/syd
// lib/src/lib.rs: SydB☮x API C Library
//
// Copyright (c) 2023 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: LGPL-3.0-or-later

//! # libsyd - SydB☮x API Rust Library
//!
//! `libsyd` is a C library written in Rust that implements the SydB☮x
//! stat API, providing an interface to the `/dev/syd` of Sydb☮x. It
//! allows for runtime configuration and interaction with the Sydb☮x
//! sandboxing environment.
//!
//! ## Overview
//! The library is designed to interact with the Sydb☮x sandboxing
//! environment, offering functionalities to check and modify the state
//! of the sandbox lock, and perform system calls to `/dev/syd`.
//!
//! ## Attention
//! This library is a work in progress, and **the API is not stable**.
//!
//! For more detailed information and usage instructions, refer to the Sydb☮x
//! manual, available at [Sydb☮x Manual](https://git.sr.ht/~alip/syd).
//!
//! ## Author
//! Ali Polatel <alip@chesswob.org>

// We like safe, clean and simple code with documentation.
#![deny(missing_docs)]
#![deny(clippy::allow_attributes_without_reason)]
#![deny(clippy::arithmetic_side_effects)]
#![deny(clippy::as_ptr_cast_mut)]
#![deny(clippy::as_underscore)]
#![deny(clippy::assertions_on_result_states)]
#![deny(clippy::borrow_as_ptr)]
#![deny(clippy::branches_sharing_code)]
#![deny(clippy::case_sensitive_file_extension_comparisons)]
#![deny(clippy::cast_lossless)]
#![deny(clippy::cast_possible_truncation)]
#![deny(clippy::cast_possible_wrap)]
#![deny(clippy::cast_precision_loss)]
#![deny(clippy::cast_ptr_alignment)]
#![deny(clippy::cast_sign_loss)]
#![deny(clippy::checked_conversions)]
#![deny(clippy::clear_with_drain)]
#![deny(clippy::clone_on_ref_ptr)]
#![deny(clippy::cloned_instead_of_copied)]
#![deny(clippy::cognitive_complexity)]
#![deny(clippy::collection_is_never_read)]
#![deny(clippy::copy_iterator)]
#![deny(clippy::create_dir)]
#![deny(clippy::dbg_macro)]
#![deny(clippy::debug_assert_with_mut_call)]
#![deny(clippy::decimal_literal_representation)]
#![deny(clippy::default_trait_access)]
#![deny(clippy::default_union_representation)]
#![deny(clippy::derive_partial_eq_without_eq)]
#![deny(clippy::doc_link_with_quotes)]
#![deny(clippy::doc_markdown)]
#![deny(clippy::explicit_into_iter_loop)]
#![deny(clippy::explicit_iter_loop)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::missing_safety_doc)]
#![deny(clippy::undocumented_unsafe_blocks)]

use std::{
    ffi::{CStr, OsStr, OsString},
    fs::{symlink_metadata, Metadata},
    os::{
        raw::{c_char, c_int},
        unix::{
            ffi::OsStrExt,
            fs::{FileTypeExt, MetadataExt},
        },
    },
    path::{Path, PathBuf},
};

/// An enumeration of the possible states for the sandbox lock.
#[repr(u8)]
#[allow(non_camel_case_types)]
pub enum lock_state_t {
    /// The sandbox lock is off, allowing all sandbox commands.
    LOCK_OFF,
    /// The sandbox lock is set to on for all processes except the initial
    /// process (Sydb☮x exec child). This is the default state.
    LOCK_EXEC,
    /// The sandbox lock is on, disallowing all sandbox commands.
    LOCK_ON,
}

const EFAULT: i32 = 14;
const EINVAL: i32 = 22;

#[inline(always)]
fn check_stat(stat: &Metadata) -> bool {
    if !stat.file_type().is_char_device() {
        return false;
    }

    let rdev = stat.rdev();

    let major = (rdev >> 8) & 0xff;
    let minor = rdev & 0xff;

    // dev/null
    major == 1 && minor == 3
}

fn stat<P: AsRef<Path>>(path: P) -> c_int {
    match symlink_metadata(path) {
        Ok(stat) if check_stat(&stat) => 0,
        Ok(_) => -EINVAL,
        Err(error) => match error.raw_os_error() {
            Some(e) => e.checked_neg().unwrap_or(-EINVAL),
            None => -EINVAL,
        },
    }
}

fn esyd<P: AsRef<Path>>(rule: P, elem: *const c_char, op: u8) -> c_int {
    if !matches!(op, b'+' | b'-' | b'^' | b':') {
        return -EINVAL;
    }

    if elem.is_null() {
        return -EFAULT;
    }

    // SAFETY: Trust that `elem` is a null-terminated string.
    let elem = unsafe { CStr::from_ptr(elem) };
    let elem = OsStr::from_bytes(elem.to_bytes());

    // Manually concatenate the path segments
    let mut path = OsString::from("/dev/syd/");
    path.push(rule.as_ref());
    path.push(OsStr::from_bytes(&[op]));
    path.push(elem);

    // Convert the OsString to PathBuf
    let path = PathBuf::from(path);

    stat(path)
}

/// Performs a Sydb☮x API check
///
/// The caller is advised to perform this check before
/// calling any other Sydb☮x API calls.
///
/// Returns API number on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_api() -> c_int {
    match stat("/dev/syd/3") {
        0 => 3,
        n => n,
    }
}

/// Performs an lstat system call on the file "/dev/syd".
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_check() -> c_int {
    stat("/dev/syd")
}

/// Causes Sydb☮x to exit immediately with code 127
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_panic() -> c_int {
    stat("/dev/syd/panic")
}

/// Causes Sydb☮x to reset sandboxing to the default state.
/// Allowlists, denylists and filters are going to be cleared.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_reset() -> c_int {
    stat("/dev/syd/reset")
}

/// Causes Sydb☮x to read configuration from the given file descriptor.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_load(fd: c_int) -> c_int {
    let mut path = PathBuf::from("/dev/syd/load");

    let mut buf = itoa::Buffer::new();
    path.push(buf.format(fd));

    stat(path)
}

/// Sets the state of the sandbox lock.
///
/// state: The desired state of the sandbox lock.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_lock(state: lock_state_t) -> c_int {
    match state as u8 {
        0 => stat("/dev/syd/lock:off"),
        1 => stat("/dev/syd/lock:exec"),
        2 => stat("/dev/syd/lock:on"),
        _ => -EINVAL,
    }
}

/// Checks if memory sandboxing is enabled.
///
/// Returns true if memory sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_mem() -> bool {
    stat("/dev/syd/sandbox/mem?") == 0
}

/// Enable memory sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_mem() -> c_int {
    stat("/dev/syd/sandbox/mem:on")
}

/// Disable memory sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_mem() -> c_int {
    stat("/dev/syd/sandbox/mem:off")
}

/// Checks if PID sandboxing is enabled.
///
/// Returns true if PID sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_pid() -> bool {
    stat("/dev/syd/sandbox/pid?") == 0
}

/// Enable PID sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_pid() -> c_int {
    stat("/dev/syd/sandbox/pid:on")
}

/// Disable PID sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_pid() -> c_int {
    stat("/dev/syd/sandbox/pid:off")
}

/// Checks if read sandboxing is enabled.
///
/// Returns true if read sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_read() -> bool {
    stat("/dev/syd/sandbox/read?") == 0
}

/// Enable read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_read() -> c_int {
    stat("/dev/syd/sandbox/read:on")
}

/// Disable read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_read() -> c_int {
    stat("/dev/syd/sandbox/read:off")
}

/// Checks if stat sandboxing is enabled.
///
/// Returns true if stat sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_stat() -> bool {
    stat("/dev/syd/sandbox/stat?") == 0
}

/// Enable stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_stat() -> c_int {
    stat("/dev/syd/sandbox/stat:on")
}

/// Disable stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_stat() -> c_int {
    stat("/dev/syd/sandbox/stat:off")
}

/// Checks if write sandboxing is enabled.
///
/// Returns true if write sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_write() -> bool {
    stat("/dev/syd/sandbox/write?") == 0
}

/// Enable write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_write() -> c_int {
    stat("/dev/syd/sandbox/write:on")
}

/// Disable write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_write() -> c_int {
    stat("/dev/syd/sandbox/write:off")
}

/// Checks if exec sandboxing is enabled.
///
/// Returns true if exec sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_exec() -> bool {
    stat("/dev/syd/sandbox/exec?") == 0
}

/// Enable exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_exec() -> c_int {
    stat("/dev/syd/sandbox/exec:on")
}

/// Disable exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_exec() -> c_int {
    stat("/dev/syd/sandbox/exec:off")
}

/// Checks if net sandboxing is enabled.
///
/// Returns true if net sandboxing is enabled, false otherwise.
#[no_mangle]
pub extern "C" fn syd_enabled_net() -> bool {
    stat("/dev/syd/sandbox/net?") == 0
}

/// Enable net sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_enable_net() -> c_int {
    stat("/dev/syd/sandbox/net:on")
}

/// Disable net sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_disable_net() -> c_int {
    stat("/dev/syd/sandbox/net:off")
}

/// Adds to the list of glob patterns used to determine which paths
/// should be killed (prevented from executing) in the sandbox.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_kill_add(glob: *const c_char) -> c_int {
    esyd("exec/kill", glob, b'+')
}

/// Deletes the first matching item from the end of the list of glob
/// patterns used to determine which paths should be killed (prevented
/// from executing) in the sandbox.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_kill_del(glob: *const c_char) -> c_int {
    esyd("exec/kill", glob, b'-')
}

/// Removes all matching items from the list of glob patterns used to
/// determine which paths should be killed (prevented from executing) in
/// the sandbox.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_kill_rem(glob: *const c_char) -> c_int {
    esyd("exec/kill", glob, b'^')
}

/// Adds to the allowlist of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_read_add(glob: *const c_char) -> c_int {
    esyd("allowlist/read", glob, b'+')
}

/// Removes the first instance from the end of the allowlist of read
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_read_del(glob: *const c_char) -> c_int {
    esyd("allowlist/read", glob, b'-')
}

/// Removes all matching patterns from the allowlist of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_read_rem(glob: *const c_char) -> c_int {
    esyd("allowlist/read", glob, b'^')
}

/// Adds to the denylist of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_read_add(glob: *const c_char) -> c_int {
    esyd("denylist/read", glob, b'+')
}

/// Removes the first instance from the end of the denylist of read
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_read_del(glob: *const c_char) -> c_int {
    esyd("denylist/read", glob, b'-')
}

/// Removes all matching patterns from the denylist of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_read_rem(glob: *const c_char) -> c_int {
    esyd("denylist/read", glob, b'^')
}

/// Adds to the filter of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_read_add(glob: *const c_char) -> c_int {
    esyd("filter/read", glob, b'+')
}

/// Removes the first instance from the end of the filter of read
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_read_del(glob: *const c_char) -> c_int {
    esyd("filter/read", glob, b'-')
}

/// Removes all matching patterns from the filter of read sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_read_rem(glob: *const c_char) -> c_int {
    esyd("filter/read", glob, b'^')
}

/// Adds to the allowlist of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_stat_add(glob: *const c_char) -> c_int {
    esyd("allowlist/stat", glob, b'+')
}

/// Removes the first instance from the end of the allowlist of stat
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_stat_del(glob: *const c_char) -> c_int {
    esyd("allowlist/stat", glob, b'-')
}

/// Removes all matching patterns from the allowlist of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_stat_rem(glob: *const c_char) -> c_int {
    esyd("allowlist/stat", glob, b'^')
}

/// Adds to the denylist of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_stat_add(glob: *const c_char) -> c_int {
    esyd("denylist/stat", glob, b'+')
}

/// Removes the first instance from the end of the denylist of stat
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_stat_del(glob: *const c_char) -> c_int {
    esyd("denylist/stat", glob, b'-')
}

/// Removes all matching patterns from the denylist of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_stat_rem(glob: *const c_char) -> c_int {
    esyd("denylist/stat", glob, b'^')
}

/// Adds to the filter of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_stat_add(glob: *const c_char) -> c_int {
    esyd("filter/stat", glob, b'+')
}

/// Removes the first instance from the end of the filter of stat
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_stat_del(glob: *const c_char) -> c_int {
    esyd("filter/stat", glob, b'-')
}

/// Removes all matching patterns from the filter of stat sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_stat_rem(glob: *const c_char) -> c_int {
    esyd("filter/stat", glob, b'^')
}

/// Adds to the allowlist of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_write_add(glob: *const c_char) -> c_int {
    esyd("allowlist/write", glob, b'+')
}

/// Removes the first instance from the end of the allowlist of write
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_write_del(glob: *const c_char) -> c_int {
    esyd("allowlist/write", glob, b'-')
}

/// Removes all matching patterns from the allowlist of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_write_rem(glob: *const c_char) -> c_int {
    esyd("allowlist/write", glob, b'^')
}

/// Adds to the denylist of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_write_add(glob: *const c_char) -> c_int {
    esyd("denylist/write", glob, b'+')
}

/// Removes the first instance from the end of the denylist of write
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_write_del(glob: *const c_char) -> c_int {
    esyd("denylist/write", glob, b'-')
}

/// Removes all matching patterns from the denylist of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_write_rem(glob: *const c_char) -> c_int {
    esyd("denylist/write", glob, b'^')
}

/// Adds to the filter of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_write_add(glob: *const c_char) -> c_int {
    esyd("filter/write", glob, b'+')
}

/// Removes the first instance from the end of the filter of write
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_write_del(glob: *const c_char) -> c_int {
    esyd("filter/write", glob, b'-')
}

/// Removes all matching patterns from the filter of write sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_write_rem(glob: *const c_char) -> c_int {
    esyd("filter/write", glob, b'^')
}

/// Adds to the allowlist of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_exec_add(glob: *const c_char) -> c_int {
    esyd("allowlist/exec", glob, b'+')
}

/// Removes the first instance from the end of the allowlist of exec
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_exec_del(glob: *const c_char) -> c_int {
    esyd("allowlist/exec", glob, b'-')
}

/// Removes all matching patterns from the allowlist of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_exec_rem(glob: *const c_char) -> c_int {
    esyd("allowlist/exec", glob, b'^')
}

/// Adds to the denylist of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_exec_add(glob: *const c_char) -> c_int {
    esyd("denylist/exec", glob, b'+')
}

/// Removes the first instance from the end of the denylist of exec
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_exec_del(glob: *const c_char) -> c_int {
    esyd("denylist/exec", glob, b'-')
}

/// Removes all matching patterns from the denylist of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_exec_rem(glob: *const c_char) -> c_int {
    esyd("denylist/exec", glob, b'^')
}

/// Adds to the filter of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_exec_add(glob: *const c_char) -> c_int {
    esyd("filter/exec", glob, b'+')
}

/// Removes the first instance from the end of the filter of exec
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_exec_del(glob: *const c_char) -> c_int {
    esyd("filter/exec", glob, b'-')
}

/// Removes all matching patterns from the filter of exec sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_exec_rem(glob: *const c_char) -> c_int {
    esyd("filter/exec", glob, b'^')
}

/// Adds to the allowlist of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_bind_add(addr: *const c_char) -> c_int {
    esyd("allowlist/net/bind", addr, b'+')
}

/// Removes the first instance from the end of the allowlist of net/bind
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_bind_del(addr: *const c_char) -> c_int {
    esyd("allowlist/net/bind", addr, b'-')
}

/// Removes all matching patterns from the allowlist of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_bind_rem(addr: *const c_char) -> c_int {
    esyd("allowlist/net/bind", addr, b'^')
}

/// Adds to the denylist of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_bind_add(addr: *const c_char) -> c_int {
    esyd("denylist/net/bind", addr, b'+')
}

/// Removes the first instance from the end of the denylist of net/bind
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_bind_del(addr: *const c_char) -> c_int {
    esyd("denylist/net/bind", addr, b'-')
}

/// Removes all matching patterns from the denylist of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_bind_rem(addr: *const c_char) -> c_int {
    esyd("denylist/net/bind", addr, b'^')
}

/// Adds to the filter of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_bind_add(addr: *const c_char) -> c_int {
    esyd("filter/net/bind", addr, b'+')
}

/// Removes the first instance from the end of the filter of net/bind
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_bind_del(addr: *const c_char) -> c_int {
    esyd("filter/net/bind", addr, b'-')
}

/// Removes all matching patterns from the filter of net/bind sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_bind_rem(addr: *const c_char) -> c_int {
    esyd("filter/net/bind", addr, b'^')
}

/// Adds to the allowlist of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_connect_add(addr: *const c_char) -> c_int {
    esyd("allowlist/net/connect", addr, b'+')
}

/// Removes the first instance from the end of the allowlist of net/connect
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_connect_del(addr: *const c_char) -> c_int {
    esyd("allowlist/net/connect", addr, b'-')
}

/// Removes all matching patterns from the allowlist of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_allow_net_connect_rem(addr: *const c_char) -> c_int {
    esyd("allowlist/net/connect", addr, b'^')
}

/// Adds to the denylist of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_connect_add(addr: *const c_char) -> c_int {
    esyd("denylist/net/connect", addr, b'+')
}

/// Removes the first instance from the end of the denylist of net/connect
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_connect_del(addr: *const c_char) -> c_int {
    esyd("denylist/net/connect", addr, b'-')
}

/// Removes all matching patterns from the denylist of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_deny_net_connect_rem(addr: *const c_char) -> c_int {
    esyd("denylist/net/connect", addr, b'^')
}

/// Adds to the filter of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_connect_add(addr: *const c_char) -> c_int {
    esyd("filter/net/connect", addr, b'+')
}

/// Removes the first instance from the end of the filter of net/connect
/// sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_connect_del(addr: *const c_char) -> c_int {
    esyd("filter/net/connect", addr, b'-')
}

/// Removes all matching patterns from the filter of net/connect sandboxing.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_net_connect_rem(addr: *const c_char) -> c_int {
    esyd("filter/net/connect", addr, b'^')
}

/// Toggle kill of the offending process for Memory sandboxing
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_kill_mem(state: bool) -> c_int {
    if state {
        stat("/dev/syd/mem/kill:1")
    } else {
        stat("/dev/syd/mem/kill:0")
    }
}

/// Set SydB☮x maximum per-process memory usage limit for memory sandboxing.
///
/// parse-size crate is used to parse the value so formatted strings are OK.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_mem_max(size: *const c_char) -> c_int {
    esyd("mem/max", size, b':')
}

/// Set SydB☮x maximum per-process virtual memory usage limit for memory sandboxing.
///
/// parse-size crate is used to parse the value so formatted strings are OK.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_mem_vm_max(size: *const c_char) -> c_int {
    esyd("mem/vm_max", size, b':')
}

/// Set SydB☮x maximum process id limit for PID sandboxing
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_pid_max(size: usize) -> c_int {
    let mut path = OsString::from("/dev/syd/pid/max:");

    let mut buf = itoa::Buffer::new();
    let max_str = OsStr::from_bytes(buf.format(size).as_bytes());
    path.push(max_str);

    stat(path)
}

/// Toggle the reporting of access violations for memory sandboxing
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_mem(state: bool) -> c_int {
    if state {
        stat("/dev/syd/filter/mem:1")
    } else {
        stat("/dev/syd/filter/mem:0")
    }
}

/// Toggle the reporting of access violations for PID sandboxing
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_filter_pid(state: bool) -> c_int {
    if state {
        stat("/dev/syd/filter/pid:1")
    } else {
        stat("/dev/syd/filter/pid:0")
    }
}

/// Toggle kill of the offending process for PID sandboxing
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub extern "C" fn syd_kill_pid(state: bool) -> c_int {
    if state {
        stat("/dev/syd/pid/kill:1")
    } else {
        stat("/dev/syd/pid/kill:0")
    }
}

/// Execute a command outside the sandbox without sandboxing
///
/// # Safety
///
/// This function is marked `unsafe` because it dereferences raw
/// pointers, which is inherently unsafe in Rust.
///
/// The caller must ensure the following conditions are met to safely
/// use this function:
///
/// 1. The `file` pointer must point to a valid, null-terminated C-style
///    string.
///
/// 2. The `argv` pointer must point to an array of pointers, where each
///    pointer refers to a valid, null-terminated C-style string. The
///    last pointer in the array must be null, indicating the end of the
///    array.
///
/// 3. The memory pointed to by `file` and `argv` must remain valid for
///    the duration of the call.
///
/// Failing to uphold these guarantees can lead to undefined behavior,
/// including memory corruption and data races.
///
/// Returns 0 on success, negated errno on failure.
#[no_mangle]
pub unsafe extern "C" fn syd_exec(file: *const c_char, argv: *const *const c_char) -> c_int {
    if file.is_null() || argv.is_null() {
        return -EFAULT;
    }

    // SAFETY: Trust that `file` is a null-terminated string.
    let file = CStr::from_ptr(file);
    let file = OsStr::from_bytes(file.to_bytes());

    let mut path = OsString::from("/dev/syd/cmd/exec!");
    path.push(file);

    let mut idx: isize = 0;
    while !(*argv.offset(idx)).is_null() {
        // SAFETY: Trust that each `argv` element is a null-terminated string.
        let arg = CStr::from_ptr(*argv.offset(idx));
        let arg = OsStr::from_bytes(arg.to_bytes());

        path.push(OsStr::from_bytes(&[b'\x1F'])); // ASCII Unit Separator
        path.push(arg);

        idx = idx.saturating_add(1);
    }

    let path = PathBuf::from(path);
    stat(path)
}