summaryrefslogtreecommitdiffstats
path: root/lasso/xml/xml.c
blob: 93decebfe3b469244acdaab80d86a86149f7dc75 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
/* $Id$ 
 *
 * Lasso - A free implementation of the Liberty Alliance specifications.
 *
 * Copyright (C) 2004 Entr'ouvert
 * http://lasso.entrouvert.org
 * 
 * Authors: Nicolas Clapies <nclapies@entrouvert.com>
 *          Valery Febvre <vfebvre@easter-eggs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <ctype.h>

#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

#include <xmlsec/base64.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/xmldsig.h>
#include <xmlsec/templates.h>
#include <xmlsec/crypto.h>

#include <lasso/xml/xml.h>
#include <lasso/xml/saml_name_identifier.h>



static void lasso_node_build_xmlNode_from_snippets(
		LassoNode *node, xmlNode *xmlnode, struct XmlSnippet *snippets);


/*****************************************************************************/
/* virtual public methods                                                    */
/*****************************************************************************/

/**
 * lasso_node_dump:
 * @node: a LassoNode
 * @encoding: the name of the encoding to use or NULL.
 * @format: is formatting allowed
 * 
 * Dumps @node. All datas in object are dumped in an XML format.
 * 
 * Return value: a full XML dump of @node
 **/
char*
lasso_node_dump(LassoNode *node, const char *encoding, int format)
{
	xmlNode *xmlnode;
	char *ret;
	xmlOutputBufferPtr buf;
	xmlCharEncodingHandlerPtr handler = NULL;

	g_return_val_if_fail (LASSO_IS_NODE(node), NULL);
	/* encoding is optional */
	g_return_val_if_fail (format == 0 || format == 1, NULL);

	if (encoding != NULL) {
		handler = xmlFindCharEncodingHandler(encoding);
		if (handler == NULL) {
			return NULL;
		}
	}
	buf = xmlAllocOutputBuffer(handler);
	if (buf == NULL) {
		return NULL;
	}
	xmlnode = lasso_node_get_xmlNode(node);
	xmlNodeDumpOutput(buf, NULL, xmlnode, 0, format, encoding);
	xmlOutputBufferFlush(buf);
	if (buf->conv != NULL) {
		ret = g_strdup(buf->conv->content);
	}
	else {
		ret = g_strdup(buf->buffer->content);
	}
	xmlOutputBufferClose(buf);

	xmlFreeNode(xmlnode);

	return ret;

}

/**
 * lasso_node_destroy:
 * @node: a LassoNode
 * 
 * Destroys the LassoNode.
 **/
void
lasso_node_destroy(LassoNode *node)
{
	if (LASSO_IS_NODE(node)) {
		LassoNodeClass *class = LASSO_NODE_GET_CLASS(node);
		class->destroy(node);
	}
}

