ctb_formats_dceutils/
dceutils.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! LLM-assisted port of dceutils. Note that most of this is a direct port of the PHP implementation and it attempts to preserve its bugs and incompleteness as-is. The `converter.rs` module is a newly created alternative that attempts to be more complete and correct. The DCE 3.02a format isn't technically implementable because it doesn't define a version selector for that version; as implemented here it uses the byte assignment where a version selector ought to have gone.
21//!
22//! Format support and notes:
23//!
24//! | Format | Format code | Read | Write — Notes |
25//! |:---|:---|:---:|:---|
26//! | **CDCE-based formats:** | | | |
27//! | CDCE | `cdce` | | |
28//! | CDCE (legacy)[^3] | `legacy_cdce` | X | X |
29//! | CDCE (legacy, strict)[^5] | `cdce_lstrict` | X | N/A |
30//! | **Generic DCE formats (automatic version selection):** | | | |
31//! | DCE[^1] | `dce` | X | X |
32//! | DCE (hex-encoded) | `hex_dce` | X | X |
33//! | **DCE 3.0a-based formats:** | | | |
34//! | DCE 3.0a[^2] | `3_0a` | X | X |
35//! | DCE 3.0a (raw) | `dce_3_0a_raw` | X | X |
36//! | DCE 3.0a (hex-encoded)[^2] | `hex_3_0a` | X | X |
37//! | DCE 3.0a (raw hex-encoded) | `hex_3_0a_raw` | X | X |
38//! | DCE 3.0a (old translator)[^6] | `3_0a_old` | (X) | N/A (No tests) |
39//! | dce2txt[^7] | `dce2txt` | (X) | N/A (No tests) |
40//! | dce2hex[^7] | `dce2hex` | (X) | N/A (No tests) |
41//! | hex2dce[^7] | `hex2dce` | (X) | N/A (No tests) |
42//! | **DCE 3.01a-based formats:** | | | |
43//! | DCE 3.01a[^2],[^4] | `3_01a` | (X) | (X) |
44//! | DCE 3.01a (raw) | `dce_3_01a_raw` | (X) | |
45//! | DCE 3.01a (hex-encoded)[^2],[^4] | `hex_3_01a` | (X) | (X) |
46//! | DCE 3.01a (raw hex-encoded) | `hex_3_01a_raw` | (X) | |
47//! | **Miscellaneous DCE formats:** | | | |
48//! | Dc ID list (ASCII)[^3] | `dc` | X | X |
49//! | **Unicode:** | | | |
50//! | UTF-8[^3] | `utf8` | X | X |
51//! | UTF-32[^3] | `utf32` | X | X |
52//! | UTF-8 (Base64-encoded) | `utf8_base64` | X | X |
53//! | UTF-8 (Base64-encoded, ASCII Dc ID list) | `utf8_dc64` | X | X |
54//! | UTF-8 (Base64-encoded, ASCII Dc ID list; with headers) | `utf8_dc64_enc` | X | X |
55//! | UTF-8 (Base64-encoded, DCE 3.01a+ encoding) | `utf8_dc64_bin` | X | X |
56//! | UTF-8 (Base64-encoded, DCE 3.01a+ encoding; hex-encoded) | `utf8_dc64_bin_hex` | X | X |
57//! | UTF-8 (Base64-encoded, DCE 3.01a+ encoding; with headers) | `utf8_dc64_bin_enc` | X | X |
58//! | UTF-8 (Base64-encoded, DCE 3.01a+ encoding; with headers; hex-encoded) | `utf8_dc64_bin_enc_hex` | X | X |
59//! | **HTML:** | | | |
60//! | HTML | `html` | | |
61//! | HTML (snippet) | `html_snippet` | | |
62//! | HTML (legacy CDCE output)[^4] | `html_l` | | (X) |
63//! | HTML (snippet) (legacy CDCE output)[^4] | `html_snippet_l` | | (X) |
64//!
65//! [^1]: Automatically detects DCE version when reading, and writes to the latest DCE version that is well supported.
66//! [^2]: Since this is a DCE format, simply enter DCE as the format when reading. Note that writing to old versions of DCE may not be lossless.
67//! [^3]: Reading/writing these formats may not be lossless with DCE 3.0a.
68//! [^4]: It'll try but it probably won't work or won't work well. Note that the HTML translators only work with legacy CDCE input and are very buggy (alpha quality).
69//! [^5]: Note that `cdce_lstrict` is not actually a separate format from `legacy_cdce`; rather, it is an alias of `legacy_cdce` that instructs the parser to halt upon reaching an incorrectly structured CDCE sequence (by default it will attempt to recover from the error).
70//! [^6]: This is an early version of the DCE 3.0a translator, not a separate format. Leave the output format blank when using this translator, since the same code handles both input and output. This is not tested or maintained, and may or may not work properly.
71//! [^7]: These are miscellaneous outdated translators, not separate formats. Leave the output format blank when using them, since the same code handles both input and output. These are not tested or maintained, and may or may not work properly.
72
73#[allow(
74    unused_imports,
75    clippy::wildcard_imports,
76    reason = "Standard workspace crate prelude"
77)]
78pub(crate) use ctb_utilities::*;
79
80pub mod cdce;
81pub mod cli;
82pub mod converter;
83pub mod dce3_01a;
84pub mod dce3_0a;
85pub mod document;
86pub mod legacy;
87pub mod tables;
88pub mod to_csv;
89pub mod tools;
90pub mod unicode;
91
92pub use converter::{
93    DceVersion, MAX_DCE_3_0A_SHORT_DC, MAX_DCE_3_01A_SHORT_DC,
94    MAX_DCE_3_02A_SHORT_DC, decode_dce_preserving_controls,
95    encode_dce_preserving_controls, is_dce_encoding_control_dc,
96};
97
98#[cfg(test)]
99#[allow(
100    clippy::panic,
101    clippy::expect_used,
102    clippy::unwrap_used,
103    clippy::unwrap_in_result,
104    clippy::panic_in_result_fn,
105    clippy::indexing_slicing,
106    clippy::arithmetic_side_effects,
107    reason = "Standard repository test boilerplate"
108)]
109mod dceutils_tests;
110
111#[cfg(test)]
112#[allow(
113    clippy::panic,
114    clippy::expect_used,
115    clippy::unwrap_used,
116    clippy::unwrap_in_result,
117    clippy::panic_in_result_fn,
118    clippy::indexing_slicing,
119    clippy::arithmetic_side_effects,
120    reason = "Standard repository test boilerplate"
121)]
122mod dceutils_tests_converter;
123
124pub use converter::{
125    dce_convert as dce_convert_new,
126    dce_convert_with_log as dce_convert_new_with_log,
127    dce_convert_with_options as dce_convert_new_with_options,
128};
129
130use anyhow::{Context, Result, anyhow, bail};
131pub use ctb_formats_utilities::FormatLog;
132
133pub fn get_dce_version(data: &[u8]) -> String {
134    let mut log = FormatLog::default();
135    let res = get_dce_version_with_log(data, &mut log);
136    log.auto_log();
137    res
138}
139
140pub fn get_dce_version_with_log(data: &[u8], log: &mut FormatLog) -> String {
141    if data.len() < 7 || data.get(0..6) != Some(b"DCEe\x02\x01".as_slice()) {
142        log.error("This document does not appear to be stored using DCE.");
143        return "This document does not appear to be stored using DCE."
144            .to_string();
145    }
146    match data.get(6) {
147        Some(&1) => "3_0a".to_string(),
148        Some(&2) => "3_01a".to_string(),
149        _ => {
150            log.error(
151                "This document is not stored using a supported version of DCE.",
152            );
153            "This document is not stored using a supported version of DCE."
154                .to_string()
155        }
156    }
157}
158
159pub fn dce_convert(
160    data: &[u8],
161    input_format: &str,
162    output_format: &str,
163) -> Result<Vec<u8>> {
164    let (res, log) = dce_convert_with_log(data, input_format, output_format)?;
165    log.auto_log();
166    Ok(res)
167}
168
169pub fn dce_convert_with_log(
170    data: &[u8],
171    input_format: &str,
172    output_format: &str,
173) -> Result<(Vec<u8>, FormatLog)> {
174    let mut log = FormatLog::default();
175    let res =
176        dce_convert_internal(data, input_format, output_format, &mut log)?;
177    Ok((res, log))
178}
179
180pub(crate) fn dce_convert_internal(
181    data: &[u8],
182    input_format: &str,
183    output_format: &str,
184    log: &mut FormatLog,
185) -> Result<Vec<u8>> {
186    if input_format == output_format && input_format != "dc" {
187        return Ok(data.to_vec());
188    }
189
190    // Detect and handle one-step conversions
191    let mut onestep = false;
192    match input_format {
193        "3_0a_old" if output_format == "none" => onestep = true,
194        "dce2txt" if output_format == "none" => onestep = true,
195        "dce2hex" if output_format == "none" => onestep = true,
196        "hex2dce" if output_format == "none" => onestep = true,
197        "legacy_cdce" if output_format == "html" => onestep = true,
198        _ => {}
199    }
200
201    if onestep {
202        return match input_format {
203            "3_0a_old" => legacy::onestep_3_0a_old_to_none(data),
204            "dce2txt" => legacy::onestep_dce2txt_to_none(data),
205            "dce2hex" => legacy::onestep_dce2hex_to_none(data),
206            "hex2dce" => legacy::onestep_hex2dce_to_none(data),
207            "legacy_cdce" => legacy::onestep_legacy_cdce_to_html_l(data),
208            _ => {
209                log.error(&format!(
210                    "Unknown one-step conversion: {input_format} to {output_format}"
211                ));
212                bail!(
213                    "Unknown one-step conversion: {input_format} to {output_format}"
214                );
215            }
216        };
217    }
218
219    // Step 4: Convert input data to a Dc list (String representation)
220    let dc = match input_format {
221        "dc" => std::str::from_utf8(data)
222            .context("invalid UTF-8 in Dc list")?
223            .to_string(),
224        "dce" => {
225            let ver = get_dce_version_with_log(data, log);
226            if ver == "3_0a" || ver == "3_01a" {
227                let res = dce_convert_internal(data, &ver, "dc", log)?;
228                String::from_utf8(res)?
229            } else if ver
230                == "This document does not appear to be stored using DCE."
231            {
232                log.error(
233                    "This document is not stored using the specified format.",
234                );
235                bail!(
236                    "This document is not stored using the specified format."
237                );
238            } else {
239                bail!("{ver}");
240            }
241        }
242        "hex_dce" => {
243            let bin = (|| -> Result<Vec<u8>> {
244                let hex_str = std::str::from_utf8(data)?;
245                ctb_formats_hexdump::hex2bin(hex_str)
246            })()
247            .map_err(|_| {
248                log.error(
249                    "This document is not stored using the specified format.",
250                );
251                anyhow!(
252                    "This document is not stored using the specified format."
253                )
254            })?;
255            let res_bytes = dce_convert_internal(&bin, "dce", "dc", log)?;
256            String::from_utf8(res_bytes)?
257        }
258        "3_0a" => dce3_0a::convert_3_0a_to_dc(data, log)?,
259        "3_0a_raw" => dce3_0a::convert_3_0a_raw_to_dc(data, log)?,
260        "hex_3_0a" => {
261            let bin = (|| -> Result<Vec<u8>> {
262                let hex_str = std::str::from_utf8(data)?;
263                ctb_formats_hexdump::hex2bin(hex_str)
264            })()
265            .map_err(|_| {
266                log.error(
267                    "This document is not stored using the specified format.",
268                );
269                anyhow!(
270                    "This document is not stored using the specified format."
271                )
272            })?;
273            let res_bytes = dce_convert_internal(&bin, "3_0a", "dc", log)?;
274            String::from_utf8(res_bytes)?
275        }
276        "hex_3_0a_raw" => {
277            let bin = (|| -> Result<Vec<u8>> {
278                let hex_str = std::str::from_utf8(data)?;
279                ctb_formats_hexdump::hex2bin(hex_str)
280            })()
281            .map_err(|_| {
282                log.error(
283                    "This document is not stored using the specified format.",
284                );
285                anyhow!(
286                    "This document is not stored using the specified format."
287                )
288            })?;
289            let res_bytes = dce_convert_internal(&bin, "3_0a_raw", "dc", log)?;
290            String::from_utf8(res_bytes)?
291        }
292        "3_01a" => dce3_01a::convert_3_01a_to_dc(data, log)?,
293        "3_01a_raw" => dce3_01a::convert_3_01a_raw_to_dc(data, log)?,
294        "hex_3_01a" => {
295            let bin = (|| -> Result<Vec<u8>> {
296                let hex_str = std::str::from_utf8(data)?;
297                ctb_formats_hexdump::hex2bin(hex_str)
298            })()
299            .map_err(|_| {
300                log.error(
301                    "This document is not stored using the specified format.",
302                );
303                anyhow!(
304                    "This document is not stored using the specified format."
305                )
306            })?;
307            let res_bytes = dce_convert_internal(&bin, "3_01a", "dc", log)?;
308            String::from_utf8(res_bytes)?
309        }
310        "hex_3_01a_raw" => {
311            let bin = (|| -> Result<Vec<u8>> {
312                let hex_str = std::str::from_utf8(data)?;
313                ctb_formats_hexdump::hex2bin(hex_str)
314            })()
315            .map_err(|_| {
316                log.error(
317                    "This document is not stored using the specified format.",
318                );
319                anyhow!(
320                    "This document is not stored using the specified format."
321                )
322            })?;
323            let res_bytes = dce_convert_internal(&bin, "3_01a_raw", "dc", log)?;
324            String::from_utf8(res_bytes)?
325        }
326        "legacy_cdce" => cdce::convert_legacy_cdce_to_dc(data, false, log)?,
327        "cdce_lstrict" => cdce::convert_legacy_cdce_to_dc(data, true, log)?,
328        "utf8" => unicode::convert_utf8_to_dc(data, log)?,
329        "utf32" => unicode::convert_utf32_to_dc(data, log)?,
330        "utf8_base64" => unicode::convert_utf8_base64_to_dc(data, log)?,
331        "utf8_dc64" => unicode::convert_utf8_dc64_to_dc(data, log)?,
332        "utf8_dc64_enc" => unicode::convert_utf8_dc64_enc_to_dc(data, log)?,
333        "utf8_dc64_bin" => unicode::convert_utf8_dc64_bin_to_dc(data, log)?,
334        "utf8_dc64_bin_hex" => {
335            unicode::convert_utf8_dc64_bin_hex_to_dc(data, log)?
336        }
337        "utf8_dc64_bin_enc" => {
338            unicode::convert_utf8_dc64_bin_enc_to_dc(data, log)?
339        }
340        "utf8_dc64_bin_enc_hex" => {
341            unicode::convert_utf8_dc64_bin_enc_hex_to_dc(data, log)?
342        }
343        _ => {
344            log.error("Unknown input format.");
345            bail!("Unknown input format.");
346        }
347    };
348
349    // Clean up the Dc list
350    let mut dc_cleaned = dc.trim_end_matches(',').to_string();
351    while dc_cleaned.contains(",,") {
352        dc_cleaned = dc_cleaned.replace(",,", ",0,");
353    }
354
355    // Step 5: Convert the Dc list to the chosen output format
356    match output_format {
357        "dc" => {
358            let dc_out = convert_dc_to_dc_output(&dc_cleaned, log);
359            Ok(dc_out.into_bytes())
360        }
361        "legacy_cdce" => {
362            cdce::convert_dc_to_legacy_cdce_output(&dc_cleaned, log)
363        }
364        "dce" => dce3_0a::convert_dc_to_3_0a_output(&dc_cleaned, log),
365        "3_0a" => dce3_0a::convert_dc_to_3_0a_output(&dc_cleaned, log),
366        "3_0a_raw" => dce3_0a::convert_dc_to_3_0a_raw_output(&dc_cleaned, log),
367        "hex_3_0a_raw" => {
368            let raw_bytes =
369                dce3_0a::convert_dc_to_3_0a_raw_output(&dc_cleaned, log)?;
370            Ok(bin2hex(raw_bytes).to_uppercase().into_bytes())
371        }
372        "3_01a" => dce3_01a::convert_dc_to_3_01a_output(&dc_cleaned, log),
373        "hex_dce" => {
374            let dce_bytes =
375                dce_convert_internal(dc_cleaned.as_bytes(), "dc", "dce", log)?;
376            Ok(bin2hex(dce_bytes).to_uppercase().into_bytes())
377        }
378        "hex_3_0a" => {
379            let bytes =
380                dce_convert_internal(dc_cleaned.as_bytes(), "dc", "3_0a", log)?;
381            Ok(bin2hex(bytes).to_uppercase().into_bytes())
382        }
383        "hex_3_01a" => {
384            let bytes = dce_convert_internal(
385                dc_cleaned.as_bytes(),
386                "dc",
387                "3_01a",
388                log,
389            )?;
390            Ok(bin2hex(bytes).to_uppercase().into_bytes())
391        }
392        "utf8" => unicode::convert_dc_to_utf8_output(&dc_cleaned, log),
393        "utf32" => unicode::convert_dc_to_utf32_output(&dc_cleaned, log),
394        "utf8_base64" => {
395            unicode::convert_dc_to_utf8_base64_output(&dc_cleaned, log)
396        }
397        "utf8_dc64" => {
398            unicode::convert_dc_to_utf8_dc64_output(&dc_cleaned, log)
399        }
400        "utf8_dc64_enc" => {
401            unicode::convert_dc_to_utf8_dc64_enc_output(&dc_cleaned, log)
402        }
403        "utf8_dc64_bin" => {
404            unicode::convert_dc_to_utf8_dc64_bin_output(&dc_cleaned, log)
405        }
406        "utf8_dc64_bin_hex" => {
407            unicode::convert_dc_to_utf8_dc64_bin_hex_output(&dc_cleaned, log)
408        }
409        "utf8_dc64_bin_enc" => {
410            unicode::convert_dc_to_utf8_dc64_bin_enc_output(&dc_cleaned, log)
411        }
412        "utf8_dc64_bin_enc_hex" => {
413            unicode::convert_dc_to_utf8_dc64_bin_enc_hex_output(
414                &dc_cleaned,
415                log,
416            )
417        }
418        _ => {
419            log.error("Unknown output format.");
420            bail!("Unknown output format.");
421        }
422    }
423}
424
425pub fn convert_dc_to_dc_output(data: &str, log: &mut FormatLog) -> String {
426    // Replicates PHP integer casting behavior where non-digit characters evaluate to 0,
427    // which prevents the `,115` suffix formatting on strict error payloads.
428    // I don't think that was an intended behavior of the PHP version, and it should be logged as an error in FormatLog if it can't be casted to a digit, but to allow the old test suite to run it has to mimic this.
429    let first_char = data.chars().next();
430    let last_char = data.chars().last();
431    // Reason for fallback: empty or non-digit first character evaluates to 0 to mirror PHP casting.
432    let first_val =
433        first_char.and_then(|c| c.to_digit(10)).unwrap_or_else(|| {
434            if let Some(c) = first_char {
435                log.error(&format!("Non-digit character '{c}' in Dc payload"));
436            }
437            0
438        });
439    // Reason for fallback: empty or non-digit last character evaluates to 0 to mirror PHP casting.
440    let last_val =
441        last_char.and_then(|c| c.to_digit(10)).unwrap_or_else(|| {
442            if let Some(c) = last_char {
443                log.error(&format!("Non-digit character '{c}' in Dc payload"));
444            }
445            0
446        });
447
448    if !data.starts_with("114") && first_val != 0 && last_val != 0 {
449        format!("114,{data},115")
450    } else if !data.starts_with("114") && first_val != 0 {
451        format!("114,{data}")
452    } else {
453        data.to_string()
454    }
455}