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
//! Module for everything relevant to plugins
//!
//! Usage:
//!
//! ```
//! use mariadb::plugin::*;
//! use mariadb::plugin::encryption::*;
//! use mariadb::plugin::SysVarConstString;
//!
//! static SYSVAR_STR: SysVarConstString = SysVarConstString::new();
//!
//!
//! // May be empty or not
//! struct ExampleKeyManager;
//!
//! impl KeyManager for ExampleKeyManager {
//!     // ...
//!     # fn get_latest_key_version(key_id: u32) -> Result<u32, KeyError> { todo!() }
//!     # fn get_key(key_id: u32, key_version: u32, dst: &mut [u8]) -> Result<(), KeyError> { todo!() }
//!     # fn key_length(_key_id: u32, _key_version: u32) -> Result<usize, KeyError> { todo!() }
//! }
//!
//! impl Init for ExampleKeyManager {
//!     // ...
//!     # fn init() -> Result<(), InitError> { todo!() }
//!     # fn deinit() -> Result<(), InitError> { todo!() }
//! }
//!
//! register_plugin! {
//!     ExampleKeyManager,                           // Name of the struct implementing KeyManager
//!     ptype: PluginType::MariaEncryption,          // plugin type; only encryption supported for now
//!     name: "name_as_sql_server_sees_it",          // loadable plugin name
//!     author: "Author Name",                       // author's name
//!     description: "Sample key managment plugin",  // give a description
//!     license: License::Gpl,                       // select a license type
//!     maturity: Maturity::Experimental,            // indicate license maturity
//!     version: "0.1",                              // provide an "a.b" version
//!     init: ExampleKeyManager,                     // optional: struct implementing Init if needed
//!     encryption: false,                           // set to `false` to use default encryption, `true` if your main
//!                                                  // struct implements 'Encryption`, and another type
//!                                                  // if a different type should be used for encryption
//!     // decryption: DecryptionContext,            // optional field: if `encryption` is specified as a type
//!                                                  // but the type that implements `Decryption` is different,
//!                                                  // it can be specified here
//!     variables: [                                 // variables should be a list of typed identifiers
//!         SysVar {
//!             ident: SYSVAR_STR,
//!             vtype: SysVarConstString,
//!             name: "sql_name",
//!             description: "this is a description",
//!             options: [SysVarOpt::ReadOnly, SysVarOpt::NoCliOption],
//!             default: "something"
//!         },
//!     //     SysVar {
//!     //         ident: OTHER_IDENT,
//!     //         vtype: AtomicI32,
//!     //         name: "other_sql_name",
//!     //         description: "this is a description",
//!     //         options: [SysVarOpt::ReqCmdArg],
//!     //         default: 100,
//!     //         min: 10,
//!     //         max: 500,
//!     //         interval: 10
//!     //     }
//!      ]
//! }
//! ```

use std::ffi::{c_int, c_uint};
use std::str::FromStr;

use mariadb_sys as bindings;

pub mod encryption;

mod encryption_wrapper;
pub mod ftparser;
#[cfg(feature = "storage")]
pub mod storage;
#[cfg(feature = "storage")]
mod storage_wrapper;
mod variables;
mod variables_parse;
mod wrapper;
pub use mariadb_macros::register_plugin;
pub use variables::{SysVarConstString, SysVarOpt, SysVarString};

/// Commonly used plugin types for reexport
pub mod prelude {
    pub use super::{register_plugin, Init, InitError, License, Maturity, PluginType};
}

/// Reexports for use in proc macros
#[doc(hidden)]
pub mod internals {
    pub use super::encryption_wrapper::{
        wrap_crypt_ctx_finish, wrap_crypt_ctx_init, wrap_crypt_ctx_size, wrap_crypt_ctx_update,
        wrap_encrypted_length, WrapKeyMgr,
    };
    #[cfg(feature = "storage")]
    pub use super::storage_wrapper::{
        build_handler_vtable, wrap_storage_deinit_fn, wrap_storage_init_fn, HandlertonMeta,
    };
    pub use super::variables::SysVarInterface;
    pub use super::wrapper::{
        default_deinit_notype, default_init_notype, new_null_plugin_st, wrap_deinit_fn,
        wrap_init_fn, PluginMeta,
    };
}

