Skip to main content

xberg_libwpd/
lib.rs

1//! WordPerfect structured document extraction for Xberg.
2//!
3//! Thin, safe wrapper over [libwpd](https://libwpd.sourceforge.net/) and its
4//! document-model dependency librevenge, both built from source against their
5//! MPL-2.0 arm (see `build.rs`). libwpd covers the whole WordPerfect binary
6//! family (WP 4.2 through the X-series).
7//!
8//! libwpd has no `extract()` entry point; it drives a librevenge callback
9//! interface. A hand-written C++ shim (`src/shim.cpp`) implements that
10//! interface, records a flat, format-agnostic internal document as libwpd
11//! walks the input, and serializes that one document into a versioned binary
12//! blob exposed through a flat C API this crate wraps. [`extract_document`]
13//! decodes that blob into a typed [`WpdDocument`]: an ordered [`WpdEvent`]
14//! stream (text runs, formatting spans, list items, table structure with
15//! column/row spans and header-row flags, hyperlinks, fields, footnotes and
16//! endnotes kept as distinct sequences, headers/footers, and comment/text-box
17//! asides) plus [`WpdMetadata`] (title, author, subject, keywords, and every
18//! raw key/value pair libwpd reported). This crate performs no text or
19//! Markdown rendering; producing a flattened string from the structured model
20//! is left to the caller. WordPerfect support targets Linux, macOS and
21//! Windows; on other platforms [`extract_document`] returns
22//! [`WpdError::UnsupportedPlatform`].
23
24mod dto;
25mod error;
26
27pub use dto::{WpdDocument, WpdEvent, WpdMetadata};
28pub use error::WpdError;
29
30#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
31mod imp {
32    use crate::{WpdDocument, WpdError, dto};
33    use std::ffi::CStr;
34    use std::os::raw::{c_char, c_int, c_uchar, c_ulong};
35    use std::{ptr, slice};
36
37    unsafe extern "C" {
38        fn xberg_wpd_is_supported(data: *const c_uchar, len: c_ulong) -> c_int;
39        fn xberg_wpd_extract_document(
40            data: *const c_uchar,
41            len: c_ulong,
42            out_buf: *mut *mut c_char,
43            out_len: *mut c_ulong,
44            out_err: *mut *mut c_char,
45        ) -> c_int;
46        fn xberg_wpd_free_string(s: *mut c_char);
47        #[cfg(test)]
48        fn xberg_wpd_self_test_separation() -> c_int;
49        #[cfg(test)]
50        fn xberg_wpd_self_test_features() -> c_int;
51    }
52
53    /// Returns true if `data` looks like a WordPerfect document libwpd can parse.
54    pub fn is_supported(data: &[u8]) -> bool {
55        if data.is_empty() || data.len() > u32::MAX as usize {
56            return false;
57        }
58        // SAFETY: `data` is a valid slice of `len` bytes; the shim only reads it
59        // and catches any C++ exception internally. ~keep
60        unsafe { xberg_wpd_is_supported(data.as_ptr(), data.len() as c_ulong) != 0 }
61    }
62
63    /// Extract the structured document model of a WordPerfect document held
64    /// entirely in memory.
65    pub fn extract_document(data: &[u8]) -> Result<WpdDocument, WpdError> {
66        if data.is_empty() || data.len() > u32::MAX as usize {
67            return Err(WpdError::InvalidArgs);
68        }
69
70        let mut out: *mut c_char = ptr::null_mut();
71        let mut out_len: c_ulong = 0;
72        let mut out_err: *mut c_char = ptr::null_mut();
73        // SAFETY: `data` is a valid slice of `len` bytes; `out`/`out_len`/`out_err`
74        // are valid out-pointers. The shim catches any C++ exception and reports
75        // it via the return code (plus, optionally, a detail message). On a zero
76        // return it hands back a malloc'd buffer of exactly `out_len` bytes whose
77        // ownership transfers to us. ~keep
78        let code = unsafe {
79            xberg_wpd_extract_document(
80                data.as_ptr(),
81                data.len() as c_ulong,
82                &mut out,
83                &mut out_len,
84                &mut out_err,
85            )
86        };
87        if !out_err.is_null() {
88            // SAFETY: `out_err` is a malloc'd, NUL-terminated buffer the shim
89            // handed us; freed unconditionally right after reading it. ~keep
90            let detail = unsafe {
91                let msg = CStr::from_ptr(out_err).to_string_lossy().into_owned();
92                xberg_wpd_free_string(out_err);
93                msg
94            };
95            tracing::warn!(code, error = %detail, "libwpd raised an exception during extraction");
96        }
97        if code != 0 {
98            // Defensive: the FFI contract is that `out` stays null on any
99            // non-zero return, but a future shim regression that sets it
100            // anyway must not leak the buffer it allocated. ~keep
101            if !out.is_null() {
102                // SAFETY: `out` would only be non-null here if the shim
103                // violated its own contract by allocating a buffer on an
104                // error path; if so it is still the same malloc'd buffer
105                // `xberg_wpd_free_string` is designed to free. ~keep
106                unsafe { xberg_wpd_free_string(out) };
107            }
108            return Err(WpdError::from_code(code));
109        }
110        if out.is_null() {
111            return Err(WpdError::Internal);
112        }
113
114        // SAFETY: `out` is the non-null buffer the shim allocated, exactly
115        // `out_len` bytes long; we copy it out and free it through the matching
116        // deallocator before returning. Using the explicit length (rather than
117        // scanning for a NUL terminator) means the binary blob's embedded
118        // length-prefixed strings can't be silently truncated at an embedded
119        // NUL. ~keep
120        let bytes = unsafe {
121            let bytes = slice::from_raw_parts(out as *const u8, out_len as usize).to_vec();
122            xberg_wpd_free_string(out);
123            bytes
124        };
125        dto::decode(&bytes)
126    }
127
128    #[cfg(test)]
129    mod tests {
130        use super::*;
131
132        #[test]
133        fn collector_separates_asides_from_body() {
134            // SAFETY: takes no arguments and only touches its own stack-local state. ~keep
135            assert_eq!(unsafe { xberg_wpd_self_test_separation() }, 1);
136        }
137
138        #[test]
139        fn collector_captures_links_tables_fields_and_notes() {
140            // SAFETY: takes no arguments and only touches its own stack-local state. ~keep
141            assert_eq!(unsafe { xberg_wpd_self_test_features() }, 1);
142        }
143    }
144}
145
146#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
147mod imp {
148    /// WordPerfect extraction is desktop-only; unavailable on this target.
149    pub fn is_supported(_data: &[u8]) -> bool {
150        false
151    }
152
153    /// WordPerfect extraction is desktop-only; unavailable on this target.
154    pub fn extract_document(_data: &[u8]) -> Result<super::WpdDocument, super::WpdError> {
155        Err(super::WpdError::UnsupportedPlatform)
156    }
157}
158
159pub use imp::{extract_document, is_supported};