static xmlNode*
lasso_node_export_to_signed_xmlnode(LassoNode *node,
		const char *private_key_file, const char *certificate_file)
{
	xmlDoc *doc;
	xmlNode *message, *sign_tmpl;
	xmlSecDSigCtx *dsig_ctx;
	char *id_attr_name = NULL;

	message = lasso_node_get_xmlNode(node);

	sign_tmpl = xmlSecFindNode(message, xmlSecNodeSignature, xmlSecDSigNs);
	if (sign_tmpl && private_key_file) {
		doc = xmlNewDoc("1.0");
		xmlDocSetRootElement(doc, message);
		xmlSetTreeDoc(sign_tmpl, doc);
		if (LASSO_NODE_GET_CLASS(node)->get_sign_attr_name)
			id_attr_name = LASSO_NODE_GET_CLASS(node)->get_sign_attr_name();
		if (id_attr_name) {
			char *id_value = xmlGetProp(message, id_attr_name);
			xmlAttr *id_attr = xmlHasProp(message, id_attr_name);
			if (id_value) {
				xmlAddID(NULL, doc, id_value, id_attr);
				xmlFree(id_value);
			}
		}

		dsig_ctx = xmlSecDSigCtxCreate(NULL);
		dsig_ctx->signKey = xmlSecCryptoAppKeyLoad(private_key_file,
				xmlSecKeyDataFormatPem,
				NULL, NULL, NULL);
		if (dsig_ctx->signKey == NULL) {
			/* XXX: file existence should actually be tested on
			 * LassoServer creation */
			message(G_LOG_LEVEL_CRITICAL,
					lasso_strerror(LASSO_DS_ERROR_PRIVATE_KEY_LOAD_FAILED),
					private_key_file);
			xmlSecDSigCtxDestroy(dsig_ctx);
			return NULL;
		}
		if (certificate_file != NULL && certificate_file[0] != 0) {
			if (xmlSecCryptoAppKeyCertLoad(dsig_ctx->signKey, certificate_file,
						xmlSecKeyDataFormatPem) < 0) {
				message(G_LOG_LEVEL_CRITICAL,
					lasso_strerror(LASSO_DS_ERROR_CERTIFICATE_LOAD_FAILED),
					certificate_file);
				xmlSecDSigCtxDestroy(dsig_ctx);
				return NULL;
			}
		}
		if (xmlSecDSigCtxSign(dsig_ctx, sign_tmpl) < 0) {
			message(G_LOG_LEVEL_CRITICAL,
					lasso_strerror(LASSO_DS_ERROR_SIGNATURE_FAILED),
					message->name);
			xmlSecDSigCtxDestroy(dsig_ctx);
			return NULL;
		}
		xmlSecDSigCtxDestroy(dsig_ctx);
		xmlUnlinkNode(message);
		xmlFreeDoc(doc);
	}

	return message;
}


/**
 * lasso_node_export_to_base64:
 * @node: a LassoNode
 * @private_key_file: path to private key for signature
 * @certificate_file: path to certificate for signature
 * 
 * Base64 XML dump
 * 
 * Return value: a Base64 encoded export of the LassoNode
 **/
char*
lasso_node_export_to_base64(LassoNode *node,
		const char *private_key_file, const char *certificate_file)
{
	xmlNode *message;
	xmlOutputBufferPtr buf;
	xmlCharEncodingHandlerPtr handler = NULL;
	char *buffer;
	char *ret;

	message = lasso_node_export_to_signed_xmlnode(node, private_key_file, certificate_file);

	handler = xmlFindCharEncodingHandler("utf-8");
	buf = xmlAllocOutputBuffer(handler);
	xmlNodeDumpOutput(buf, NULL, message, 0, 0, "utf-8");
	xmlOutputBufferFlush(buf);
	buffer = buf->conv ? buf->conv->content : buf->buffer->content;

	ret = xmlSecBase64Encode(buffer, strlen(buffer), 0);
	xmlOutputBufferClose(buf);

	return ret;
}

/**
 * lasso_node_export_to_query:
 * @node: a LassoNode
 * @sign_method: the Signature transform method
 * @private_key_file: a private key (may be NULL)
 * 
 * URL-encodes and signes the LassoNode.
 * If private_key_file is NULL, query won't be signed.
 * 
 * Return value: URL-encoded and signed LassoNode
 **/
char*
lasso_node_export_to_query(LassoNode *node,
		lassoSignatureMethod sign_method, const char *private_key_file)
{
	char *unsigned_query, *query;

	g_return_val_if_fail (LASSO_IS_NODE(node), NULL);

	unsigned_query = lasso_node_build_query(node);
	if (private_key_file)
		query = lasso_query_sign(unsigned_query, sign_method, private_key_file);
	else
		query = g_strdup(unsigned_query);
	g_free(unsigned_query);

	return query;
}

/**
 * lasso_node_export_to_soap:
 * @node: a LassoNode
 * @private_key_file: path to private key for signature
 * @certificate_file: path to certificate for signature
 * 
 * Like lasso_node_export() method except that result is SOAP enveloped.
 * 
 * Return value: a SOAP enveloped export of the LassoNode
 **/
