-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlibxml2.go
More file actions
551 lines (476 loc) · 15.7 KB
/
libxml2.go
File metadata and controls
551 lines (476 loc) · 15.7 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package xsdvalidate
/*
#cgo CFLAGS: -std=c99
#cgo pkg-config: libxml-2.0
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <libxml/xmlschemastypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define GO_ERR_INIT 1024
#define P_ERR_DEFAULT 1
#define P_ERR_VERBOSE 2
#define LIBXML_STATIC
#define NOOP ((void)0)
struct xsdParserResult {
xmlSchemaPtr schemaPtr;
char* errorStr;
};
struct xmlParserResult {
xmlDocPtr docPtr;
char* errorStr;
};
typedef enum {
NO_ERROR = 0,
LIBXML2_ERROR = 1,
XSD_PARSER_ERROR = 2,
XML_PARSER_ERROR = 3,
VALIDATION_ERROR = 4
} errorType;
struct simpleXmlError {
errorType type;
int code;
char* message;
int level;
int line;
char* node;
};
typedef struct _errArray {
struct simpleXmlError* data;
size_t len;
size_t cap;
} errArray;
typedef struct _errCtx {
char* errBuf;
size_t len;
size_t cap;
} errCtx;
static errArray initErrArray() {
errArray errArr = {
.data = calloc(2, sizeof(struct simpleXmlError)), .len = 0, .cap = 2};
return errArr;
}
static void freeErrArray(errArray* errArr) {
for (int i = 0; i < errArr->len; i++) {
free(errArr->data[i].message);
free(errArr->data[i].node);
}
free(errArr->data);
}
static errCtx initErrCtx(size_t len, size_t cap) {
errCtx ectx = {.errBuf = malloc(cap), .len = len, .cap = cap};
memset(ectx.errBuf, '\0', len);
return ectx;
}
static void freeErrCtx(errCtx ectx) {
free(ectx.errBuf);
ectx.len=0;
ectx.cap=0;
}
static void appendErrCtxErrBuff(errCtx* ectx, const char* buffStr) {
size_t buffStrLen = strlen(buffStr);
size_t capWanted = ectx->len + buffStrLen;
if (capWanted > ectx->cap) {
size_t newCap = capWanted + GO_ERR_INIT;
char* tmp = malloc(newCap);
memcpy(tmp, ectx->errBuf, ectx->len);
free(ectx->errBuf);
ectx->errBuf = tmp;
ectx->cap = newCap;
}
size_t newLen = ectx->len + buffStrLen;
char* tmp = malloc(newLen);
if (ectx->len > 1) {
memcpy(tmp, ectx->errBuf, ectx->len);
}
memcpy(&tmp[ectx->len - 1], buffStr, buffStrLen + 1);
// strcat(tmp, newLine);
free(ectx->errBuf);
ectx->errBuf = tmp;
ectx->len = newLen;
}
static void noOutputCallback(void* ctx, const char* message, ...) {}
static void init() {
xmlInitParser();
}
static void cleanup() {
#if LIBXML_VERSION < 21000
xmlSchemaCleanupTypes();
#endif
xmlCleanupParser();
}
static void genErrorCallback(void* ctx, const char* message, ...) {
errCtx* ectx = ctx;
char* newLine = malloc(GO_ERR_INIT);
va_list varArgs;
va_start(varArgs, message);
size_t lineLen = 1 + vsnprintf(newLine, GO_ERR_INIT, message, varArgs);
if (lineLen > GO_ERR_INIT) {
va_end(varArgs);
va_start(varArgs, message);
free(newLine);
newLine = malloc(lineLen);
vsnprintf(newLine, lineLen, message, varArgs);
va_end(varArgs);
} else {
va_end(varArgs);
}
appendErrCtxErrBuff(ectx, newLine);
free(newLine);
}
static void simpleStructErrorCallback(
void* ctx,
#if LIBXML_VERSION >= 21200
const xmlError *p
#else
xmlErrorPtr p
#endif
) {
errArray* sErrArr = ctx;
struct simpleXmlError sErr;
sErr.message = calloc(GO_ERR_INIT, sizeof(char));
sErr.node = calloc(GO_ERR_INIT, sizeof(char));
sErr.type = VALIDATION_ERROR;
sErr.code = p->code;
sErr.level = p->level;
sErr.line = p->line;
int cpyLen = 1 + snprintf(sErr.message, GO_ERR_INIT, "%s", p->message);
if (cpyLen > GO_ERR_INIT) {
free(sErr.message);
sErr.message = malloc(cpyLen);
snprintf(sErr.message, cpyLen, "%s", p->message);
}
if (p->node != NULL) {
cpyLen = 1 + snprintf(sErr.node, GO_ERR_INIT, "%s",
(((xmlNodePtr)p->node)->name));
if (cpyLen > GO_ERR_INIT) {
free(sErr.node);
sErr.node = malloc(cpyLen);
snprintf(sErr.node, cpyLen, "%s", (((xmlNodePtr)p->node)->name));
}
}
if (sErrArr->len >= sErrArr->cap) {
sErrArr->cap = sErrArr->cap * 2;
struct simpleXmlError* tmp = calloc(sErrArr->cap, sizeof(*tmp));
memcpy(tmp, sErrArr->data, sErrArr->len * sizeof(*tmp));
free(sErrArr->data);
sErrArr->data = tmp;
}
sErrArr->data[sErrArr->len] = sErr;
sErrArr->len++;
}
static struct xsdParserResult parseSchema(
xmlSchemaParserCtxtPtr schemaParserCtxt,
const short int options) {
bool err = false;
struct xsdParserResult parserResult;
errCtx ectx = initErrCtx(1, GO_ERR_INIT);
errCtx ectxParse = initErrCtx(1, GO_ERR_INIT);
xmlSchemaPtr schema = NULL;
if (schemaParserCtxt == NULL) {
err = true;
const char msg[] = "Xsd parser internal error";
freeErrCtx(ectxParse);
appendErrCtxErrBuff(&ectx, msg);
} else {
if (options & P_ERR_VERBOSE) {
xmlSchemaSetParserErrors(schemaParserCtxt, genErrorCallback, noOutputCallback, &ectxParse);
xmlSetGenericErrorFunc(&ectx, genErrorCallback);
} else {
xmlSetGenericErrorFunc(NULL, noOutputCallback);
xmlSchemaSetParserErrors(schemaParserCtxt, genErrorCallback, noOutputCallback, &ectx);
}
schema = xmlSchemaParse(schemaParserCtxt);
xmlSchemaFreeParserCtxt(schemaParserCtxt);
if (schema == NULL) {
freeErrCtx(ectx);
ectx = ectxParse;
err = true;
} else {
freeErrCtx(ectxParse);
}
}
parserResult.errorStr = malloc(ectx.len);
memcpy(parserResult.errorStr, ectx.errBuf, ectx.len);
freeErrCtx(ectx);
parserResult.schemaPtr = schema;
errno = err ? -1 : 0;
return parserResult;
}
static struct xsdParserResult cParseUrlSchema(const char* url,
const short int options) {
xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;
schemaParserCtxt = xmlSchemaNewParserCtxt(url);
return parseSchema(schemaParserCtxt, options);
}
static struct xsdParserResult cParseMemSchema(const void* xsd,
const int goXsdSourceLen,
const short int options) {
xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;
schemaParserCtxt = xmlSchemaNewMemParserCtxt(xsd, goXsdSourceLen);
return parseSchema(schemaParserCtxt, options);
}
static struct xmlParserResult cParseDoc(const void* goXmlSource,
const int goXmlSourceLen,
const short int options) {
bool err = false;
struct xmlParserResult parserResult;
errCtx ectx = initErrCtx(1, GO_ERR_INIT);
xmlDocPtr doc = NULL;
xmlParserCtxtPtr xmlParserCtxt = NULL;
if (goXmlSourceLen == 0) {
err = true;
if (options & P_ERR_VERBOSE) {
const char msg[] = "parser error : Document is empty";
appendErrCtxErrBuff(&ectx, msg);
} else {
const char msg[] = "Malformed xml document";
appendErrCtxErrBuff(&ectx, msg);
}
} else {
xmlParserCtxt = xmlNewParserCtxt();
if (xmlParserCtxt == NULL) {
err = true;
const char msg[] = "Xml parser internal error";
appendErrCtxErrBuff(&ectx, msg);
} else {
if (options & P_ERR_VERBOSE) {
xmlSetGenericErrorFunc(&ectx, genErrorCallback);
} else {
xmlSetGenericErrorFunc(NULL, noOutputCallback);
}
doc = xmlReadMemory(goXmlSource, goXmlSourceLen, NULL, NULL, 0);
xmlFreeParserCtxt(xmlParserCtxt);
if (doc == NULL) {
err = true;
if (!(options & P_ERR_VERBOSE)) {
const char msg[] = "Malformed xml document";
appendErrCtxErrBuff(&ectx, msg);
}
}
}
}
parserResult.errorStr = malloc(ectx.len);
memcpy(parserResult.errorStr, ectx.errBuf, ectx.len);
freeErrCtx(ectx);
parserResult.docPtr = doc;
errno = err ? -1 : 0;
return parserResult;
}
static errArray cValidate(const xmlDocPtr doc, const xmlSchemaPtr schema) {
errArray errArr = initErrArray();
struct simpleXmlError simpleError;
simpleError.message = calloc(GO_ERR_INIT, sizeof(char));
simpleError.node = calloc(GO_ERR_INIT, sizeof(char));
if (schema == NULL) {
simpleError.type = LIBXML2_ERROR;
strcpy(simpleError.message, "Xsd schema null pointer");
errArr.data[errArr.len] = simpleError;
errArr.len++;
} else if (doc == NULL) {
simpleError.type = LIBXML2_ERROR;
strcpy(simpleError.message, "Xml doc null pointer");
errArr.data[errArr.len] = simpleError;
errArr.len++;
} else {
xmlSchemaValidCtxtPtr schemaCtxt;
schemaCtxt = xmlSchemaNewValidCtxt(schema);
if (schemaCtxt == NULL) {
simpleError.type = LIBXML2_ERROR;
strcpy(simpleError.message, "Xml validation internal error");
errArr.data[errArr.len] = simpleError;
errArr.len++;
} else {
xmlSchemaSetValidStructuredErrors(schemaCtxt, simpleStructErrorCallback,
&errArr);
int schemaErr = xmlSchemaValidateDoc(schemaCtxt, doc);
xmlSchemaFreeValidCtxt(schemaCtxt);
if (schemaErr < 0 && errArr.len == 0) {
simpleError.type = LIBXML2_ERROR;
strcpy(simpleError.message, "Xml validation internal error");
errArr.data[errArr.len] = simpleError;
errArr.len++;
} else {
free(simpleError.node);
free(simpleError.message);
}
}
}
errno = errArr.len == NO_ERROR ? 0 : -1;
return errArr;
}
static errArray cValidateBuf(const void* goXmlSource,
const int goXmlSourceLen,
const short int xmlParserOptions,
const xmlSchemaPtr schema) {
errArray errArr = initErrArray();
struct simpleXmlError simpleError;
simpleError.message = calloc(GO_ERR_INIT, sizeof(char));
simpleError.node = calloc(GO_ERR_INIT, sizeof(char));
struct xmlParserResult parserResult =
cParseDoc(goXmlSource, goXmlSourceLen, xmlParserOptions);
if (schema == NULL) {
simpleError.type = LIBXML2_ERROR;
const char msg[] = "Xsd schema null pointer";
strcpy(simpleError.message, msg);
errArr.data[errArr.len] = simpleError;
errArr.len++;
xmlFreeDoc(parserResult.docPtr);
free(parserResult.errorStr);
errno = -1;
return errArr;
} else if (parserResult.docPtr == NULL) {
simpleError.type = XML_PARSER_ERROR;
free(simpleError.message);
simpleError.message = malloc(strlen(parserResult.errorStr) + 1);
strcpy(simpleError.message, parserResult.errorStr);
errArr.data[errArr.len] = simpleError;
errArr.len++;
xmlFreeDoc(parserResult.docPtr);
free(parserResult.errorStr);
errno = -1;
return errArr;
}
free(simpleError.node);
free(simpleError.message);
freeErrArray(&errArr);
free(parserResult.errorStr);
errArray valErrArr = cValidate(parserResult.docPtr, schema);
xmlFreeDoc(parserResult.docPtr);
errno = valErrArr.len == NO_ERROR ? 0 : -1;
return valErrArr;
}
*/
import "C"
import (
"runtime"
"strings"
"time"
"unsafe"
)
// XsdHandler handles schema parsing and validation and wraps a pointer to libxml2's xmlSchemaPtr.
type XsdHandler struct {
schemaPtr C.xmlSchemaPtr
}
// XmlHandler handles xml parsing and wraps a pointer to libxml2's xmlDocPtr.
type XmlHandler struct {
docPtr C.xmlDocPtr
}
// Initializes the libxml2 parser, suggested for multithreading
func libXml2Init() {
C.init()
}
// Cleans up the libxml2 parser
func libXml2Cleanup() {
C.cleanup()
}
// The helper function for parsing xml
func parseXmlMem(inXml []byte, options Options) (C.xmlDocPtr, error) {
strXml := C.CBytes(inXml)
defer C.free(unsafe.Pointer(strXml))
pRes, err := C.cParseDoc(strXml, C.int(len(inXml)), C.short(options))
defer C.free(unsafe.Pointer(pRes.errorStr))
if err != nil {
rStr := C.GoString(pRes.errorStr)
return nil, XmlParserError{errorMessage{strings.Trim(rStr, "\n")}}
}
return pRes.docPtr, nil
}
// The helper function for parsing the schema
func parseUrlSchema(url string, options Options) (C.xmlSchemaPtr, error) {
strUrl := C.CString(url)
defer C.free(unsafe.Pointer(strUrl))
pRes, err := C.cParseUrlSchema(strUrl, C.short(options))
defer C.free(unsafe.Pointer(pRes.errorStr))
if err != nil {
rStr := C.GoString(pRes.errorStr)
return nil, XsdParserError{errorMessage{strings.Trim(rStr, "\n")}}
}
return pRes.schemaPtr, nil
}
// The helper function for parsing an in-memory schema
func parseMemSchema(xsd []byte, options Options) (C.xmlSchemaPtr, error) {
strXsd := C.CBytes(xsd)
defer C.free(unsafe.Pointer(strXsd))
pRes, err := C.cParseMemSchema(strXsd, C.int(len(xsd)), C.short(options))
defer C.free(unsafe.Pointer(pRes.errorStr))
if err != nil {
rStr := C.GoString(pRes.errorStr)
return nil, XsdParserError{errorMessage{strings.Trim(rStr, "\n")}}
}
return pRes.schemaPtr, nil
}
func handleErrArray(errSlice []C.struct_simpleXmlError) ValidationError {
ve := ValidationError{make([]StructError, len(errSlice))}
for i := 0; i < len(errSlice); i++ {
ve.Errors[i] = StructError{
Code: int(errSlice[i].code),
Message: strings.Trim(C.GoString(errSlice[i].message), "\n"),
Level: int(errSlice[i].level),
Line: int(errSlice[i].line),
NodeName: C.GoString(errSlice[i].node)}
}
return ve
}
// Helper function for validating given an xml document
func validateWithXsd(xmlHandler *XmlHandler, xsdHandler *XsdHandler) error {
sErr, err := C.cValidate(xmlHandler.docPtr, xsdHandler.schemaPtr)
defer C.freeErrArray(&sErr)
if err != nil {
errSlice := (*[1 << 30]C.struct_simpleXmlError)(unsafe.Pointer(sErr.data))[:sErr.len:sErr.len]
return handleErrArray(errSlice)
}
return nil
}
// Helper function for validating given an xml byte slice
func validateBufWithXsd(inXml []byte, options Options, xsdHandler *XsdHandler) error {
strXml := C.CBytes(inXml)
defer C.free(unsafe.Pointer(strXml))
sErr, err := C.cValidateBuf(strXml, C.int(len(inXml)), C.short(options), xsdHandler.schemaPtr)
defer C.freeErrArray(&sErr)
if err != nil {
errSlice := (*[1 << 30]C.struct_simpleXmlError)(unsafe.Pointer(sErr.data))[:sErr.len:sErr.len]
switch errSlice[0]._type {
case C.VALIDATION_ERROR:
return handleErrArray(errSlice)
case C.XML_PARSER_ERROR:
return XmlParserError{errorMessage{strings.Trim(C.GoString(errSlice[0].message), "\n")}}
case C.LIBXML2_ERROR:
return Libxml2Error{errorMessage{strings.Trim(C.GoString(errSlice[0].message), "\n")}}
case C.XSD_PARSER_ERROR:
return XsdParserError{errorMessage{strings.Trim(C.GoString(errSlice[0].message), "\n")}}
default:
return Libxml2Error{errorMessage{"Unknown error"}}
}
return ValidationError{}
}
return nil
}
// Wrapper for the xmlSchemaFree function
func freeSchemaPtr(xsdHandler *XsdHandler) {
if xsdHandler.schemaPtr != nil {
C.xmlSchemaFree(xsdHandler.schemaPtr)
}
}
// Wrapper for the xmlFreeDoc function
func freeDocPtr(xmlHandler *XmlHandler) {
if xmlHandler.docPtr != nil {
C.xmlFreeDoc(xmlHandler.docPtr)
}
}
// Ticker for gc
func gcTicker(d time.Duration, quit chan struct{}) {
ticker := time.NewTicker(d)
for {
select {
case <-ticker.C:
runtime.GC()
//C.malloc_trim(0)
case <-quit:
ticker.Stop()
return
}
}
}