Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TimXmlRpc.cpp - github.com/drtimcooper/XmlRpc4Win.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7b9535ddeab84233db745e93748475da0dfff624 (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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
/*
XmlRpc C++ client for Windows
-----------------------------

Created by Dr Tim Cooper,  tco@smartsgroup.com,   March 2009.

This lets you talk to web sites using XmlRpc from C++ on Windows.  It differs
from similar libraries as follows:
	- works on Windows
	- supports HTTPS (SSL)
	- uses wininet to manage HTTP/HTTPS, so it's really very minimal
	- much faster than XmlRpc++ which suffers from STL performance problems.

This project consists of 2 files:   "TimXmlRpc.h"  &&  "TimXmlRpc.cpp".

Parts of this project have been taken from Chris Morley's "XmlRpc++" project,
in particular the API.  Chris's contribution is acknowledged by marking his
work with the token:  "/*ChrisMorley/".  Thanks, Chris!

*/

#include <windows.h>
#include <wininet.h>
#include <cmath>
#include <iterator>
#include <limits>
#include "TimXmlRpc.h"




static const char VALUE_TAG[]			= "<value>";
static const char VALUE_ETAG[]			= "</value>";

static const char BOOLEAN_TAG[]			= "<boolean>";
static const char BOOLEAN_ETAG[]		= "</boolean>";
static const char DOUBLE_TAG[]			= "<double>";
static const char DOUBLE_ETAG[]			= "</double>";
static const char INT_TAG[]				= "<int>";
static const char INT_ETAG[]			= "</int>";
static const char I4_TAG[]				= "<i4>";
static const char I4_ETAG[]				= "</i4>";
static const char STRING_TAG[]			= "<string>";
static const char STRING_ETAG[]			= "</string>";
static const char DATETIME_TAG[]		= "<dateTime.iso8601>";
static const char DATETIME_ETAG[]		= "</dateTime.iso8601>";
static const char BASE64_TAG[]			= "<base64>";
static const char BASE64_ETAG[]			= "</base64>";

static const char ARRAY_TAG[]		 = "<array>";
static const char DATA_TAG[]			= "<data>";
static const char DATA_ETAG[]		 = "</data>";
static const char ARRAY_ETAG[]		= "</array>";

static const char STRUCT_TAG[]		= "<struct>";
static const char MEMBER_TAG[]		= "<member>";
static const char NAME_TAG[]			= "<name>";
static const char NAME_ETAG[]		 = "</name>";
static const char MEMBER_ETAG[]	 = "</member>";
static const char STRUCT_ETAG[]	 = "</struct>";


//---------------------------------- Misc: -------------------------------

static bool strieq(const char* a, const char* b)
{
	return _stricmp(a, b) == 0;
}


static bool strbegins(const char* bigstr, const char* smallstr, bool casesensitive)
{
    const char* smalls = smallstr;
    const char* bigs = bigstr;
    while (*smalls) {
        if (casesensitive) {
            if (*bigs != *smalls)
                return false;
            else bigs++, smalls++;
        }
        else {
            if (toupper(*bigs) != toupper(*smalls))
                return false;
            else bigs++, smalls++;
        }
    }
    return true;
}


//---------------------------------- ValueArray: -------------------------------

void XmlRpcValue::ValueArray::resize(int n)
{
	if (n >= _allocated) {
		// Optimise growing of the array:
		int power2 = n - 1;
		power2 |= power2 >> 1;
		power2 |= power2 >> 2;
		power2 |= power2 >> 4;
		power2 |= power2 >> 8;
		power2 |= power2 >> 16;
		power2++;

		// Set the size:
		A = (XmlRpcValue*)realloc(A, power2 * sizeof(XmlRpcValue));
		memset(A + _allocated, 0, (power2 - _allocated) * sizeof(XmlRpcValue));
		_allocated = power2;
	}
	_size = n;
}


bool XmlRpcValue::ValueArray::operator==(ValueArray &other)
{
	if (_size != other._size)
		return false;
	for (int i=0; i < _size; i++) {
		if (A[i] != other.A[i])
			return false;
	}
	return true;
}


XmlRpcValue::ValueArray::~ValueArray()
{
	for (int i=0; i < _size; i++)
		A[i].invalidate();
	free(A);
}




//---------------------------------- base64.h: -------------------------------
	/* <Chris Morley> */
static const
int _base64Chars[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
						 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
							 '0','1','2','3','4','5','6','7','8','9',
							 '+','/' };


#define _0000_0011 0x03
#define _1111_1100 0xFC
#define _1111_0000 0xF0
#define _0011_0000 0x30
#define _0011_1100 0x3C
#define _0000_1111 0x0F
#define _1100_0000 0xC0
#define _0011_1111 0x3F

#define _EQUAL_CHAR	 (-1)
#define _UNKNOWN_CHAR (-2)

#define _IOS_FAILBIT	 std::ios_base::failbit
#define _IOS_EOFBIT		std::ios_base::eofbit
#define _IOS_BADBIT		std::ios_base::badbit
#define _IOS_GOODBIT	 std::ios_base::goodbit

// TEMPLATE CLASS base64_put
class base64
{
public:

	typedef unsigned char byte_t;
	typedef char						char_type;
	typedef std::char_traits<char>					 traits_type; 

	// base64 requires max line length <= 72 characters
	// you can fill end of line
	// it may be crlf, crlfsp, noline or other class like it


	struct crlf
	{
		template<class _OI>
			_OI operator()(_OI _To) const{
			*_To = std::char_traits<char>::to_char_type('\r'); ++_To;
			*_To = std::char_traits<char>::to_char_type('\n'); ++_To;

			return (_To);
		}
	};


	struct crlfsp
	{
		template<class _OI>
			_OI operator()(_OI _To) const{
			*_To = std::char_traits<char>::to_char_type('\r'); ++_To;
			*_To = std::char_traits<char>::to_char_type('\n'); ++_To;
			*_To = std::char_traits<char>::to_char_type(' '); ++_To;

			return (_To);
		}
	};

	struct noline
	{
		template<class _OI>
			_OI operator()(_OI _To) const{
			return (_To);
		}
	};

	struct three2four
	{
		void zero()
		{
			_data[0] = 0;
			_data[1] = 0;
			_data[2] = 0;
		}

		byte_t get_0()	const
		{
			return _data[0];
		}
		byte_t get_1()	const
		{
			return _data[1];
		}
		byte_t get_2()	const
		{
			return _data[2];
		}

		void set_0(byte_t _ch)
		{
			_data[0] = _ch;
		}

		void set_1(byte_t _ch)
		{
			_data[1] = _ch;
		}

		void set_2(byte_t _ch)
		{
			_data[2] = _ch;
		}

		// 0000 0000	1111 1111	2222 2222
		// xxxx xxxx	xxxx xxxx	xxxx xxxx
		// 0000 0011	1111 2222	2233 3333

		int b64_0()	const	{return (_data[0] & _1111_1100) >> 2;}
		int b64_1()	const	{return ((_data[0] & _0000_0011) << 4) + ((_data[1] & _1111_0000)>>4);}
		int b64_2()	const	{return ((_data[1] & _0000_1111) << 2) + ((_data[2] & _1100_0000)>>6);}
		int b64_3()	const	{return (_data[2] & _0011_1111);}

		void b64_0(int _ch)	{_data[0] = ((_ch & _0011_1111) << 2) | (_0000_0011 & _data[0]);}

		void b64_1(int _ch)	{
			_data[0] = ((_ch & _0011_0000) >> 4) | (_1111_1100 & _data[0]);
			_data[1] = ((_ch & _0000_1111) << 4) | (_0000_1111 & _data[1]);	}

		void b64_2(int _ch)	{
			_data[1] = ((_ch & _0011_1100) >> 2) | (_1111_0000 & _data[1]);
			_data[2] = ((_ch & _0000_0011) << 6) | (_0011_1111 & _data[2]);	}

		void b64_3(int _ch){
			_data[2] = (_ch & _0011_1111) | (_1100_0000 & _data[2]);}

	private:
		byte_t _data[3];

	};




	template<class _II, class _OI, class _State, class _Endline>
		_II put(_II _First, _II _Last, _OI _To, _State&, _Endline)	const
	{
		three2four _3to4;
		int line_octets = 0;

		while(_First != _Last)
		{
			_3to4.zero();

			// 
			_3to4.set_0(*_First);
			_First++;

			if(_First == _Last)
			{
				*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To;
				*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To;
				*_To = std::char_traits<char>::to_char_type('='); ++_To;
				*_To = std::char_traits<char>::to_char_type('='); ++_To;
				goto __end;
			}

			_3to4.set_1(*_First);
			_First++;

			if(_First == _Last)
			{
				*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To;
				*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To;
				*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_2()]); ++_To;
				*_To = std::char_traits<char>::to_char_type('='); ++_To;
				goto __end;
			}

			_3to4.set_2(*_First);
			_First++;

			*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_0()]); ++_To;
			*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_1()]); ++_To;
			*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_2()]); ++_To;
			*_To = std::char_traits<char>::to_char_type(_base64Chars[_3to4.b64_3()]); ++_To;

			if(line_octets == 17) // base64 
			{
				//_To = _Endl(_To);
				*_To = '\n'; ++_To;
				line_octets = 0;
			}
			else
				++line_octets;
		}

		__end: ;

		return (_First);

	}


	template<class _II, class _OI, class _State>
		_II get(_II _First, _II _Last, _OI _To, _State& _St) const
	{
		three2four _3to4;
		int _Char;

		while(_First != _Last)
		{

			// Take octet
			_3to4.zero();

			// -- 0 --
			// Search next valid char... 
			while((_Char =	_getCharType(*_First)) < 0 && _Char == _UNKNOWN_CHAR)
			{
				if(++_First == _Last)
				{
					_St |= _IOS_FAILBIT|_IOS_EOFBIT; return _First; // unexpected EOF
				}
			}

			if(_Char == _EQUAL_CHAR){
				// Error! First character in octet can't be '='
				_St |= _IOS_FAILBIT; 
				return _First; 
			}
			else
				_3to4.b64_0(_Char);


			// -- 1 --
			// Search next valid char... 
			while(++_First != _Last)
				if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR)
					break;

			if(_First == _Last)	{
				_St |= _IOS_FAILBIT|_IOS_EOFBIT; // unexpected EOF 
				return _First;
			}

			if(_Char == _EQUAL_CHAR){
				// Error! Second character in octet can't be '='
				_St |= _IOS_FAILBIT; 
				return _First; 
			}
			else
				_3to4.b64_1(_Char);


			// -- 2 --
			// Search next valid char... 
			while(++_First != _Last)
				if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR)
					break;

			if(_First == _Last)	{
				// Error! Unexpected EOF. Must be '=' or base64 character
				_St |= _IOS_FAILBIT|_IOS_EOFBIT; 
				return _First; 
			}

			if(_Char == _EQUAL_CHAR){
				// OK!
				_3to4.b64_2(0); 
				_3to4.b64_3(0); 

				// chek for EOF
				if(++_First == _Last)
				{
					// Error! Unexpected EOF. Must be '='. Ignore it.
					//_St |= _IOS_BADBIT|_IOS_EOFBIT;
					_St |= _IOS_EOFBIT;
				}
				else 
					if(_getCharType(*_First) != _EQUAL_CHAR)
					{
						// Error! Must be '='. Ignore it.
						//_St |= _IOS_BADBIT;
					}
				else
					++_First; // Skip '='

				// write 1 byte to output
				*_To = (byte_t) _3to4.get_0();
				return _First;
			}
			else
				_3to4.b64_2(_Char);


			// -- 3 --
			// Search next valid char... 
			while(++_First != _Last)
				if((_Char = _getCharType(*_First)) != _UNKNOWN_CHAR)
					break;

			if(_First == _Last)	{
				// Unexpected EOF. It's error. But ignore it.
				//_St |= _IOS_FAILBIT|_IOS_EOFBIT; 
					_St |= _IOS_EOFBIT; 
				
				return _First; 
			}

			if(_Char == _EQUAL_CHAR)
			{
				// OK!
				_3to4.b64_3(0); 

				// write to output 2 bytes
				*_To = (byte_t) _3to4.get_0();
				*_To = (byte_t) _3to4.get_1();

				++_First; // set position to next character

				return _First;
			}
			else
				_3to4.b64_3(_Char);


			// write to output 3 bytes
			*_To = (byte_t) _3to4.get_0();
			*_To = (byte_t) _3to4.get_1();
			*_To = (byte_t) _3to4.get_2();

			++_First;
			

		} // while(_First != _Last)

		return (_First);
	}