char*
lasso_node_export_to_soap(LassoNode *node,
		const char *private_key_file, const char *certificate_file)
{
	xmlNode *envelope, *body, *message;
	xmlOutputBuffer *buf;
	xmlCharEncodingHandler *handler;
	char *ret;

	g_return_val_if_fail (LASSO_IS_NODE(node), NULL);

	message = lasso_node_export_to_signed_xmlnode(node, private_key_file, certificate_file);

	envelope = xmlNewNode(NULL, "Envelope");
	xmlSetNs(envelope, xmlNewNs(envelope, LASSO_SOAP_ENV_HREF, LASSO_SOAP_ENV_PREFIX));

	body = xmlNewTextChild(envelope, NULL, "Body", NULL);
	xmlAddChild(body, message);

	handler = xmlFindCharEncodingHandler("utf-8");
	buf = xmlAllocOutputBuffer(handler);
	xmlNodeDumpOutput(buf, NULL, envelope, 0, 0, "utf-8");
	xmlOutputBufferFlush(buf);
	ret = g_strdup( buf->conv ? buf->conv->content : buf->buffer->content );
	xmlOutputBufferClose(buf);

	xmlFreeNode(envelope);

	return ret;
}


gboolean
lasso_node_init_from_query(LassoNode *node, const char *query)
{
	LassoNodeClass *class;
	char **query_fields;
	int i;
	gboolean rc;

	g_return_val_if_fail(LASSO_IS_NODE(node), FALSE);
	class = LASSO_NODE_GET_CLASS(node);

	query_fields = urlencoded_to_strings(query);
	rc = class->init_from_query(node, query_fields);
	for (i=0; query_fields[i]; i++) {
		free(query_fields[i]);
	}
	free(query_fields);
	return rc;
}

int
lasso_node_init_from_xml(LassoNode *node, xmlNode *xmlnode)
{
	LassoNodeClass *class;

	g_return_val_if_fail(LASSO_IS_NODE(node), -1);
	class = LASSO_NODE_GET_CLASS(node);

	return class->init_from_xml(node, xmlnode);
}


/**
 * lasso_node_verify_signature:
 * @node: a LassoNode
 * @public_key_file: a public key (or a certificate) file
 * @ca_cert_chain_file: a CA certificate chain file
 * 
 * Verifies the node signature of @node.
 * 
 * Return value: 0 if signature is valid
 * a positive value if signature was not found or is invalid
 * a negative value if an error occurs during verification
 **/
gint
lasso_node_verify_signature(LassoNode *node,
		const char *public_key_file, const char *ca_cert_chain_file)
{
	return 0;
#if 0 /* XXX: signature should be verified when importing request */
	xmlDocPtr doc = NULL;
	xmlNodePtr xmlNode = NULL;
	xmlNodePtr signature = NULL;
	xmlNodePtr x509data = NULL;
	xmlSecKeysMngrPtr keys_mngr = NULL;
	xmlSecDSigCtxPtr dsigCtx = NULL;
	xmlIDPtr id;
	xmlAttrPtr id_attr;
	xmlChar *id_value;
	lassoPemFileType public_key_file_type;
	gint ret = 0;

	doc = xmlNewDoc("1.0");
	/* Don't use xmlCopyNode here because it changes the attrs and ns order :-( */
	xmlNode = lasso_node_get_xmlNode(node);
	xmlAddChild((xmlNodePtr)doc, xmlNode);

	/* FIXME : register 'AssertionID' ID attribute manually */
	id_attr = lasso_node_get_attr(node, "AssertionID", NULL);
	if (id_attr != NULL) {
		id_value = xmlNodeListGetString(doc, id_attr->children, 1);
		id = xmlAddID(NULL, doc, id_value, id_attr);
		xmlFree(id_value);
	}

	/* find start node */
	signature = xmlSecFindNode(xmlNode, xmlSecNodeSignature,
			xmlSecDSigNs);
	if (signature == NULL) {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_SIGNATURE_NOT_FOUND),
				node->private->node->name);
		ret = LASSO_DS_ERROR_SIGNATURE_NOT_FOUND;
		goto done;	
	}

	x509data = xmlSecFindNode(xmlNode, xmlSecNodeX509Data,
			xmlSecDSigNs);
	if (x509data != NULL && ca_cert_chain_file != NULL) {
		/* create a keys manager */
		keys_mngr = lasso_load_certs_from_pem_certs_chain_file(ca_cert_chain_file);
		if (keys_mngr == NULL) {
			message(G_LOG_LEVEL_CRITICAL,
					lasso_strerror(LASSO_DS_ERROR_CA_CERT_CHAIN_LOAD_FAILED));
			ret = LASSO_DS_ERROR_CA_CERT_CHAIN_LOAD_FAILED;
			goto done;
		}
	}

	/* create signature context */
	dsigCtx = xmlSecDSigCtxCreate(keys_mngr);
	if (dsigCtx == NULL) {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_CONTEXT_CREATION_FAILED));
		ret = LASSO_DS_ERROR_CONTEXT_CREATION_FAILED;
		goto done;
	}

	if (keys_mngr == NULL) {
		if (public_key_file != NULL) {
			/* auto-detect public_key_file type */
			public_key_file_type = lasso_get_pem_file_type(public_key_file);
			if (public_key_file_type == LASSO_PEM_FILE_TYPE_CERT) {
				/* public_key_file is a certificate file => get public key in it */
				dsigCtx->signKey = lasso_get_public_key_from_pem_cert_file(
						public_key_file);
			}
			else {
				/* load public key */
				dsigCtx->signKey = xmlSecCryptoAppKeyLoad(public_key_file,
						xmlSecKeyDataFormatPem,
						NULL, NULL, NULL);
			}
		}
		if (dsigCtx->signKey == NULL) {
			message(G_LOG_LEVEL_CRITICAL,
					lasso_strerror(LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED),
					public_key_file);
			ret = LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED;
			goto done;
		}
	}

	/* verify signature */
	if (xmlSecDSigCtxVerify(dsigCtx, signature) < 0) {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_SIGNATURE_VERIFICATION_FAILED),
				node->private->node->name);
		ret = LASSO_DS_ERROR_SIGNATURE_VERIFICATION_FAILED;
		goto done;
	}

	if (dsigCtx->status == xmlSecDSigStatusSucceeded) {
		ret = 0;
	}
	else {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_INVALID_SIGNATURE),
				node->private->node->name);
		ret = LASSO_DS_ERROR_INVALID_SIGNATURE;
	}

