Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/XML.swift3// Description: Small XML layer for the DOCX engine: a defensive tree parser on top of Foundation's XMLParser4// (no DTD, no external entities, size / depth / node caps, namespace prefixes canonicalised) and an escaping writer.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocContainer1011/// Limits applied to every XML part of a package.12struct XMLLimits: Sendable {13 var maxBytes = 96 * 1024 * 102414 var maxDepth = 25615 var maxNodes = 4_000_00016 static let standard = XMLLimits()17}1819/// An element of a parsed XML tree. `name` is the canonical qualified name ("w:p"): the prefix is derived from the20/// namespace URI, so documents that bind unusual prefixes (or the ISO "strict" namespaces) read the same way.21final class XMLNode {22 let name: String23 var attrs: [String: String]24 var children: [XMLNode] = []25 /// Character data directly inside the element (concatenated).26 var text: String = ""2728 init(name: String, attrs: [String: String] = [:]) { self.name = name; self.attrs = attrs }2930 func attr(_ name: String) -> String? { attrs[name] }31 func first(_ name: String) -> XMLNode? { children.first { $0.name == name } }32 func all(_ name: String) -> [XMLNode] { children.filter { $0.name == name } }33 /// Follows a path of child names.34 func path(_ names: String...) -> XMLNode? {35 var cur: XMLNode? = self36 for n in names { cur = cur?.first(n) }37 return cur38 }39 /// `w:val` of a child element.40 func val(_ child: String, _ attribute: String = "w:val") -> String? { first(child)?.attrs[attribute] }4142 /// First descendant with the given name (depth first), self excluded.43 func firstDescendant(_ name: String) -> XMLNode? {44 var stack = Array(children.reversed())45 while let n = stack.popLast() {46 if n.name == name { return n }47 stack.append(contentsOf: n.children.reversed())48 }49 return nil50 }51 /// Every descendant with the given name in document order; does not descend into matches.52 func descendants(_ name: String) -> [XMLNode] {53 var out: [XMLNode] = []54 var stack = Array(children.reversed())55 while let n = stack.popLast() {56 if n.name == name { out.append(n); continue }57 stack.append(contentsOf: n.children.reversed())58 }59 return out60 }61 /// All character data below this element, in document order.62 var deepText: String {63 var out = text64 for c in children { out += c.deepText }65 return out66 }6768 /// Serialises the subtree (canonical prefixes, no namespace declarations).69 func serialized() -> String {70 var s = "<" + name71 for k in attrs.keys.sorted() { s += " \(k)=\"\(XMLEscape.attr(attrs[k]!))\"" }72 if children.isEmpty && text.isEmpty { return s + "/>" }73 s += ">"74 if children.isEmpty { s += XMLEscape.text(text) } else { for c in children { s += c.serialized() } }75 return s + "</\(name)>"76 }77}7879enum XMLEscape {80 /// Removes the characters XML 1.0 cannot carry.81 static func clean(_ s: String) -> String {82 var needs = false83 for u in s.unicodeScalars where !isValid(u) { needs = true; break }84 guard needs else { return s }85 var out = String.UnicodeScalarView()86 for u in s.unicodeScalars where isValid(u) { out.append(u) }87 return String(out)88 }89 static func isValid(_ u: Unicode.Scalar) -> Bool {90 let v = u.value91 return v == 0x9 || v == 0xA || v == 0xD || (v >= 0x20 && v <= 0xD7FF) || (v >= 0xE000 && v <= 0xFFFD) || v >= 0x1000092 }93 static func text(_ s: String) -> String {94 var out = ""95 out.reserveCapacity(s.utf8.count + 8)96 for u in s.unicodeScalars where isValid(u) {97 switch u {98 case "&": out += "&"99 case "<": out += "<"100 case ">": out += ">"101 case "\r": out += " "102 default: out.unicodeScalars.append(u)103 }104 }105 return out106 }107 static func attr(_ s: String) -> String {108 var out = ""109 out.reserveCapacity(s.utf8.count + 8)110 for u in s.unicodeScalars where isValid(u) {111 switch u {112 case "&": out += "&"113 case "<": out += "<"114 case ">": out += ">"115 case "\"": out += """116 case "\n": out += " "117 case "\r": out += " "118 case "\t": out += "	"119 default: out.unicodeScalars.append(u)120 }121 }122 return out123 }124}125126/// Builds an element string. `attrs` keep their order; nil values are skipped.127func xmlTag(_ name: String, _ attrs: [(String, String?)] = [], _ body: String? = nil) -> String {128 var s = "<" + name129 for (k, v) in attrs { if let v { s += " \(k)=\"\(XMLEscape.attr(v))\"" } }130 guard let body else { return s + "/>" }131 return s + ">" + body + "</\(name)>"132}133134let xmlDeclaration = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"135136/// Namespace URI → canonical prefix. Both the transitional (ECMA-376) and the strict (ISO 29500) URIs are known.137enum XMLNS {138 static let w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"139 static let r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"140 static let m = "http://schemas.openxmlformats.org/officeDocument/2006/math"141 static let wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"142 static let a = "http://schemas.openxmlformats.org/drawingml/2006/main"143 static let pic = "http://schemas.openxmlformats.org/drawingml/2006/picture"144 static let mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"145 static let w14 = "http://schemas.microsoft.com/office/word/2010/wordml"146 static let w15 = "http://schemas.microsoft.com/office/word/2012/wordml"147 static let wps = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"148 static let v = "urn:schemas-microsoft-com:vml"149 static let o = "urn:schemas-microsoft-com:office:office"150 static let w10 = "urn:schemas-microsoft-com:office:word"151 static let rel = "http://schemas.openxmlformats.org/package/2006/relationships"152 static let ct = "http://schemas.openxmlformats.org/package/2006/content-types"153 static let cp = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"154 static let dc = "http://purl.org/dc/elements/1.1/"155 static let dcterms = "http://purl.org/dc/terms/"156 static let xsi = "http://www.w3.org/2001/XMLSchema-instance"157 static let orix = "https://spboucher.ai/ns/orixdocs/docx/1"158159 static let prefixes: [String: String] = [160 w: "w", "http://purl.oclc.org/ooxml/wordprocessingml/main": "w",161 r: "r", "http://purl.oclc.org/ooxml/officeDocument/relationships": "r",162 m: "m", "http://purl.oclc.org/ooxml/officeDocument/math": "m",163 wp: "wp", "http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing": "wp",164 a: "a", "http://purl.oclc.org/ooxml/drawingml/main": "a",165 pic: "pic", "http://purl.oclc.org/ooxml/drawingml/picture": "pic",166 mc: "mc", w14: "w14", w15: "w15", wps: "wps", v: "v", o: "o", w10: "w10",167 "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup": "wpg",168 "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas": "wpc",169 "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing": "wp14",170 "http://schemas.openxmlformats.org/drawingml/2006/chart": "c",171 "http://schemas.openxmlformats.org/drawingml/2006/diagram": "dgm",172 "http://schemas.microsoft.com/office/word/2016/wordml/cid": "w16cid",173 "http://schemas.microsoft.com/office/word/2018/wordml/cex": "w16cex",174 rel: "rel", ct: "ct", cp: "cp", dc: "dc", dcterms: "dcterms", xsi: "xsi",175 "http://schemas.openxmlformats.org/officeDocument/2006/bibliography": "b",176 "http://schemas.openxmlformats.org/officeDocument/2006/customXml": "ds",177 "http://www.w3.org/XML/1998/namespace": "xml",178 orix: "orix",179 ]180}181182enum XMLTree {183 /// Parses one XML part. Throws `FormatError` for anything unsafe or malformed.184 static func parse(_ data: Data, part: String = "XML", limits: XMLLimits = .standard) throws -> XMLNode {185 guard data.count <= limits.maxBytes else { throw FormatError.tooLarge("\(part) is \(data.count) bytes of XML") }186 var utf8 = data187 // UTF-16 parts are transcoded so the DOCTYPE scan below sees them.188 if data.count >= 2, (data[data.startIndex] == 0xFF && data[data.startIndex + 1] == 0xFE) || (data[data.startIndex] == 0xFE && data[data.startIndex + 1] == 0xFF) {189 guard var s = String(data: data, encoding: .utf16) else { throw FormatError.unreadable("\(part) is not valid UTF-16") }190 if s.hasPrefix("<?xml"), let end = s.range(of: "?>") { s.removeSubrange(s.startIndex..<end.upperBound) }191 utf8 = Data(s.utf8)192 }193 // OOXML never needs a DTD; refusing them outright removes entity-expansion and external-entity attacks.194 if utf8.range(of: Data("<!DOCTYPE".utf8)) != nil || utf8.range(of: Data("<!ENTITY".utf8)) != nil {195 throw FormatError.unreadable("\(part) contains a document type declaration, which is not allowed in an Office document")196 }197 let parser = XMLParser(data: utf8)198 parser.shouldResolveExternalEntities = false199 parser.shouldProcessNamespaces = true200 parser.shouldReportNamespacePrefixes = true201 let builder = TreeBuilder(limits: limits)202 parser.delegate = builder203 let ok = parser.parse()204 if let f = builder.failure { throw f }205 guard ok, let root = builder.root else {206 throw FormatError.unreadable("\(part) is not well-formed XML (\(parser.parserError?.localizedDescription ?? "unknown error"))")207 }208 return root209 }210211 private final class TreeBuilder: NSObject, XMLParserDelegate {212 let limits: XMLLimits213 var root: XMLNode?214 var stack: [XMLNode] = []215 var prefixMap: [String: [String]] = [:]216 var nodes = 0217 var failure: FormatError?218219 init(limits: XMLLimits) { self.limits = limits }220221 func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) {222 prefixMap[prefix, default: []].append(namespaceURI)223 }224 func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) {225 if prefixMap[prefix]?.isEmpty == false { prefixMap[prefix]!.removeLast() }226 }227228 func canonical(_ qName: String, namespaceURI: String?, isAttribute: Bool) -> String {229 let parts = qName.split(separator: ":", maxSplits: 1)230 let local = String(parts.last ?? "")231 if isAttribute {232 guard parts.count == 2 else { return qName }233 let prefix = String(parts[0])234 if prefix == "xml" || prefix == "xmlns" { return qName }235 if let uri = prefixMap[prefix]?.last, let canon = XMLNS.prefixes[uri] { return canon + ":" + local }236 return qName237 }238 if let uri = namespaceURI, !uri.isEmpty {239 if let canon = XMLNS.prefixes[uri] { return canon + ":" + local }240 return parts.count == 2 ? qName : local241 }242 return qName243 }244245 func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {246 nodes += 1247 if stack.count >= limits.maxDepth { failure = .tooLarge("XML nesting deeper than \(limits.maxDepth) levels"); parser.abortParsing(); return }248 if nodes > limits.maxNodes { failure = .tooLarge("more than \(limits.maxNodes) XML elements in one part"); parser.abortParsing(); return }249 var attrs: [String: String] = [:]250 attrs.reserveCapacity(attributeDict.count)251 for (k, v) in attributeDict where !k.hasPrefix("xmlns") { attrs[canonical(k, namespaceURI: nil, isAttribute: true)] = v }252 let node = XMLNode(name: canonical(qName ?? elementName, namespaceURI: namespaceURI, isAttribute: false), attrs: attrs)253 if let parent = stack.last { parent.children.append(node) } else { root = node }254 stack.append(node)255 }256 func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {257 if !stack.isEmpty { stack.removeLast() }258 }259 func parser(_ parser: XMLParser, foundCharacters string: String) { stack.last?.text += string }260 func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { stack.last?.text += String(decoding: CDATABlock, as: UTF8.self) }261 func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? { Data() }262 }263}264