falco_plugin 0.5.1

High level bindings for the Falco plugin API
Documentation
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
use crate::plugin::error::as_result::{AsResult, WithLastError};
use crate::plugin::tables::data::{FieldTypeId, Key, Value};
use crate::plugin::tables::entry::raw::RawEntry;
use crate::plugin::tables::field::raw::RawField;
use crate::plugin::tables::traits::TableMetadata;
use crate::plugin::tables::vtable::fields::TableFields;
use crate::plugin::tables::vtable::reader::private::TableReaderImpl;
use crate::plugin::tables::vtable::reader::TableReader;
use crate::plugin::tables::vtable::writer::private::TableWriterImpl;
use crate::plugin::tables::vtable::writer::TableWriter;
use crate::plugin::tables::vtable::TablesInput;
use crate::strings::from_ptr::try_str_from_ptr_with_lifetime;
use falco_plugin_api::{
    ss_plugin_bool, ss_plugin_rc_SS_PLUGIN_SUCCESS, ss_plugin_state_data, ss_plugin_state_type,
    ss_plugin_table_entry_t, ss_plugin_table_field_t, ss_plugin_table_fieldinfo,
    ss_plugin_table_iterator_func_t, ss_plugin_table_iterator_state_t, ss_plugin_table_t,
};
use num_traits::FromPrimitive;
use std::ffi::CStr;
use std::ops::ControlFlow;

struct TemporaryTableEntry<'a> {
    tables_input: &'a TablesInput<'a>,
    table: *mut ss_plugin_table_t,
    entry: *mut ss_plugin_table_entry_t,
}

impl TemporaryTableEntry<'_> {
    fn create<'a>(
        tables_input: &'a TablesInput<'a>,
        table: *mut ss_plugin_table_t,
    ) -> Result<TemporaryTableEntry<'a>, anyhow::Error> {
        let entry = unsafe { tables_input.writer_ext.create_table_entry(table)? };
        if entry.is_null() {
            anyhow::bail!("Failed to create temporary table entry");
        }

        Ok(TemporaryTableEntry {
            tables_input,
            table,
            entry,
        })
    }
}

impl Drop for TemporaryTableEntry<'_> {
    fn drop(&mut self) {
        unsafe {
            self.tables_input
                .writer_ext
                .destroy_table_entry(self.table, self.entry);
        }
    }
}

/// # A low-level representation of a table
///
/// This is a thin wrapper around the Falco plugin API and provides little type safety.
///
/// You will probably want to use [`crate::tables::import::Table`] instead.
#[derive(Debug)]
pub struct RawTable {
    pub(crate) table: *mut ss_plugin_table_t,
}