protected:
	
	int _getCharType(int _Ch) const
	{
		if(_base64Chars[62] == _Ch)
			return 62;

		if(_base64Chars[63] == _Ch)
			return 63;

		if((_base64Chars[0] <= _Ch) && (_base64Chars[25] >= _Ch))
			return _Ch - _base64Chars[0];

		if((_base64Chars[26] <= _Ch) && (_base64Chars[51] >= _Ch))
			return _Ch - _base64Chars[26] + 26;

		if((_base64Chars[52] <= _Ch) && (_base64Chars[61] >= _Ch))
			return _Ch - _base64Chars[52] + 52;

		if(_Ch == std::char_traits<char>::to_int_type('='))
			return _EQUAL_CHAR;

		return _UNKNOWN_CHAR;
	}


};



/*-----------------------------------------------------------------------*/

void XmlRpcValue::invalidate()
{
	switch (_type) {
		case TypeString:	free(u.asString); break;
		case TypeDateTime:	delete u.asTime;	 break;
		case TypeBase64:	delete u.asBinary; break;
		case TypeArray:		delete u.asArray;	break;
		case TypeStruct:	delete u.asStruct; break;
		default:			break;
	}
	_type = TypeInvalid;
	u.asBinary = 0;
}


// Type checking
void XmlRpcValue::assertTypeOrInvalid(Type t)
{
	if (_type == TypeInvalid || _type == TypeNil) {
		_type = t;
		switch (_type) {		// Ensure there is a valid value for the type
			case TypeString:	u.asString = _strdup(""); break;
			case TypeDateTime:	u.asTime = new struct tm();		 break;
			case TypeBase64:	u.asBinary = new BinaryData();	break;
			case TypeArray:		u.asArray = new ValueArray();	 break;
			case TypeStruct:	u.asStruct = new ValueStruct(); break;
			default:			u.asBinary = 0; break;
		}
	}
	else if (_type != t)
		throw XmlRpcException("type error");
}


