Coverage Report

Created: 2026-12-03 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/poco/XML/src/ParserEngine.h
Line
Count
Source
1
//
2
// ParserEngine.h
3
//
4
// Library: XML
5
// Package: XML
6
// Module:  ParserEngine
7
//
8
// Definition of the ParseEngine class.
9
//
10
// Copyright (c) 2004-2026, Applied Informatics Software Engineering GmbH.
11
// and Contributors.
12
//
13
// SPDX-License-Identifier: BSL-1.0
14
15
16
#ifndef XML_ParserEngine_INCLUDED
17
#define XML_ParserEngine_INCLUDED
18
19
20
#include "Poco/XML/XML.h"
21
#include "Poco/XML/XMLString.h"
22
#include "Poco/XML/XMLStream.h"
23
#include "Poco/SAX/Locator.h"
24
#include "Poco/TextEncoding.h"
25
#include <expat.h>
26
#include <exception>
27
#include <map>
28
#include <vector>
29
30
31
namespace Poco::XML {
32
33
34
class InputSource;
35
class EntityResolver;
36
class DTDHandler;
37
class DeclHandler;
38
class ContentHandler;
39
class LexicalHandler;
40
class ErrorHandler;
41
class NamespaceStrategy;
42
class ContextLocator;
43
44
45
class XML_API ParserEngine: public Locator
46
  /// This class provides an object-oriented, stream-based,
47
  /// low-level interface to the XML Parser Toolkit (expat).
48
  /// It is strongly recommended, that you use the
49
  /// SAX parser classes (which are based on this
50
  /// class) instead of this class, since they provide
51
  /// a standardized, higher-level interface to the parser.
52
{
53
public:
54
  ParserEngine();
55
    /// Creates the parser engine.
56
57
  ParserEngine(const XMLString& encoding);
58
    /// Creates the parser engine and passes the encoding
59
    /// to the underlying parser.
60
61
  ~ParserEngine();
62
    /// Destroys the parser.
63
64
  void setEncoding(const XMLString& encoding);
65
    /// Sets the encoding used by expat. The encoding must be
66
    /// set before parsing begins, otherwise it will be ignored.
67
68
  const XMLString& getEncoding() const;
69
    /// Returns the encoding used by expat.
70
71
  void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding);
72
    /// Adds an encoding to the parser.
73
74
  void setNamespaceStrategy(NamespaceStrategy* pStrategy);
75
    /// Sets the NamespaceStrategy used by the parser.
76
    /// The parser takes ownership of the strategy object
77
    /// and deletes it when it's no longer needed.
78
    /// The default is NoNamespacesStrategy.
79
80
  NamespaceStrategy* getNamespaceStrategy() const;
81
    /// Returns the NamespaceStrategy currently in use.
82
83
  void setExpandInternalEntities(bool flag = true);
84
    /// Enables/disables expansion of internal entities (enabled by
85
    /// default). If entity expansion is disabled, internal entities
86
    /// are reported via the default handler.
87
    /// Must be set before parsing begins, otherwise it will be
88
    /// ignored.
89
90
  bool getExpandInternalEntities() const;
91
    /// Returns true if internal entities will be expanded automatically,
92
    /// which is the default.
93
94
  void setExternalGeneralEntities(bool flag = true);
95
    /// Enable or disable processing of external general entities.
96
97
  bool getExternalGeneralEntities() const;
98
    /// Returns true if external general entities will be processed; false otherwise.
99
100
  void setExternalParameterEntities(bool flag = true);
101
    /// Enable or disable processing of external parameter entities.
102
103
  bool getExternalParameterEntities() const;
104
    /// Returns true if external parameter entities will be processed; false otherwise.
105
106
  void setEntityResolver(EntityResolver* pResolver);
107
    /// Allow an application to register an entity resolver.
108
109
  EntityResolver* getEntityResolver() const;
110
    /// Return the current entity resolver.
111
112
  void setDTDHandler(DTDHandler* pDTDHandler);
113
    /// Allow an application to register a DTD event handler.
114
115
  DTDHandler* getDTDHandler() const;
116
    /// Return the current DTD handler.
117
118
  void setDeclHandler(DeclHandler* pDeclHandler);
119
    /// Allow an application to register a DTD declarations event handler.
120
121
  DeclHandler* getDeclHandler() const;
122
    /// Return the current DTD declarations handler.
123
124
  void setContentHandler(ContentHandler* pContentHandler);
125
    /// Allow an application to register a content event handler.
126
127
  ContentHandler* getContentHandler() const;
128
    /// Return the current content handler.
129
130
  void setLexicalHandler(LexicalHandler* pLexicalHandler);
131
    /// Allow an application to register a lexical event handler.
132
133
  LexicalHandler* getLexicalHandler() const;
134
    /// Return the current lexical handler.
135
136
  void setErrorHandler(ErrorHandler* pErrorHandler);
137
    /// Allow an application to register an error event handler.
138
139
  ErrorHandler* getErrorHandler() const;
140
    /// Return the current error handler.
141
142
  void setEnablePartialReads(bool flag = true);
143
    /// Enable or disable partial reads from the input source.
144
    ///
145
    /// This is useful for parsing XML from a socket stream for
146
    /// a protocol like XMPP, where basically single elements
147
    /// are read one at a time from the input source's stream, and
148
    /// following elements depend upon responses sent back to
149
    /// the peer.
150
    ///
151
    /// Normally, the parser always reads blocks of PARSE_BUFFER_SIZE
152
    /// at a time, and blocks until a complete block has been read (or
153
    /// the end of the stream has been reached).
154
    /// This allows for efficient parsing of "complete" XML documents,
155
    /// but fails in a case such as XMPP, where only XML fragments
156
    /// are sent at a time.
157
158
  bool getEnablePartialReads() const;
159
    /// Returns true if partial reads are enabled (see
160
    /// setEnablePartialReads()), false otherwise.
161
162
  void setBillionLaughsAttackProtectionMaximumAmplification(float maximumAmplificationFactor);
163
    /// Sets the maximum tolerated amplification factor
164
      /// for protection against Billion Laughs Attacks.
165
      ///
166
      /// The amplification factor is calculated as:
167
      ///     amplification := (direct + indirect) / direct
168
      /// while parsing, whereas:
169
      ///   - direct is the number of bytes read from the primary document in parsing and
170
      ///   - indirect is the number of bytes added by expanding entities and reading of
171
      ///     external DTD files, combined.
172
      ///
173
      /// maximumAmplificationFactor must be non-NaN and greater than or equal to 1.0.
174
    ///
175
    /// Requires an underlying Expat version >= 2.4.0.
176
177
  void setBillionLaughsAttackProtectionActivationThreshold(Poco::UInt64 activationThresholdBytes);
178
    /// Sets number of output bytes (including amplification from entity expansion and reading DTD files)
179
    /// needed to activate protection against Billion Laughs Attacks.
180
    ///
181
    /// Defaults to 8 MiB.
182
    ///
183
    /// Requires an underlying Expat version >= 2.4.0.
184
185
  void parse(InputSource* pInputSource);
186
    /// Parse an XML document from the given InputSource.
187
188
  void parse(const char* pBuffer, std::size_t size);
189
    /// Parses an XML document from the given buffer.
190
191
  // Locator
192
  XMLString getPublicId() const;
193
    /// Return the public identifier for the current document event.
194
195
  XMLString getSystemId() const;
196
    /// Return the system identifier for the current document event.
197
198
  int getLineNumber() const;
199
    /// Return the line number where the current document event ends.
200
201
  int getColumnNumber() const;
202
    /// Return the column number where the current document event ends.
203
204
protected:
205
  void init();
206
    /// initializes expat
207
208
  void parseByteInputStream(XMLByteInputStream& istr);
209
    /// Parses an entity from the given stream.
210
211
  void parseCharInputStream(XMLCharInputStream& istr);
212
    /// Parses an entity from the given stream.
213
214
  std::streamsize readBytes(XMLByteInputStream& istr, char* pBuffer, std::streamsize bufferSize);
215
    /// Reads at most bufferSize bytes from the given stream into the given buffer.
216
217
  std::streamsize readChars(XMLCharInputStream& istr, XMLChar* pBuffer, std::streamsize bufferSize);
218
    /// Reads at most bufferSize chars from the given stream into the given buffer.
219
220
  [[noreturn]] void handleError(int errorNo);
221
    /// Throws an XMLException with a message corresponding
222
    /// to the given Expat error code.
223
224
  [[noreturn]] void checkError(XML_Parser parser);
225
    /// Called after a failed XML_Parse()/XML_ParseBuffer() call.
226
    /// If a C++ exception thrown from within a handler has been
227
    /// captured by abortParse(), rethrows it (and clears it);
228
    /// otherwise translates the parser's current Expat error code
229
    /// into an exception via handleError().
230
231
  void abortParse(XML_Parser parser, std::exception_ptr ex);
232
    /// Called from an Expat callback when invoking application code
233
    /// (a SAX/DTD/lexical handler or entity resolver) throws a C++
234
    /// exception. Expat is a C library and does not support C++
235
    /// exceptions unwinding through its call stack -- doing so skips
236
    /// Expat's internal handler-call-depth bookkeeping and leaves the
237
    /// parser (and everything it owns) permanently leaked, since Expat
238
    /// then refuses to free a parser it believes is still inside a
239
    /// handler call.
240
    ///
241
    /// Instead, the exception is captured here and the parser is
242
    /// stopped gracefully via XML_StopParser(), which Expat fully
243
    /// supports from within a handler. Once XML_Parse() returns,
244
    /// checkError() rethrows the captured exception.
245
246
  XML_Parser currentParser() const;
247
    /// Returns the Expat parser instance (the main parser, or the
248
    /// external entity sub-parser currently being parsed) that is
249
    /// active for the top-most entry of the context stack.
250
251
  void parseExternal(XML_Parser extParser, InputSource* pInputSource);
252
    /// Parse an XML document from the given InputSource.
253
254
  void parseExternalByteInputStream(XML_Parser extParser, XMLByteInputStream& istr);
255
    /// Parses an external entity from the given stream, with a separate parser.
256
257
  void parseExternalCharInputStream(XML_Parser extParser, XMLCharInputStream& istr);
258
    /// Parses an external entity from the given stream, with a separate parser.
259
260
  void pushContext(XML_Parser parser, InputSource* pInputSource);
261
    /// Pushes a new entry to the context stack.
262
263
  void popContext();
264
    /// Pops the top-most entry from the context stack.
265
266
  void resetContext();
267
    /// Resets and clears the context stack.
268
269
  const Locator& locator() const;
270
    /// Returns a locator denoting the current parse location.
271
272
  // expat handler procedures
273
  static void handleStartElement(void* userData, const XML_Char* name, const XML_Char** atts);
274
  static void handleEndElement(void* userData, const XML_Char* name);
275
  static void handleCharacterData(void* userData, const XML_Char* s, int len);
276
  static void handleProcessingInstruction(void* userData, const XML_Char* target, const XML_Char* data);
277
  static void handleDefault(void* userData, const XML_Char* s, int len);
278
  static void handleUnparsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId, const XML_Char* notationName);