impl RawTable {
    /// # List the available fields
    ///
    /// **Note**: this method is of limited utility in actual plugin code (you know the fields you
    /// want to access), so it returns the unmodified structure from the plugin API, including
    /// raw pointers to C-style strings. This may change later.
    pub fn list_fields(&self, fields_vtable: &TableFields) -> &[ss_plugin_table_fieldinfo] {
        let mut num_fields = 0u32;
        let fields = fields_vtable
            .list_table_fields(self.table, &mut num_fields as *mut _)
            .unwrap_or(std::ptr::null_mut());
        if fields.is_null() {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(fields, num_fields as usize) }
        }
    }

    /// # Get a table field by name
    ///
    /// The field must exist in the table and must be of the type `V`, otherwise an error
    /// will be returned.
    ///
    /// Note that you must not use fields with tables they did not come from. When using fields
    /// returned from this method, no such validation happens.
    pub fn get_field<V: Value + ?Sized>(
        &self,
        tables_input: &TablesInput,
        name: &CStr,
    ) -> Result<RawField<V>, anyhow::Error> {
        let field = tables_input.fields_ext.get_table_field(
            self.table,
            name.as_ptr().cast(),
            V::TYPE_ID as ss_plugin_state_type,
        )?;
        let raw_field = unsafe {
            field
                .as_mut()
                .ok_or_else(|| anyhow::anyhow!("Failed to get table field {:?}", name))
                .with_last_error(&tables_input.last_error)?;
            field
        };

        let assoc = unsafe { V::get_assoc_from_raw_table(self, raw_field, tables_input) }?;

        Ok(RawField {
            field: raw_field,
            assoc_data: assoc,
        })
    }

    /// # Add a table field
    ///
    /// The field will have the specified name and the type is derived from the generic argument.
    ///
    /// Note that you must not use fields with tables they did not come from. When using fields
    /// returned from this method, no such validation happens.
    pub fn add_field<V: Value<AssocData = ()> + ?Sized>(
        &self,
        tables_input: &TablesInput,
        name: &CStr,
    ) -> Result<RawField<V>, anyhow::Error> {
        let field = tables_input.fields_ext.add_table_field(
            self.table,
            name.as_ptr().cast(),
            V::TYPE_ID as ss_plugin_state_type,
        )?;
        let raw_field = unsafe {
            field
                .as_mut()
                .ok_or_else(|| anyhow::anyhow!("Failed to add table field {:?}", name))
                .with_last_error(&tables_input.last_error)?;
            field
        };

        Ok(RawField {
            field: raw_field,
            assoc_data: (),
        })
    }

    /// # Look up an entry in `table` corresponding to `key`
    pub fn get_entry<K: Key>(
        &self,
        reader_vtable: &impl TableReader,
        key: &K,
    ) -> Result<RawEntry, anyhow::Error> {
        let input = unsafe { &*(self.table as *mut falco_plugin_api::ss_plugin_table_input) };
        if input.key_type != K::TYPE_ID as ss_plugin_state_type {
            anyhow::bail!(
                "Bad key type, requested {:?}, table has {:?}",
                K::TYPE_ID,
                FieldTypeId::from_u32(input.key_type),
            );
        }

        let entry =
            unsafe { reader_vtable.get_table_entry(self.table, &key.to_data() as *const _) }?;

        if entry.is_null() {
            Err(anyhow::anyhow!("table entry not found"))
        } else {
            Ok(RawEntry {
                table: self.table,
                entry: entry as *mut _,
                destructor: reader_vtable.release_table_entry_fn(),
            })
        }
    }

    /// # Erase a table entry by key
    ///
    /// # Safety
    /// The key type must be the same as actually used by the table. Using the wrong type
    /// (especially using a number if the real key type is a string) will lead to UB.
    pub unsafe fn erase<K: Key>(
        &self,
        writer_vtable: &impl TableWriter,
        key: &K,
    ) -> Result<(), anyhow::Error> {
        unsafe {
            writer_vtable
                .erase_table_entry(self.table, &key.to_data() as *const _)?
                .as_result()?
        };
        Ok(())
    }

    /// # Create a table entry
    ///
    /// This creates an entry that's not attached to any particular key. To insert it into
    /// the table, pass it to [`RawTable::insert`]
    pub fn create_entry(
        &self,
        writer_vtable: &impl TableWriter,
    ) -> Result<RawEntry, anyhow::Error> {
        let entry = unsafe { writer_vtable.create_table_entry(self.table) }?;

        if entry.is_null() {
            Err(anyhow::anyhow!("Failed to create table entry"))
        } else {
            Ok(RawEntry {
                table: self.table,
                entry,
                destructor: writer_vtable.destroy_table_entry_fn(),
            })
        }
    }

    /// # Insert an entry into the table
    ///
    /// This attaches an entry to a table key, making it accessible to other plugins
    ///
    /// # Safety
    /// The key type must be the same as actually used by the table. Using the wrong type
    /// (especially using a number if the real key type is a string) will lead to UB.
    pub unsafe fn insert<K: Key>(
        &self,
        reader_vtable: &impl TableReader,
        writer_vtable: &impl TableWriter,
        key: &K,
        mut entry: RawEntry,
    ) -> Result<RawEntry, anyhow::Error> {
        let ret = unsafe {
            writer_vtable.add_table_entry(self.table, &key.to_data() as *const _, entry.entry)?
        };

        if ret.is_null() {
            Err(anyhow::anyhow!("Failed to attach entry"))
        } else {
            entry.destructor.take();
            Ok(RawEntry {
                table: self.table,
                entry: ret,
                destructor: reader_vtable.release_table_entry_fn(),
            })
        }
    }

    /// # Get the table name
    ///
    /// This method returns an error if the name cannot be represented as UTF-8
    pub fn get_name(&self, reader_vtable: &impl TableReader) -> anyhow::Result<&str> {
        unsafe {
            Ok(try_str_from_ptr_with_lifetime(
                reader_vtable.get_table_name(self.table)?,
                self,
            )?)
        }
    }

    /// # Get the table size
    ///
    /// Return the number of entries in the table
    pub fn get_size(&self, reader_vtable: &impl TableReader) -> anyhow::Result<usize> {
        Ok(unsafe { reader_vtable.get_table_size(self.table) }? as usize)
    }

    /// # Iterate over all entries in a table with mutable access
    ///
    /// The closure is called once for each table entry with a corresponding [`RawEntry`]
    /// object as a parameter.
    ///
    /// The iteration stops when either all entries have been processed or the closure returns
    /// [`ControlFlow::Break`].
    pub fn iter_entries_mut<F>(
        &self,
        reader_vtable: &impl TableReader,
        mut func: F,
    ) -> anyhow::Result<IterationResult>
    where
        F: FnMut(RawEntry) -> ControlFlow<()>,
    {
        Ok(iter_inner(
            self.table,
            reader_vtable.iterate_entries_fn()?,
            move |s: *mut ss_plugin_table_entry_t| {
                // Do not call the destructor on TableEntryReader: we do not have
                // our own refcount for it, just borrowing
                let raw_entry = RawEntry {
                    table: self.table,
                    entry: s,
                    destructor: None,
                };
                func(raw_entry).is_continue()
            },
        ))
    }

    /// # Clear the table
    ///
    /// Removes all entries from the table
    pub fn clear(&self, writer_vtable: &impl TableWriter) -> Result<(), anyhow::Error> {
        Ok(unsafe { writer_vtable.clear_table(self.table) }?.as_result()?)
    }

    pub(in crate::plugin::tables) unsafe fn with_subtable<K, F, R>(
        &self,
        field: *mut ss_plugin_table_field_t,
        tables_input: &TablesInput,
        func: F,
    ) -> Result<R, anyhow::Error>
    where
        K: Key,
        F: FnOnce(&RawTable) -> R,
    {
        let entry = TemporaryTableEntry::create(tables_input, self.table)?;

        let mut val = ss_plugin_state_data { u64_: 0 };
        let rc = unsafe {
            tables_input.reader_ext.read_entry_field(
                self.table,
                entry.entry,
                field,
                &mut val as *mut _,
            )?
        };

        if rc != ss_plugin_rc_SS_PLUGIN_SUCCESS {
            anyhow::bail!("Failed to get field value for temporary table entry")
        }

        let input = unsafe { val.table } as *mut falco_plugin_api::ss_plugin_table_input;
        let input = unsafe { input.as_mut() };
        let Some(input) = input else {
            anyhow::bail!("Temporary table entry has a null value for table");
        };

        if input.key_type != K::TYPE_ID as ss_plugin_state_type {
            anyhow::bail!(
                "Bad key type, requested {:?}, table has {:?}",
                K::TYPE_ID,
                FieldTypeId::from_u32(input.key_type),
            );
        }

        let raw_table = unsafe { RawTable { table: val.table } };
        let ret = func(&raw_table);
        Ok(ret)
    }

    #[doc(hidden)]
    // this is not really intended to be called by the end user, it's just for the derive macros
    pub fn get_metadata<K: Key, M: TableMetadata, V: Value + ?Sized>(
        &self,
        field: &RawField<V>,
        tables_input: &TablesInput,
    ) -> Result<M, anyhow::Error> {
        unsafe {
            self.with_subtable::<K, _, _>(field.field, tables_input, |subtable| {
                M::new(subtable, tables_input)
            })
        }?
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum IterationResult {
    Finished,
    Exited,
}

fn iter_inner<F>(
    table: *mut ss_plugin_table_t,
    iterate_entries: unsafe extern "C-unwind" fn(
        *mut ss_plugin_table_t,
        it: ss_plugin_table_iterator_func_t,
        s: *mut ss_plugin_table_iterator_state_t,
    ) -> ss_plugin_bool,
    mut func: F,
) -> IterationResult
where
    F: FnMut(*mut ss_plugin_table_entry_t) -> bool,
{
    extern "C-unwind" fn iter_wrapper<WF>(
        s: *mut ss_plugin_table_iterator_state_t,
        entry: *mut ss_plugin_table_entry_t,
    ) -> ss_plugin_bool
    where
        WF: FnMut(*mut ss_plugin_table_entry_t) -> bool,
    {
        unsafe {
            let Some(closure) = (s as *mut WF).as_mut() else {
                return 0;
            };
            let res = closure(entry);
            if res {
                1
            } else {
                0
            }
        }
    }

    let finished = unsafe {
        iterate_entries(
            table,
            Some(iter_wrapper::<F>),
            &mut func as *mut _ as *mut ss_plugin_table_iterator_state_t,
        ) != 0
    };

    match finished {
        true => IterationResult::Finished,
        false => IterationResult::Exited,
    }
}