void XmlRpcValue::assertArray(int size) const
{
	if (_type != TypeArray)
		throw XmlRpcException("type error: expected an array");
	else if (int(u.asArray->size()) < size)
		throw XmlRpcException("range error: array index too large");
}


void XmlRpcValue::assertArray(int size)
{
	if (_type == TypeInvalid) {
		_type = TypeArray;
		u.asArray = new ValueArray(size);
	}
	else if (_type == TypeArray) {
		if (int(u.asArray->size()) < size) {
			u.asArray->resize(size);
		}
	}
	else
		throw XmlRpcException("type error: expected an array");
}


void XmlRpcValue::assertStruct()
{
	if (_type == TypeInvalid) {
		_type = TypeStruct;
		u.asStruct = new ValueStruct();
	} else if (_type != TypeStruct)
		throw XmlRpcException("type error: expected a struct");
}


XmlRpcValue::ValueArray::ValueArray(ValueArray &other)
{
	A = NULL; 
	_size = _allocated = 0;
	resize(other._size);
    for (int i=0 ; i < _size; i++) {
        A[i] = other.A[i];
    }
}


/* This copy constructor does a deep copy.  It's equivalent to:  "XmlRpcValue(XmlRpcValue&orig);".
Tim> In my applications, I manage to avoid using copy constructors, && if you're interested
in performance, you should also consider whether you can avoid copy constructors, e.g. by
passing values by reference.
Thanks to Eric Schneider for identifying a fault with a previous version of this copy constructor.
*/
XmlRpcValue& XmlRpcValue::operator=(XmlRpcValue const& rhs)
{
	if (this != &rhs) {
		invalidate();
		_type = rhs._type;
		switch (_type) {
			case TypeBoolean:	u.asBool = rhs.u.asBool; break;
			case TypeInt:		u.asInt = rhs.u.asInt; break;
			case TypeDouble:	u.asDouble = rhs.u.asDouble; break;
			case TypeDateTime:	u.asTime = new struct tm(*rhs.u.asTime); break;
			case TypeString:	u.asString = _strdup(rhs.u.asString); break;
			case TypeBase64:	u.asBinary = new BinaryData(*rhs.u.asBinary); break;
			case TypeArray:		u.asArray = new ValueArray(*rhs.u.asArray); break;
			case TypeStruct:	u.asStruct = new ValueStruct(*rhs.u.asStruct); break;
			default:			u.asBinary = 0; break;
		}
	}
	return *this;
}
	/* </Chris Morley> */




// Map something like:    "T2-D&amp;T1"  to  "T2-D&T1"
// Returns a 'strdup()' version of the input string.

static char* xmlDecode(const char* s, const char* end)
{
	char* dest = (char*)malloc(end - s + 1);
	char* d = dest;
	while (s < end) {
		if (*s != '&')
			*d++ = *s++;
		else if (strbegins(s, "&amp;", true))
			*d++ = '&', s += 5;
		else if (strbegins(s, "&quot;", true))
			*d++ = '\"', s += 6;
		else if (strbegins(s, "&apos;", true)/*! standard*/ || strbegins(s, "&#039;", true))
			*d++ = '\'', s += 6;
		else if (strbegins(s, "&lt;", true))
			*d++ = '<', s += 4;
		else if (strbegins(s, "&gt;", true))
			*d++ = '>', s += 4;
		else if (strbegins(s, "&#", true)) {
			s += 2;
			*d++ = (char)atoi(s);
			while (*s >= '0' && *s <= '9')
				s++;
			if (*s == ';')
				s++;
		}
		else
			*d++ = *s++;	// assert(false);
	}
	*d = '\0';
	return dest;
}


// Replace raw text with xml-encoded entities.

static std::string xmlEncode(const char* s)
{
	std::ostringstream ostr;

	while (*s) {
		if (*s == '&')
			ostr << "&amp;";
		else if (*s == '<')
			ostr << "&lt;";
		else if (*s == '>')
			ostr << "&gt;";
		else if (*s == '"')
			ostr << "&quot;";
		else if (*s == '\'')
			ostr << "&apos;";// Would David prefer:  "&#039;" ?
		else if (*s < ' ' || *s >= 127)
			ostr << "&#" << int((unsigned char)*s) << ';';
		else ostr << *s;
		s++;
	}
	return ostr.str();
}


	/* <Chris Morley> */
// Predicate for tm equality
static bool tmEq(struct tm const& t1, struct tm const& t2) 
{
	return t1.tm_sec == t2.tm_sec && t1.tm_min == t2.tm_min &&
					t1.tm_hour == t2.tm_hour && t1.tm_mday == t2.tm_mday &&
					t1.tm_mon == t2.tm_mon && t1.tm_year == t2.tm_year;
}