/// Defines possible licenses for plugins
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
#[allow(clippy::cast_possible_wrap)]
pub enum License {
    Proprietary = bindings::PLUGIN_LICENSE_PROPRIETARY as isize,
    Gpl = bindings::PLUGIN_LICENSE_GPL as isize,
    Bsd = bindings::PLUGIN_LICENSE_BSD as isize,
}

impl License {
    #[must_use]
    #[doc(hidden)]
    pub const fn to_license_registration(self) -> c_int {
        self as c_int
    }
}

impl FromStr for License {
    type Err = String;

    /// Create a license type from a string
    fn from_str(s: &str) -> Result<Self, String> {
        match s.to_lowercase().as_str() {
            "proprietary" => Ok(Self::Proprietary),
            "gpl" => Ok(Self::Gpl),
            "bsd" => Ok(Self::Bsd),
            _ => Err(format!("'{s}' has no matching license type")),
        }
    }
}

/// Defines a type of plugin. This determines the required implementation.
#[non_exhaustive]
#[allow(clippy::cast_possible_wrap)]
pub enum PluginType {
    MyUdf = bindings::MYSQL_UDF_PLUGIN as isize,
    MyStorageEngine = bindings::MYSQL_STORAGE_ENGINE_PLUGIN as isize,
    MyFtParser = bindings::MYSQL_FTPARSER_PLUGIN as isize,
    MyDaemon = bindings::MYSQL_DAEMON_PLUGIN as isize,
    MyInformationSchema = bindings::MYSQL_INFORMATION_SCHEMA_PLUGIN as isize,
    MyAudit = bindings::MYSQL_AUDIT_PLUGIN as isize,
    MyReplication = bindings::MYSQL_REPLICATION_PLUGIN as isize,
    MyAuthentication = bindings::MYSQL_AUTHENTICATION_PLUGIN as isize,
    MariaPasswordValidation = bindings::MariaDB_PASSWORD_VALIDATION_PLUGIN as isize,
    /// Use this plugin type both for key managers and for full encryption plugins
    MariaEncryption = bindings::MariaDB_ENCRYPTION_PLUGIN as isize,
    MariaDataType = bindings::MariaDB_DATA_TYPE_PLUGIN as isize,
    MariaFunction = bindings::MariaDB_FUNCTION_PLUGIN as isize,
}

impl PluginType {
    #[must_use]
    #[doc(hidden)]
    pub const fn to_ptype_registration(self) -> c_int {
        self as c_int
    }
}

/// Defines possible licenses for plugins
#[non_exhaustive]
#[allow(clippy::cast_possible_wrap)]
pub enum Maturity {
    Unknown = bindings::MariaDB_PLUGIN_MATURITY_UNKNOWN as isize,
    Experimental = bindings::MariaDB_PLUGIN_MATURITY_EXPERIMENTAL as isize,
    Alpha = bindings::MariaDB_PLUGIN_MATURITY_ALPHA as isize,
    Beta = bindings::MariaDB_PLUGIN_MATURITY_BETA as isize,
    Gamma = bindings::MariaDB_PLUGIN_MATURITY_GAMMA as isize,
    Stable = bindings::MariaDB_PLUGIN_MATURITY_STABLE as isize,
}

impl Maturity {
    #[must_use]
    #[doc(hidden)]
    pub const fn to_maturity_registration(self) -> c_uint {
        self as c_uint
    }
}

/// Indicate that an error occured during initialization or deinitialization
pub struct InitError;

/// Implement this trait if your plugin requires init or deinit functions
pub trait Init {
    /// Initialize the plugin
    fn init() -> Result<(), InitError> {
        Ok(())
    }

    /// Deinitialize the plugin
    fn deinit() -> Result<(), InitError> {
        Ok(())
    }
}