done:
	/* cleanup */
	if(dsigCtx != NULL) {
		xmlSecDSigCtxDestroy(dsigCtx);
	}
	if(keys_mngr != NULL) {
		xmlSecKeysMngrDestroy(keys_mngr);
	}
	/* FIXME xmlFreeDoc(doc); */
	return ret;
#endif
}

/*****************************************************************************/
/* virtual private methods                                                   */
/*****************************************************************************/

char*
lasso_node_build_query(LassoNode *node)
{
	LassoNodeClass *class;
	g_return_val_if_fail (LASSO_IS_NODE(node), NULL);

	class = LASSO_NODE_GET_CLASS(node);
	return class->build_query(node);
}

xmlNodePtr
lasso_node_get_xmlNode(LassoNode *node)
{
	LassoNodeClass *class;
	g_return_val_if_fail (LASSO_IS_NODE(node), NULL);
	class = LASSO_NODE_GET_CLASS(node);
	return class->get_xmlNode(node);
}

/*****************************************************************************/
/* implementation methods                                                    */
/*****************************************************************************/

static void
lasso_node_impl_destroy(LassoNode *node)
{
	g_object_unref(G_OBJECT(node));
}

static int
lasso_node_impl_init_from_xml(LassoNode *node, xmlNode *xmlnode)
{
	struct XmlSnippet *snippet;
	xmlNode *t;
	LassoNodeClass *class;
	void *value;
	SnippetType type;

	class = LASSO_NODE_GET_CLASS(node);

	if (class->node_data == NULL)
		return 0;

	while (class && LASSO_IS_NODE_CLASS(class) && class->node_data) {
		
		for (t = xmlnode->children; t; t = t->next) {
			if (t->type != XML_ELEMENT_NODE)
				continue;

			for (snippet = class->node_data->snippets;
					snippet && snippet->name; snippet++) {
				type = snippet->type & 0xff;
				value = G_STRUCT_MEMBER_P(node, snippet->offset);

				if (strcmp(t->name, snippet->name) != 0)
					continue;

				if (type == SNIPPET_NODE) {
					(*(LassoNode**)value) = lasso_node_new_from_xmlNode(t);
				} else if (type == SNIPPET_NODE_IN_CHILD) {
					xmlNode *t2 = t->children;
					while (t2 && t2->type != XML_ELEMENT_NODE)
						t2 = t2->next;
					if (t2)
						(*(LassoNode**)value) =
							lasso_node_new_from_xmlNode(t2);
				} else if (type == SNIPPET_CONTENT)
					(*(char**)value) = xmlNodeGetContent(t);
				else if (type == SNIPPET_NAME_IDENTIFIER)
					(*(LassoSamlNameIdentifier**)value) =
						lasso_saml_name_identifier_new_from_xmlNode(t);
				else if (type == SNIPPET_LIST_NODES) {
					GList **location = value;
					LassoNode *n = lasso_node_new_from_xmlNode(t);
					*location = g_list_append(*location, n);
				} else if (type == SNIPPET_LIST_CONTENT) {
					GList **location = value;
					xmlChar *s = xmlNodeGetContent(t);
					*location = g_list_append(*location, s);
				}
				break;
			}
		}

		for (snippet = class->node_data->snippets; snippet && snippet->name; snippet++) {
			type = snippet->type & 0xff;
			value = G_STRUCT_MEMBER_P(node, snippet->offset);
			if (type == SNIPPET_ATTRIBUTE)
				(*(char**)value) = xmlGetProp(xmlnode, snippet->name);
			if (type == SNIPPET_TEXT_CHILD)
				(*(char**)value) = xmlNodeGetContent(xmlnode);
		}

		/* last turn; fixup types */
		for (snippet = class->node_data->snippets; snippet && snippet->name; snippet++) {
			value = G_STRUCT_MEMBER_P(node, snippet->offset);
			if (snippet->type & SNIPPET_INTEGER) {
				char *s = *(char**)value;
				int val = atoi(s);
				xmlFree(s);
				(*(void**)value) = GINT_TO_POINTER(val);
			}

			if (snippet->type & SNIPPET_BOOLEAN) {
				char *s = *(char**)value;
				int val = (strcmp(s, "true") == 0);
				(*(void**)value) = GINT_TO_POINTER(val);
				xmlFree(s);
			}
		}

		class = g_type_class_peek_parent(class);
	}
	return 0;
}