bool XmlRpcValue::operator==(XmlRpcValue const& other) const
{
	if (_type != other._type)
		return false;

	switch (_type) {
		case TypeBoolean:	return ( !u.asBool && !other.u.asBool) ||
											( u.asBool && other.u.asBool);
		case TypeInt:		return u.asInt == other.u.asInt;
		case TypeDouble:	return std::abs(u.asDouble - other.u.asDouble) < std::numeric_limits<double>::epsilon();
		case TypeDateTime:	return tmEq(*u.asTime, *other.u.asTime);
		case TypeString:	return *u.asString == *other.u.asString;
		case TypeBase64:	return *u.asBinary == *other.u.asBinary;
		case TypeArray:		return *u.asArray == *other.u.asArray;

		// The map<>::operator== requires the definition of value< for kcc
		case TypeStruct:	 //return *u.asStruct == *other.u.asStruct;
			{
				if (u.asStruct->size() != other.u.asStruct->size())
					return false;
				
				ValueStruct::const_iterator it1=u.asStruct->begin();
				ValueStruct::const_iterator it2=other.u.asStruct->begin();
				while (it1 != u.asStruct->end()) {
					const XmlRpcValue& v1 = it1->second;
					const XmlRpcValue& v2 = it2->second;
					if ( ! (v1 == v2))
						return false;
					it1++;
					it2++;
				}
				return true;
			}
		default: break;
	}
	return true;		// Both invalid values ...
}


// Works for strings, binary data, arrays, && structs.
int XmlRpcValue::size() const
{
	switch (_type) {
		case TypeString: return int(strlen(u.asString));
		case TypeBase64: return int(u.asBinary->size());
		case TypeArray:	return int(u.asArray->size());
		case TypeStruct: return int(u.asStruct->size());
		default: break;
	}

	throw XmlRpcException("type error");
}


// Checks for existence of struct member
bool XmlRpcValue::hasMember(const std::string& name) const
{
	return _type == TypeStruct && u.asStruct->find(name) != u.asStruct->end();
}
	/* </Chris Morley> */


static void SkipWhiteSpace(const char* &s)
{
	while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r')
		s++;
}


static char* GobbleTag(const char* &s, char dest[128])
// E.g. given:  "< string  / >",  return "<string/>"
{
	*dest = '\0';
	SkipWhiteSpace(s);
	if (*s != '<')
		return dest;
	char* d = dest;
	*d++ = *s++;
	SkipWhiteSpace(s);
	while (*s && *s != '>') {
		if (*s == ' ' && (d[-1] == '<' || d[-1] == '/' || s[1] == ' ' || s[1] == '/' || s[1] == '>'))
			s++;
		else *d++ = *s++;
	}
	*d++ = '>';
	*d = '\0';
	if (*s == '>')
		s++;
	return dest;
}


static void GobbleExpectedTag(const char* &s, const char* etag)
{
	char tag[128];
	GobbleTag(s, tag);
	if (! strieq(tag, etag))
		throw XmlRpcException(std::string("Expecting tag: ") + etag);
}


// Set the value from xml. The chars at *offset into valueXml 
// should be the start of a <value> tag. Destroys any existing value.
void XmlRpcValue::fromXml(const char* &s)
{
	char tag[128];

	invalidate();

	// Gobble the <value> tag:
	GobbleTag(s, tag);
	if (strieq(tag, "<value>"))
		;	// good
	else if (strieq(tag, "<value/>")) {
		// Jeff Rasmussen claims that <value/> is valid XmlRpc. I think he's correct.
		_type = TypeString;
		u.asString = _strdup("");
		return;
	}
	else
		throw XmlRpcException(std::string("Expecting tag: <value>"));

	// Gobble the type tag:
	GobbleTag(s, tag);
	if (*tag == '\0') {
		// If no type is indicated, the type is string.
		stringFromXml(s);
	}
	else if (strieq(tag, BOOLEAN_TAG)) {
		boolFromXml(s);
		GobbleExpectedTag(s, BOOLEAN_ETAG);
	}
	else if (strieq(tag, I4_TAG)) {
		intFromXml(s);
		GobbleExpectedTag(s, I4_ETAG);
	}
	else if (strieq(tag, INT_TAG)) {
		intFromXml(s);
		GobbleExpectedTag(s, INT_ETAG);
	}
	else if (strieq(tag, DOUBLE_TAG)) {
		doubleFromXml(s);
		GobbleExpectedTag(s, DOUBLE_ETAG);
	}
	else if (strieq(tag, STRING_TAG)) {
		stringFromXml(s);
		GobbleExpectedTag(s, STRING_ETAG);
	}
	else if (strieq(tag, DATETIME_TAG)) {
		timeFromXml(s);
		GobbleExpectedTag(s, DATETIME_ETAG);
	}
	else if (strieq(tag, BASE64_TAG)) {
		binaryFromXml(s);
		GobbleExpectedTag(s, BASE64_ETAG);
	}
	else if (strieq(tag, ARRAY_TAG)) {
		arrayFromXml(s);
		GobbleExpectedTag(s, ARRAY_ETAG);
	}
	else if (strieq(tag, STRUCT_TAG)) {
		structFromXml(s);
		GobbleExpectedTag(s, STRUCT_ETAG);
	}
	else if (strieq(tag, "<string/>")) {
		_type = TypeString;
		u.asString = _strdup("");
	}
	else if (strieq(tag, "<nil/>")) {
		_type = TypeNil;
	}
	else if (strieq(tag, "<struct/>")) {
		_type = TypeStruct;
		u.asStruct = new ValueStruct;
	}
	else if (strieq(tag, VALUE_ETAG)) {	
		// "If no type is indicated, the type is string."
		_type = TypeString;
		u.asString = _strdup("");
		return;	// don't gobble VALUE_ETAG because we already did
	}
	else {
		throw XmlRpcException(std::string("Unknown type tag: ") + tag);
	}

	GobbleExpectedTag(s, VALUE_ETAG);
}


// Encode the Value in xml
void XmlRpcValue::toXml(std::ostringstream &ostr) const
{
	switch (_type) {
		case TypeBoolean:		return boolToXml(ostr);
		case TypeInt:			return intToXml(ostr);
		case TypeDouble:		return doubleToXml(ostr);
		case TypeString:		return stringToXml(ostr);
		case TypeDateTime:		return timeToXml(ostr);
		case TypeBase64:		return binaryToXml(ostr);
		case TypeArray:			return arrayToXml(ostr);
		case TypeStruct:		return structToXml(ostr);
		case TypeNil:			return nilToXml(ostr);
		case TypeInvalid:		throw XmlRpcException("Undefined XmlRpc value");
		default: break;
	}
}


void XmlRpcValue::boolFromXml(const char* &s)
{
	if (*s == '0' && s[1] == '<') {
		_type = TypeBoolean;
		u.asBool = false;
		s++;
	}
	else if (*s == '1' && s[1] == '<') {
		_type = TypeBoolean;
		u.asBool = true;
		s++;
	}
	else throw XmlRpcException("bad BOOL");
}


