| 1 | package xml |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/xml" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/tomwright/dasel/v3/model" |
| 12 | "github.com/tomwright/dasel/v3/parsing" |
| 13 | ) |
| 14 | |
| 15 | // Security limits for XML parsing to prevent DoS attacks. |
| 16 | // These limits are intentionally conservative to balance usability and safety. |
| 17 | const ( |
| 18 | maxCommentLength = 10_000 // Maximum bytes per comment (10KB) - prevents memory exhaustion from single large comments |
| 19 | maxTotalComments = 1_000 // Maximum comments per document - prevents abuse via comment flooding |
| 20 | maxXMLSize = 10_000_000 // Maximum XML input size (10MB) - prevents processing of excessively large files |
| 21 | maxXMLDepth = 10_000 // Maximum element nesting depth - prevents stack overflow from deeply nested documents |
| 22 | ) |
| 23 | |
| 24 | // ErrXMLMaxDepthExceeded is returned when XML nesting depth exceeds maxXMLDepth. |
| 25 | var ErrXMLMaxDepthExceeded = errors.New("xml nesting depth exceeded") |
| 26 | |
| 27 | func newXMLReader(options parsing.ReaderOptions) (parsing.Reader, error) { |
| 28 | return &xmlReader{ |
| 29 | structured: options.Ext["xml-mode"] == "structured", |
| 30 | }, nil |
| 31 | } |
| 32 | |
| 33 | type xmlReader struct { |
| 34 | structured bool |
| 35 | } |
| 36 | |
| 37 | // Read reads a value from a byte slice. |
| 38 | func (j *xmlReader) Read(data []byte) (*model.Value, error) { |
| 39 | if len(data) > maxXMLSize { |
| 40 | return nil, fmt.Errorf("XML input exceeds maximum size of %d bytes", maxXMLSize) |
| 41 | } |
| 42 | |
| 43 | decoder := xml.NewDecoder(bytes.NewReader(data)) |
| 44 | decoder.Strict = true |
| 45 | |
| 46 | totalComments := 0 |
| 47 | el, err := j.parseElement(decoder, xml.StartElement{ |
| 48 | Name: xml.Name{ |
| 49 | Local: "root", |
| 50 | }, |
| 51 | }, &totalComments, 0) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | |
| 56 | if j.structured { |
| 57 | return el.toStructuredModel() |
| 58 | } |
| 59 | return el.toFriendlyModel() |
| 60 | } |
| 61 | |
| 62 | func (e *xmlElement) toStructuredModel() (*model.Value, error) { |
| 63 | attrs := model.NewMapValue() |
| 64 | for _, attr := range e.Attrs { |
| 65 | if err := attrs.SetMapKey(attr.Name, model.NewStringValue(attr.Value)); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | } |
| 69 | res := model.NewMapValue() |
| 70 | if len(e.ProcessingInstructions) > 0 { |
| 71 | res.SetMetadataValue("xml_processing_instructions", e.ProcessingInstructions) |
| 72 | } |
| 73 | if len(e.Comments) > 0 { |
| 74 | res.SetMetadataValue("xml_comments", e.Comments) |
| 75 | } |
| 76 | if err := res.SetMapKey("name", model.NewStringValue(e.Name)); err != nil { |
| 77 | return nil, err |
| 78 | } |
| 79 | if err := res.SetMapKey("attrs", attrs); err != nil { |
| 80 | return nil, err |
| 81 | } |
| 82 | |
| 83 | if err := res.SetMapKey("content", model.NewStringValue(e.Content)); err != nil { |
| 84 | return nil, err |
| 85 | } |
| 86 | children := model.NewSliceValue() |
| 87 | for _, child := range e.Children { |
| 88 | childModel, err := child.toStructuredModel() |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | if err := children.Append(childModel); err != nil { |
| 93 | return nil, err |
| 94 | } |
| 95 | } |
| 96 | if err := res.SetMapKey("children", children); err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | return res, nil |
| 100 | } |
| 101 | |
| 102 | func (e *xmlElement) toFriendlyModel() (*model.Value, error) { |
| 103 | if len(e.Attrs) == 0 && len(e.Children) == 0 && len(e.Comments) == 0 { |
| 104 | return model.NewStringValue(e.Content), nil |
| 105 | } |
| 106 | |
| 107 | res := model.NewMapValue() |
| 108 | if len(e.ProcessingInstructions) > 0 { |
| 109 | res.SetMetadataValue("xml_processing_instructions", e.ProcessingInstructions) |
| 110 | } |
| 111 | if len(e.Comments) > 0 { |
| 112 | res.SetMetadataValue("xml_comments", e.Comments) |
| 113 | } |
| 114 | for _, attr := range e.Attrs { |
| 115 | if err := res.SetMapKey("-"+attr.Name, model.NewStringValue(attr.Value)); err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | if len(e.Content) > 0 { |
| 121 | if err := res.SetMapKey("#text", model.NewStringValue(e.Content)); err != nil { |
| 122 | return nil, err |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | if len(e.Children) > 0 { |
| 127 | childElementKeys := make([]string, 0) |
| 128 | childElements := make(map[string][]*xmlElement) |
| 129 | // childOrder records document-order child names for round-trip preservation. |
| 130 | childOrder := make([]string, 0, len(e.Children)) |
| 131 | |
| 132 | for _, child := range e.Children { |
| 133 | if _, ok := childElements[child.Name]; !ok { |
| 134 | childElementKeys = append(childElementKeys, child.Name) |
| 135 | } |
| 136 | childElements[child.Name] = append(childElements[child.Name], child) |
| 137 | childOrder = append(childOrder, child.Name) |
| 138 | } |
| 139 | |
| 140 | for _, key := range childElementKeys { |
| 141 | cs := childElements[key] |
| 142 | switch len(cs) { |
| 143 | case 0: |
| 144 | continue |
| 145 | case 1: |
| 146 | childModel, err := cs[0].toFriendlyModel() |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | if err := res.SetMapKey(key, childModel); err != nil { |
| 151 | return nil, err |
| 152 | } |
| 153 | default: |
| 154 | children := model.NewSliceValue() |
| 155 | for _, child := range cs { |
| 156 | childModel, err := child.toFriendlyModel() |
| 157 | if err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | if err := children.Append(childModel); err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | } |
| 164 | if err := res.SetMapKey(key, children); err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | res.SetMetadataValue(xmlChildOrderKey, childOrder) |
| 171 | } |
| 172 | |
| 173 | return res, nil |
| 174 | } |
| 175 | |
| 176 | func (j *xmlReader) parseElement(decoder *xml.Decoder, element xml.StartElement, totalComments *int, depth int) (*xmlElement, error) { |
| 177 | if depth > maxXMLDepth { |
| 178 | return nil, ErrXMLMaxDepthExceeded |
| 179 | } |
| 180 | |
| 181 | el := &xmlElement{ |
| 182 | Name: element.Name.Local, |
| 183 | Attrs: make([]xmlAttr, 0), |
| 184 | Children: make([]*xmlElement, 0), |
| 185 | ProcessingInstructions: make([]*xmlProcessingInstruction, 0), |
| 186 | Comments: make([]*xmlComment, 0), |
| 187 | } |
| 188 | |
| 189 | for _, attr := range element.Attr { |
| 190 | el.Attrs = append(el.Attrs, xmlAttr{ |
| 191 | Name: attr.Name.Local, |
| 192 | Value: attr.Value, |
| 193 | }) |
| 194 | } |
| 195 | |
| 196 | var processingInstructions []*xmlProcessingInstruction |
| 197 | var comments []*xmlComment |
| 198 | |
| 199 | for { |
| 200 | t, err := decoder.Token() |
| 201 | if errors.Is(err, io.EOF) { |
| 202 | if el.Name == "root" { |
| 203 | return el, nil |
| 204 | } |
| 205 | return nil, fmt.Errorf("unexpected EOF") |
| 206 | } |
| 207 | if err != nil { |
| 208 | return nil, fmt.Errorf("failed to read token: %w", err) |
| 209 | } |
| 210 | if t == nil { |
| 211 | if el.Name == "root" { |
| 212 | return el, nil |
| 213 | } |
| 214 | return nil, fmt.Errorf("unexpected nil token") |
| 215 | } |
| 216 | |
| 217 | switch t := t.(type) { |
| 218 | case xml.StartElement: |
| 219 | child, err := j.parseElement(decoder, t, totalComments, depth+1) |
| 220 | if err != nil { |
| 221 | return nil, err |
| 222 | } |
| 223 | if len(comments) > 0 { |
| 224 | child.Comments = append(comments, child.Comments...) |
| 225 | comments = nil |
| 226 | } |
| 227 | if len(processingInstructions) > 0 { |
| 228 | child.ProcessingInstructions = processingInstructions |
| 229 | processingInstructions = nil |
| 230 | } |
| 231 | el.Children = append(el.Children, child) |
| 232 | case xml.CharData: |
| 233 | stringContent := string(t) |
| 234 | if strings.TrimSpace(stringContent) == "" { |
| 235 | continue |
| 236 | } |
| 237 | el.Content += stringContent |
| 238 | case xml.EndElement: |
| 239 | if len(comments) > 0 { |
| 240 | el.Comments = append(el.Comments, comments...) |
| 241 | } |
| 242 | return el, nil |
| 243 | case xml.Comment: |
| 244 | commentText := string(t) |
| 245 | if len(commentText) > maxCommentLength { |
| 246 | return nil, fmt.Errorf("comment exceeds maximum length of %d bytes", maxCommentLength) |
| 247 | } |
| 248 | if *totalComments >= maxTotalComments { |
| 249 | return nil, fmt.Errorf("document exceeds maximum comment count of %d", maxTotalComments) |
| 250 | } |
| 251 | comment := &xmlComment{ |
| 252 | Text: commentText, |
| 253 | } |
| 254 | comments = append(comments, comment) |
| 255 | *totalComments++ |
| 256 | continue |
| 257 | case xml.ProcInst: |
| 258 | pi := &xmlProcessingInstruction{ |
| 259 | Target: t.Target, |
| 260 | Value: string(t.Inst), |
| 261 | } |
| 262 | processingInstructions = append(processingInstructions, pi) |
| 263 | continue |
| 264 | case xml.Directive: |
| 265 | continue |
| 266 | case xml.Attr: |
| 267 | continue |
| 268 | default: |
| 269 | return nil, fmt.Errorf("unexpected token: %v", t) |
| 270 | } |
| 271 | } |
| 272 | } |