/*** private methods **********************************************************/

static char*
lasso_node_impl_build_query(LassoNode *node)
{
	g_assert_not_reached();
	return NULL;
}

static xmlNode*
lasso_node_impl_get_xmlNode(LassoNode *node)
{
	LassoNodeClass *class = LASSO_NODE_GET_CLASS(node);
	xmlNode *xmlnode;
	xmlNs *ns;
	GList *list_ns = NULL, *t;

	if (class->node_data == NULL)
		return NULL;

	xmlnode = xmlNewNode(NULL, class->node_data->node_name);
	while (class && LASSO_IS_NODE_CLASS(class) && class->node_data) {
		if (class->node_data->ns)
			list_ns = g_list_append(list_ns, class->node_data->ns);
		lasso_node_build_xmlNode_from_snippets(node, xmlnode, class->node_data->snippets);
		class = g_type_class_peek_parent(class);
	}

	t = g_list_first(list_ns);
	while (t) {
		ns = t->data;
		xmlNewNs(xmlnode, ns->href, ns->prefix);
		t = g_list_next(t);
	}

	xmlSetNs(xmlnode, xmlnode->nsDef);

	xmlReconciliateNs(NULL, xmlnode);

	return xmlnode;
}

/*****************************************************************************/
/* overridden parent class methods                                           */
/*****************************************************************************/

static GObjectClass *parent_class = NULL;