void XmlRpcValue::boolToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << BOOLEAN_TAG << (u.asBool ? "1" : "0") << BOOLEAN_ETAG << VALUE_ETAG;
}


void XmlRpcValue::intFromXml(const char* &s)
{
	char* valueEnd;
	long ivalue = strtol(s, &valueEnd, 10);
	if (valueEnd == s)
		throw XmlRpcException("Bad double");
	_type = TypeInt;
	u.asInt = int(ivalue);
	s = valueEnd;
}


void XmlRpcValue::intToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << I4_TAG << u.asInt << I4_ETAG << VALUE_ETAG;
}


void XmlRpcValue::doubleFromXml(const char* &s)
{
	char* valueEnd;
	double dvalue = strtod(s, &valueEnd);
	if (valueEnd == s)
		throw XmlRpcException("Bad double");
	_type = TypeDouble;
	u.asDouble = dvalue;
	s = valueEnd;
}


void XmlRpcValue::doubleToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << DOUBLE_TAG << u.asDouble << DOUBLE_ETAG << VALUE_ETAG;
	// This will use the default ostream::precision() to display the double.  To display
	// values with greater accuracy, call e.g.  'ostr.precision(12)' at the top level.
}


void XmlRpcValue::stringFromXml(const char* &s)
{
	const char* valueEnd = strchr(s, '<');
	if (valueEnd == NULL)
		throw XmlRpcException("Bad string");
	_type = TypeString;
	u.asString = xmlDecode(s, valueEnd);
	s = valueEnd;
}


void XmlRpcValue::stringToXml(std::ostringstream &ostr) const
{
	if (u.asString == NULL || *u.asString == '\0')
		ostr << VALUE_TAG << "<string/>" << VALUE_ETAG;
	else ostr << VALUE_TAG << xmlEncode(u.asString) << VALUE_ETAG;
	// The 'STRING_TAG' is optional.
}


void XmlRpcValue::nilToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << "<nil/>" << VALUE_ETAG;
}


void XmlRpcValue::timeFromXml(const char* &s)
{
	const char* valueEnd = strchr(s, '<');
	if (valueEnd == NULL)
		throw XmlRpcException("Bad time value");

	struct tm t;
	if (sscanf_s(s, "%4d%2d%2dT%2d:%2d:%2d", &t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec) != 6)
		throw XmlRpcException("Bad time value");

	t.tm_wday = t.tm_yday = t.tm_isdst = -1;
	t.tm_mon -= 1;
	_type = TypeDateTime;
	u.asTime = new struct tm(t);
	s = valueEnd;
}


void XmlRpcValue::timeToXml(std::ostringstream &ostr) const
{
	struct tm* t = u.asTime;
	char buf[30];
	_snprintf_s(buf, sizeof(buf), sizeof(buf)-1, 
				"%4d%02d%02dT%02d:%02d:%02d", 
				t->tm_year,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);

	ostr << VALUE_TAG << DATETIME_TAG << buf << DATETIME_ETAG << VALUE_ETAG;
}


void XmlRpcValue::binaryFromXml(const char* &s)
{
	const char* valueEnd = strchr(s, '<');
	if (valueEnd == NULL)
		throw XmlRpcException("Bad base64");

	_type = TypeBase64;
	u.asBinary = new BinaryData();
	// check whether base64 encodings can contain chars xml encodes...

	// convert from base64 to binary
	int iostatus = 0;
	base64 decoder;
	std::back_insert_iterator<BinaryData> ins = std::back_inserter(*(u.asBinary));
	decoder.get(s, valueEnd, ins, iostatus);

	s = valueEnd;
}


void XmlRpcValue::binaryToXml(std::ostringstream &ostr) const
{
	// convert to base64
	std::vector<char> base64data;
	int iostatus = 0;
	base64 encoder;
	std::back_insert_iterator<std::vector<char> > ins = std::back_inserter(base64data);
	encoder.put(u.asBinary->begin(), u.asBinary->end(), ins, iostatus, base64::crlf());

	// Wrap with xml
	ostr << VALUE_TAG << BASE64_TAG;
	ostr.write(&base64data[0], base64data.size());
	ostr << BASE64_ETAG << VALUE_ETAG;
}


void XmlRpcValue::arrayFromXml(const char* &s)
{
	char tag[128];

	_type = TypeArray;
	u.asArray = new ValueArray;

	GobbleTag(s, tag);
	if (strieq(tag, "<data/>"))
		return;
	if (! strieq(tag, DATA_TAG))
		throw XmlRpcException("Expecting tag:  <data>");

	do {
		SkipWhiteSpace(s);
		if (strbegins(s, DATA_ETAG, true))
			break;
		int n = u.asArray->size();
		u.asArray->resize(n+1);
		u.asArray->at(n).fromXml(s);
	} while (true);

	// Skip the trailing </data>
	GobbleExpectedTag(s, DATA_ETAG);
}


void XmlRpcValue::arrayToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << ARRAY_TAG << DATA_TAG;

	int limit = int(u.asArray->size());
	for (int i=0; i < limit; ++i)
		 u.asArray->at(i).toXml(ostr);

	ostr << DATA_ETAG << ARRAY_ETAG << VALUE_ETAG;
}


void XmlRpcValue::structFromXml(const char* &s)
{
	_type = TypeStruct;
	u.asStruct = new ValueStruct;

	size_t memberTagLen = strlen(MEMBER_TAG);
	SkipWhiteSpace(s);
	while (strbegins(s, MEMBER_TAG, true)) {
		s += memberTagLen;

		// name
		GobbleExpectedTag(s, NAME_TAG);
		const char* nameEnd = strchr(s, '<');
		if (nameEnd == NULL)
			throw XmlRpcException("Bad 'name' tag in struct");
		char* name = xmlDecode(s, nameEnd);
		s = nameEnd;
		GobbleExpectedTag(s, NAME_ETAG);

		// value
		XmlRpcValue val;
		val.fromXml(s);
		if ( ! val.valid()) {
			free(name);
			invalidate();
			return;
		}
		const std::pair<const std::string, XmlRpcValue> p(name, val);
		u.asStruct->insert(p);
		free(name);

		GobbleExpectedTag(s, MEMBER_ETAG);
		SkipWhiteSpace(s);
	}
}


