summaryrefslogtreecommitdiff
path: root/bindings/xml/xmlparser.c
blob: 3826d52a880a5243e8c8155dd098b225c88f6e88 (plain)
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
/*
 * This file is part of libdom.
 * Licensed under the MIT License,
 *                http://www.opensource.org/licenses/mit-license.php
 * Copyright 2007 John-Mark Bell <jmb@netsurf-browser.org>
 */

#include <stdbool.h>

#include <libxml/parser.h>
#include <libxml/SAX2.h>
#include <libxml/xmlerror.h>

#include <dom/dom.h>

#include "xmlerror.h"
#include "xmlparser.h"
#include "utils.h"

static void xml_parser_start_document(void *ctx);
static void xml_parser_start_element_ns(void *ctx, const xmlChar *localname,
		const xmlChar *prefix, const xmlChar *URI,
		int nb_namespaces, const xmlChar **namespaces,
		int nb_attributes, int nb_defaulted,
		const xmlChar **attributes);

/**
 * XML parser object
 */
struct xml_parser {
	xmlParserCtxtPtr xml_ctx;	/**< libxml parser context */

	struct dom_document *doc;	/**< DOM Document we're building */

	bool complete;			/**< Indicate stream completion */

	xml_alloc alloc;		/**< Memory (de)allocation function */
	void *pw;			/**< Pointer to client data */
};

/**
 * SAX callback dispatch table
 */
static xmlSAXHandler sax_handler = {
	.internalSubset = xmlSAX2InternalSubset,
	.isStandalone = xmlSAX2IsStandalone,
	.hasInternalSubset = xmlSAX2HasInternalSubset,
	.hasExternalSubset = xmlSAX2HasExternalSubset,
	.resolveEntity = xmlSAX2ResolveEntity,
	.getEntity = xmlSAX2GetEntity,
	.entityDecl = xmlSAX2EntityDecl,
	.notationDecl = xmlSAX2NotationDecl,
	.attributeDecl = xmlSAX2AttributeDecl,
	.elementDecl = xmlSAX2ElementDecl,
	.unparsedEntityDecl = xmlSAX2UnparsedEntityDecl,
	.setDocumentLocator = xmlSAX2SetDocumentLocator,
	.startDocument = xml_parser_start_document,
	.endDocument = xmlSAX2EndDocument,
	.startElement = NULL,
	.endElement = NULL,
	.reference = xmlSAX2Reference,
	.characters = xmlSAX2Characters,
	.ignorableWhitespace = xmlSAX2Characters,
	.processingInstruction = NULL,
	.comment = xmlSAX2Comment,
	.warning = xmlParserWarning,
	.error = xmlParserError,
	.fatalError = xmlParserError,
	.getParameterEntity = xmlSAX2GetParameterEntity,
	.cdataBlock = xmlSAX2CDataBlock,
	.externalSubset = xmlSAX2ExternalSubset,
	.initialized = XML_SAX2_MAGIC,
	._private = NULL,
	.startElementNs = xml_parser_start_element_ns,
	.endElementNs = xmlSAX2EndElementNs,
	.serror = NULL,
};

/**
 * Create an XML parser instance
 *
 * \param enc      Source charset, or NULL
 * \param int_enc  Desired charset of document buffer (UTF-8 or UTF-16)
 * \param alloc    Memory (de)allocation function
 * \param pw       Pointer to client-specific private data
 * \return Pointer to instance, or NULL on memory exhaustion
 *
 * Neither ::enc nor ::int_enc are used here.
 * libxml only supports a UTF-8 document buffer and forcibly setting the
 * parser encoding is not yet implemented
 */
xml_parser *xml_parser_create(const char *enc, const char *int_enc,
		xml_alloc alloc, void *pw)
{
	xml_parser *parser;

	UNUSED(enc);
	UNUSED(int_enc);

	parser = alloc(NULL, sizeof(xml_parser), pw);
	if (parser == NULL)
		return NULL;

	parser->xml_ctx =
		xmlCreatePushParserCtxt(&sax_handler, parser, "", 0,
				NULL);
	if (parser->xml_ctx == NULL) {
		alloc(parser, 0, pw);
		return NULL;
	}

	parser->doc = NULL;

	parser->complete = false;

	parser->alloc = alloc;
	parser->pw = pw;

	return parser;
}

/**
 * Destroy an XML parser instance
 *
 * \param parser  The parser instance to destroy
 */
void xml_parser_destroy(xml_parser *parser)
{
	xmlFreeParserCtxt(parser->xml_ctx);

	/** \todo Do we want to clean up the document here, too? */
	/* Obviously, document cleanup wouldn't happen if the client has
	 * claimed the document from us via xml_parser_get_document() */

	parser->alloc(parser, 0, parser->pw);
}