static void
lasso_node_dispose(GObject *object)
{
	LassoNodeClass *class;
	struct XmlSnippet *snippet;
	SnippetType type;

	class = LASSO_NODE_GET_CLASS(object);
	while (class && LASSO_IS_NODE_CLASS(class) && class->node_data) {
		for (snippet = class->node_data->snippets; snippet && snippet->name; snippet++) {
			void **value = G_STRUCT_MEMBER_P(object, snippet->offset);
			type = snippet->type & 0xff;

			if (snippet->type & SNIPPET_BOOLEAN)
				continue;
			if (snippet->type & SNIPPET_INTEGER)
				continue;

			if (*value == NULL)
				continue;

#if 0 /* to debug memory management problems */
			fprintf(stderr, "freeing %s/%s (at %p)\n",
					G_OBJECT_TYPE_NAME(object), snippet->name, *value);
#endif
			if (snippet->type & SNIPPET_NODE) {
				g_object_unref(*value);
			} else {
				g_free(*value);
			}

			/* XXX: memory management for lists */
			*value = NULL;
		}
		class = g_type_class_peek_parent(class);
	}

	parent_class->dispose(object);
}

static void
lasso_node_finalize(GObject *object)
{
	parent_class->finalize(object);
}

/*****************************************************************************/
/* instance and class init functions                                         */
/*****************************************************************************/

static void
instance_init(LassoNode *node)
{
}

static void
class_init(LassoNodeClass *class)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS(class);

	parent_class = g_type_class_peek_parent(class);
	/* virtual public methods */
	class->destroy = lasso_node_impl_destroy;
	class->init_from_query = NULL;
	class->init_from_xml = lasso_node_impl_init_from_xml;
	class->get_sign_attr_name = NULL;

	/* virtual private methods */
	class->build_query = lasso_node_impl_build_query;
	class->get_xmlNode = lasso_node_impl_get_xmlNode;

	/* override */
	gobject_class->dispose = lasso_node_dispose;
	gobject_class->finalize = lasso_node_finalize;

	class->node_data = NULL;
}

GType
lasso_node_get_type()
{
	static GType this_type = 0;

	if (!this_type) {
		static const GTypeInfo this_info = {
			sizeof (LassoNodeClass),
			NULL,
			NULL,
			(GClassInitFunc) class_init,
			NULL,
			NULL,
			sizeof(LassoNode),
			0,
			(GInstanceInitFunc) instance_init,
		};

		this_type = g_type_register_static(G_TYPE_OBJECT , "LassoNode", &this_info, 0);
	}
	return this_type;
}

/**
 * lasso_node_new:
 * 
 * The main LassoNode constructor.
 * 
 * Return value: a new node
 **/
LassoNode*
lasso_node_new()
{
	return g_object_new(LASSO_TYPE_NODE, NULL);
}

LassoNode*
lasso_node_new_from_dump(const char *dump)
{
	LassoNode *node;
	xmlDoc *doc;

	doc = xmlParseMemory(dump, strlen(dump));
	node = lasso_node_new_from_xmlNode(xmlDocGetRootElement(doc));
	xmlFreeDoc(doc);
	return node;
}

LassoNode*
lasso_node_new_from_soap(const char *soap)
{
	xmlDoc *doc;
	xmlXPathContext *xpathCtx;
	xmlXPathObject *xpathObj;
	xmlNode *xmlnode;
	LassoNode *node = NULL;

	doc = xmlParseMemory(soap, strlen(soap));
	xpathCtx = xmlXPathNewContext(doc);
	xmlXPathRegisterNs(xpathCtx, "s", LASSO_SOAP_ENV_HREF);
	xpathObj = xmlXPathEvalExpression("//s:Body/*", xpathCtx);

	xmlnode = xpathObj->nodesetval->nodeTab[0];

	if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr)
		node = lasso_node_new_from_xmlNode(xmlnode);

	xmlFreeDoc(doc);
	xmlXPathFreeContext(xpathCtx);
	xmlXPathFreeObject(xpathObj);

	return node;
}

/**
 * lasso_node_new_from_xmlNode:
 * @node: an xmlNode
 * 
 * Builds a new LassoNode from an xmlNode.
 * 
 * Return value: a new node
 **/