void XmlRpcValue::structToXml(std::ostringstream &ostr) const
{
	ostr << VALUE_TAG << STRUCT_TAG;

	ValueStruct::const_iterator it;
	for (it=u.asStruct->begin(); it!=u.asStruct->end(); ++it) {
		ostr << MEMBER_TAG << NAME_TAG << xmlEncode(it->first.c_str()) << NAME_ETAG;
		it->second.toXml(ostr);
		ostr << MEMBER_ETAG;
	}

	ostr << STRUCT_ETAG << VALUE_ETAG << '\n';
}


bool XmlRpcValue::parseMethodResponse(const char* s)
{
	char xmlVersion[128];
	char tag[128];

	GobbleTag(s, xmlVersion);
	if (! strbegins(xmlVersion, "<?xml version", false)) {
		if (strstr(s, "<html") != NULL || strstr(s, "<HTML") != NULL)
			throw XmlRpcException("It looks like you've configured the wrong URL. That URL is sending us HTML text, "
						"whereas we need RPC data.");
		else throw XmlRpcException(std::string(s));
	}
	GobbleTag(s, tag);
	if (! strieq(tag, "<methodResponse>")) {
		if (strstr(s, "<title>Bad request!</title>"))
			throw XmlRpcException(std::string("Talking HTTP to a HTTPS server?"));
		else if (strstr(s, "Object not found"))
			throw XmlRpcException(std::string("Wrong URL (\"Object not found\")"));
		else throw XmlRpcException(std::string(s));
	}
	SkipWhiteSpace(s);
	if (strbegins(s, "<fault>", true)) {
		GobbleExpectedTag(s, "<fault>");
		fromXml(s);
		GobbleExpectedTag(s, "</fault>");
		return false;
	}
	else {
		GobbleExpectedTag(s, "<params>");
		GobbleExpectedTag(s, "<param>");
		fromXml(s);
		// There's false real need to parse the bits at the end, is there?
		//GobbleExpectedTag(s, "</param>");
		//GobbleExpectedTag(s, "</params>");
	}
	//GobbleExpectedTag(s, "</methodResponse>");
	return true;
}


void XmlRpcValue::buildCall(const char* method, std::ostringstream &ostr) const
{
	ostr << "<?xml version=\"1.0\"?>\r\n";
	ostr << "<methodCall><methodName>" << method << "</methodName>\r\n<params>";
	if (getType() == XmlRpcValue::TypeArray)	{
		for (int i=0; i < size(); ++i) {
			ostr << "<param>";
			(*this)[i].toXml(ostr);
			ostr << "</param>";
		}
	}
	else if (getType() == XmlRpcValue::TypeInvalid) {
	}
	else {
		ostr << "<param>";
		toXml(ostr);
		ostr << "</param>\n";
	}
	ostr << "</params></methodCall>\r\n";
}




/*-------------------------- class XmlRpcClient: ----------------------*/

class XmlRpcImplementation {
	XmlRpcClient::protocol_enum protocol;
	bool ignoreCertificateAuthority;
	HINTERNET hInternet;
	HINTERNET hConnect;
	std::string object;
	INTERNET_PORT port;

	void hadError(const char* function);
	bool connect(const char* server);

public:
	struct BasicAuth_node {
		getBasicAuth_UsernameAndPassword_fn FindUsernameAndPassword;
		char username[256];
		char password[256];

		BasicAuth_node() { 
			FindUsernameAndPassword = NULL;
			username[0] = '\0';
			password[0] = '\0';
		}
	} BasicAuth;
	XmlRpcCallback Callback;
	void *context;
	int totalBytes;
	std::string errmsg;
	int HttpErrcode;
	bool isFault;

	XmlRpcImplementation(const char* server, INTERNET_PORT port, const char* object, XmlRpcClient::protocol_enum protocol);
	XmlRpcImplementation(const char* URI);
	bool execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result);
	void setCallback(XmlRpcCallback Callback_, void* context_)
			{ Callback = Callback_; context = context_; }
	void setIgnoreCertificateAuthority(bool value) { ignoreCertificateAuthority = value; }
	~XmlRpcImplementation();
};


XmlRpcClient::XmlRpcClient(const char* server, int port, const char* object, protocol_enum protocol)
{
	secret = new XmlRpcImplementation(server, (INTERNET_PORT)port, object, protocol);
}


XmlRpcClient::XmlRpcClient(const char* URI)
{
	secret = new XmlRpcImplementation(URI);
}


bool XmlRpcClient::execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result)
{
	return secret->execute(method, params, result);
}


std::string XmlRpcClient::getError()
{
	if (secret->errmsg.size() > 1254)
		secret->errmsg.resize(1254);
	return secret->errmsg;
}


void XmlRpcClient::setError(std::string msg)
{
	secret->errmsg = msg;
}


int XmlRpcClient::getHttpErrorCode()
{
	return secret->HttpErrcode;
}


void XmlRpcClient::setCallback(XmlRpcCallback Callback, void* context)
{
	secret->setCallback(Callback, context);
}


void XmlRpcClient::setBasicAuth_Callback(getBasicAuth_UsernameAndPassword_fn fn)
{
	secret->BasicAuth.FindUsernameAndPassword = fn;
}


void XmlRpcClient::setBasicAuth_UsernameAndPassword(const char* username, const char* password)
{
	strcpy_s(secret->BasicAuth.username, username);
	strcpy_s(secret->BasicAuth.password, password);
}


void XmlRpcClient::setIgnoreCertificateAuthority(bool value)
{
	secret->setIgnoreCertificateAuthority(value);
}


bool XmlRpcClient::isFault() const
{
	return secret->isFault;
}


void XmlRpcClient::close()
{
	delete secret;
	secret = NULL;
}


XmlRpcImplementation::XmlRpcImplementation(const char* server, INTERNET_PORT _port, const char* _object,
												XmlRpcClient::protocol_enum _protocol)
{
	port = _port;
	object = _object;
	HttpErrcode = -1;
	if (_protocol == XmlRpcClient::XMLRPC_AUTO)
		protocol =	(port == 80) ? XmlRpcClient::XMLRPC_HTTP : 
					(port == 443) ? XmlRpcClient::XMLRPC_HTTPS : XmlRpcClient::XMLRPC_HTTP;
	else protocol = _protocol;
	ignoreCertificateAuthority = false;
	hConnect = NULL;
	connect(server);
}