279
  static void handleNotationDecl(void* userData, const XML_Char* notationName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
280
  static int handleExternalEntityRef(XML_Parser parser, const XML_Char* openEntityNames, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
281
  static int handleUnknownEncoding(void* encodingHandlerData, const XML_Char* name, XML_Encoding* info);
282
  static void handleComment(void* userData, const XML_Char* data);
283
  static void handleStartCdataSection(void* userData);
284
  static void handleEndCdataSection(void* userData);
285
  static void handleStartNamespaceDecl(void* userData, const XML_Char* prefix, const XML_Char* uri);
286
  static void handleEndNamespaceDecl(void* userData, const XML_Char* prefix);
287
  static void handleStartDoctypeDecl(void* userData, const XML_Char* doctypeName, const XML_Char *systemId, const XML_Char* publicId, int hasInternalSubset);
288
  static void handleEndDoctypeDecl(void* userData);
289
  static void handleEntityDecl(void *userData, const XML_Char *entityName, int isParamEntity, const XML_Char *value, int valueLength,
290
                               const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName);
291
  static void handleExternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
292
  static void handleInternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* replacementText, int replacementTextLength);
293
  static void handleSkippedEntity(void* userData, const XML_Char* entityName, int isParameterEntity);
294
295
  // encoding support
296
  static int convert(void *data, const char *s);
297
298
private:
299
  typedef std::map<XMLString, Poco::TextEncoding*> EncodingMap;
300
  typedef std::vector<ContextLocator*> ContextStack;
301
302
  XML_Parser _parser;
303
  char*      _pBuffer;
304
  bool       _encodingSpecified;
305
  XMLString  _encoding;
306
  bool       _expandInternalEntities;
307
  bool       _externalGeneralEntities;
308
  bool       _externalParameterEntities;
309
  bool       _enablePartialReads;
310
  NamespaceStrategy* _pNamespaceStrategy;
311
  EncodingMap        _encodings;
312
  ContextStack       _context;
313
314
  EntityResolver* _pEntityResolver;
315
  DTDHandler*     _pDTDHandler;
316
  DeclHandler*    _pDeclHandler;
317
  ContentHandler* _pContentHandler;
318
  LexicalHandler* _pLexicalHandler;
319
  ErrorHandler*   _pErrorHandler;
320
321
  std::exception_ptr _exception;
322
323
  float _maximumAmplificationFactor;
324
  Poco::UInt64 _activationThresholdBytes;
325
326
  static constexpr int PARSE_BUFFER_SIZE = 4096;
327
  static const XMLString EMPTY_STRING;
328
};
329
330
331
//
332
// inlines
333
//
334
inline const XMLString& ParserEngine::getEncoding() const
335
0
{
336
0
  return _encoding;
337
0
}
338
339
340
inline NamespaceStrategy* ParserEngine::getNamespaceStrategy() const
341
0
{
342
0
  return _pNamespaceStrategy;
343
0
}
344
345
346
inline bool ParserEngine::getExpandInternalEntities() const
347
0
{
348
0
  return _expandInternalEntities;
349
0
}
350
351
352
inline bool ParserEngine::getExternalGeneralEntities() const
353
0
{
354
0
  return _externalGeneralEntities;
355
0
}
356
357
358
inline bool ParserEngine::getExternalParameterEntities() const
359
0
{
360
0
  return _externalParameterEntities;
361
0
}
362
363
364
inline EntityResolver* ParserEngine::getEntityResolver() const
365
0
{
366
0
  return _pEntityResolver;
367
0
}
368
369
370
inline DTDHandler* ParserEngine::getDTDHandler() const
371
0
{
372
0
  return _pDTDHandler;
373
0
}
374
375
376
inline DeclHandler* ParserEngine::getDeclHandler() const
377
0
{
378
0
  return _pDeclHandler;
379
0
}
380
381
382
inline ContentHandler* ParserEngine::getContentHandler() const
383
0
{
384
0
  return _pContentHandler;
385
0
}
386
387
388
inline LexicalHandler* ParserEngine::getLexicalHandler() const
389
0
{
390
0
  return _pLexicalHandler;
391
0
}
392
393
394
inline ErrorHandler* ParserEngine::getErrorHandler() const
395
0
{
396
0
  return _pErrorHandler;
397
0
}
398
399
400
inline bool ParserEngine::getEnablePartialReads() const
401
0
{
402
0
  return _enablePartialReads;
403
0
}
404
405
406
} // namespace Poco::XML
407
408
409
#endif // XML_ParserEngine_INCLUDED