LassoNode*
lasso_node_new_from_xmlNode(xmlNode *xmlnode)
{
	char *prefix = NULL;
	char *typename;
	GType gtype;
	LassoNode *node;
	char *xsitype;
	int rc;

	if (xmlnode == NULL || xmlnode->ns == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Impossible to build LassoNode from xml node");
		return NULL;
	}

	if (strcmp(xmlnode->ns->href, LASSO_DISCO_HREF) == 0)
		prefix = "Disco";
	if (strcmp(xmlnode->ns->href, LASSO_LIB_HREF) == 0)
		prefix = "Lib";
	if (strcmp(xmlnode->ns->href, LASSO_LASSO_HREF) == 0)
		prefix = "";
	if (strcmp(xmlnode->ns->href, LASSO_SAML_ASSERTION_HREF) == 0)
		prefix = "Saml";
	if (strcmp(xmlnode->ns->href, LASSO_SAML_PROTOCOL_HREF) == 0)
		prefix = "Samlp";

	/* XXX: new Dst namespaces can be added dynamically; they should not
	 * be hardcoded here
	 */
	if (strcmp(xmlnode->ns->href, LASSO_PP_HREF) == 0)
		prefix = "Dst";
	if (strcmp(xmlnode->ns->href, LASSO_EP_HREF) == 0)
		prefix = "Dst";

	xsitype = xmlGetNsProp(xmlnode, "type", LASSO_XSI_HREF);
	if (xsitype) {
		/* XXX: should look for proper namespace prefix declaration
		 * and not assumes blindly that lib: is the liberty prefix;
		 * should also use the declared type to get the proper typename
		 * instead of falling back to good ol' xmlnode->name later.
		 * yada yada
		 */
		if (strncmp(xsitype, "lib:", 4) == 0)
			prefix = "Lib";
		xmlFree(xsitype);
	}

	if (prefix == NULL)
		return NULL;

	typename = g_strdup_printf("Lasso%s%s", prefix, xmlnode->name);

	gtype = g_type_from_name(typename);
	g_free(typename);
	if (gtype == 0)
		return NULL;

	node = g_object_new(gtype, NULL);
	rc = lasso_node_init_from_xml(node, xmlnode);
	if (rc) {
		g_object_unref(node);
		return NULL;
	}

	return node;
}

static gboolean
is_base64(const char *message)
{
	const char *c;

	c = message;
	while (*c != 0 && (isalnum(*c) || *c == '+' || *c == '/')) c++;
	while (*c == '=') c++; /* trailing = */

	if (*c == 0)
		return TRUE;

	return FALSE;
}

LassoMessageFormat
lasso_node_init_from_message(LassoNode *node, const char *message)
{
	char *msg;
	gboolean b64 = FALSE;
	int rc;

	msg = (char*)message;
	if (message[0] != 0 && is_base64(message)) {
		msg = g_malloc(strlen(message));
		rc = xmlSecBase64Decode(message, msg, strlen(message));
		if (rc >= 0) {
			b64 = TRUE;
		} else {
			/* oops; was not base64 after all */
			g_free(msg);
			msg = (char*)message;
		}
	}

	if (strchr(msg, '<')) {
		/* looks like xml */
		xmlDoc *doc;
		xmlNode *root;
		xmlXPathContext *xpathCtx = NULL;
		xmlXPathObject *xpathObj;

		doc = xmlParseMemory(msg, strlen(msg));
		if (doc == NULL)
			return LASSO_MESSAGE_FORMAT_UNKNOWN;
		root = xmlDocGetRootElement(doc);
		if (root->ns && strcmp(root->ns->href, LASSO_SOAP_ENV_HREF) == 0) {
			xpathCtx = xmlXPathNewContext(doc);
			xmlXPathRegisterNs(xpathCtx, "s", LASSO_SOAP_ENV_HREF);
			xpathObj = xmlXPathEvalExpression("//s:Body/*", xpathCtx);
			if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr ) {
				root = xpathObj->nodesetval->nodeTab[0];
			}
			xmlXPathFreeObject(xpathObj);
			xmlXPathFreeContext(xpathCtx);
		}
		lasso_node_init_from_xml(node, root);
		xmlFreeDoc(doc);
		if (xpathCtx)
			return LASSO_MESSAGE_FORMAT_SOAP;
		if (b64) {
			g_free(msg);
			return LASSO_MESSAGE_FORMAT_BASE64;
		}
		return LASSO_MESSAGE_FORMAT_XML;
	}

	if (strchr(msg, '&')) {
		/* looks like a query string */
		if (lasso_node_init_from_query(node, msg) == FALSE) {
			return LASSO_MESSAGE_FORMAT_ERROR;
		}
		return LASSO_MESSAGE_FORMAT_QUERY;
	}

	return LASSO_MESSAGE_FORMAT_UNKNOWN;
}