/**
 * Parse a chunk of data
 *
 * \param parser  The XML parser instance to use for parsing
 * \param data    Pointer to data chunk
 * \param len     Byte length of data chunk
 * \return XML_OK on success, XML_LIBXML_ERR | <libxml error> on failure
 */
xml_error xml_parser_parse_chunk(xml_parser *parser,
		uint8_t *data, size_t len)
{
	xmlParserErrors err;

	err = xmlParseChunk(parser->xml_ctx, (char *) data, len, 0);
	if (err != XML_ERR_OK)
		return XML_LIBXML_ERR | err;

	return XML_OK;
}

/**
 * Notify parser that datastream is empty
 *
 * \param parser  The XML parser instance to notify
 * \return XML_OK on success, XML_LIBXML_ERR | <libxml error> on failure
 *
 * This will force any remaining data through the parser
 */
xml_error xml_parser_completed(xml_parser *parser)
{
	xmlParserErrors err;

	err = xmlParseChunk(parser->xml_ctx, "", 0, 1);
	if (err != XML_ERR_OK)
		return XML_LIBXML_ERR | err;

	parser->complete = true;

	return XML_OK;
}

/**
 * Retrieve the created DOM Document from a parser
 *
 * \param parser  The parser instance to retrieve the document from
 * \return Pointer to document, or NULL if parsing is not complete
 *
 * This may only be called after xml_parser_completed().
 */
struct dom_document *xml_parser_get_document(xml_parser *parser)
{
	return (parser->complete ? parser->doc : NULL);
}

/**
 * Handle a document start SAX event
 *
 * \param ctx  The callback context
 */
void xml_parser_start_document(void *ctx)
{
	xml_parser *parser = (xml_parser *) ctx;
	struct dom_implementation *impl;
	struct dom_string *features, *udkey;
	struct dom_document *doc;
	void *ignored;
	dom_exception err;

	/* Invoke libxml2's default behaviour */
	xmlSAX2StartDocument(parser->xml_ctx);

	/* Create a string representation of the features we want */
	err = dom_string_create_from_ptr_no_doc((dom_alloc) parser->alloc,
			parser->pw, (const uint8_t *) "XML", SLEN("XML"),
			&features);
	if (err != DOM_NO_ERR)
		return;

	/* Now, try to get an appropriate implementation from the registry */
	err = dom_implregistry_get_dom_implementation(features, &impl,
			(dom_alloc) parser->alloc, parser->pw);
	if (err != DOM_NO_ERR) {
		dom_string_unref(features);
		return;
	}

	/* No longer need the features string */
	dom_string_unref(features);

	/* Attempt to create a document */
	err = dom_implementation_create_document(impl, /* namespace */ NULL,
			/* qname */ NULL, /* doctype */ NULL,
			&doc, (dom_alloc) parser->alloc, parser->pw);
	if (err != DOM_NO_ERR) {
		dom_implementation_unref(impl);
		return;
	}

	/* No longer need the implementation */
	dom_implementation_unref(impl);

	/* Create key for user data registration */
	err = dom_string_create_from_const_ptr(doc,
			(const uint8_t *) "__xmlnode", SLEN("__xmlnode"),
			&udkey);
	if (err != DOM_NO_ERR)
		return;

	/* Register xmlNode as userdata for document */
	err = dom_node_set_user_data((struct dom_node *) doc,
			udkey, parser->xml_ctx->myDoc, NULL, &ignored);
	if (err != DOM_NO_ERR) {
		dom_string_unref(udkey);
		return;
	}

	/* No longer need the key */
	dom_string_unref(udkey);

	/* Register the DOM node with the xmlNode */
	dom_node_ref((struct dom_node *) doc);
	parser->xml_ctx->myDoc->_private = doc;

	/* And squirrel the document away for later use */
	parser->doc = doc;
}

/**
 * Handle an element open SAX event
 *
 * \param ctx            The callback context
 * \param localname      The local name of the element
 * \param prefix         The element namespace prefix
 * \param URI            The element namespace URI
 * \param nb_namespaces  The number of namespace definitions
 * \param namespaces     Array of nb_namespaces prefix/URI pairs
 * \param nb_attributes  The number of attributes
 * \param nb_defaulted   The number of defaulted attributes
 * \param attributes     Array of [nb_attributes + nb_defaulted] attribute
 *                       values
 */
void xml_parser_start_element_ns(void *ctx, const xmlChar *localname,
		const xmlChar *prefix, const xmlChar *URI,
		int nb_namespaces, const xmlChar **namespaces,
		int nb_attributes, int nb_defaulted,
		const xmlChar **attributes)
{
	xml_parser *parser = (xml_parser *) ctx;

	/* Invoke libxml2's default behaviour */
	xmlSAX2StartElementNs(parser->xml_ctx, localname, prefix, URI,
			nb_namespaces, namespaces, nb_attributes,
			nb_defaulted, attributes);

	/** \todo mirror the xml tree in the DOM */
}