forked from lestrrat-go/libxml2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclib.go
2256 lines (1881 loc) · 48.9 KB
/
clib.go
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Package clib holds all of the dirty C interaction for go-libxml2.
Although this package is visible to the outside world, the API in this
package is in NO WAY guaranteed to be stable. This package was
initially meant to be placed in an internal package so that the
API was not available to the outside world.
The only reason this is visible is so that the REALLY advanced users
can abuse the quasi-direct-C-API to overcome shortcomings of the
"public" API, if any (and of course, you WILL send me a pull request
later... won't you?)
Please DO NOT rely on this API and expect that it will keep backcompat.
When the need arises, it WILL be changed, and if you are not ready
for it, your code WILL break in horrible ways. You have been
warned.
*/
package clib
/*
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>
#include <libxml/globals.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxml/c14n.h>
#include <libxml/xmlschemas.h>
#include <libxml/schemasInternals.h>
static inline void MY_nilErrorHandler(void *ctx, const char *msg, ...) {}
static inline void MY_xmlSilenceParseErrors() {
xmlSetGenericErrorFunc(NULL, MY_nilErrorHandler);
}
static inline void MY_xmlDefaultParseErrors() {
// Checked in the libxml2 source code that using NULL in the second
// argument restores the default error handler
xmlSetGenericErrorFunc(NULL, NULL);
}
// Macro wrapper function. cgo cannot detect function-like macros,
// so this is how we avoid it
static inline void MY_xmlFree(void *p) {
xmlFree(p);
}
// Macro wrapper function. cgo cannot detect function-like macros,
// so this is how we avoid it
static inline xmlError* MY_xmlLastError() {
return (xmlError*) xmlGetLastError();
}
// Macro wrapper function. cgo cannot detect function-like macros,
// so this is how we avoid it
static inline xmlError* MY_xmlCtxtLastError(void *ctx) {
return (xmlError*) xmlCtxtGetLastError(ctx);
}
// Change xmlIndentTreeOutput global, return old value, so caller can
// change it back to old value later
static inline int MY_setXmlIndentTreeOutput(int i) {
int old = xmlIndentTreeOutput;
xmlIndentTreeOutput = i;
return old;
}
// Parse a single char out of cur
// Stolen from XML::LibXML
static inline int
MY_parseChar( xmlChar *cur, int *len )
{
unsigned char c;
unsigned int val;
// We are supposed to handle UTF8, check it's valid
// From rfc2044: encoding of the Unicode values on UTF-8:
//
// UCS-4 range (hex.) UTF-8 octet sequence (binary)
// 0000 0000-0000 007F 0xxxxxxx
// 0000 0080-0000 07FF 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
//
// Check for the 0x110000 limit too
if ( cur == NULL || *cur == 0 ) {
*len = 0;
return(0);
}
c = *cur;
if ( (c & 0x80) == 0 ) {
*len = 1;
return((int)c);
}
if ((c & 0xe0) == 0xe0) {
if ((c & 0xf0) == 0xf0) {
// 4-byte code
*len = 4;
val = (cur[0] & 0x7) << 18;
val |= (cur[1] & 0x3f) << 12;
val |= (cur[2] & 0x3f) << 6;
val |= cur[3] & 0x3f;
} else {
// 3-byte code
*len = 3;
val = (cur[0] & 0xf) << 12;
val |= (cur[1] & 0x3f) << 6;
val |= cur[2] & 0x3f;
}
} else {
// 2-byte code
*len = 2;
val = (cur[0] & 0x1f) << 6;
val |= cur[1] & 0x3f;
}
if ( !IS_CHAR(val) ) {
*len = -1;
return 0;
}
return val;
}
// Checks if the given name is a valid name in XML
// stolen from XML::LibXML
static inline int
MY_test_node_name( xmlChar * name )
{
xmlChar * cur = name;
int tc = 0;
int len = 0;
if ( cur == NULL || *cur == 0 ) {
return 0;
}
tc = MY_parseChar( cur, &len );
if ( !( IS_LETTER( tc ) || (tc == '_') || (tc == ':')) ) {
return 0;
}
tc = 0;
cur += len;
while (*cur != 0 ) {
tc = MY_parseChar( cur, &len );
if (!(IS_LETTER(tc) || IS_DIGIT(tc) || (tc == '_') ||
(tc == '-') || (tc == ':') || (tc == '.') ||
IS_COMBINING(tc) || IS_EXTENDER(tc)) )
{
return 0;
}
tc = 0;
cur += len;
}
return(1);
}
// optimization
static xmlNode*
MY_xmlCreateElement(xmlDoc *doc, xmlChar *name) {
if (MY_test_node_name(name) == 0) {
return NULL;
}
xmlNode *ptr = xmlNewNode(NULL, name);
if (ptr == NULL) {
return NULL;
}
ptr->doc = doc;
return ptr;
}
static
xmlNode *
MY_xmlCreateElementNS(xmlDoc *doc, xmlChar *nsuri, xmlChar *name) {
xmlChar *local = name;
xmlChar *prefix = NULL;
xmlNode *node = NULL;
int i;
if (MY_test_node_name(name) == 0) {
return NULL;
}
for (i = 0; i < xmlStrlen(name); i++) {
local++;
// XXX boundary check!
if (*local == ':') {
local++;
break;
}
}
if (local != name) {
prefix = (xmlChar *) malloc(sizeof(xmlChar) * (local - name));
memcpy(prefix, name, local - name - 1);
prefix[(local - name - 1)] = '\0';
}
xmlNode *root = xmlDocGetRootElement(doc);
xmlNs *ns;
if (root == NULL) {
// No document element
ns = xmlNewNs(NULL, nsuri, prefix);
} else if (prefix != NULL) {
// Prefix exists, check if this is declared
ns = xmlSearchNs(doc, root, prefix);
if (ns == NULL) { // Not declared, create a new one
ns = xmlNewNs(NULL, nsuri, prefix);
} else { // Declared. Does the uri match?
if (xmlStrcmp(ns->href, nsuri) != 0) {
// Cleanup prefix
goto CLEANUP;
}
// Namespace is already registered, we don't need to provide a
// namespace element to xmlNewDocNode
ns = NULL;
local = name;
}
} else {
// If the name does not contain a prefix, check for the
// existence of this namespace via the URI
ns = xmlSearchNsByHref(doc, root, nsuri);
if (ns == NULL) {
ns = xmlNewNs(NULL, nsuri, NULL);
}
}
node = xmlNewDocNode(doc, ns, local, NULL);
if (ns != NULL) {
node->nsDef = ns;
}
CLEANUP:
if (prefix != NULL) {
free(prefix);
}
return node;
}
#define GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE 32
typedef struct go_libxml2_errwarn_accumulator {
char *errors[GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE];
char *warnings[GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE];
int erridx;
int warnidx;
} go_libxml2_errwarn_accumulator;
static
go_libxml2_errwarn_accumulator*
MY_createErrWarnAccumulator() {
int i;
go_libxml2_errwarn_accumulator *ctx;
ctx = (go_libxml2_errwarn_accumulator *) malloc(sizeof(go_libxml2_errwarn_accumulator));
for (i = 0; i < GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE; i++) {
ctx->errors[i] = NULL;
ctx->warnings[i] = NULL;
}
ctx->erridx = 0;
ctx->warnidx = 0;
return ctx;
}
static
void
MY_freeErrWarnAccumulator(go_libxml2_errwarn_accumulator* ctx) {
int i = 0;
for (i = 0; i < GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE; i++) {
if (ctx->errors[i] != NULL) {
free(ctx->errors[i]);
}
if (ctx->warnings[i] != NULL) {
free(ctx->errors[i]);
}
}
free(ctx);
}
static
void
MY_accumulateErr(void *ctx, const char *msg, ...) {
char buf[1024];
va_list args;
go_libxml2_errwarn_accumulator *accum;
int len;
accum = (go_libxml2_errwarn_accumulator *) ctx;
if (accum->erridx >= GO_LIBXML2_ERRWARN_ACCUMULATOR_SIZE) {
return;
}
va_start(args, msg);
len = vsnprintf(buf, sizeof(buf), msg, args);
va_end(args);
if (len == 0) {
return;
}
char *out = (char *) calloc(sizeof(char), len);
if (buf[len-1] == '\n') {
// don't want newlines in my error values
buf[len-1] = '\0';
len--;
}
memcpy(out, buf, len);
int i = accum->erridx++;
accum->errors[i] = out;
}
static
void
MY_setErrWarnAccumulator(xmlSchemaValidCtxtPtr ctxt, go_libxml2_errwarn_accumulator *accum) {
xmlSchemaSetValidErrors(ctxt, MY_accumulateErr, NULL, accum);
}
*/
import "C"
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
"unsafe"
"github.com/lestrrat-go/libxml2/internal/debug"
"github.com/lestrrat-go/libxml2/internal/option"
"github.com/pkg/errors"
)
const _XPathObjectTypeName = "XPathUndefinedXPathNodeSetXPathBooleanXPathNumberXPathStringXPathPointXPathRangeXPathLocationSetXPathUSersXPathXsltTree"
var _XPathObjectTypeIndex = [...]uint8{0, 14, 26, 38, 49, 60, 70, 80, 96, 106, 119}
// String returns the stringified version of XPathObjectType
func (i XPathObjectType) String() string {
if i < 0 || i+1 >= XPathObjectType(len(_XPathObjectTypeIndex)) {
return fmt.Sprintf("XPathObjectType(%d)", i)
}
return _XPathObjectTypeName[_XPathObjectTypeIndex[i]:_XPathObjectTypeIndex[i+1]]
}
func validDocumentPtr(doc PtrSource) (*C.xmlDoc, error) {
if doc == nil {
return nil, ErrInvalidDocument
}
if dptr := doc.Pointer(); dptr != 0 {
return (*C.xmlDoc)(unsafe.Pointer(dptr)), nil
}
return nil, ErrInvalidDocument
}
func validParserCtxtPtr(s PtrSource) (*C.xmlParserCtxt, error) {
if s == nil {
return nil, ErrInvalidParser
}
if ptr := s.Pointer(); ptr != 0 {
return (*C.xmlParserCtxt)(unsafe.Pointer(ptr)), nil
}
return nil, ErrInvalidParser
}
func validNodePtr(n PtrSource) (*C.xmlNode, error) {
if n == nil {
return nil, ErrInvalidNode
}
nptr := n.Pointer()
if nptr == 0 {
return nil, ErrInvalidNode
}
return (*C.xmlNode)(unsafe.Pointer(nptr)), nil
}
func validAttributePtr(n PtrSource) (*C.xmlAttr, error) {
if n == nil {
return nil, ErrInvalidAttribute
}
if nptr := n.Pointer(); nptr != 0 {
return (*C.xmlAttr)(unsafe.Pointer(nptr)), nil
}
return nil, ErrInvalidAttribute
}
func validXPathContextPtr(x PtrSource) (*C.xmlXPathContext, error) {
if x == nil {
return nil, ErrInvalidXPathContext
}
if xptr := x.Pointer(); xptr != 0 {
return (*C.xmlXPathContext)(unsafe.Pointer(xptr)), nil
}
return nil, ErrInvalidXPathContext
}
func validXPathExpressionPtr(x PtrSource) (*C.xmlXPathCompExpr, error) {
if x == nil {
return nil, ErrInvalidXPathExpression
}
if xptr := x.Pointer(); xptr != 0 {
return (*C.xmlXPathCompExpr)(unsafe.Pointer(xptr)), nil
}
return nil, ErrInvalidXPathExpression
}
func validXPathObjectPtr(x PtrSource) (*C.xmlXPathObject, error) {
if x == nil {
return nil, ErrInvalidXPathObject
}
if xptr := x.Pointer(); xptr != 0 {
return (*C.xmlXPathObject)(unsafe.Pointer(xptr)), nil
}
return nil, ErrInvalidXPathObject
}
var _XMLNodeTypeIndex = [...]uint8{0, 11, 24, 32, 48, 61, 71, 77, 88, 100, 116, 132, 144, 160, 167, 178, 191, 201, 214, 227, 238, 254}
const _XMLNodeTypeName = `ElementNodeAttributeNodeTextNodeCDataSectionNodeEntityRefNodeEntityNodePiNodeCommentNodeDocumentNodeDocumentTypeNodeDocumentFragNodeNotationNodeHTMLDocumentNodeDTDNodeElementDeclAttributeDeclEntityDeclNamespaceDeclXIncludeStartXIncludeEndDocbDocumentNode`
// String returns the string representation of this XMLNodeType
func (i XMLNodeType) String() string {
x := i - 1
if x < 0 || x+1 >= XMLNodeType(len(_XMLNodeTypeIndex)) {
return fmt.Sprintf("XMLNodeType(%d)", x+1)
}
return _XMLNodeTypeName[_XMLNodeTypeIndex[x]:_XMLNodeTypeIndex[x+1]]
}
// ReportErrors *globally* changes the behavior of reporting errors.
// By default libxml2 spews out lots of data to stderr. When you call
// this function with a `false` value, all those messages are suppressed.
// When you call this function a `true` value, the default behavior is
// restored
func ReportErrors(b bool) {
if b {
C.MY_xmlDefaultParseErrors()
} else {
C.MY_xmlSilenceParseErrors()
}
}
func xmlCtxtLastError(ctx PtrSource) error {
return xmlCtxtLastErrorRaw(ctx.Pointer())
}
func xmlCtxtLastErrorRaw(ctx uintptr) error {
e := C.MY_xmlCtxtLastError(unsafe.Pointer(ctx))
if e == nil {
return errors.New(`unknown error`)
}
msg := strings.TrimSuffix(C.GoString(e.message), "\n")
return errors.Errorf("Entity: line %v: parser error : %v", e.line, msg)
}
func xmlCharToString(s *C.xmlChar) string {
return C.GoString((*C.char)(unsafe.Pointer(s)))
}
// stringToXMLChar creates a new *C.xmlChar from a Go string.
// Remember to always free this data, as C.CString creates a copy
// of the byte buffer contained in the string
func stringToXMLChar(s string) *C.xmlChar {
return (*C.xmlChar)(unsafe.Pointer(C.CString(s)))
}
func XMLSchemaParseFromFile(path string) (uintptr, error) {
parserCtx := C.xmlSchemaNewParserCtxt(C.CString(path))
if parserCtx == nil {
return 0, errors.New("failed to create parser")
}
defer C.xmlSchemaFreeParserCtxt(parserCtx)
s := C.xmlSchemaParse(parserCtx)
if s == nil {
return 0, errors.New("failed to parse schema")
}
return uintptr(unsafe.Pointer(s)), nil
}
func XMLCreateMemoryParserCtxt(s string, o int) (uintptr, error) {
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
ctx := C.xmlCreateMemoryParserCtxt(cs, C.int(len(s)))
if ctx == nil {
return 0, errors.New("error creating parser")
}
C.xmlCtxtUseOptions(ctx, C.int(o))
return uintptr(unsafe.Pointer(ctx)), nil
}
func XMLParseDocument(ctx PtrSource) error {
ctxptr, err := validParserCtxtPtr(ctx)
if err != nil {
return err
}
if C.xmlParseDocument(ctxptr) != C.int(0) {
return errors.Errorf("parse failed: %v", xmlCtxtLastError(ctx))
}
return nil
}
func XMLFreeParserCtxt(ctx PtrSource) error {
ctxptr, err := validParserCtxtPtr(ctx)
if err != nil {
return err
}
C.xmlFreeParserCtxt(ctxptr)
return nil
}
func HTMLReadDoc(content, url, encoding string, opts int) (uintptr, error) {
// TODO: use htmlCtxReadDoc later, so we can get the error
ccontent := C.CString(content)
curl := C.CString(url)
cencoding := C.CString(encoding)
defer C.free(unsafe.Pointer(ccontent))
defer C.free(unsafe.Pointer(curl))
defer C.free(unsafe.Pointer(cencoding))
doc := C.htmlReadDoc(
(*C.xmlChar)(unsafe.Pointer(ccontent)),
curl,
cencoding,
C.int(opts),
)
if doc == nil {
return 0, errors.New("failed to parse document")
}
return uintptr(unsafe.Pointer(doc)), nil
}
func XMLCreateDocument(version, encoding string) uintptr {
cver := stringToXMLChar(version)
defer C.free(unsafe.Pointer(cver))
doc := C.xmlNewDoc(cver)
if encoding != "" {
cenc := stringToXMLChar(encoding)
defer C.free(unsafe.Pointer(cenc))
doc.encoding = C.xmlStrdup(cenc)
}
return uintptr(unsafe.Pointer(doc))
}
func XMLEncodeEntitiesReentrant(docptr *C.xmlDoc, s string) (*C.xmlChar, error) {
cent := stringToXMLChar(s)
defer C.free(unsafe.Pointer(cent))
return C.xmlEncodeEntitiesReentrant(docptr, cent), nil
}
func isSafeName(name string) error {
if utf8.ValidString(name) { // UTF-8, we can do everything in go
if len(name) > MaxValueBufferSize {
return ErrValueTooLong
}
p := name
r, n := utf8.DecodeRuneInString(p)
p = p[n:]
if !unicode.IsLetter(r) && r != '_' && r != ':' {
return ErrInvalidNodeName
}
for len(p) > 0 {
r, n = utf8.DecodeRuneInString(p)
p = p[n:]
if !unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_' && r != ':' {
return ErrInvalidNodeName
}
}
return nil
}
// Need to call out to C
var buf [MaxValueBufferSize]C.xmlChar
for i := 0; i < len(name); i++ {
buf[i] = C.xmlChar(name[i])
}
bufptr := unsafe.Pointer(&buf[0])
if C.MY_test_node_name((*C.xmlChar)(bufptr)) == 0 {
return ErrInvalidNodeName
}
return nil
}
func validNamespacePtr(s PtrSource) (*C.xmlNs, error) {
if s == nil {
return nil, ErrInvalidNamespace
}
if ptr := s.Pointer(); ptr != 0 {
return (*C.xmlNs)(unsafe.Pointer(ptr)), nil
}
return nil, ErrInvalidNamespace
}
func XMLNewNode(ns PtrSource, name string) (uintptr, error) {
nsptr, err := validNamespacePtr(ns)
if err != nil {
return 0, err
}
if err := isSafeName(name); err != nil {
return 0, err
}
var cname [MaxElementNameLength]C.xmlChar
if len(name) > MaxElementNameLength {
return 0, ErrElementNameTooLong
}
for i := 0; i < len(name); i++ {
cname[i] = C.xmlChar(name[i])
}
cnameptr := unsafe.Pointer(&cname[0])
n := C.xmlNewNode(
(*C.xmlNs)(unsafe.Pointer(nsptr)),
(*C.xmlChar)(cnameptr),
)
return uintptr(unsafe.Pointer(n)), nil
}
func XMLNewDocProp(doc PtrSource, k, v string) (uintptr, error) {
docptr, err := validDocumentPtr(doc)
if err != nil {
return 0, err
}
if err := isSafeName(k); err != nil {
return 0, err
}
if len(k) > MaxAttributeNameLength {
return 0, ErrAttributeNameTooLong
}
var kx [MaxAttributeNameLength]C.xmlChar
for i := 0; i < len(k); i++ {
kx[i] = C.xmlChar(k[i])
}
// Taking the pointer as uintptr somehow fools the go compiler
// to not think this escapes to heap
kxptr := unsafe.Pointer(&kx[0])
ent, err := XMLEncodeEntitiesReentrant(docptr, v)
if err != nil {
return 0, err
}
attr := C.xmlNewDocProp(docptr, (*C.xmlChar)(kxptr), ent)
return uintptr(unsafe.Pointer(attr)), nil
}
func XMLSearchNsByHref(doc PtrSource, _ PtrSource, uri string) (uintptr, error) {
docptr, err := validDocumentPtr(doc)
if err != nil {
return 0, err
}
nptr, err := validNodePtr(doc)
if err != nil {
return 0, err
}
if len(uri) > MaxNamespaceURILength {
return 0, ErrNamespaceURITooLong
}
var xcuri [MaxNamespaceURILength]C.xmlChar
for i := 0; i < len(uri); i++ {
xcuri[i] = C.xmlChar(uri[i])
}
xcuriptr := unsafe.Pointer(&xcuri[0])
ns := C.xmlSearchNsByHref(
(*C.xmlDoc)(unsafe.Pointer(docptr)),
(*C.xmlNode)(unsafe.Pointer(nptr)),
(*C.xmlChar)(xcuriptr),
)
if ns == nil {
return 0, ErrNamespaceNotFound{Target: uri}
}
return uintptr(unsafe.Pointer(ns)), nil
}
func XMLSearchNs(doc PtrSource, n PtrSource, prefix string) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
docptr, err := validDocumentPtr(doc)
if err != nil {
return 0, err
}
cprefix := stringToXMLChar(prefix)
defer C.free(unsafe.Pointer(cprefix))
ns := C.xmlSearchNs(docptr, nptr, cprefix)
if ns == nil {
return 0, ErrNamespaceNotFound{Target: prefix}
}
return uintptr(unsafe.Pointer(ns)), nil
}
func XMLNewDocNode(doc PtrSource, ns PtrSource, local, content string) (uintptr, error) {
docptr, err := validDocumentPtr(doc)
if err != nil {
return 0, err
}
nsptr, err := validNamespacePtr(ns)
if err != nil {
return 0, err
}
var c *C.xmlChar
if len(content) > 0 {
c = stringToXMLChar(content)
defer C.free(unsafe.Pointer(c))
}
clocal := stringToXMLChar(local)
defer C.free(unsafe.Pointer(c))
ptr := C.xmlNewDocNode(docptr, nsptr, clocal, c)
if ptr == nil {
return 0, errors.New("failed to create node")
}
return uintptr(unsafe.Pointer(ptr)), nil
}
func XMLNewNs(n PtrSource, nsuri, prefix string) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
var cprefix *C.xmlChar
cnsuri := stringToXMLChar(nsuri)
if prefix != "" {
cprefix = stringToXMLChar(prefix)
defer C.free(unsafe.Pointer(cprefix))
}
defer C.free(unsafe.Pointer(cnsuri))
nsptr := C.xmlNewNs(nptr, cnsuri, cprefix)
if nsptr == nil {
return 0, errors.New("failed to create namespace")
}
return uintptr(unsafe.Pointer(nsptr)), nil
}
func XMLSetNs(n PtrSource, ns PtrSource) error {
nptr, err := validNodePtr(n)
if err != nil {
return err
}
nsptr, err := validNamespacePtr(ns)
if err != nil {
return err
}
C.xmlSetNs(nptr, nsptr)
return nil
}
func XMLNewCDataBlock(doc PtrSource, txt string) (uintptr, error) {
dptr, err := validDocumentPtr(doc)
if err != nil {
return 0, err
}
ctxt := stringToXMLChar(txt)
defer C.free(unsafe.Pointer(ctxt))
ptr := C.xmlNewCDataBlock(dptr, ctxt, C.int(len(txt)))
if ptr == nil {
return 0, errors.New("failed to create CDATA block")
}
return uintptr(unsafe.Pointer(ptr)), nil
}
func XMLNewComment(txt string) (uintptr, error) {
ctxt := stringToXMLChar(txt)
defer C.free(unsafe.Pointer(ctxt))
ptr := C.xmlNewComment(ctxt)
if ptr == nil {
return 0, errors.New("failed to create comment node")
}
return uintptr(unsafe.Pointer(ptr)), nil
}
func XMLNewText(txt string) (uintptr, error) {
ctxt := stringToXMLChar(txt)
defer C.free(unsafe.Pointer(ctxt))
ptr := C.xmlNewText(ctxt)
if ptr == nil {
return 0, errors.New("failed to create text node")
}
return uintptr(unsafe.Pointer(ptr)), nil
}
func XMLNodeName(n PtrSource) (string, error) {
nptr, err := validNodePtr(n)
if err != nil {
return "", err
}
var s string
switch XMLNodeType(nptr._type) {
case XIncludeStart, XIncludeEnd, EntityRefNode, EntityNode, DTDNode, EntityDecl, DocumentTypeNode, NotationNode, NamespaceDecl:
s = xmlCharToString(nptr.name)
case CommentNode:
s = "#comment"
case CDataSectionNode:
s = "#cdata-section"
case TextNode:
s = "#text"
case DocumentNode, HTMLDocumentNode, DocbDocumentNode:
s = "#document"
case DocumentFragNode:
s = "#document-fragment"
case ElementNode, AttributeNode:
if ns := nptr.ns; ns != nil {
if nsstr := xmlCharToString(ns.prefix); nsstr != "" {
s = fmt.Sprintf("%s:%s", xmlCharToString(ns.prefix), xmlCharToString(nptr.name))
}
}
if s == "" {
s = xmlCharToString(nptr.name)
}
case ElementDecl, AttributeDecl:
panic("unimplemented")
default:
panic("unknown")
}
return s, nil
}
func XMLNodeValue(n PtrSource) (string, error) {
nptr, err := validNodePtr(n)
if err != nil {
return "", err
}
var s string
switch XMLNodeType(nptr._type) {
case AttributeNode, ElementNode, TextNode, CommentNode, PiNode, EntityRefNode:
xc := C.xmlXPathCastNodeToString(nptr)
s = xmlCharToString(xc)
C.MY_xmlFree(unsafe.Pointer(xc))
case CDataSectionNode, EntityDecl:
if nptr.content != nil {
xc := C.xmlStrdup(nptr.content)
s = xmlCharToString(xc)
C.MY_xmlFree(unsafe.Pointer(xc))
}
default:
panic("unimplmented")
}
return s, nil
}
func XMLAddChild(n PtrSource, child PtrSource) error {
nptr, err := validNodePtr(n)
if err != nil {
return err
}
cptr, err := validNodePtr(child)
if err != nil {
return err
}
if C.xmlAddChild(nptr, cptr) == nil {
return errors.New("failed to add child")
}
return nil
}
func XMLOwnerDocument(n PtrSource) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
if nptr.doc == nil {
return 0, ErrInvalidDocument
}
return uintptr(unsafe.Pointer(nptr.doc)), nil
}
func XMLFirstChild(n PtrSource) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
if !XMLHasChildNodes(n) {
return 0, errors.New("no children")
}
return uintptr(unsafe.Pointer(nptr.children)), nil
}
func XMLHasChildNodes(n PtrSource) bool {
nptr, err := validNodePtr(n)
if err != nil {
return false
}
return nptr.children != nil
}
func XMLLastChild(n PtrSource) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
return uintptr(unsafe.Pointer(nptr.last)), nil
}
func XMLLocalName(n PtrSource) string {
nptr, err := validNodePtr(n)
if err != nil {
return ""
}
switch XMLNodeType(nptr._type) {
case ElementNode, AttributeNode, ElementDecl, AttributeDecl:
return xmlCharToString(nptr.name)
}
return ""
}
func XMLNamespaceURI(n PtrSource) string {
nptr, err := validNodePtr(n)
if err != nil {
return ""
}
switch XMLNodeType(nptr._type) {
case ElementNode, AttributeNode, PiNode:
if ns := nptr.ns; ns != nil && ns.href != nil {
return xmlCharToString(ns.href)
}
}
return ""
}
func XMLNextSibling(n PtrSource) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err
}
return uintptr(unsafe.Pointer(nptr.next)), nil
}
func XMLParentNode(n PtrSource) (uintptr, error) {
nptr, err := validNodePtr(n)
if err != nil {
return 0, err