/**
 * lasso_node_class_add_snippets
 * @klass: object class
 * @snippets: array of XmlSnippet (NULL terminated)
 **/
void
lasso_node_class_add_snippets(LassoNodeClass *klass, struct XmlSnippet *snippets)
{
	klass->node_data->snippets = snippets;
}


/**
 * lasso_node_class_set_nodename
 * @klass: object class
 * @name: name for element node
 **/
void
lasso_node_class_set_nodename(LassoNodeClass *klass, char *name)
{
	if (klass->node_data->node_name)
		g_free(klass->node_data->node_name);
	klass->node_data->node_name = g_strdup(name);
}


/**
 * lasso_node_class_set_ns
 * @klass: object class
 * @href: namespace uri
 * @prefix: namespace prefix
 **/
void
lasso_node_class_set_ns(LassoNodeClass *klass, char *href, char *prefix)
{
	if (klass->node_data->ns)
		xmlFreeNs(klass->node_data->ns);
	klass->node_data->ns = xmlNewNs(NULL, href, prefix);
}


static void
lasso_node_build_xmlNode_from_snippets(LassoNode *node, xmlNode *xmlnode,
		struct XmlSnippet *snippets)
{
	struct XmlSnippet *snippet;
	SnippetType type;
	xmlNode *t;
	xmlNs *xmlns;
	GList *elem;

	for (snippet = snippets; snippet && snippet->name; snippet++) {
		void *value = G_STRUCT_MEMBER(void*, node, snippet->offset);
		char *str = value;
		type = snippet->type & 0xff;

		if (value == NULL && ! (snippet->type & SNIPPET_BOOLEAN ||
					snippet->type & SNIPPET_INTEGER) )
			continue;

		if (snippet->type & SNIPPET_BOOLEAN)
			str = GPOINTER_TO_INT(value) ? "true" : "false";
		if (snippet->type & SNIPPET_INTEGER)
			str = g_strdup_printf("%d", GPOINTER_TO_INT(value));

		switch (type) {
			case SNIPPET_ATTRIBUTE:
				xmlSetProp(xmlnode, snippet->name, str);
				break;
			case SNIPPET_TEXT_CHILD:
				xmlAddChild(xmlnode, xmlNewText(str));
				break;
			case SNIPPET_NODE:
				xmlAddChild(xmlnode, lasso_node_get_xmlNode(LASSO_NODE(value)));
				break;
			case SNIPPET_CONTENT:
				xmlNewTextChild(xmlnode, NULL, snippet->name, str);
				break;
			case SNIPPET_NAME_IDENTIFIER:
				xmlns = xmlNewNs(NULL, LASSO_LIB_HREF, LASSO_LIB_PREFIX);

				t = xmlAddChild(xmlnode, lasso_node_get_xmlNode(
							LASSO_NODE(value)));
				xmlNodeSetName(t, snippet->name);
				xmlSetNs(t, xmlns);
				break;
			case SNIPPET_NODE_IN_CHILD:
				t = xmlNewTextChild(xmlnode, NULL, snippet->name, NULL);
				xmlAddChild(t, lasso_node_get_xmlNode(LASSO_NODE(value)));
				break;
			case SNIPPET_LIST_NODES:
				elem = (GList *)value;
				while (elem) {
					xmlAddChild(xmlnode, lasso_node_get_xmlNode(
								LASSO_NODE(elem->data)));
					elem = g_list_next(elem);
				}
				break;
			case SNIPPET_LIST_CONTENT:
				/* sequence of simple elements (no children,
				 * no attrs, just content) */
				elem = (GList *)value;
				while (elem) {
					xmlNewTextChild(xmlnode, NULL,
							snippet->name, (char*)(elem->data));
					elem = g_list_next(elem);
				}
				break;
			case SNIPPET_INTEGER:
			case SNIPPET_BOOLEAN:
				g_assert_not_reached();
		}
		if (snippet->type & SNIPPET_INTEGER)
			g_free(str);
	}
}