rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! 재조립 HWPX 패키지(ZIP) 구조 검증 (Task #1315).
//!
//! `serialize_hwpx()` 산출 바이트가 한컴/OPF 패키지 규약을 지키는지 IR 대비 검사한다.
//!
//! 검사 항목:
//! 1. ZIP 아카이브로 열림
//! 2. `mimetype` — 최초 엔트리, STORED, 내용 `application/hwp+zip`
//! 3. 필수 엔트리 존재 (version.xml, header.xml, content.hpf, Preview, settings,
//!    META-INF/container.xml·container.rdf·manifest.xml)
//! 4. `Contents/section{N}.xml` 엔트리 수 = IR 섹션 수 (잉여 섹션 엔트리 금지)
//! 5. `Contents/content.hpf` manifest 가 참조하는 href 가 모두 ZIP 에 실재
//! 6. `Contents/masterpage{N}.xml` 엔트리·manifest·section idRef = IR 바탕쪽 보존
//! 7. `BinData/` 엔트리 수·확장자 멀티셋 = IR `bin_data_content` 보존
//!
//! 주의: serializer 가 BinData href 를 `BinData/image{N}.{ext}` 로 재명명하므로
//! 원본 ZIP 의 엔트리 **이름**이 아니라 IR 기준 **수·확장자**를 보존 기준으로 삼는다.

use std::collections::HashSet;
use std::io::{Cursor, Read};

use crate::model::document::Document;

/// HWPX mimetype 고정 내용.
const HWPX_MIMETYPE: &[u8] = b"application/hwp+zip";

/// 섹션 수와 무관하게 항상 있어야 하는 엔트리.
const REQUIRED_ENTRIES: [&str; 9] = [
    "version.xml",
    "Contents/header.xml",
    "Contents/content.hpf",
    "Preview/PrvText.txt",
    "Preview/PrvImage.png",
    "settings.xml",
    "META-INF/container.xml",
    "META-INF/container.rdf",
    "META-INF/manifest.xml",
];

/// 패키지 검사 결과 — 발견된 문제 목록.
#[derive(Debug, Default)]
pub struct PackageCheckReport {
    pub problems: Vec<String>,
}

impl PackageCheckReport {
    pub fn is_ok(&self) -> bool {
        self.problems.is_empty()
    }

    pub fn summary(&self) -> String {
        self.problems.join("; ")
    }

    fn push(&mut self, problem: String) {
        self.problems.push(problem);
    }
}

/// 재조립 HWPX 바이트를 IR(`doc`) 기준으로 패키지 구조 검사한다.
///
/// `doc` 은 직렬화에 입력한 Document (원본 파싱 결과)여야 한다.
pub fn check_package(hwpx_bytes: &[u8], doc: &Document) -> PackageCheckReport {
    let mut report = PackageCheckReport::default();

    let mut archive = match zip::ZipArchive::new(Cursor::new(hwpx_bytes)) {
        Ok(a) => a,
        Err(e) => {
            report.push(format!("ZIP 열기 실패: {e}"));
            return report;
        }
    };

    let names: HashSet<String> = match archive
        .file_names()
        .map(|name| name.map(|name| name.into_owned()))
        .collect::<Result<_, _>>()
    {
        Ok(names) => names,
        Err(error) => {
            report.push(format!("ZIP 엔트리 이름 읽기 실패: {error}"));
            return report;
        }
    };

    // 2. mimetype — 최초 엔트리 + STORED + 내용 일치
    match archive.by_index(0) {
        Ok(mut first) => {
            let name = match first.name() {
                Ok(name) => name,
                Err(error) => {
                    report.push(format!("첫 엔트리 이름 읽기 실패: {error}"));
                    return report;
                }
            };
            if name != "mimetype" {
                report.push(format!(
                    "mimetype 이 최초 엔트리가 아님 (첫 엔트리: {})",
                    name
                ));
            } else {
                if first.compression() != zip::CompressionMethod::Stored {
                    report.push(format!(
                        "mimetype 압축 방식이 STORED 가 아님: {:?}",
                        first.compression()
                    ));
                }
                let mut content = Vec::new();
                if first.read_to_end(&mut content).is_ok() {
                    if content != HWPX_MIMETYPE {
                        report.push(format!(
                            "mimetype 내용 불일치: {:?}",
                            String::from_utf8_lossy(&content)
                        ));
                    }
                } else {
                    report.push("mimetype 읽기 실패".to_string());
                }
            }
        }
        Err(e) => report.push(format!("첫 엔트리 접근 실패: {e}")),
    }

    // 3. 필수 엔트리
    for required in REQUIRED_ENTRIES {
        if !names.contains(required) {
            report.push(format!("필수 엔트리 누락: {required}"));
        }
    }

    // 4. 섹션 엔트리 수 = IR 섹션 수
    for i in 0..doc.sections.len() {
        let entry = format!("Contents/section{i}.xml");
        if !names.contains(&entry) {
            report.push(format!("섹션 엔트리 누락: {entry} (IR 섹션 {i})"));
        }
    }
    let section_entry_count = names.iter().filter(|n| is_section_entry_name(n)).count();
    if section_entry_count != doc.sections.len() {
        report.push(format!(
            "섹션 엔트리 수 불일치: zip={} ir={}",
            section_entry_count,
            doc.sections.len()
        ));
    }

    // 5. content.hpf manifest href 실재 확인
    let content_hpf = match read_entry_string(&mut archive, "Contents/content.hpf") {
        Ok(hpf) => {
            for href in extract_hrefs(&hpf) {
                if !names.contains(href.as_str()) {
                    report.push(format!("content.hpf 참조 엔트리 누락: {href}"));
                }
            }
            Some(hpf)
        }
        Err(e) => {
            // 필수 엔트리 검사에서 이미 누락 보고됐을 수 있으므로 읽기 실패만 기록
            if names.contains("Contents/content.hpf") {
                report.push(format!("content.hpf 읽기 실패: {e}"));
            }
            None
        }
    };

    // 5b. container.rdf section graph coverage.
    // Hancom checks this package graph separately from content.hpf; stale RDF
    // can make otherwise ZIP-valid multi-section HWPX exports fail to open.
    match read_entry_string(&mut archive, "META-INF/container.rdf") {
        Ok(rdf) => check_container_rdf(&mut report, &rdf, doc),
        Err(e) => {
            if names.contains("META-INF/container.rdf") {
                report.push(format!("container.rdf 읽기 실패: {e}"));
            }
        }
    }

    // 6. 바탕쪽(masterpage) 엔트리·manifest·section idRef 보존.
    check_master_pages(
        &mut report,
        &mut archive,
        &names,
        content_hpf.as_deref(),
        doc,
    );

    // 7. BinData 수·확장자 보존 (IR 기준)
    // [#3546] OOXML 차트(extension="ooxml_chart", HWPX 파서가 60000+N 으로 주입)는
    // BinData 가 아니라 Chart/chartN.xml 원형 경로로 방출된다 — 기대값을 분리한다.
    // HWP5 연결 레코드 자리 항목은 ZIP 엔트리가 없으므로 기대값에서 뺀다.
    let (ir_chart, ir_bin): (Vec<_>, Vec<_>) = doc
        .bin_data_content
        .iter()
        .enumerate()
        .filter(|(i, b)| {
            !crate::model::bin_data::is_hwp5_link_slot(b, doc.doc_info.bin_data_list.get(*i))
        })
        .map(|(_, b)| b)
        .partition(|b| b.extension == "ooxml_chart");
    let zip_bin: Vec<&String> = names.iter().filter(|n| n.starts_with("BinData/")).collect();
    if zip_bin.len() != ir_bin.len() {
        report.push(format!(
            "BinData 엔트리 수 불일치: zip={} ir={}",
            zip_bin.len(),
            ir_bin.len()
        ));
    } else {
        let mut zip_exts: Vec<String> = zip_bin.iter().map(|n| extension_lower(n)).collect();
        let mut ir_exts: Vec<String> = ir_bin
            .iter()
            .map(|b| b.extension.to_ascii_lowercase())
            .collect();
        zip_exts.sort();
        ir_exts.sort();
        if zip_exts != ir_exts {
            report.push(format!(
                "BinData 확장자 멀티셋 불일치: zip={:?} ir={:?}",
                zip_exts, ir_exts
            ));
        }
    }

    // 7-1. [#3546] 차트 파트 원형 보존 — Chart/chartN.xml 존재 + BinData 이동 금지.
    for b in &ir_chart {
        let expected = format!("Chart/chart{}.xml", b.id.saturating_sub(60000));
        if !names.contains(&expected) {
            report.push(format!("차트 파트 누락: {expected}"));
        }
    }
    if let Some(moved) = zip_bin
        .iter()
        .find(|n| n.to_ascii_lowercase().ends_with(".ooxml_chart"))
    {
        report.push(format!("차트 파트가 BinData 로 이동됨: {moved}"));
    }

    report
}

/// `Contents/section{숫자}.xml` 형태인지 확인.
fn is_section_entry_name(name: &str) -> bool {
    name.strip_prefix("Contents/section")
        .and_then(|rest| rest.strip_suffix(".xml"))
        .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
}

/// `Contents/masterpage{숫자}.xml` 형태인지 확인.
fn is_master_page_entry_name(name: &str) -> bool {
    name.strip_prefix("Contents/masterpage")
        .and_then(|rest| rest.strip_suffix(".xml"))
        .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
}

fn check_master_pages(
    report: &mut PackageCheckReport,
    archive: &mut zip::ZipArchive<Cursor<&[u8]>>,
    names: &HashSet<String>,
    content_hpf: Option<&str>,
    doc: &Document,
) {
    let expected_count: usize = doc
        .sections
        .iter()
        .map(|section| section.section_def.master_pages.len())
        .sum();
    let zip_count = names
        .iter()
        .filter(|n| is_master_page_entry_name(n))
        .count();
    if zip_count != expected_count {
        report.push(format!(
            "바탕쪽 엔트리 수 불일치: zip={} ir={}",
            zip_count, expected_count
        ));
    }

    let mut global = 0usize;
    for (section_idx, section) in doc.sections.iter().enumerate() {
        let section_master_count = section.section_def.master_pages.len();
        let ids: Vec<String> = (0..section_master_count)
            .map(|offset| format!("masterpage{}", global + offset))
            .collect();

        for id in &ids {
            let href = format!("Contents/{id}.xml");
            if !names.contains(&href) {
                report.push(format!("바탕쪽 엔트리 누락: {href}"));
            }
            if let Some(hpf) = content_hpf {
                if !hpf.contains(&format!(r#"id="{id}""#))
                    || !hpf.contains(&format!(r#"href="{href}""#))
                {
                    report.push(format!("content.hpf 바탕쪽 manifest 누락: {id} -> {href}"));
                }
            }
        }

        if section_master_count > 0 {
            let section_href = format!("Contents/section{section_idx}.xml");
            match read_entry_string(archive, &section_href) {
                Ok(section_xml) => {
                    let expected_cnt = format!(r#"masterPageCnt="{section_master_count}""#);
                    if !section_xml.contains(&expected_cnt) {
                        report.push(format!(
                            "section{section_idx} masterPageCnt 불일치: expected {section_master_count}"
                        ));
                    }
                    for id in &ids {
                        let expected_ref = format!(r#"idRef="{id}""#);
                        if !section_xml.contains(&expected_ref) {
                            report.push(format!("section{section_idx} 바탕쪽 idRef 누락: {id}"));
                        }
                    }
                }
                Err(e) => {
                    if names.contains(&section_href) {
                        report.push(format!("{section_href} 읽기 실패: {e}"));
                    }
                }
            }
        }

        global += section_master_count;
    }
}

fn check_container_rdf(report: &mut PackageCheckReport, rdf: &str, doc: &Document) {
    if !rdf.contains(r#"rdf:resource="Contents/header.xml""#)
        || !rdf.contains(r#"rdf:about="Contents/header.xml""#)
    {
        report.push("container.rdf header 참조 누락".to_string());
    }

    for i in 0..doc.sections.len() {
        let href = format!("Contents/section{i}.xml");
        if !rdf.contains(&format!(r#"rdf:resource="{href}""#))
            || !rdf.contains(&format!(r#"rdf:about="{href}""#))
        {
            report.push(format!("container.rdf 섹션 참조 누락: {href}"));
        }
    }

    let rdf_section_count = extract_rdf_resources(rdf)
        .iter()
        .filter(|href| is_section_entry_name(href))
        .count();
    if rdf_section_count != doc.sections.len() {
        report.push(format!(
            "container.rdf 섹션 참조 수 불일치: rdf={} ir={}",
            rdf_section_count,
            doc.sections.len()
        ));
    }
}

/// ZIP 엔트리를 문자열로 읽는다.
fn read_entry_string(
    archive: &mut zip::ZipArchive<Cursor<&[u8]>>,
    name: &str,
) -> Result<String, String> {
    let mut entry = archive.by_name(name).map_err(|e| e.to_string())?;
    let mut s = String::new();
    entry.read_to_string(&mut s).map_err(|e| e.to_string())?;
    Ok(s)
}

/// XML 텍스트에서 `href="..."` 값을 단순 스캔으로 추출한다.
///
/// content.hpf 는 자체 writer 산출물이므로 따옴표 이스케이프 변형이 없다.
fn extract_hrefs(xml: &str) -> Vec<String> {
    // [#1891] isEmbeded="0"(외부 파일 참조) 항목의 href 는 ZIP 엔트리가 아니므로
    // 실재 검사 대상에서 제외한다. href/isEmbeded 속성 순서에 의존하지 않도록
    // 태그 단위로 스캔한다.
    let mut hrefs = Vec::new();
    let mut rest = xml;
    while let Some(pos) = rest.find('<') {
        rest = &rest[pos + 1..];
        let Some(end) = rest.find('>') else { break };
        let tag = &rest[..end];
        rest = &rest[end + 1..];
        if tag.contains("isEmbeded=\"0\"") {
            continue;
        }
        if let Some(hpos) = tag.find("href=\"") {
            let after = &tag[hpos + "href=\"".len()..];
            if let Some(hend) = after.find('"') {
                hrefs.push(after[..hend].to_string());
            }
        }
    }
    hrefs
}

fn extract_rdf_resources(xml: &str) -> Vec<String> {
    let mut resources = Vec::new();
    let mut rest = xml;
    while let Some(pos) = rest.find("rdf:resource=\"") {
        rest = &rest[pos + "rdf:resource=\"".len()..];
        if let Some(end) = rest.find('"') {
            resources.push(rest[..end].to_string());
            rest = &rest[end + 1..];
        } else {
            break;
        }
    }
    resources
}

/// 파일명에서 소문자 확장자 추출 (없으면 빈 문자열).
fn extension_lower(name: &str) -> String {
    name.rsplit_once('.')
        .map(|(_, ext)| ext.to_ascii_lowercase())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::bin_data::BinDataContent;
    use crate::serializer::hwpx::serialize_hwpx;

    fn doc_with_sections(n: usize) -> Document {
        let mut doc = Document::default();
        for _ in 0..n {
            doc.sections
                .push(crate::model::document::Section::default());
        }
        doc
    }

    #[test]
    fn empty_doc_package_passes() {
        let doc = Document::default();
        let bytes = serialize_hwpx(&doc).expect("serialize");
        let report = check_package(&bytes, &doc);
        assert!(report.is_ok(), "problems: {}", report.summary());
    }

    #[test]
    fn one_section_package_passes() {
        let doc = doc_with_sections(1);
        let bytes = serialize_hwpx(&doc).expect("serialize");
        let report = check_package(&bytes, &doc);
        assert!(report.is_ok(), "problems: {}", report.summary());
    }

    #[test]
    fn detects_missing_section_entry() {
        // 섹션 0개로 직렬화한 ZIP 을 "섹션 1개 IR" 기준으로 검사 → 누락 검출
        let doc0 = Document::default();
        let bytes = serialize_hwpx(&doc0).expect("serialize");
        let doc1 = doc_with_sections(1);
        let report = check_package(&bytes, &doc1);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("섹션 엔트리 누락"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn detects_extra_section_entry() {
        // 섹션 1개로 직렬화한 ZIP 을 "섹션 0개 IR" 기준으로 검사 → 잉여 검출
        let doc1 = doc_with_sections(1);
        let bytes = serialize_hwpx(&doc1).expect("serialize");
        let doc0 = Document::default();
        let report = check_package(&bytes, &doc0);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("섹션 엔트리 수 불일치"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn detects_bin_data_count_mismatch() {
        // BinData 없는 ZIP 을 "BinData 1개 IR" 기준으로 검사 → 불일치 검출
        let doc0 = Document::default();
        let bytes = serialize_hwpx(&doc0).expect("serialize");
        let mut doc_bin = Document::default();
        doc_bin.bin_data_content.push(BinDataContent {
            id: 1,
            data: vec![1, 2, 3].into(),
            extension: "png".to_string(),
        });
        let report = check_package(&bytes, &doc_bin);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("BinData 엔트리 수 불일치"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn master_page_package_parts_are_required_when_ir_has_master_pages() {
        use crate::model::document::Section;
        use crate::model::header_footer::{HeaderFooterApply, MasterPage};
        use crate::model::paragraph::Paragraph;

        let mut doc = Document::default();
        let mut section = Section::default();
        let mut master_para = Paragraph::default();
        master_para.text = "master".to_string();
        section.section_def.master_pages.push(MasterPage {
            apply_to: HeaderFooterApply::Both,
            text_width: 10_000,
            text_height: 10_000,
            text_ref: 1,
            paragraphs: vec![master_para],
            ..Default::default()
        });
        doc.sections.push(section);

        let bytes = serialize_hwpx(&doc).expect("serialize");
        let report = check_package(&bytes, &doc);
        assert!(report.is_ok(), "problems: {}", report.summary());

        let missing_master_bytes = serialize_hwpx(&doc_with_sections(1)).expect("serialize stale");
        let report = check_package(&missing_master_bytes, &doc);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("바탕쪽 엔트리 수 불일치")
                && report
                    .summary()
                    .contains("content.hpf 바탕쪽 manifest 누락")
                && report.summary().contains("section0 masterPageCnt 불일치"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn detects_container_rdf_section_coverage_mismatch() {
        let stale_bytes = serialize_hwpx(&doc_with_sections(1)).expect("serialize stale");
        let expected_doc = doc_with_sections(2);
        let report = check_package(&stale_bytes, &expected_doc);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("container.rdf 섹션 참조 누락")
                && report
                    .summary()
                    .contains("container.rdf 섹션 참조 수 불일치"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn rejects_non_zip_bytes() {
        let doc = Document::default();
        let report = check_package(b"not a zip at all", &doc);
        assert!(!report.is_ok());
        assert!(
            report.summary().contains("ZIP 열기 실패"),
            "summary: {}",
            report.summary()
        );
    }

    #[test]
    fn section_entry_name_matcher() {
        assert!(is_section_entry_name("Contents/section0.xml"));
        assert!(is_section_entry_name("Contents/section12.xml"));
        assert!(!is_section_entry_name("Contents/section.xml"));
        assert!(!is_section_entry_name("Contents/sectionA.xml"));
        assert!(!is_section_entry_name("Contents/header.xml"));
        assert!(is_master_page_entry_name("Contents/masterpage0.xml"));
        assert!(is_master_page_entry_name("Contents/masterpage12.xml"));
        assert!(!is_master_page_entry_name("Contents/masterpage.xml"));
        assert!(!is_master_page_entry_name("Contents/masterpageA.xml"));
    }

    #[test]
    fn extract_hrefs_basic() {
        let xml = r#"<opf:item href="Contents/header.xml"/><opf:item href="settings.xml"/>"#;
        assert_eq!(
            extract_hrefs(xml),
            vec![
                "Contents/header.xml".to_string(),
                "settings.xml".to_string()
            ]
        );
    }

    #[test]
    fn extract_rdf_resources_basic() {
        let xml = r#"<rdf:type rdf:resource="pkg#Document"/><ns0:hasPart rdf:resource="Contents/section0.xml"/>"#;
        assert_eq!(
            extract_rdf_resources(xml),
            vec![
                "pkg#Document".to_string(),
                "Contents/section0.xml".to_string()
            ]
        );
    }
}