XmlRpcImplementation::XmlRpcImplementation(const char* URI)
{
	port = 0;
	ignoreCertificateAuthority = false;
	if (strbegins(URI, "https://", false)) {
		protocol = XmlRpcClient::XMLRPC_HTTPS;
		URI += 8;
		port = 443;
	}
	else if (strbegins(URI, "http://", false)) {
		protocol = XmlRpcClient::XMLRPC_HTTP;
		URI += 7;
		port = 80;
	}
	else {
		errmsg = "The URI must begin with \"https://\" or \"http://\".";
		return;
	}
	const char* t = URI;
	while (*t != ':' && *t != '\0' && *t != '/')
		t++;
	std::string server(URI, t - URI);
	if (*t == ':') {
		t++;
		port = (INTERNET_PORT)atoi(t);
		while (*t >= '0' && *t <= '9')
			t++;
	}
	object = t;		// should start with '/'.
	connect(server.c_str());
}


bool XmlRpcImplementation::connect(const char* server)
{
	Callback = NULL;
	context = NULL;
	totalBytes = 0;
	hInternet = InternetOpenA("XmlRpc", 0, NULL, NULL, 0);
	if (hInternet == NULL) {
		hadError("InternetOpen");
		return false;
	}
	hConnect = InternetConnectA(hInternet, server, port, 
					NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)this);
	if (hConnect == NULL) {
		hadError("InternetConnect");
		return false;
	}
	DWORD dwTimeout=999000;		// 999 seconds
	InternetSetOptionA(hInternet, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeout, sizeof(DWORD)); 
	InternetSetOptionA(hConnect, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeout, sizeof(DWORD));
	return true;
}


// Converts a GetLastError() code into a human-readable string.
void XmlRpcImplementation::hadError(const char* function)
{   
	errmsg = function;
	errmsg += " : ";

	int LastError = GetLastError();
	if (LastError == ERROR_INTERNET_TIMEOUT)
		errmsg += "Internet timeout";
	else if (LastError == ERROR_INTERNET_INVALID_CA)
		errmsg += "Invalid certificate authority";
	else if (LastError == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
		errmsg += "Talking HTTPS to an HTTP server?";
	else if (LastError == ERROR_INTERNET_CANNOT_CONNECT)
		errmsg += "Failed to connect";
	else if (LastError == ERROR_INTERNET_INVALID_URL)
		errmsg += "Invalid URL";
	else if (LastError == ERROR_INTERNET_NAME_NOT_RESOLVED)
		errmsg += "Domain name not resolved";
	else if (LastError == ERROR_INTERNET_CONNECTION_RESET)
		errmsg += "Connection reset";
	else if (LastError == ERROR_INTERNET_NOT_INITIALIZED)
		errmsg += "Internet not initialised";
	else if (LastError == ERROR_INTERNET_CONNECTION_ABORTED)
		errmsg += "Connection aborted";
	else if (LastError == ERROR_INTERNET_SEC_CERT_REV_FAILED)
		errmsg += "Unable to check whether security certificate was revoked or not. Is your system clock time correct?";
	else {
		static char* buf;
		FormatMessageA(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				LastError,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(char*)&buf,
				0,
				NULL
		);
		if (buf == NULL) {
			char tmp[512];
			sprintf_s(tmp, "Error %d", LastError);
			errmsg += tmp;
		}
		else {
			errmsg += buf;
		    LocalFree(buf);
		}
	}
}


static void CALLBACK myInternetCallback(HINTERNET,
				DWORD_PTR dwContext,
				DWORD dwInternetStatus,
				LPVOID,
				DWORD)
{
	XmlRpcImplementation *connection = (XmlRpcImplementation*)dwContext;
	if (connection && connection->Callback) {
		static char buf[512];
		const char* status;
		switch (dwInternetStatus) {
			case INTERNET_STATUS_RECEIVING_RESPONSE:	if (connection->totalBytes == 0)
															status = "Waiting for response"; 
														else status = "Receiving response";
														break;
			case INTERNET_STATUS_RESPONSE_RECEIVED:		status = "Response received"; break;
			case INTERNET_STATUS_HANDLE_CLOSING:		status = "Handle closing"; break;
			case INTERNET_STATUS_REQUEST_SENT:			status = "Data sent"; break;
			case INTERNET_STATUS_SENDING_REQUEST:		status = "Sending data"; break;
			default:									status = buf; 
														sprintf_s(buf, "Status %u", dwInternetStatus);
														break;
		}
		connection->Callback(connection->context, status);
	}
}


bool XmlRpcImplementation::execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result)
{
	errmsg.clear();

	if (hConnect == NULL) {
		errmsg = "No connection";
		return false;
	}

	// Build the request as an XML file:
	std::ostringstream ostr;
	try {
		params.buildCall(method, ostr);
	} catch (XmlRpcException e) {
		errmsg = e.getMessage();
		return false;
	}

	// Create the HttpOpenRequest object:
	if (Callback)
		Callback(context, "Sending data");
	const char* acceptTypes[2] = { "text/*", NULL };
	int flags = INTERNET_FLAG_DONT_CACHE;
	flags |= INTERNET_FLAG_KEEP_CONNECTION;
	if (protocol != XmlRpcClient::XMLRPC_HTTP)
		flags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
RETRY:
	HINTERNET hHttpFile = HttpOpenRequestA(
					  hConnect,
					  "POST",
					  object.c_str(),
					  HTTP_VERSIONA,
					  NULL,
					  acceptTypes,
					  flags, 
					  (DWORD_PTR)this);
	if (hHttpFile == NULL) {
		hadError("HttpOpenRequest");
		return false;
	}
	InternetSetStatusCallback(hHttpFile, myInternetCallback);

	if (ignoreCertificateAuthority) {
		DWORD dwFlags;
		DWORD dwBuffLen = sizeof(dwFlags);

		InternetQueryOption(hHttpFile, INTERNET_OPTION_SECURITY_FLAGS,
					(LPVOID)&dwFlags, &dwBuffLen);
		dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
		InternetSetOption(hHttpFile, INTERNET_OPTION_SECURITY_FLAGS,
							&dwFlags, sizeof (dwFlags) );
	}

	// Add the 'Content-Type' && 'Content-length' headers
	char header[255];		// Thanks, Anthony Chan.
	const std::string& requestStr = ostr.str();
	sprintf_s(header, "Content-Type: text/xml\r\nContent-length: %Iu", requestStr.size());
	HttpAddRequestHeadersA(hHttpFile, header, (DWORD)strlen(header), HTTP_ADDREQ_FLAG_ADD);

	// Send the request:
	if (! HttpSendRequestA(hHttpFile, NULL, 0, (LPVOID)requestStr.c_str(), (DWORD)requestStr.size())) {
		hadError("HttpSendRequest");
		return false;
	}
	if (Callback)
		Callback(context, "Data sent...");

	// Read the response:
	char* buf = NULL;
	int len = 0;
	do {
		DWORD bytesAvailable;
		if (!InternetQueryDataAvailable(hHttpFile, &bytesAvailable, 0, (DWORD_PTR)this)) {
			hadError("InternetQueryDataAvailable");
			break;
		}
		if (bytesAvailable == 0)
			break;		// This is the EOF condition.

		buf = (char*)realloc(buf, len+bytesAvailable+1);

		// Read the data from the HINTERNET handle.
		DWORD bytesRead;
		if (!InternetReadFile(hHttpFile,
							 (LPVOID)(buf + len),
							 bytesAvailable,
							 &bytesRead))
		{
			hadError("InternetReadFile");
			break;
		}

		len += bytesRead;
		buf[len] = '\0';
		totalBytes = len;

	} while (true);

	// Roel Vanhout's insertion:  Did we get a HTTP_STATUS_OK response?  If not, why not?
	// XMLRPC spec says always return 200 for a valid answer. So if it's anything other than
 	// 200, it's an error (i.e., no support for redirects etc.).
 	DWORD buf_size, dummy;
  	buf_size = sizeof(DWORD);
 	if (!HttpQueryInfo(hHttpFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &HttpErrcode, &buf_size, 0)) {
 		errmsg = "Could not query HTTP result status";
 		free(buf);
 		return false;
 	}

	// What was the response?
	if (HttpErrcode == HTTP_STATUS_OK) {
		// good - we have our data.
	}
  	else if (HttpErrcode == HTTP_STATUS_DENIED || HttpErrcode == HTTP_STATUS_PROXY_AUTH_REQ) {
		if (BasicAuth.FindUsernameAndPassword) {
			free(buf);
			buf = NULL;
			if (BasicAuth.FindUsernameAndPassword(BasicAuth.username[0] != '\0', BasicAuth.username, BasicAuth.password)) {
				InternetSetOptionA(hConnect, INTERNET_OPTION_PROXY_USERNAME, 
										(LPVOID)BasicAuth.username, DWORD(strlen(BasicAuth.username)));
				InternetSetOptionA(hConnect, INTERNET_OPTION_PROXY_PASSWORD, 
										(LPVOID)BasicAuth.password, DWORD(strlen(BasicAuth.password)));
				goto RETRY;
			}
		}
		errmsg = "HTTP Basic authentication failed. You need to provide a username and password.";
		free(buf);
	    InternetCloseHandle(hHttpFile);
		return false;
	}
  	else {
 		buf_size = 0;
 		HttpQueryInfo(hHttpFile, HTTP_QUERY_STATUS_TEXT, &dummy, &buf_size, 0);
 		buf_size++;	// For the '\0'
 		char* status_text = (char*)::malloc(buf_size);
 		if (!HttpQueryInfo(hHttpFile, HTTP_QUERY_STATUS_TEXT, status_text, &buf_size, 0))
 			errmsg = "Could not query HTTP result status";
		else {
			std::ostringstream sstream;
			sstream << "Low level (HTTP) error: " << HttpErrcode << " " << status_text;
			errmsg = sstream.str();
		}
		free(status_text);
	    InternetCloseHandle(hHttpFile);
 		free(buf);
 		return false;
 	}
 
    // Close the HttpRequest object:
    InternetCloseHandle(hHttpFile);

	// Parse the response:
	if (len == 0) {
		errmsg = "Invalid XMLRPC response: content size is 0";
		free(buf);		// 'buf' will always be NULL unless for some strange reason,
						// InternetReadFile() returns 'false' on the first pass.
		return false;
	}

	try {
		isFault = ! result.parseMethodResponse(buf);
		if (isFault) {
			XmlRpcValue possible = result["faultString"];
			if (possible.getType() == XmlRpcValue::TypeString)
				errmsg = std::string(possible);
			else errmsg = "unspecified error";
		}
	}
	catch (XmlRpcException err) {
		errmsg = err.getMessage();
	}
	free(buf);

	// Finished:
	return errmsg.empty();
}


