diff --git a/acceleration/internal/api/documents.go b/acceleration/internal/api/documents.go
index 720a8cfe05..32d8a7e2f9 100644
--- a/acceleration/internal/api/documents.go
+++ b/acceleration/internal/api/documents.go
@@ -292,7 +292,11 @@ func documentFailure(err error) error {
}
switch reason {
case extract.TooLarge:
- return documentTooLarge(fmt.Sprintf("the file is larger than a file sent with a question may be (at most %d pages): %v", maxDocumentPages, err))
+ var pages extract.PageLimit
+ if errors.As(err, &pages) {
+ return documentTooLarge(fmt.Sprintf("the file is larger than a file sent with a question may be (at most %d pages): %v", maxDocumentPages, err))
+ }
+ return documentTooLarge(fmt.Sprintf("the file is too large or too deeply nested for a file sent with a question: %v", err))
case extract.Unsupported:
return newAPIError(ErrorTypeUnsupportedMediaType, "the file is no format that can be read: a PDF or a Word document (DOCX or DOC) can be sent")
case extract.Encrypted:
diff --git a/acceleration/internal/api/documents_unit_test.go b/acceleration/internal/api/documents_unit_test.go
new file mode 100644
index 0000000000..bc45428c62
--- /dev/null
+++ b/acceleration/internal/api/documents_unit_test.go
@@ -0,0 +1,85 @@
+package api
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/suite"
+
+ "github.com/GetStream/Vision-Agents/acceleration/internal/knowledge/extract"
+)
+
+// DocumentFailureSuite covers how a refused file is answered to the person who sent it.
+type DocumentFailureSuite struct {
+ suite.Suite
+}
+
+func TestDocumentFailureSuite(t *testing.T) {
+ suite.Run(t, new(DocumentFailureSuite))
+}
+
+// Defect: every too-large refusal said the file had too many pages, so a Word file refused for its
+// nesting told the sender to cut pages that were not the problem.
+func (s *DocumentFailureSuite) TestAFileRefusedForItsNestingIsNotToldItHasTooManyPages() {
+ var archive bytes.Buffer
+ writer := zip.NewWriter(&archive)
+ part, err := writer.Create("word/document.xml")
+ s.Require().NoError(err)
+ _, err = part.Write([]byte(`` +
+ strings.Repeat("", 1<<12) + strings.Repeat("", 1<<12) + ``))
+ s.Require().NoError(err)
+ s.Require().NoError(writer.Close())
+ _, err = NewDocumentReader(extract.Options{}).Extract(context.Background(), "a.docx", archive.Bytes())
+ s.Require().Error(err)
+
+ failure := documentFailure(err)
+
+ var refused APIError
+ s.Require().ErrorAs(failure, &refused)
+ s.Equal(codeDocumentTooLarge, refused.Code)
+ s.Contains(refused.Message, "nested")
+ s.NotContains(refused.Message, "pages")
+}
+
+func (s *DocumentFailureSuite) TestAFileOverThePageLimitIsToldHowManyPagesAreRead() {
+ data, err := os.ReadFile("../knowledge/extract/testdata/manual.pdf")
+ s.Require().NoError(err)
+ _, err = extract.New(extract.Options{MaxPages: 1}).Extract(context.Background(), "manual.pdf", data)
+ s.Require().Error(err)
+
+ failure := documentFailure(err)
+
+ var refused APIError
+ s.Require().ErrorAs(failure, &refused)
+ s.Equal(codeDocumentTooLarge, refused.Code)
+ s.Contains(refused.Message, "(at most 100 pages)")
+}
+
+// Defect: a Word file with more pages than the limit was refused by the generic too-large wording,
+// so the sender was not told how many pages are read.
+func (s *DocumentFailureSuite) TestAWordFileOverThePageLimitIsToldHowManyPagesAreRead() {
+ var archive bytes.Buffer
+ writer := zip.NewWriter(&archive)
+ part, err := writer.Create("word/document.xml")
+ s.Require().NoError(err)
+ _, err = part.Write([]byte(`` +
+ `one` +
+ `two` +
+ `three` +
+ ``))
+ s.Require().NoError(err)
+ s.Require().NoError(writer.Close())
+ _, err = extract.New(extract.Options{MaxPages: 1}).Extract(context.Background(), "a.docx", archive.Bytes())
+ s.Require().Error(err)
+
+ failure := documentFailure(err)
+
+ var refused APIError
+ s.Require().ErrorAs(failure, &refused)
+ s.Equal(codeDocumentTooLarge, refused.Code)
+ s.Contains(refused.Message, "(at most 100 pages)")
+}
diff --git a/acceleration/internal/knowledge/extract/docx.go b/acceleration/internal/knowledge/extract/docx.go
index b9b08c363c..2ec0b4fb3e 100644
--- a/acceleration/internal/knowledge/extract/docx.go
+++ b/acceleration/internal/knowledge/extract/docx.go
@@ -80,14 +80,14 @@ func wordImages(data []byte) (map[string]string, error) {
if data == nil {
return images, nil
}
- decoder := xml.NewDecoder(bytes.NewReader(data))
+ decoder := newDocumentDecoder(data)
for {
token, err := decoder.Token()
if errors.Is(err, io.EOF) {
return images, nil
}
if err != nil {
- return nil, fail(Corrupt, DOCX, fmt.Errorf("document.xml.rels: %w", err))
+ return nil, xmlFailure(DOCX, fmt.Errorf("document.xml.rels: %w", err))
}
element, ok := token.(xml.StartElement)
if !ok || element.Name.Local != "Relationship" || attr(element, "TargetMode") == "External" ||
@@ -109,7 +109,7 @@ func wordStyles(data []byte) (map[string]wordStyle, error) {
if data == nil {
return styles, nil
}
- decoder := xml.NewDecoder(bytes.NewReader(data))
+ decoder := newDocumentDecoder(data)
var id string
var current wordStyle
for {
@@ -118,7 +118,7 @@ func wordStyles(data []byte) (map[string]wordStyle, error) {
return styles, nil
}
if err != nil {
- return nil, fail(Corrupt, DOCX, fmt.Errorf("styles.xml: %w", err))
+ return nil, xmlFailure(DOCX, fmt.Errorf("styles.xml: %w", err))
}
switch element := token.(type) {
case xml.StartElement:
@@ -154,7 +154,7 @@ func wordBullets(data []byte) (map[string]map[int]bool, error) {
if data == nil {
return out, nil
}
- decoder := xml.NewDecoder(bytes.NewReader(data))
+ decoder := newDocumentDecoder(data)
abstract := map[string]map[int]bool{}
lists := map[string]string{}
var abstractID, numID string
@@ -165,7 +165,7 @@ func wordBullets(data []byte) (map[string]map[int]bool, error) {
break
}
if err != nil {
- return nil, fail(Corrupt, DOCX, fmt.Errorf("numbering.xml: %w", err))
+ return nil, xmlFailure(DOCX, fmt.Errorf("numbering.xml: %w", err))
}
element, ok := token.(xml.StartElement)
if !ok {
@@ -224,7 +224,7 @@ type wordReader struct {
}
func (w *wordReader) read(ctx context.Context, body []byte) error {
- decoder := xml.NewDecoder(bytes.NewReader(body))
+ decoder := newDocumentDecoder(body)
// skip is how deep the reader is in something that is not text a reader sees: a
// deletion kept for review, a field's code, a footnote's number.
skip := 0
diff --git a/acceleration/internal/knowledge/extract/extract.go b/acceleration/internal/knowledge/extract/extract.go
index ac7d374e2a..92920b7265 100644
--- a/acceleration/internal/knowledge/extract/extract.go
+++ b/acceleration/internal/knowledge/extract/extract.go
@@ -191,16 +191,32 @@ func ReasonOf(err error) (Reason, bool) {
return "", false
}
+// PageLimit is the error of a file with more pages than are allowed, among the TooLarge ones.
+type PageLimit struct{ error }
+
+func (p PageLimit) Unwrap() error { return p.error }
+
func fail(reason Reason, format Format, err error) error {
return stack.Wrap(&Error{Reason: reason, Format: format, Err: err})
}
-// unreadable is err from reading a file's content: the deadline when reading was stopped
-// by it, and otherwise a file that is corrupt.
+// unreadable turns an error from reading a file's content into an extract error: the deadline
+// when reading was stopped by it, TooLarge when the file went past a limit such as nesting,
+// and Corrupt otherwise.
func unreadable(ctx context.Context, format Format, err error) error {
if ctx.Err() != nil {
return stack.Wrap(fmt.Errorf("extract: read the %s: %w", format, ctx.Err()))
}
+ return xmlFailure(format, err)
+}
+
+// xmlFailure turns an error from reading the XML of a file into an extract error: TooLarge when
+// the XML is nested too deep, Corrupt otherwise.
+func xmlFailure(format Format, err error) error {
+ var over overLimit
+ if errors.As(err, &over) {
+ return fail(TooLarge, format, err)
+ }
return fail(Corrupt, format, err)
}
@@ -301,7 +317,7 @@ func (e *Extractor) Extract(ctx context.Context, name string, data []byte) (Docu
return Document{}, err
}
if len(document.Pages) > e.options.MaxPages {
- return Document{}, fail(TooLarge, format, fmt.Errorf("%s has %d pages, more than the %d allowed", name, len(document.Pages), e.options.MaxPages))
+ return Document{}, fail(TooLarge, format, PageLimit{fmt.Errorf("%s has %d pages, more than the %d allowed", name, len(document.Pages), e.options.MaxPages)})
}
document.Format = format
return document, nil
diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go
index 147df382ab..fb0cf201e0 100644
--- a/acceleration/internal/knowledge/extract/extract_test.go
+++ b/acceleration/internal/knowledge/extract/extract_test.go
@@ -1568,7 +1568,7 @@ func (s *ExtractSuite) TestAPartNestedPastTheLimitIsRefusedBeforeItIsDecoded() {
runtime.ReadMemStats(&after)
s.requireReason(err, TooLarge)
- s.Contains(err.Error(), "nested", name)
+ s.Contains(err.Error(), "deeper than a spreadsheet program writes them", name)
// The refused read allocates for the levels it reads up to the limit, a few KiB, and
// reading every level allocates more than a hundred bytes for each. The length of the part
// is far between the two.
@@ -1576,6 +1576,135 @@ func (s *ExtractSuite) TestAPartNestedPastTheLimitIsRefusedBeforeItIsDecoded() {
}
}
+const (
+ wordNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"`
+ odfNS = `xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"`
+)
+
+// wordPart is a Word document with a part of it replaced.
+func (s *ExtractSuite) wordPart(name, xml string) []byte {
+ return s.rezip(s.fixture("handbook.docx"), map[string][]byte{name: []byte(xml)})
+}
+
+// openDocumentPart is an OpenDocument text with a part of it replaced.
+func (s *ExtractSuite) openDocumentPart(name, xml string) []byte {
+ return s.rezip(s.fixture("handbook.odt"), map[string][]byte{name: []byte(xml)})
+}
+
+// An element nested far deeper than the limit makes a small Word or OpenDocument file, and
+// encoding/xml keeps every level that is still open as it reads it. Each part the reader decodes is
+// refused when it is too deep, whichever of them holds the elements.
+func (s *ExtractSuite) TestAWordOrOpenDocumentPartNestedPastTheLimitIsRefusedBeforeItIsDecoded() {
+ nested := s.deep(1 << 18)
+ for name, test := range map[string]struct {
+ file string
+ data []byte
+ }{
+ "the Word body": {"a.docx", s.wordPart("word/document.xml", ``+nested+``)},
+ "the Word styles": {"a.docx", s.wordPart("word/styles.xml", ``+nested+``)},
+ "the Word numbering": {"a.docx", s.wordPart("word/numbering.xml", ``+nested+``)},
+ "the Word relationships": {"a.docx", s.wordPart("word/_rels/document.xml.rels", ``+nested+``)},
+ "the OpenDocument body": {"a.odt", s.openDocumentPart("content.xml", ``+nested+``)},
+ "the OpenDocument styles": {"a.odt", s.openDocumentPart("styles.xml", ``+nested+``)},
+ } {
+ s.Less(len(test.data), 128<<10, "%s: the file is small", name)
+
+ var before, after runtime.MemStats
+ runtime.GC()
+ runtime.ReadMemStats(&before)
+ _, err := s.extractor.Extract(context.Background(), test.file, test.data)
+ runtime.ReadMemStats(&after)
+
+ s.requireReason(err, TooLarge)
+ s.Contains(err.Error(), "deeper than a word processor writes them", name)
+ // Reading the part out of the archive and the rest of the file allocates two to three times the
+ // part's length. Reading every level of it allocates more than a hundred bytes for each, which
+ // is over fourteen times it.
+ s.Less(after.TotalAlloc-before.TotalAlloc, uint64(6*len(nested)), name)
+ }
+}
+
+// The body of an OpenDocument text is counted by its own reader, whatever the list styles read
+// of it before. A reader that went on without its cap would hold every level that is open.
+func (s *ExtractSuite) TestTheOpenDocumentBodyReaderRefusesABodyNestedPastTheLimit() {
+ body := `` + s.deep(1<<18) + ``
+
+ err := (&odtReader{}).read(context.Background(), []byte(body))
+
+ var over overLimit
+ s.Require().ErrorAs(err, &over)
+ s.Contains(err.Error(), "nested")
+}
+
+// A reader that went on after the limit was passed would read the rest of the part as if the
+// elements that follow were within it.
+func (s *ExtractSuite) TestAPartStaysRefusedOnceItIsNestedPastTheLimit() {
+ tokens := &depthTokens{raw: xml.NewDecoder(strings.NewReader(strings.Repeat("", maxXMLDepth+1) + "")), nesting: nesting{what: "document", writer: "a word processor"}}
+ var first error
+ for first == nil {
+ _, first = tokens.Token()
+ }
+
+ for range 3 {
+ _, err := tokens.Token()
+
+ s.Equal(first, err)
+ }
+}
+
+// A part that is broken, and not nested too deep, is a corrupt file: only nesting is too large.
+func (s *ExtractSuite) TestABrokenWordOrOpenDocumentPartIsRefusedAsCorrupt() {
+ for name, test := range map[string]struct {
+ file string
+ data []byte
+ }{
+ "a Word body closed by the wrong tag": {"a.docx", s.wordPart("word/document.xml", ``)},
+ "a Word body that ends open": {"a.docx", s.wordPart("word/document.xml", ``)},
+ "Word styles": {"a.docx", s.wordPart("word/styles.xml", ``)},
+ "Word numbering": {"a.docx", s.wordPart("word/numbering.xml", ``)},
+ "Word relationships": {"a.docx", s.wordPart("word/_rels/document.xml.rels", ``)},
+ "an OpenDocument body": {"a.odt", s.openDocumentPart("content.xml", ``)},
+ "OpenDocument styles": {"a.odt", s.openDocumentPart("styles.xml", ``)},
+ } {
+ _, err := s.extractor.Extract(context.Background(), test.file, test.data)
+
+ s.requireReason(err, Corrupt)
+ s.NotContains(err.Error(), "nested", name)
+ }
+}
+
+// An element of a Word or OpenDocument part may be nested as deep as the limit, counted from the
+// part's root, and no deeper.
+func (s *ExtractSuite) TestAWordOrOpenDocumentElementMayBeNestedAsDeepAsTheLimit() {
+ // Elements that follow one another are not nested, however many there are.
+ siblings := strings.Repeat("", 2*maxXMLDepth)
+ for _, test := range []struct {
+ file string
+ data func(levels int) []byte
+ // root is how many elements enclose the nested ones, and inner how many hold the text.
+ root, inner int
+ }{
+ {"a.docx", func(levels int) []byte {
+ return s.wordPart("word/document.xml", ``+strings.Repeat("", levels)+`Deep text`+strings.Repeat("", levels)+siblings+``)
+ }, 2, 3},
+ {"a.odt", func(levels int) []byte {
+ return s.openDocumentPart("content.xml", ``+strings.Repeat("", levels)+`Deep text`+strings.Repeat("", levels)+siblings+``)
+ }, 3, 1},
+ } {
+ for _, past := range []bool{false, true} {
+ levels := maxXMLDepth - test.root - test.inner + btoi(past)
+ read, err := s.extractor.Extract(context.Background(), test.file, test.data(levels))
+
+ if past {
+ s.requireReason(err, TooLarge)
+ continue
+ }
+ s.Require().NoError(err, test.file)
+ s.Contains(read.Pages[0].Text, "Deep text", test.file)
+ }
+ }
+}
+
// An element may be nested as deep as the limit, counted from the part's root, and no deeper.
func (s *ExtractSuite) TestAnElementMayBeNestedAsDeepAsTheLimit() {
for _, test := range []struct {
diff --git a/acceleration/internal/knowledge/extract/odt.go b/acceleration/internal/knowledge/extract/odt.go
index 081f246001..43e78dd695 100644
--- a/acceleration/internal/knowledge/extract/odt.go
+++ b/acceleration/internal/knowledge/extract/odt.go
@@ -66,7 +66,7 @@ func odtListStyles(data []byte, bullets map[string]map[int]bool) error {
if data == nil {
return nil
}
- decoder := xml.NewDecoder(bytes.NewReader(data))
+ decoder := newDocumentDecoder(data)
style := ""
for {
token, err := decoder.Token()
@@ -74,7 +74,7 @@ func odtListStyles(data []byte, bullets map[string]map[int]bool) error {
return nil
}
if err != nil {
- return fail(Corrupt, ODT, err)
+ return xmlFailure(ODT, err)
}
element, ok := token.(xml.StartElement)
if !ok {
@@ -111,7 +111,7 @@ type odtReader struct {
}
func (o *odtReader) read(ctx context.Context, content []byte) error {
- decoder := xml.NewDecoder(bytes.NewReader(content))
+ decoder := newDocumentDecoder(content)
body := false
// skip is how deep the reader is in something that is not text a reader sees: a
// footnote, a comment, a change kept for review.
diff --git a/acceleration/internal/knowledge/extract/pdf.go b/acceleration/internal/knowledge/extract/pdf.go
index edb597bc22..4c2cffa89e 100644
--- a/acceleration/internal/knowledge/extract/pdf.go
+++ b/acceleration/internal/knowledge/extract/pdf.go
@@ -404,7 +404,7 @@ func (e *Extractor) readPDF(ctx context.Context, data []byte) (Document, error)
return Document{}, fail(Corrupt, PDF, fmt.Errorf("the pages cannot be counted: %w", err))
}
if count.PageCount > e.options.MaxPages {
- return Document{}, fail(TooLarge, PDF, fmt.Errorf("the PDF has %d pages, more than the %d allowed", count.PageCount, e.options.MaxPages))
+ return Document{}, fail(TooLarge, PDF, PageLimit{fmt.Errorf("the PDF has %d pages, more than the %d allowed", count.PageCount, e.options.MaxPages)})
}
pages := make([]pdfPage, 0, count.PageCount)
diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go
index 1f82e4a0f8..79652679f6 100644
--- a/acceleration/internal/knowledge/extract/xlsx.go
+++ b/acceleration/internal/knowledge/extract/xlsx.go
@@ -52,7 +52,7 @@ const maxWorkbookText = 2 * maxUnzipped
// that grows with the square of its length for each cell it is on.
const maxFormatCode = 255
-// maxXMLDepth is the deepest an element of a workbook part may be nested. encoding/xml keeps every
+// maxXMLDepth is the deepest an element of a workbook, Word or OpenDocument part may be nested. encoding/xml keeps every
// element that is still open, so a part nested deep enough holds far more memory than it is long.
// 256 is libxml2's default limit (xmlParserMaxDepth), set for the same reason.
const maxXMLDepth = 256
@@ -367,7 +367,7 @@ func (c *cellCount) part(file *zip.File, counts *tally, read func(*xml.Decoder)
return err
}
defer r.Close()
- tokens := &limitedTokens{guard: newTagGuard(r), counts: counts, tick: c.tick}
+ tokens := &limitedTokens{guard: newTagGuard(r), counts: counts, tick: c.tick, nesting: nesting{what: "workbook", writer: "a spreadsheet program"}}
tokens.raw = xml.NewDecoder(tokens.guard)
tokens.raw.CharsetReader = func(label string, input io.Reader) (io.Reader, error) {
// The decoder reads the decoded text from here on, so a new guard reads that text: a byte in
@@ -386,8 +386,9 @@ func (c *cellCount) part(file *zip.File, counts *tally, read func(*xml.Decoder)
return tokens.err
}
-// overLimit is a workbook past one of the limits the count checks: its size, elements, nesting,
-// runs, or the length or attributes of a tag.
+// overLimit is a document past one of the limits the count checks: its size, elements, nesting,
+// runs, or the length or attributes of a tag. Workbooks reach all of them, Word and OpenDocument
+// files only the nesting.
type overLimit struct{ error }
// limitedTokens hands a part's tokens to the decoder and stops after the first element that passes
@@ -407,7 +408,7 @@ type limitedTokens struct {
tick func() error
// counts is the count this part adds to.
counts *tally
- depth int
+ nesting
// rows is, for each open element, whether it is a row.
rows []bool
// inCells is the depth of the outermost element holding cells being read (a sheet's cells, the
@@ -439,7 +440,7 @@ func (l *limitedTokens) Token() (xml.Token, error) {
}
switch element := token.(type) {
case xml.StartElement:
- l.depth++
+ l.err = l.enter()
l.counts.elements++
name := element.Name.Local
if name == "c" && len(l.rows) > 0 && l.rows[len(l.rows)-1] {
@@ -463,7 +464,9 @@ func (l *limitedTokens) Token() (xml.Token, error) {
case l.inString != 0 && l.depth == l.inString+1 && name == "rPh":
l.phonetic++
}
- l.err = l.limit()
+ if l.err == nil {
+ l.err = l.limit()
+ }
case xml.EndElement:
if l.depth == l.inString {
l.inString = 0
@@ -472,7 +475,7 @@ func (l *limitedTokens) Token() (xml.Token, error) {
l.inCells = 0
}
l.rows = l.rows[:max(len(l.rows)-1, 0)]
- l.depth--
+ l.leave()
}
return token, err
}
@@ -480,8 +483,6 @@ func (l *limitedTokens) Token() (xml.Token, error) {
// limit is the error of the first limit the part is past, or nil.
func (l *limitedTokens) limit() error {
switch {
- case l.depth > maxXMLDepth:
- return overLimit{fmt.Errorf("the workbook has XML elements nested more than %d deep, deeper than a spreadsheet program writes them", maxXMLDepth)}
case l.counts.elements > maxWorkbookElements:
return overLimit{fmt.Errorf("the workbook has more than the %d XML elements allowed. Split it into smaller workbooks", maxWorkbookElements)}
case l.counts.rows > maxWorkbookCells || l.counts.cells > maxWorkbookCells:
diff --git a/acceleration/internal/knowledge/extract/xmldepth.go b/acceleration/internal/knowledge/extract/xmldepth.go
new file mode 100644
index 0000000000..211b46304d
--- /dev/null
+++ b/acceleration/internal/knowledge/extract/xmldepth.go
@@ -0,0 +1,63 @@
+package extract
+
+import (
+ "bytes"
+ "encoding/xml"
+ "fmt"
+)
+
+// nesting counts how deep the open elements of a part are, so that a part nested deeper than
+// maxXMLDepth can be refused. The workbook reader and the Word and OpenDocument readers count with it.
+type nesting struct {
+ depth int
+ // what names the file in the error message, such as "workbook", and writer the program that
+ // writes such files, such as "a spreadsheet program".
+ what, writer string
+}
+
+// enter counts an element that opens. It returns an overLimit error once the element is nested
+// deeper than maxXMLDepth.
+func (n *nesting) enter() error {
+ n.depth++
+ if n.depth > maxXMLDepth {
+ return overLimit{fmt.Errorf("the %s has XML elements nested more than %d deep, deeper than %s writes them", n.what, maxXMLDepth, n.writer)}
+ }
+ return nil
+}
+
+// leave counts an element that closes.
+func (n *nesting) leave() {
+ n.depth--
+}
+
+// depthTokens counts the nesting of a part before the XML decoder sees it, and stops at the first
+// element nested deeper than maxXMLDepth. It reads raw tokens, which keep no stack of open
+// elements, so no stack grows past the limit.
+type depthTokens struct {
+ raw *xml.Decoder
+ nesting
+ // err is the first error, kept so that a reader that goes on after it is refused again.
+ err error
+}
+
+func (d *depthTokens) Token() (xml.Token, error) {
+ if d.err != nil {
+ return nil, d.err
+ }
+ token, err := d.raw.RawToken()
+ switch token.(type) {
+ case xml.StartElement:
+ if d.err = d.enter(); d.err != nil {
+ return nil, d.err
+ }
+ case xml.EndElement:
+ d.leave()
+ }
+ return token, err
+}
+
+// newDocumentDecoder reads a part of a Word or OpenDocument file as XML. A part nested deeper than
+// maxXMLDepth fails with an overLimit error, which unreadable and xmlFailure report as too large.
+func newDocumentDecoder(part []byte) *xml.Decoder {
+ return xml.NewTokenDecoder(&depthTokens{raw: xml.NewDecoder(bytes.NewReader(part)), nesting: nesting{what: "document", writer: "a word processor"}})
+}