/src/suricata7/rust/src/ffi/base64.rs
Line | Count | Source |
1 | | /* Copyright (C) 2021 Open Information Security Foundation |
2 | | * |
3 | | * You can copy, redistribute or modify this Program under the terms of |
4 | | * the GNU General Public License version 2 as published by the Free |
5 | | * Software Foundation. |
6 | | * |
7 | | * This program is distributed in the hope that it will be useful, |
8 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
9 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
10 | | * GNU General Public License for more details. |
11 | | * |
12 | | * You should have received a copy of the GNU General Public License |
13 | | * version 2 along with this program; if not, write to the Free Software |
14 | | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
15 | | * 02110-1301, USA. |
16 | | */ |
17 | | |
18 | | use std::os::raw::c_uchar; |
19 | | use libc::c_ulong; |
20 | | |
21 | | #[repr(C)] |
22 | | #[allow(non_camel_case_types)] |
23 | | pub enum Base64ReturnCode { |
24 | | SC_BASE64_OK = 0, |
25 | | SC_BASE64_INVALID_ARG, |
26 | | SC_BASE64_OVERFLOW, |
27 | | } |
28 | | |
29 | | /// Base64 encode a buffer. |
30 | | /// |
31 | | /// This method exposes the Rust base64 encoder to C and should not be called from |
32 | | /// Rust code. |
33 | | /// |
34 | | /// The output parameter must be an allocated buffer of at least the size returned |
35 | | /// from Base64EncodeBufferSize for the input_len, and this length must be provided |
36 | | /// in the output_len variable. |
37 | | #[no_mangle] |
38 | 0 | pub unsafe extern "C" fn Base64Encode( |
39 | 0 | input: *const u8, input_len: c_ulong, output: *mut c_uchar, output_len: *mut c_ulong, |
40 | 0 | ) -> Base64ReturnCode { |
41 | 0 | if input.is_null() || output.is_null() || output_len.is_null() { |
42 | 0 | return Base64ReturnCode::SC_BASE64_INVALID_ARG; |
43 | 0 | } |
44 | 0 | let input = std::slice::from_raw_parts(input, input_len as usize); |
45 | 0 | let encoded = base64::encode(input); |
46 | 0 | if encoded.len() + 1 > *output_len as usize { |
47 | 0 | return Base64ReturnCode::SC_BASE64_OVERFLOW; |
48 | 0 | } |
49 | 0 | let output = std::slice::from_raw_parts_mut(&mut *output, *output_len as usize); |
50 | 0 | output[0..encoded.len()].copy_from_slice(encoded.as_bytes()); |
51 | 0 | output[encoded.len()] = 0; |
52 | 0 | *output_len = encoded.len() as c_ulong; |
53 | 0 | Base64ReturnCode::SC_BASE64_OK |
54 | 0 | } |
55 | | |
56 | | /// Ratio of output bytes to input bytes for Base64 Encoding is 4:3, hence the |
57 | | /// required output bytes are 4 * ceil(input_len / 3) and an additional byte for |
58 | | /// storing the NULL pointer. |
59 | | #[no_mangle] |
60 | 0 | pub extern "C" fn Base64EncodeBufferSize(len: c_ulong) -> c_ulong { |
61 | 0 | (4 * ((len) + 2) / 3) + 1 |
62 | 0 | } |