XmlRpcImplementation::~XmlRpcImplementation()
{
	if (hConnect)
		InternetCloseHandle(hConnect);
	if (hInternet)
		InternetCloseHandle(hInternet);
}



//---------------------------- Unit testing: ----------------------

#ifdef XML_RPC_UNIT_TEST

#include <fstream>

static void assert_failed(int line, char* filename, char* msg)
{
	printf("Assert failed|   %s:%d   %s\n", filename, line, msg);
}

#define assert(c)		if (c) ; else assert_failed(__LINE__,__FILE__,#c)

static void RoundTrip(XmlRpcValue &a)
{
	std::ostringstream ostr;
	a.toXml(ostr);
	std::string buf = ostr.str();
	XmlRpcValue b;
	const char* s = buf.c_str();
	b.fromXml(s);
	assert(a == b);
}


void XmlRpcUnitTest()
{
	try {
		XmlRpcValue result;
		char buf[327680];
		std::ifstream input("C:\\Documents && Settings\\edval\\Desktop\\Edval data\\debug.txt");
		input.read(buf, sizeof(buf));
		const char* s = buf;
		result.fromXml(s);
		for (int i=0; i < result.size(); i++) {
			XmlRpcValue el = result[i];
			std::string _AcademicYear = el["ACADEMIC_YEAR"];
			int AcademicYearId = el["ACADEMIC_YEAR_ID"];
		}
	} catch (XmlRpcException e) {
	}

	std::vector<XmlRpcValue> V;
	V.push_back(10);
	V.push_back(20);
	V.push_back(30);
	V.push_back(40);
	V.push_back(50);

	XmlRpcValue a = "Hello you";
	RoundTrip(a);

	XmlRpcValue harry;
	harry[0] = 56;
	harry[1] = 560;
	harry[2] = 115;
	harry[3] = 145;
	harry[4] = 35;

	//5
	XmlRpcValue binny((void*)XmlRpcUnitTest, 30);
	RoundTrip(binny);

	XmlRpcValue jenny;
	jenny["NAME"] = "Electric boots";
	jenny["code"] = "54121";
	jenny["status"] = true;

	//14
	a.clear();
	a["CHARGE"] = 505;
	a["SPIN"] = "foo";
	a["COLOUR"] = false;
	a["BENNY"] = harry;
	a["BINNY"] = binny;
	a["JENNY"] = jenny;
	a["EMPTY"] = "";
	RoundTrip(a);

	// Copy constructors:
	XmlRpcValue b;
	{
		XmlRpcValue copy = a;
		XmlRpcValue tmp = copy;
		b = tmp;
	}
	assert(a == b);
}

#endif