File: parserInternals.c

package info (click to toggle)
libxml2 2.15.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 9,964 kB
  • sloc: ansic: 138,103; python: 6,692; sh: 4,736; xml: 1,476; makefile: 715
file content (3754 lines) | stat: -rw-r--r-- 100,919 bytes parent folder | download | duplicates (3)
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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
/*
 * parserInternals.c : Internal routines (and obsolete ones) needed for the
 *                     XML and HTML parsers.
 *
 * See Copyright for the status of this software.
 *
 * Author: Daniel Veillard
 */

#define IN_LIBXML
#include "libxml.h"

#if defined(_WIN32)
#define XML_DIR_SEP '\\'
#else
#define XML_DIR_SEP '/'
#endif

#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#include <libxml/xmlmemory.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/entities.h>
#include <libxml/xmlerror.h>
#include <libxml/encoding.h>
#include <libxml/xmlIO.h>
#include <libxml/uri.h>
#include <libxml/dict.h>
#include <libxml/xmlsave.h>
#ifdef LIBXML_CATALOG_ENABLED
#include <libxml/catalog.h>
#endif
#include <libxml/chvalid.h>

#define CUR(ctxt) ctxt->input->cur
#define END(ctxt) ctxt->input->end

#include "private/buf.h"
#include "private/enc.h"
#include "private/error.h"
#include "private/globals.h"
#include "private/io.h"
#include "private/memory.h"
#include "private/parser.h"

#ifndef SIZE_MAX
  #define SIZE_MAX ((size_t) -1)
#endif

#define XML_MAX_ERRORS 100

/*
 * XML_MAX_AMPLIFICATION_DEFAULT is the default maximum allowed amplification
 * factor of serialized output after entity expansion.
 */
#define XML_MAX_AMPLIFICATION_DEFAULT 5

/*
 * Various global defaults for parsing
 */

/**
 * check the compiled lib version against the include one.
 *
 * @param version  the include version number
 */
void
xmlCheckVersion(int version) {
    int myversion = LIBXML_VERSION;

    xmlInitParser();

/*
 * Disable the version check. Questionable by library handling of the 
 * distribution.  See https://bugs.debian.org/1072012 for the rationale.
*/
#if 0
    if ((myversion / 10000) != (version / 10000)) {
	xmlPrintErrorMessage(
		"Fatal: program compiled against libxml %d using libxml %d\n",
		(version / 10000), (myversion / 10000));
    } else if ((myversion / 100) < (version / 100)) {
	xmlPrintErrorMessage(
		"Warning: program compiled against libxml %d using older %d\n",
		(version / 100), (myversion / 100));
    }
#endif
}


/************************************************************************
 *									*
 *		Some factorized error routines				*
 *									*
 ************************************************************************/


/**
 * Register a callback function that will be called on errors and
 * warnings. If handler is NULL, the error handler will be deactivated.
 *
 * If you only want to disable parser errors being printed to
 * stderr, use xmlParserOption XML_PARSE_NOERROR.
 *
 * This is the recommended way to collect errors from the parser and
 * takes precedence over all other error reporting mechanisms.
 * These are (in order of precedence):
 *
 * - per-context structured handler (#xmlCtxtSetErrorHandler)
 * - per-context structured "serror" SAX handler
 * - global structured handler (#xmlSetStructuredErrorFunc)
 * - per-context generic "error" and "warning" SAX handlers
 * - global generic handler (#xmlSetGenericErrorFunc)
 * - print to stderr
 *
 * @since 2.13.0
 * @param ctxt  an XML parser context
 * @param handler  error handler
 * @param data  data for error handler
 */
void
xmlCtxtSetErrorHandler(xmlParserCtxt *ctxt, xmlStructuredErrorFunc handler,
                       void *data)
{
    if (ctxt == NULL)
        return;
    ctxt->errorHandler = handler;
    ctxt->errorCtxt = data;
}

/**
 * Get the last error raised.
 *
 * Note that the XML parser typically doesn't stop after
 * encountering an error and will often report multiple errors.
 * Most of the time, the last error isn't useful. Future
 * versions might return the first parser error instead.
 *
 * @param ctx  an XML parser context
 * @returns NULL if no error occurred or a pointer to the error
 */
const xmlError *
xmlCtxtGetLastError(void *ctx)
{
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

    if (ctxt == NULL)
        return (NULL);
    if (ctxt->lastError.code == XML_ERR_OK)
        return (NULL);
    return (&ctxt->lastError);
}

/**
 * Reset the last parser error to success. This does not change
 * the well-formedness status.
 *
 * @param ctx  an XML parser context
 */
void
xmlCtxtResetLastError(void *ctx)
{
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

    if (ctxt == NULL)
        return;
    ctxt->errNo = XML_ERR_OK;
    if (ctxt->lastError.code == XML_ERR_OK)
        return;
    xmlResetError(&ctxt->lastError);
}

/**
 * Handle an out-of-memory error.
 *
 * @since 2.13.0
 * @param ctxt  an XML parser context
 */
void
xmlCtxtErrMemory(xmlParserCtxt *ctxt)
{
    xmlStructuredErrorFunc schannel = NULL;
    xmlGenericErrorFunc channel = NULL;
    void *data;

    if (ctxt == NULL) {
        xmlRaiseMemoryError(NULL, NULL, NULL, XML_FROM_PARSER, NULL);
        return;
    }

    ctxt->errNo = XML_ERR_NO_MEMORY;
    ctxt->instate = XML_PARSER_EOF; /* TODO: Remove after refactoring */
    ctxt->wellFormed = 0;
    ctxt->disableSAX = 2;

    if (ctxt->errorHandler) {
        schannel = ctxt->errorHandler;
        data = ctxt->errorCtxt;
    } else if ((ctxt->sax->initialized == XML_SAX2_MAGIC) &&
        (ctxt->sax->serror != NULL)) {
        schannel = ctxt->sax->serror;
        data = ctxt->userData;
    } else {
        channel = ctxt->sax->error;
        data = ctxt->userData;
    }

    xmlRaiseMemoryError(schannel, channel, data, XML_FROM_PARSER,
                        &ctxt->lastError);
}

/**
 * If filename is empty, use the one from context input if available.
 *
 * Report an IO error to the parser context.
 *
 * @param ctxt  parser context
 * @param code  xmlParserErrors code
 * @param uri  filename or URI (optional)
 */
void
xmlCtxtErrIO(xmlParserCtxt *ctxt, int code, const char *uri)
{
    const char *errstr, *msg, *str1, *str2;
    xmlErrorLevel level;

    if (ctxt == NULL)
        return;

    if (((code == XML_IO_ENOENT) ||
         (code == XML_IO_UNKNOWN))) {
        /*
         * Only report a warning if a file could not be found. This should
         * only be done for external entities, but the external entity loader
         * of xsltproc can try multiple paths and assumes that ENOENT doesn't
         * raise an error and aborts parsing.
         */
        if (ctxt->validate == 0)
            level = XML_ERR_WARNING;
        else
            level = XML_ERR_ERROR;
    } else if (code == XML_IO_NETWORK_ATTEMPT) {
        level = XML_ERR_ERROR;
    } else {
        level = XML_ERR_FATAL;
    }

    errstr = xmlErrString(code);

    if (uri == NULL) {
        msg = "%s\n";
        str1 = errstr;
        str2 = NULL;
    } else {
        msg = "failed to load \"%s\": %s\n";
        str1 = uri;
        str2 = errstr;
    }

    xmlCtxtErr(ctxt, NULL, XML_FROM_IO, code, level,
               (const xmlChar *) uri, NULL, NULL, 0,
               msg, str1, str2);
}

/**
 * @param ctxt  parser context
 * @returns true if the last error is catastrophic.
 */
int
xmlCtxtIsCatastrophicError(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(1);

    return(xmlIsCatastrophicError(ctxt->lastError.level,
                                  ctxt->lastError.code));
}

/**
 * Raise a parser error.
 *
 * @param ctxt  a parser context
 * @param node  the current node or NULL
 * @param domain  the domain for the error
 * @param code  the code for the error
 * @param level  the xmlErrorLevel for the error
 * @param str1  extra string info
 * @param str2  extra string info
 * @param str3  extra string info
 * @param int1  extra int info
 * @param msg  the message to display/transmit
 * @param ap  extra parameters for the message display
 */
void
xmlCtxtVErr(xmlParserCtxt *ctxt, xmlNode *node, xmlErrorDomain domain,
            xmlParserErrors code, xmlErrorLevel level,
            const xmlChar *str1, const xmlChar *str2, const xmlChar *str3,
            int int1, const char *msg, va_list ap)
{
    xmlStructuredErrorFunc schannel = NULL;
    xmlGenericErrorFunc channel = NULL;
    void *data = NULL;
    const char *file = NULL;
    int line = 0;
    int col = 0;
    int res;

    if (code == XML_ERR_NO_MEMORY) {
        xmlCtxtErrMemory(ctxt);
        return;
    }

    if (ctxt == NULL) {
        res = xmlVRaiseError(NULL, NULL, NULL, NULL, node, domain, code,
                             level, NULL, 0, (const char *) str1,
                             (const char *) str2, (const char *) str3,
                             int1, 0, msg, ap);
        if (res < 0)
            xmlRaiseMemoryError(NULL, NULL, NULL, XML_FROM_PARSER, NULL);

        return;
    }

    if (PARSER_STOPPED(ctxt))
	return;

    /* Don't overwrite catastrophic errors */
    if (xmlCtxtIsCatastrophicError(ctxt))
        return;

    if (level == XML_ERR_WARNING) {
        if (ctxt->nbWarnings >= XML_MAX_ERRORS)
            return;
        ctxt->nbWarnings += 1;
    } else {
        /*
         * By long-standing design, the parser isn't completely
         * stopped on well-formedness errors. Only SAX callbacks
         * are disabled.
         *
         * In some situations, we really want to abort as fast
         * as possible.
         */
        if (xmlIsCatastrophicError(level, code) ||
            code == XML_ERR_RESOURCE_LIMIT ||
            code == XML_ERR_ENTITY_LOOP) {
            ctxt->disableSAX = 2; /* really stop parser */
        } else {
            /* Report at least one fatal error. */
            if (ctxt->nbErrors >= XML_MAX_ERRORS &&
                (level < XML_ERR_FATAL || ctxt->wellFormed == 0))
                return;

            if (level == XML_ERR_FATAL && ctxt->recovery == 0)
                ctxt->disableSAX = 1;
        }

        if (level == XML_ERR_FATAL)
            ctxt->wellFormed = 0;
        ctxt->errNo = code;
        ctxt->nbErrors += 1;
    }

    if (((ctxt->options & XML_PARSE_NOERROR) == 0) &&
        ((level != XML_ERR_WARNING) ||
         ((ctxt->options & XML_PARSE_NOWARNING) == 0))) {
        if (ctxt->errorHandler) {
            schannel = ctxt->errorHandler;
            data = ctxt->errorCtxt;
        } else if ((ctxt->sax->initialized == XML_SAX2_MAGIC) &&
            (ctxt->sax->serror != NULL)) {
            schannel = ctxt->sax->serror;
            data = ctxt->userData;
        } else if ((domain == XML_FROM_VALID) || (domain == XML_FROM_DTD)) {
            if (level == XML_ERR_WARNING)
                channel = ctxt->vctxt.warning;
            else
                channel = ctxt->vctxt.error;
            data = ctxt->vctxt.userData;
        } else {
            if (level == XML_ERR_WARNING)
                channel = ctxt->sax->warning;
            else
                channel = ctxt->sax->error;
            data = ctxt->userData;
        }
    }

    if (ctxt->input != NULL) {
        xmlParserInputPtr input = ctxt->input;

        if ((input->filename == NULL) &&
            (ctxt->inputNr > 1)) {
            input = ctxt->inputTab[ctxt->inputNr - 2];
        }
        file = input->filename;
        line = input->line;
        col = input->col;
    }

    res = xmlVRaiseError(schannel, channel, data, ctxt, node, domain, code,
                         level, file, line, (const char *) str1,
                         (const char *) str2, (const char *) str3, int1, col,
                         msg, ap);

    if (res < 0) {
        xmlCtxtErrMemory(ctxt);
        return;
    }
}

/**
 * Raise a parser error.
 *
 * @param ctxt  a parser context
 * @param node  the current node or NULL
 * @param domain  the domain for the error
 * @param code  the code for the error
 * @param level  the xmlErrorLevel for the error
 * @param str1  extra string info
 * @param str2  extra string info
 * @param str3  extra string info
 * @param int1  extra int info
 * @param msg  the message to display/transmit
 * @param ...  extra parameters for the message display
 */
void
xmlCtxtErr(xmlParserCtxt *ctxt, xmlNode *node, xmlErrorDomain domain,
           xmlParserErrors code, xmlErrorLevel level,
           const xmlChar *str1, const xmlChar *str2, const xmlChar *str3,
           int int1, const char *msg, ...)
{
    va_list ap;

    va_start(ap, msg);
    xmlCtxtVErr(ctxt, node, domain, code, level,
                str1, str2, str3, int1, msg, ap);
    va_end(ap);
}

/**
 * Get well-formedness and validation status after parsing. Also
 * reports catastrophic errors which are not related to parsing
 * like out-of-memory, I/O or other errors.
 *
 * @since 2.14.0
 *
 * @param ctxt  an XML parser context
 * @returns a bitmask of XML_STATUS_* flags ORed together.
 */
xmlParserStatus
xmlCtxtGetStatus(xmlParserCtxt *ctxt) {
    xmlParserStatus bits = 0;

    if (xmlCtxtIsCatastrophicError(ctxt)) {
        bits |= XML_STATUS_CATASTROPHIC_ERROR |
                XML_STATUS_NOT_WELL_FORMED |
                XML_STATUS_NOT_NS_WELL_FORMED;
        if ((ctxt != NULL) && (ctxt->validate))
            bits |= XML_STATUS_DTD_VALIDATION_FAILED;

        return(bits);
    }

    if (!ctxt->wellFormed)
        bits |= XML_STATUS_NOT_WELL_FORMED;
    if (!ctxt->nsWellFormed)
        bits |= XML_STATUS_NOT_NS_WELL_FORMED;
    if ((ctxt->validate) && (!ctxt->valid))
        bits |= XML_STATUS_DTD_VALIDATION_FAILED;

    return(bits);
}

/**
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
 *
 * @param ctxt  an XML parser context
 * @param code  the error number
 * @param info  extra information string
 */
void
xmlFatalErr(xmlParserCtxt *ctxt, xmlParserErrors code, const char *info)
{
    const char *errmsg;
    xmlErrorDomain domain = XML_FROM_PARSER;
    xmlErrorLevel level = XML_ERR_FATAL;

    errmsg = xmlErrString(code);

    if ((ctxt != NULL) && (ctxt->html)) {
        domain = XML_FROM_HTML;

        /* Continue if encoding is unsupported */
        if (code == XML_ERR_UNSUPPORTED_ENCODING)
            level = XML_ERR_ERROR;
    }

    if (info == NULL) {
        xmlCtxtErr(ctxt, NULL, domain, code, level,
                   NULL, NULL, NULL, 0, "%s\n", errmsg);
    } else {
        xmlCtxtErr(ctxt, NULL, domain, code, level,
                   (const xmlChar *) info, NULL, NULL, 0,
                   "%s: %s\n", errmsg, info);
    }
}

/**
 * Return window into current parser data.
 *
 * @param input  parser input
 * @param startOut  start of window (output)
 * @param sizeInOut  maximum size of window (in)
 *                   actual size of window (out)
 * @param offsetOut  offset of current position inside
 *                   window (out)
 */
void
xmlParserInputGetWindow(xmlParserInput *input, const xmlChar **startOut,
                        int *sizeInOut, int *offsetOut) {
    const xmlChar *cur, *base, *start;
    int n, col;
    int size = *sizeInOut;

    cur = input->cur;
    base = input->base;
    /* skip backwards over any end-of-lines */
    while ((cur > base) && ((*(cur) == '\n') || (*(cur) == '\r'))) {
	cur--;
    }
    n = 0;
    /* search backwards for beginning-of-line (to max buff size) */
    while ((n < size) && (cur > base) &&
	   (*cur != '\n') && (*cur != '\r')) {
        cur--;
        n++;
    }
    if ((n > 0) && ((*cur == '\n') || (*cur == '\r'))) {
        cur++;
    } else {
        /* skip over continuation bytes */
        while ((cur < input->cur) && ((*cur & 0xC0) == 0x80))
            cur++;
    }
    /* calculate the error position in terms of the current position */
    col = input->cur - cur;
    /* search forward for end-of-line (to max buff size) */
    n = 0;
    start = cur;
    /* copy selected text to our buffer */
    while ((*cur != 0) && (*(cur) != '\n') && (*(cur) != '\r')) {
        int len = input->end - cur;
        int c = xmlGetUTF8Char(cur, &len);

        if ((c < 0) || (n + len > size))
            break;
        cur += len;
	n += len;
    }

    /*
     * col can only point to the end of the buffer if
     * there's space for a marker.
     */
    if (col >= n)
        col = n < size ? n : size - 1;

    *startOut = start;
    *sizeInOut = n;
    *offsetOut = col;
}

/**
 * Check whether the character is allowed by the production
 *
 * @deprecated Internal function, don't use.
 *
 * ```
 * [84] Letter ::= BaseChar | Ideographic
 * ```
 *
 * @param c  an unicode character (int)
 * @returns 0 if not, non-zero otherwise
 */
int
xmlIsLetter(int c) {
    return(IS_BASECHAR(c) || IS_IDEOGRAPHIC(c));
}

/************************************************************************
 *									*
 *		Input handling functions for progressive parsing	*
 *									*
 ************************************************************************/

/* we need to keep enough input to show errors in context */
#define LINE_LEN        80

/**
 * @deprecated This function was internal and is deprecated.
 *
 * @param in  an XML parser input
 * @param len  an indicative size for the lookahead
 * @returns -1 as this is an error to use it.
 */
int
xmlParserInputRead(xmlParserInput *in ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED) {
    return(-1);
}

/**
 * Grow the input buffer.
 *
 * @param ctxt  an XML parser context
 * @returns the number of bytes read or -1 in case of error.
 */
int
xmlParserGrow(xmlParserCtxt *ctxt) {
    xmlParserInputPtr in = ctxt->input;
    xmlParserInputBufferPtr buf = in->buf;
    size_t curEnd = in->end - in->cur;
    size_t curBase = in->cur - in->base;
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
                       XML_MAX_HUGE_LENGTH :
                       XML_MAX_LOOKUP_LIMIT;
    int ret;

    if (buf == NULL)
        return(0);
    /* Don't grow push parser buffer. */
    if (PARSER_PROGRESSIVE(ctxt))
        return(0);
    /* Don't grow memory buffers. */
    if ((buf->encoder == NULL) && (buf->readcallback == NULL))
        return(0);
    if (buf->error != 0)
        return(-1);

    if (curBase > maxLength) {
        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
                    "Buffer size limit exceeded, try XML_PARSE_HUGE\n");
	return(-1);
    }

    if (curEnd >= INPUT_CHUNK)
        return(0);

    ret = xmlParserInputBufferGrow(buf, INPUT_CHUNK);
    xmlBufUpdateInput(buf->buffer, in, curBase);

    if (ret < 0) {
        xmlCtxtErrIO(ctxt, buf->error, NULL);
    }

    return(ret);
}

/**
 * Raises an error with `code` if the input wasn't consumed
 * completely.
 *
 * @param ctxt  parser ctxt
 * @param code  error code
 */
void
xmlParserCheckEOF(xmlParserCtxt *ctxt, xmlParserErrors code) {
    xmlParserInputPtr in = ctxt->input;
    xmlParserInputBufferPtr buf;

    if (ctxt->errNo != XML_ERR_OK)
        return;

    if (in->cur < in->end) {
        xmlFatalErr(ctxt, code, NULL);
        return;
    }

    buf = in->buf;
    if ((buf != NULL) && (buf->encoder != NULL)) {
        size_t curBase = in->cur - in->base;
        size_t sizeOut = 64;
        xmlCharEncError ret;

        /*
         * Check for truncated multi-byte sequence
         */
        ret = xmlCharEncInput(buf, &sizeOut, /* flush */ 1);
        xmlBufUpdateInput(buf->buffer, in, curBase);
        if (ret != XML_ENC_ERR_SUCCESS) {
            xmlCtxtErrIO(ctxt, buf->error, NULL);
            return;
        }

        /* Shouldn't happen */
        if (in->cur < in->end)
            xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "expected EOF");
    }
}

/**
 * This function increase the input for the parser. It tries to
 * preserve pointers to the input buffer, and keep already read data
 *
 * @deprecated Don't use.
 *
 * @param in  an XML parser input
 * @param len  an indicative size for the lookahead
 * @returns the amount of char read, or -1 in case of error, 0 indicate the
 * end of this entity
 */
int
xmlParserInputGrow(xmlParserInput *in, int len) {
    int ret;
    size_t indx;

    if ((in == NULL) || (len < 0)) return(-1);
    if (in->buf == NULL) return(-1);
    if (in->base == NULL) return(-1);
    if (in->cur == NULL) return(-1);
    if (in->buf->buffer == NULL) return(-1);

    /* Don't grow memory buffers. */
    if ((in->buf->encoder == NULL) && (in->buf->readcallback == NULL))
        return(0);

    indx = in->cur - in->base;
    if (xmlBufUse(in->buf->buffer) > (unsigned int) indx + INPUT_CHUNK) {
        return(0);
    }
    ret = xmlParserInputBufferGrow(in->buf, len);

    in->base = xmlBufContent(in->buf->buffer);
    if (in->base == NULL) {
        in->base = BAD_CAST "";
        in->cur = in->base;
        in->end = in->base;
        return(-1);
    }
    in->cur = in->base + indx;
    in->end = xmlBufEnd(in->buf->buffer);

    return(ret);
}

/**
 * Shrink the input buffer.
 *
 * @param ctxt  an XML parser context
 */
void
xmlParserShrink(xmlParserCtxt *ctxt) {
    xmlParserInputPtr in = ctxt->input;
    xmlParserInputBufferPtr buf = in->buf;
    size_t used, res;

    if (buf == NULL)
        return;

    used = in->cur - in->base;

    if (used > LINE_LEN) {
        res = xmlBufShrink(buf->buffer, used - LINE_LEN);

        if (res > 0) {
            used -= res;
            xmlSaturatedAddSizeT(&in->consumed, res);
        }

        xmlBufUpdateInput(buf->buffer, in, used);
    }
}

/**
 * This function removes used input for the parser.
 *
 * @deprecated Don't use.
 *
 * @param in  an XML parser input
 */
void
xmlParserInputShrink(xmlParserInput *in) {
    size_t used;
    size_t ret;

    if (in == NULL) return;
    if (in->buf == NULL) return;
    if (in->base == NULL) return;
    if (in->cur == NULL) return;
    if (in->buf->buffer == NULL) return;

    used = in->cur - in->base;

    if (used > LINE_LEN) {
	ret = xmlBufShrink(in->buf->buffer, used - LINE_LEN);
	if (ret > 0) {
            used -= ret;
            xmlSaturatedAddSizeT(&in->consumed, ret);
	}

        xmlBufUpdateInput(in->buf->buffer, in, used);
    }
}

/************************************************************************
 *									*
 *		UTF8 character input and related functions		*
 *									*
 ************************************************************************/

/**
 * Skip to the next char input char.
 *
 * @deprecated Internal function, do not use.
 *
 * @param ctxt  the XML parser context
 */

void
xmlNextChar(xmlParserCtxt *ctxt)
{
    const unsigned char *cur;
    size_t avail;
    int c;

    if ((ctxt == NULL) || (ctxt->input == NULL))
        return;

    avail = ctxt->input->end - ctxt->input->cur;

    if (avail < INPUT_CHUNK) {
        xmlParserGrow(ctxt);
        if (ctxt->input->cur >= ctxt->input->end)
            return;
        avail = ctxt->input->end - ctxt->input->cur;
    }

    cur = ctxt->input->cur;
    c = *cur;

    if (c < 0x80) {
        if (c == '\n') {
            ctxt->input->cur++;
            ctxt->input->line++;
            ctxt->input->col = 1;
        } else if (c == '\r') {
            /*
             *   2.11 End-of-Line Handling
             *   the literal two-character sequence "#xD#xA" or a standalone
             *   literal #xD, an XML processor must pass to the application
             *   the single character #xA.
             */
            ctxt->input->cur += ((cur[1] == '\n') ? 2 : 1);
            ctxt->input->line++;
            ctxt->input->col = 1;
            return;
        } else {
            ctxt->input->cur++;
            ctxt->input->col++;
        }
    } else {
        ctxt->input->col++;

        if ((avail < 2) || (cur[1] & 0xc0) != 0x80)
            goto encoding_error;

        if (c < 0xe0) {
            /* 2-byte code */
            if (c < 0xc2)
                goto encoding_error;
            ctxt->input->cur += 2;
        } else {
            unsigned int val = (c << 8) | cur[1];

            if ((avail < 3) || (cur[2] & 0xc0) != 0x80)
                goto encoding_error;

            if (c < 0xf0) {
                /* 3-byte code */
                if ((val < 0xe0a0) || ((val >= 0xeda0) && (val < 0xee00)))
                    goto encoding_error;
                ctxt->input->cur += 3;
            } else {
                if ((avail < 4) || ((cur[3] & 0xc0) != 0x80))
                    goto encoding_error;

                /* 4-byte code */
                if ((val < 0xf090) || (val >= 0xf490))
                    goto encoding_error;
                ctxt->input->cur += 4;
            }
        }
    }

    return;

encoding_error:
    /* Only report the first error */
    if ((ctxt->input->flags & XML_INPUT_ENCODING_ERROR) == 0) {
        xmlCtxtErrIO(ctxt, XML_ERR_INVALID_ENCODING, NULL);
        ctxt->input->flags |= XML_INPUT_ENCODING_ERROR;
    }
    ctxt->input->cur++;
}

/**
 * The current char value, if using UTF-8 this may actually span multiple
 * bytes in the input buffer. Implement the end of line normalization:
 *
 * @deprecated Internal function, do not use.
 *
 * 2.11 End-of-Line Handling
 *
 * Wherever an external parsed entity or the literal entity value
 * of an internal parsed entity contains either the literal two-character
 * sequence "#xD#xA" or a standalone literal \#xD, an XML processor
 * must pass to the application the single character \#xA.
 * This behavior can conveniently be produced by normalizing all
 * line breaks to \#xA on input, before parsing.)
 *
 * @param ctxt  the XML parser context
 * @param len  pointer to the length of the char read
 * @returns the current char value and its length
 */

int
xmlCurrentChar(xmlParserCtxt *ctxt, int *len) {
    const unsigned char *cur;
    size_t avail;
    int c;

    if ((ctxt == NULL) || (len == NULL) || (ctxt->input == NULL)) return(0);

    avail = ctxt->input->end - ctxt->input->cur;

    if (avail < INPUT_CHUNK) {
        xmlParserGrow(ctxt);
        avail = ctxt->input->end - ctxt->input->cur;
    }

    cur = ctxt->input->cur;
    c = *cur;

    if (c < 0x80) {
	/* 1-byte code */
        if (c < 0x20) {
            /*
             *   2.11 End-of-Line Handling
             *   the literal two-character sequence "#xD#xA" or a standalone
             *   literal #xD, an XML processor must pass to the application
             *   the single character #xA.
             */
            if (c == '\r') {
                /*
                 * TODO: This function shouldn't change the 'cur' pointer
                 * as side effect, but the NEXTL macro in parser.c relies
                 * on this behavior when incrementing line numbers.
                 */
                if (cur[1] == '\n')
                    ctxt->input->cur++;
                *len = 1;
                c = '\n';
            } else if (c == 0) {
                if (ctxt->input->cur >= ctxt->input->end) {
                    *len = 0;
                } else {
                    *len = 1;
                    /*
                     * TODO: Null bytes should be handled by callers,
                     * but this can be tricky.
                     */
                    xmlFatalErr(ctxt, XML_ERR_INVALID_CHAR,
                            "Char 0x0 out of allowed range\n");
                }
            } else {
                *len = 1;
            }
        } else {
            *len = 1;
        }

        return(c);
    } else {
        int val;

        if (avail < 2)
            goto incomplete_sequence;
        if ((cur[1] & 0xc0) != 0x80)
            goto encoding_error;

        if (c < 0xe0) {
            /* 2-byte code */
            if (c < 0xc2)
                goto encoding_error;
            val = (c & 0x1f) << 6;
            val |= cur[1] & 0x3f;
            *len = 2;
        } else {
            if (avail < 3)
                goto incomplete_sequence;
            if ((cur[2] & 0xc0) != 0x80)
                goto encoding_error;

            if (c < 0xf0) {
                /* 3-byte code */
                val = (c & 0xf) << 12;
                val |= (cur[1] & 0x3f) << 6;
                val |= cur[2] & 0x3f;
                if ((val < 0x800) || ((val >= 0xd800) && (val < 0xe000)))
                    goto encoding_error;
                *len = 3;
            } else {
                if (avail < 4)
                    goto incomplete_sequence;
                if ((cur[3] & 0xc0) != 0x80)
                    goto encoding_error;

                /* 4-byte code */
                val = (c & 0x0f) << 18;
                val |= (cur[1] & 0x3f) << 12;
                val |= (cur[2] & 0x3f) << 6;
                val |= cur[3] & 0x3f;
                if ((val < 0x10000) || (val >= 0x110000))
                    goto encoding_error;
                *len = 4;
            }
        }

        return(val);
    }

encoding_error:
    /* Only report the first error */
    if ((ctxt->input->flags & XML_INPUT_ENCODING_ERROR) == 0) {
        xmlCtxtErrIO(ctxt, XML_ERR_INVALID_ENCODING, NULL);
        ctxt->input->flags |= XML_INPUT_ENCODING_ERROR;
    }
    *len = 1;
    return(XML_INVALID_CHAR);

incomplete_sequence:
    /*
     * An encoding problem may arise from a truncated input buffer
     * splitting a character in the middle. In that case do not raise
     * an error but return 0. This should only happen when push parsing
     * char data.
     */
    *len = 0;
    return(0);
}

/**
 * The current char value, if using UTF-8 this may actually span multiple
 * bytes in the input buffer.
 *
 * @deprecated Internal function, do not use.
 *
 * @param ctxt  the XML parser context
 * @param cur  pointer to the beginning of the char
 * @param len  pointer to the length of the char read
 * @returns the current char value and its length
 */

int
xmlStringCurrentChar(xmlParserCtxt *ctxt ATTRIBUTE_UNUSED,
                     const xmlChar *cur, int *len) {
    int c;

    if ((cur == NULL) || (len == NULL))
        return(0);

    /* cur is zero-terminated, so we can lie about its length. */
    *len = 4;
    c = xmlGetUTF8Char(cur, len);

    return((c < 0) ? 0 : c);
}

/**
 * append the char value in the array
 *
 * @deprecated Internal function, don't use.
 *
 * @param out  pointer to an array of xmlChar
 * @param val  the char value
 * @returns the number of xmlChar written
 */
int
xmlCopyCharMultiByte(xmlChar *out, int val) {
    if ((out == NULL) || (val < 0)) return(0);
    /*
     * 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
     */
    if  (val >= 0x80) {
	xmlChar *savedout = out;
	int bits;
	if (val <   0x800) { *out++= (val >>  6) | 0xC0;  bits=  0; }
	else if (val < 0x10000) { *out++= (val >> 12) | 0xE0;  bits=  6;}
	else if (val < 0x110000)  { *out++= (val >> 18) | 0xF0;  bits=  12; }
	else {
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
            xmlAbort("xmlCopyCharMultiByte: codepoint out of range\n");
#endif
	    return(0);
	}
	for ( ; bits >= 0; bits-= 6)
	    *out++= ((val >> bits) & 0x3F) | 0x80 ;
	return (out - savedout);
    }
    *out = val;
    return 1;
}

/**
 * append the char value in the array
 *
 * @deprecated Don't use.
 *
 * @param len  Ignored, compatibility
 * @param out  pointer to an array of xmlChar
 * @param val  the char value
 * @returns the number of xmlChar written
 */

int
xmlCopyChar(int len ATTRIBUTE_UNUSED, xmlChar *out, int val) {
    if ((out == NULL) || (val < 0)) return(0);
    /* the len parameter is ignored */
    if  (val >= 0x80) {
	return(xmlCopyCharMultiByte (out, val));
    }
    *out = val;
    return 1;
}

/************************************************************************
 *									*
 *		Commodity functions to switch encodings			*
 *									*
 ************************************************************************/

/**
 * Installs a custom implementation to convert between character
 * encodings.
 *
 * This bypasses legacy feature like global encoding handlers or
 * encoding aliases.
 *
 * @since 2.14.0
 * @param ctxt  parser context
 * @param impl  callback
 * @param vctxt  user data
 */
void
xmlCtxtSetCharEncConvImpl(xmlParserCtxt *ctxt, xmlCharEncConvImpl impl,
                          void *vctxt) {
    if (ctxt == NULL)
        return;

    ctxt->convImpl = impl;
    ctxt->convCtxt = vctxt;
}

static xmlParserErrors
xmlDetectEBCDIC(xmlParserCtxtPtr ctxt, xmlCharEncodingHandlerPtr *hout) {
    xmlChar out[200];
    xmlParserInputPtr input = ctxt->input;
    xmlCharEncodingHandlerPtr handler;
    int inlen, outlen, i;
    xmlParserErrors code;
    xmlCharEncError res;

    *hout = NULL;

    /*
     * To detect the EBCDIC code page, we convert the first 200 bytes
     * to IBM037 (EBCDIC-US) and try to find the encoding declaration.
     */
    code = xmlCreateCharEncodingHandler("IBM037", XML_ENC_INPUT,
            ctxt->convImpl, ctxt->convCtxt, &handler);
    if (code != XML_ERR_OK)
        return(code);
    outlen = sizeof(out) - 1;
    inlen = input->end - input->cur;
    res = xmlEncInputChunk(handler, out, &outlen, input->cur, &inlen,
                           /* flush */ 0);
    /*
     * Return the EBCDIC handler if decoding failed. The error will
     * be reported later.
     */
    if (res < 0)
        goto done;
    out[outlen] = 0;

    for (i = 0; i < outlen; i++) {
        if (out[i] == '>')
            break;
        if ((out[i] == 'e') &&
            (xmlStrncmp(out + i, BAD_CAST "encoding", 8) == 0)) {
            int start, cur, quote;

            i += 8;
            while (IS_BLANK_CH(out[i]))
                i += 1;
            if (out[i++] != '=')
                break;
            while (IS_BLANK_CH(out[i]))
                i += 1;
            quote = out[i++];
            if ((quote != '\'') && (quote != '"'))
                break;
            start = i;
            cur = out[i];
            while (((cur >= 'a') && (cur <= 'z')) ||
                   ((cur >= 'A') && (cur <= 'Z')) ||
                   ((cur >= '0') && (cur <= '9')) ||
                   (cur == '.') || (cur == '_') ||
                   (cur == '-'))
                cur = out[++i];
            if (cur != quote)
                break;
            out[i] = 0;
            xmlCharEncCloseFunc(handler);
            code = xmlCreateCharEncodingHandler((char *) out + start,
                    XML_ENC_INPUT, ctxt->convImpl, ctxt->convCtxt,
                    &handler);
            if (code != XML_ERR_OK)
                return(code);
            *hout = handler;
            return(XML_ERR_OK);
        }
    }

done:
    /*
     * Encoding handlers are stateful, so we have to recreate them.
     */
    xmlCharEncCloseFunc(handler);
    code = xmlCreateCharEncodingHandler("IBM037", XML_ENC_INPUT,
            ctxt->convImpl, ctxt->convCtxt, &handler);
    if (code != XML_ERR_OK)
        return(code);
    *hout = handler;
    return(XML_ERR_OK);
}

/**
 * Use encoding specified by enum to decode input data. This overrides
 * the encoding found in the XML declaration.
 *
 * This function can also be used to override the encoding of chunks
 * passed to #xmlParseChunk.
 *
 * @param ctxt  the parser context
 * @param enc  the encoding value (number)
 * @returns 0 in case of success, -1 otherwise
 */
int
xmlSwitchEncoding(xmlParserCtxt *ctxt, xmlCharEncoding enc)
{
    xmlCharEncodingHandlerPtr handler = NULL;
    int ret;
    xmlParserErrors code;

    if ((ctxt == NULL) || (ctxt->input == NULL))
        return(-1);

    code = xmlLookupCharEncodingHandler(enc, &handler);
    if (code != 0) {
        xmlFatalErr(ctxt, code, NULL);
        return(-1);
    }

    ret = xmlSwitchToEncoding(ctxt, handler);

    if ((ret >= 0) && (enc == XML_CHAR_ENCODING_NONE)) {
        ctxt->input->flags &= ~XML_INPUT_HAS_ENCODING;
    }

    return(ret);
}

/**
 * @param ctxt  the parser context
 * @param input  the input strea,
 * @param encoding  the encoding name
 * @returns 0 in case of success, -1 otherwise
 */
static int
xmlSwitchInputEncodingName(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
                           const char *encoding) {
    xmlCharEncodingHandlerPtr handler;
    xmlParserErrors res;

    if (encoding == NULL)
        return(-1);

    res = xmlCreateCharEncodingHandler(encoding, XML_ENC_INPUT,
            ctxt->convImpl, ctxt->convCtxt, &handler);
    if (res == XML_ERR_UNSUPPORTED_ENCODING) {
        xmlWarningMsg(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
                      "Unsupported encoding: %s\n", BAD_CAST encoding, NULL);
        return(-1);
    } else if (res != XML_ERR_OK) {
        xmlFatalErr(ctxt, res, encoding);
        return(-1);
    }

    res  = xmlInputSetEncodingHandler(input, handler);
    if (res != XML_ERR_OK) {
        xmlCtxtErrIO(ctxt, res, NULL);
        return(-1);
    }

    return(0);
}

/**
 * Use specified encoding to decode input data. This overrides the
 * encoding found in the XML declaration.
 *
 * This function can also be used to override the encoding of chunks
 * passed to #xmlParseChunk.
 *
 * @since 2.13.0
 *
 * @param ctxt  the parser context
 * @param encoding  the encoding name
 * @returns 0 in case of success, -1 otherwise
 */
int
xmlSwitchEncodingName(xmlParserCtxt *ctxt, const char *encoding) {
    if (ctxt == NULL)
        return(-1);

    return(xmlSwitchInputEncodingName(ctxt, ctxt->input, encoding));
}

/**
 * Use encoding handler to decode input data.
 *
 * Closes the handler on error.
 *
 * @param input  the input stream
 * @param handler  the encoding handler
 * @returns an xmlParserErrors code.
 */
xmlParserErrors
xmlInputSetEncodingHandler(xmlParserInput *input,
                           xmlCharEncodingHandler *handler) {
    xmlParserInputBufferPtr in;
    xmlBufPtr buf;
    xmlParserErrors code = XML_ERR_OK;

    if ((input == NULL) || (input->buf == NULL)) {
        xmlCharEncCloseFunc(handler);
	return(XML_ERR_ARGUMENT);
    }
    in = input->buf;

    input->flags |= XML_INPUT_HAS_ENCODING;

    /*
     * UTF-8 requires no encoding handler.
     */
    if ((handler != NULL) &&
        (xmlStrcasecmp(BAD_CAST handler->name, BAD_CAST "UTF-8") == 0)) {
        xmlCharEncCloseFunc(handler);
        handler = NULL;
    }

    if (in->encoder == handler)
        return(XML_ERR_OK);

    if (in->encoder != NULL) {
        /*
         * Switching encodings during parsing is a really bad idea,
         * but Chromium can switch between ISO-8859-1 and UTF-16 before
         * separate calls to xmlParseChunk.
         *
         * TODO: We should check whether the "raw" input buffer is empty and
         * convert the old content using the old encoder.
         */

        xmlCharEncCloseFunc(in->encoder);
        in->encoder = handler;
        return(XML_ERR_OK);
    }

    buf = xmlBufCreate(XML_IO_BUFFER_SIZE);
    if (buf == NULL) {
        xmlCharEncCloseFunc(handler);
        return(XML_ERR_NO_MEMORY);
    }

    in->encoder = handler;
    in->raw = in->buffer;
    in->buffer = buf;

    /*
     * Is there already some content down the pipe to convert ?
     */
    if (input->end > input->base) {
        size_t processed;
        size_t nbchars;
        xmlCharEncError res;

        /*
         * Shrink the current input buffer.
         * Move it as the raw buffer and create a new input buffer
         */
        processed = input->cur - input->base;
        xmlBufShrink(in->raw, processed);
        input->consumed += processed;
        in->rawconsumed = processed;

        /*
         * If we're push-parsing, we must convert the whole buffer.
         *
         * If we're pull-parsing, we could be parsing from a huge
         * memory buffer which we don't want to convert completely.
         */
        if (input->flags & XML_INPUT_PROGRESSIVE)
            nbchars = SIZE_MAX;
        else
            nbchars = 4000 /* MINLEN */;
        res = xmlCharEncInput(in, &nbchars, /* flush */ 0);
        if (res != XML_ENC_ERR_SUCCESS)
            code = in->error;
    }

    xmlBufResetInput(in->buffer, input);

    return(code);
}

/**
 * Use encoding handler to decode input data.
 *
 * @deprecated Internal function, don't use.
 *
 * @param ctxt  the parser context, only for error reporting
 * @param input  the input stream
 * @param handler  the encoding handler
 * @returns 0 in case of success, -1 otherwise
 */
int
xmlSwitchInputEncoding(xmlParserCtxt *ctxt, xmlParserInput *input,
                       xmlCharEncodingHandler *handler) {
    xmlParserErrors code = xmlInputSetEncodingHandler(input, handler);

    if (code != XML_ERR_OK) {
        xmlCtxtErrIO(ctxt, code, NULL);
        return(-1);
    }

    return(0);
}

/**
 * Use encoding handler to decode input data.
 *
 * This function can be used to enforce the encoding of chunks passed
 * to #xmlParseChunk.
 *
 * @param ctxt  the parser context
 * @param handler  the encoding handler
 * @returns 0 in case of success, -1 otherwise
 */
int
xmlSwitchToEncoding(xmlParserCtxt *ctxt, xmlCharEncodingHandler *handler)
{
    xmlParserErrors code;

    if (ctxt == NULL)
        return(-1);

    code = xmlInputSetEncodingHandler(ctxt->input, handler);
    if (code != XML_ERR_OK) {
        xmlCtxtErrIO(ctxt, code, NULL);
        return(-1);
    }

    return(0);
}

/**
 * Handle optional BOM, detect and switch to encoding.
 *
 * Assumes that there are at least four bytes in the input buffer.
 *
 * @param ctxt  the parser context
 */
void
xmlDetectEncoding(xmlParserCtxt *ctxt) {
    const xmlChar *in;
    xmlCharEncoding enc;
    int bomSize;
    int autoFlag = 0;

    if (xmlParserGrow(ctxt) < 0)
        return;
    in = ctxt->input->cur;
    if (ctxt->input->end - in < 4)
        return;

    if (ctxt->input->flags & XML_INPUT_HAS_ENCODING) {
        /*
         * If the encoding was already set, only skip the BOM which was
         * possibly decoded to UTF-8.
         */
        if ((in[0] == 0xEF) && (in[1] == 0xBB) && (in[2] == 0xBF)) {
            ctxt->input->cur += 3;
        }

        return;
    }

    enc = XML_CHAR_ENCODING_NONE;
    bomSize = 0;

    /*
     * BOM sniffing and detection of initial bytes of an XML
     * declaration.
     *
     * The HTML5 spec doesn't cover UTF-32 (UCS-4) or EBCDIC.
     */
    switch (in[0]) {
        case 0x00:
            if ((!ctxt->html) &&
                (in[1] == 0x00) && (in[2] == 0x00) && (in[3] == 0x3C)) {
                enc = XML_CHAR_ENCODING_UCS4BE;
                autoFlag = XML_INPUT_AUTO_OTHER;
            } else if ((in[1] == 0x3C) && (in[2] == 0x00) && (in[3] == 0x3F)) {
                /*
                 * TODO: The HTML5 spec requires to check that the
                 * next codepoint is an 'x'.
                 */
                enc = XML_CHAR_ENCODING_UTF16BE;
                autoFlag = XML_INPUT_AUTO_UTF16BE;
            }
            break;

        case 0x3C:
            if (in[1] == 0x00) {
                if ((!ctxt->html) &&
                    (in[2] == 0x00) && (in[3] == 0x00)) {
                    enc = XML_CHAR_ENCODING_UCS4LE;
                    autoFlag = XML_INPUT_AUTO_OTHER;
                } else if ((in[2] == 0x3F) && (in[3] == 0x00)) {
                    /*
                     * TODO: The HTML5 spec requires to check that the
                     * next codepoint is an 'x'.
                     */
                    enc = XML_CHAR_ENCODING_UTF16LE;
                    autoFlag = XML_INPUT_AUTO_UTF16LE;
                }
            }
            break;

        case 0x4C:
	    if ((!ctxt->html) &&
                (in[1] == 0x6F) && (in[2] == 0xA7) && (in[3] == 0x94)) {
	        enc = XML_CHAR_ENCODING_EBCDIC;
                autoFlag = XML_INPUT_AUTO_OTHER;
            }
            break;

        case 0xEF:
            if ((in[1] == 0xBB) && (in[2] == 0xBF)) {
                enc = XML_CHAR_ENCODING_UTF8;
                autoFlag = XML_INPUT_AUTO_UTF8;
                bomSize = 3;
            }
            break;

        case 0xFE:
            if (in[1] == 0xFF) {
                enc = XML_CHAR_ENCODING_UTF16BE;
                autoFlag = XML_INPUT_AUTO_UTF16BE;
                bomSize = 2;
            }
            break;

        case 0xFF:
            if (in[1] == 0xFE) {
                enc = XML_CHAR_ENCODING_UTF16LE;
                autoFlag = XML_INPUT_AUTO_UTF16LE;
                bomSize = 2;
            }
            break;
    }

    if (bomSize > 0) {
        ctxt->input->cur += bomSize;
    }

    if (enc != XML_CHAR_ENCODING_NONE) {
        ctxt->input->flags |= autoFlag;

        if (enc == XML_CHAR_ENCODING_EBCDIC) {
            xmlCharEncodingHandlerPtr handler;
            xmlParserErrors res;

            res = xmlDetectEBCDIC(ctxt, &handler);
            if (res != XML_ERR_OK) {
                xmlFatalErr(ctxt, res, "detecting EBCDIC\n");
            } else {
                xmlSwitchToEncoding(ctxt, handler);
            }
        } else {
            xmlSwitchEncoding(ctxt, enc);
        }
    }
}

/**
 * Set the encoding from a declaration in the document.
 *
 * If no encoding was set yet, switch the encoding. Otherwise, only warn
 * about encoding mismatches.
 *
 * Takes ownership of 'encoding'.
 *
 * @param ctxt  the parser context
 * @param encoding  declared encoding
 */
void
xmlSetDeclaredEncoding(xmlParserCtxt *ctxt, xmlChar *encoding) {
    if (((ctxt->input->flags & XML_INPUT_HAS_ENCODING) == 0) &&
        ((ctxt->options & XML_PARSE_IGNORE_ENC) == 0)) {
        xmlCharEncodingHandlerPtr handler;
        xmlParserErrors res;
        xmlCharEncFlags flags = XML_ENC_INPUT;

        /*
         * xmlSwitchEncodingName treats unsupported encodings as
         * warnings, but we want it to be an error in an encoding
         * declaration.
         */
        if (ctxt->html)
            flags |= XML_ENC_HTML;
        res = xmlCreateCharEncodingHandler((const char *) encoding,
                flags, ctxt->convImpl, ctxt->convCtxt, &handler);
        if (res != XML_ERR_OK) {
            xmlFatalErr(ctxt, res, (const char *) encoding);
            xmlFree(encoding);
            return;
        }

        res  = xmlInputSetEncodingHandler(ctxt->input, handler);
        if (res != XML_ERR_OK) {
            xmlCtxtErrIO(ctxt, res, NULL);
            xmlFree(encoding);
            return;
        }

        ctxt->input->flags |= XML_INPUT_USES_ENC_DECL;
    } else if (ctxt->input->flags & XML_INPUT_AUTO_ENCODING) {
        static const char *allowedUTF8[] = {
            "UTF-8", "UTF8", NULL
        };
        static const char *allowedUTF16LE[] = {
            "UTF-16", "UTF-16LE", "UTF16", NULL
        };
        static const char *allowedUTF16BE[] = {
            "UTF-16", "UTF-16BE", "UTF16", NULL
        };
        const char **allowed = NULL;
        const char *autoEnc = NULL;

        switch (ctxt->input->flags & XML_INPUT_AUTO_ENCODING) {
            case XML_INPUT_AUTO_UTF8:
                allowed = allowedUTF8;
                autoEnc = "UTF-8";
                break;
            case XML_INPUT_AUTO_UTF16LE:
                allowed = allowedUTF16LE;
                autoEnc = "UTF-16LE";
                break;
            case XML_INPUT_AUTO_UTF16BE:
                allowed = allowedUTF16BE;
                autoEnc = "UTF-16BE";
                break;
        }

        if (allowed != NULL) {
            const char **p;
            int match = 0;

            for (p = allowed; *p != NULL; p++) {
                if (xmlStrcasecmp(encoding, BAD_CAST *p) == 0) {
                    match = 1;
                    break;
                }
            }

            if (match == 0) {
                xmlWarningMsg(ctxt, XML_WAR_ENCODING_MISMATCH,
                              "Encoding '%s' doesn't match "
                              "auto-detected '%s'\n",
                              encoding, BAD_CAST autoEnc);
                xmlFree(encoding);
                encoding = xmlStrdup(BAD_CAST autoEnc);
                if (encoding == NULL)
                    xmlCtxtErrMemory(ctxt);
            }
        }
    }

    if (ctxt->encoding != NULL)
        xmlFree(ctxt->encoding);
    ctxt->encoding = encoding;
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the encoding from the encoding declaration. This can differ
 * from the actual encoding.
 */
const xmlChar *
xmlCtxtGetDeclaredEncoding(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(ctxt->encoding);
}

/**
 * @param ctxt  the parser context
 * @returns the actual used to parse the document. This can differ from
 * the declared encoding.
 */
const xmlChar *
xmlGetActualEncoding(xmlParserCtxt *ctxt) {
    const xmlChar *encoding = NULL;

    if ((ctxt->input->flags & XML_INPUT_USES_ENC_DECL) ||
        (ctxt->input->flags & XML_INPUT_AUTO_ENCODING)) {
        /* Preserve encoding exactly */
        encoding = ctxt->encoding;
    } else if ((ctxt->input->buf) && (ctxt->input->buf->encoder)) {
        encoding = BAD_CAST ctxt->input->buf->encoder->name;
    } else if (ctxt->input->flags & XML_INPUT_HAS_ENCODING) {
        encoding = BAD_CAST "UTF-8";
    }

    return(encoding);
}

/************************************************************************
 *									*
 *	Commodity functions to handle entities processing		*
 *									*
 ************************************************************************/

/**
 * Free up an input stream.
 *
 * @param input  an xmlParserInput
 */
void
xmlFreeInputStream(xmlParserInput *input) {
    if (input == NULL) return;

    if (input->filename != NULL) xmlFree((char *) input->filename);
    if (input->version != NULL) xmlFree((char *) input->version);
    if ((input->free != NULL) && (input->base != NULL))
        input->free((xmlChar *) input->base);
    if (input->buf != NULL)
        xmlFreeParserInputBuffer(input->buf);
    xmlFree(input);
}

/**
 * Create a new input stream structure.
 *
 * @deprecated Use #xmlNewInputFromUrl or similar functions.
 *
 * @param ctxt  an XML parser context
 * @returns the new input stream or NULL
 */
xmlParserInput *
xmlNewInputStream(xmlParserCtxt *ctxt) {
    xmlParserInputPtr input;

    input = (xmlParserInputPtr) xmlMalloc(sizeof(xmlParserInput));
    if (input == NULL) {
        xmlCtxtErrMemory(ctxt);
	return(NULL);
    }
    memset(input, 0, sizeof(xmlParserInput));
    input->line = 1;
    input->col = 1;

    return(input);
}

/**
 * Creates a new parser input from the filesystem, the network or
 * a user-defined resource loader.
 *
 * @param ctxt  parser context
 * @param url  filename or URL
 * @param publicId  publid ID from doctype (optional)
 * @param encoding  character encoding (optional)
 * @param flags  unused, pass 0
 * @returns a new parser input.
 */
xmlParserInput *
xmlCtxtNewInputFromUrl(xmlParserCtxt *ctxt, const char *url,
                       const char *publicId, const char *encoding,
                       xmlParserInputFlags flags ATTRIBUTE_UNUSED) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (url == NULL))
	return(NULL);

    input = xmlLoadResource(ctxt, url, publicId, XML_RESOURCE_MAIN_DOCUMENT);
    if (input == NULL)
        return(NULL);

    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Internal helper function.
 *
 * @param buf  parser input buffer
 * @param filename  filename or URL
 * @returns a new parser input.
 */
static xmlParserInputPtr
xmlNewInputInternal(xmlParserInputBufferPtr buf, const char *filename) {
    xmlParserInputPtr input;

    input = (xmlParserInputPtr) xmlMalloc(sizeof(xmlParserInput));
    if (input == NULL) {
	xmlFreeParserInputBuffer(buf);
	return(NULL);
    }
    memset(input, 0, sizeof(xmlParserInput));
    input->line = 1;
    input->col = 1;

    input->buf = buf;
    xmlBufResetInput(input->buf->buffer, input);

    if (filename != NULL) {
        input->filename = xmlMemStrdup(filename);
        if (input->filename == NULL) {
            xmlFreeInputStream(input);
            return(NULL);
        }
    }

    return(input);
}

/**
 * Creates a new parser input to read from a memory area.
 *
 * `url` is used as base to resolve external entities and for
 * error reporting.
 *
 * If the XML_INPUT_BUF_STATIC flag is set, the memory area must
 * stay unchanged until parsing has finished. This can avoid
 * temporary copies.
 *
 * If the XML_INPUT_BUF_ZERO_TERMINATED flag is set, the memory
 * area must contain a zero byte after the buffer at position `size`.
 * This can avoid temporary copies.
 *
 * @since 2.14.0
 *
 * @param url  base URL (optional)
 * @param mem  pointer to char array
 * @param size  size of array
 * @param flags  optimization hints
 * @returns a new parser input or NULL if a memory allocation failed.
 */
xmlParserInput *
xmlNewInputFromMemory(const char *url, const void *mem, size_t size,
                      xmlParserInputFlags flags) {
    xmlParserInputBufferPtr buf;

    if (mem == NULL)
	return(NULL);

    buf = xmlNewInputBufferMemory(mem, size, flags, XML_CHAR_ENCODING_NONE);
    if (buf == NULL)
        return(NULL);

    return(xmlNewInputInternal(buf, url));
}

/**
 * @param ctxt  parser context
 * @param url  base URL (optional)
 * @param mem  pointer to char array
 * @param size  size of array
 * @param encoding  character encoding (optional)
 * @param flags  optimization hints
 * @returns a new parser input or NULL in case of error.
 */
xmlParserInput *
xmlCtxtNewInputFromMemory(xmlParserCtxt *ctxt, const char *url,
                          const void *mem, size_t size,
                          const char *encoding, xmlParserInputFlags flags) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (mem == NULL))
	return(NULL);

    input = xmlNewInputFromMemory(url, mem, size, flags);
    if (input == NULL) {
        xmlCtxtErrMemory(ctxt);
        return(NULL);
    }

    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Creates a new parser input to read from a zero-terminated string.
 *
 * `url` is used as base to resolve external entities and for
 * error reporting.
 *
 * If the XML_INPUT_BUF_STATIC flag is set, the string must
 * stay unchanged until parsing has finished. This can avoid
 * temporary copies.
 *
 * @since 2.14.0
 *
 * @param url  base URL (optional)
 * @param str  zero-terminated string
 * @param flags  optimization hints
 * @returns a new parser input or NULL if a memory allocation failed.
 */
xmlParserInput *
xmlNewInputFromString(const char *url, const char *str,
                      xmlParserInputFlags flags) {
    xmlParserInputBufferPtr buf;

    if (str == NULL)
	return(NULL);

    buf = xmlNewInputBufferString(str, flags);
    if (buf == NULL)
        return(NULL);

    return(xmlNewInputInternal(buf, url));
}

/**
 * @param ctxt  parser context
 * @param url  base URL (optional)
 * @param str  zero-terminated string
 * @param encoding  character encoding (optional)
 * @param flags  optimization hints
 * @returns a new parser input.
 */
xmlParserInput *
xmlCtxtNewInputFromString(xmlParserCtxt *ctxt, const char *url,
                          const char *str, const char *encoding,
                          xmlParserInputFlags flags) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (str == NULL))
	return(NULL);

    input = xmlNewInputFromString(url, str, flags);
    if (input == NULL) {
        xmlCtxtErrMemory(ctxt);
        return(NULL);
    }

    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Creates a new parser input to read from a file descriptor.
 *
 * `url` is used as base to resolve external entities and for
 * error reporting.
 *
 * `fd` is closed after parsing has finished.
 *
 * Supported `flags` are XML_INPUT_UNZIP to decompress data
 * automatically. This feature is deprecated and will be removed
 * in a future release.
 *
 * @since 2.14.0
 *
 * @param url  base URL (optional)
 * @param fd  file descriptor
 * @param flags  input flags
 * @returns a new parser input or NULL if a memory allocation failed.
 */
xmlParserInput *
xmlNewInputFromFd(const char *url, int fd, xmlParserInputFlags flags) {
    xmlParserInputBufferPtr buf;

    if (fd < 0)
	return(NULL);

    buf = xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE);
    if (buf == NULL)
        return(NULL);

    if (xmlInputFromFd(buf, fd, flags) != XML_ERR_OK) {
        xmlFreeParserInputBuffer(buf);
        return(NULL);
    }

    return(xmlNewInputInternal(buf, url));
}

/**
 * @param ctxt  parser context
 * @param url  base URL (optional)
 * @param fd  file descriptor
 * @param encoding  character encoding (optional)
 * @param flags  unused, pass 0
 * @returns a new parser input.
 */
xmlParserInput *
xmlCtxtNewInputFromFd(xmlParserCtxt *ctxt, const char *url,
                      int fd, const char *encoding,
                      xmlParserInputFlags flags) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (fd < 0))
	return(NULL);

    if (ctxt->options & XML_PARSE_UNZIP)
        flags |= XML_INPUT_UNZIP;

    input = xmlNewInputFromFd(url, fd, flags);
    if (input == NULL) {
	xmlCtxtErrMemory(ctxt);
        return(NULL);
    }

    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Creates a new parser input to read from input callbacks and
 * context.
 *
 * `url` is used as base to resolve external entities and for
 * error reporting.
 *
 * `ioRead` is called to read new data into a provided buffer.
 * It must return the number of bytes written into the buffer
 * ot a negative xmlParserErrors code on failure.
 *
 * `ioClose` is called after parsing has finished.
 *
 * `ioCtxt` is an opaque pointer passed to the callbacks.
 *
 * @since 2.14.0
 *
 * @param url  base URL (optional)
 * @param ioRead  read callback
 * @param ioClose  close callback (optional)
 * @param ioCtxt  IO context
 * @param flags  unused, pass 0
 * @returns a new parser input or NULL if a memory allocation failed.
 */
xmlParserInput *
xmlNewInputFromIO(const char *url, xmlInputReadCallback ioRead,
                  xmlInputCloseCallback ioClose, void *ioCtxt,
                  xmlParserInputFlags flags ATTRIBUTE_UNUSED) {
    xmlParserInputBufferPtr buf;

    if (ioRead == NULL)
	return(NULL);

    buf = xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE);
    if (buf == NULL) {
        if (ioClose != NULL)
            ioClose(ioCtxt);
        return(NULL);
    }

    buf->context = ioCtxt;
    buf->readcallback = ioRead;
    buf->closecallback = ioClose;

    return(xmlNewInputInternal(buf, url));
}

/**
 * @param ctxt  parser context
 * @param url  base URL (optional)
 * @param ioRead  read callback
 * @param ioClose  close callback (optional)
 * @param ioCtxt  IO context
 * @param encoding  character encoding (optional)
 * @param flags  unused, pass 0
 * @returns a new parser input.
 */
xmlParserInput *
xmlCtxtNewInputFromIO(xmlParserCtxt *ctxt, const char *url,
                      xmlInputReadCallback ioRead,
                      xmlInputCloseCallback ioClose,
                      void *ioCtxt, const char *encoding,
                      xmlParserInputFlags flags) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (ioRead == NULL))
	return(NULL);

    input = xmlNewInputFromIO(url, ioRead, ioClose, ioCtxt, flags);
    if (input == NULL) {
        xmlCtxtErrMemory(ctxt);
        return(NULL);
    }

    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Creates a new parser input for a push parser.
 *
 * @param url  base URL (optional)
 * @param chunk  pointer to char array
 * @param size  size of array
 * @returns a new parser input or NULL if a memory allocation failed.
 */
xmlParserInput *
xmlNewPushInput(const char *url, const char *chunk, int size) {
    xmlParserInputBufferPtr buf;
    xmlParserInputPtr input;

    buf = xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE);
    if (buf == NULL)
        return(NULL);

    input = xmlNewInputInternal(buf, url);
    if (input == NULL)
	return(NULL);

    input->flags |= XML_INPUT_PROGRESSIVE;

    if ((size > 0) && (chunk != NULL)) {
        int res;

	res = xmlParserInputBufferPush(input->buf, size, chunk);
        xmlBufResetInput(input->buf->buffer, input);
        if (res < 0) {
            xmlFreeInputStream(input);
            return(NULL);
        }
    }

    return(input);
}

/**
 * Create a new input stream structure encapsulating the `input` into
 * a stream suitable for the parser.
 *
 * @param ctxt  an XML parser context
 * @param buf  an input buffer
 * @param enc  the charset encoding if known
 * @returns the new input stream or NULL
 */
xmlParserInput *
xmlNewIOInputStream(xmlParserCtxt *ctxt, xmlParserInputBuffer *buf,
	            xmlCharEncoding enc) {
    xmlParserInputPtr input;
    const char *encoding;

    if ((ctxt == NULL) || (buf == NULL))
        return(NULL);

    input = xmlNewInputInternal(buf, NULL);
    if (input == NULL) {
        xmlCtxtErrMemory(ctxt);
	return(NULL);
    }

    encoding = xmlGetCharEncodingName(enc);
    if (encoding != NULL)
        xmlSwitchInputEncodingName(ctxt, input, encoding);

    return(input);
}

/**
 * Create a new input stream based on an xmlEntity
 *
 * @deprecated Internal function, do not use.
 *
 * @param ctxt  an XML parser context
 * @param ent  an Entity pointer
 * @returns the new input stream or NULL
 */
xmlParserInput *
xmlNewEntityInputStream(xmlParserCtxt *ctxt, xmlEntity *ent) {
    xmlParserInputPtr input;

    if ((ctxt == NULL) || (ent == NULL))
	return(NULL);

    if (ent->content != NULL) {
        input = xmlCtxtNewInputFromString(ctxt, NULL,
                (const char *) ent->content, NULL, XML_INPUT_BUF_STATIC);
    } else if (ent->URI != NULL) {
        xmlResourceType rtype;

        if (ent->etype == XML_EXTERNAL_PARAMETER_ENTITY)
            rtype = XML_RESOURCE_PARAMETER_ENTITY;
        else
            rtype = XML_RESOURCE_GENERAL_ENTITY;

        input = xmlLoadResource(ctxt, (char *) ent->URI,
                                (char *) ent->ExternalID, rtype);
    } else {
        return(NULL);
    }

    if (input == NULL)
        return(NULL);

    input->entity = ent;

    return(input);
}

/**
 * Create a new input stream based on a memory buffer.
 *
 * @deprecated Use #xmlNewInputFromString.
 *
 * @param ctxt  an XML parser context
 * @param buffer  an memory buffer
 * @returns the new input stream
 */
xmlParserInput *
xmlNewStringInputStream(xmlParserCtxt *ctxt, const xmlChar *buffer) {
    return(xmlCtxtNewInputFromString(ctxt, NULL, (const char *) buffer,
                                     NULL, 0));
}


/****************************************************************
 *								*
 *		External entities loading			*
 *								*
 ****************************************************************/

#ifdef LIBXML_CATALOG_ENABLED

/**
 * Resolves an external ID or URL against the appropriate catalog.
 *
 * @param url  the URL or system ID for the entity to load
 * @param publicId  the public ID for the entity to load (optional)
 * @param localCatalogs  local catalogs (optional)
 * @param allowGlobal  allow global system catalog
 * @param out  resulting resource or NULL
 * @returns an xmlParserErrors code
 */
static xmlParserErrors
xmlResolveFromCatalog(const char *url, const char *publicId,
                      void *localCatalogs, int allowGlobal, char **out) {
    xmlError oldError;
    xmlError *lastError;
    char *resource = NULL;
    xmlParserErrors code;

    if (out == NULL)
        return(XML_ERR_ARGUMENT);
    *out = NULL;
    if ((localCatalogs == NULL) && (!allowGlobal))
        return(XML_ERR_OK);

    /*
     * Don't try to resolve if local file exists.
     *
     * TODO: This is somewhat non-deterministic.
     */
    if (xmlNoNetExists(url))
        return(XML_ERR_OK);

    /* Backup and reset last error */
    lastError = xmlGetLastErrorInternal();
    oldError = *lastError;
    lastError->code = XML_ERR_OK;

    /*
     * Do a local lookup
     */
    if (localCatalogs != NULL) {
        resource = (char *) xmlCatalogLocalResolve(localCatalogs,
                                                   BAD_CAST publicId,
                                                   BAD_CAST url);
    }
    /*
     * Try a global lookup
     */
    if ((resource == NULL) && (allowGlobal)) {
        resource = (char *) xmlCatalogResolve(BAD_CAST publicId,
                                              BAD_CAST url);
    }

    /*
     * Try to resolve url using URI rules.
     *
     * TODO: We should consider using only a single resolution
     * mechanism depending on resource type. Either by external ID
     * or by URI.
     */
    if ((resource == NULL) && (url != NULL)) {
        if (localCatalogs != NULL) {
            resource = (char *) xmlCatalogLocalResolveURI(localCatalogs,
                                                          BAD_CAST url);
        }
        if ((resource == NULL) && (allowGlobal)) {
            resource = (char *) xmlCatalogResolveURI(BAD_CAST url);
        }
    }

    code = lastError->code;
    if (code == XML_ERR_OK) {
        *out = resource;
    } else {
        xmlFree(resource);
    }

    *lastError = oldError;

    return(code);
}

static char *
xmlCtxtResolveFromCatalog(xmlParserCtxtPtr ctxt, const char *url,
                          const char *publicId) {
    char *resource;
    void *localCatalogs = NULL;
    int allowGlobal = 1;
    xmlParserErrors code;

    if (ctxt != NULL) {
        /*
         * Loading of HTML documents shouldn't use XML catalogs.
         */
        if (ctxt->html)
            return(NULL);

        localCatalogs = ctxt->catalogs;

        if (ctxt->options & XML_PARSE_NO_SYS_CATALOG)
            allowGlobal = 0;
    }

    switch (xmlCatalogGetDefaults()) {
        case XML_CATA_ALLOW_NONE:
            return(NULL);
        case XML_CATA_ALLOW_DOCUMENT:
            allowGlobal = 0;
            break;
        case XML_CATA_ALLOW_GLOBAL:
            localCatalogs = NULL;
            break;
        case XML_CATA_ALLOW_ALL:
            break;
    }

    code = xmlResolveFromCatalog(url, publicId, localCatalogs,
                                 allowGlobal, &resource);
    if (code != XML_ERR_OK)
        xmlCtxtErr(ctxt, NULL, XML_FROM_CATALOG, code, XML_ERR_ERROR,
                   BAD_CAST url, BAD_CAST publicId, NULL, 0,
                   "%s\n", xmlErrString(code), NULL);

    return(resource);
}

#endif

/**
 * @deprecated Internal function, don't use.
 *
 * @param ctxt  an XML parser context
 * @param ret  an XML parser input
 * @returns NULL.
 */
xmlParserInput *
xmlCheckHTTPInput(xmlParserCtxt *ctxt ATTRIBUTE_UNUSED,
                  xmlParserInput *ret ATTRIBUTE_UNUSED) {
    return(NULL);
}

/**
 * Create a new input stream based on a file or a URL.
 *
 * The flag XML_INPUT_UNZIP allows decompression.
 *
 * The flag XML_INPUT_NETWORK allows network access.
 *
 * The following resource loaders will be called if they were
 * registered (in order of precedence):
 *
 * - the per-thread #xmlParserInputBufferCreateFilenameFunc set with
 *   #xmlParserInputBufferCreateFilenameDefault (deprecated)
 * - the default loader which will return
 *   - the result from a matching global input callback set with
 *     #xmlRegisterInputCallbacks (deprecated)
 *   - a file opened from the filesystem, with automatic detection
 *     of compressed files if support is compiled in.
 *
 * @since 2.14.0
 *
 * @param url  the filename to use as entity
 * @param flags  XML_INPUT flags
 * @param out  pointer to new parser input
 * @returns an xmlParserErrors code.
 */
xmlParserErrors
xmlNewInputFromUrl(const char *url, xmlParserInputFlags flags,
                   xmlParserInput **out) {
    char *resource = NULL;
    xmlParserInputBufferPtr buf;
    xmlParserInputPtr input;
    xmlParserErrors code = XML_ERR_OK;

    if (out == NULL)
        return(XML_ERR_ARGUMENT);
    *out = NULL;
    if (url == NULL)
        return(XML_ERR_ARGUMENT);

#ifdef LIBXML_CATALOG_ENABLED
    if (flags & XML_INPUT_USE_SYS_CATALOG) {
        code = xmlResolveFromCatalog(url, NULL, NULL, 1, &resource);
        if (code != XML_ERR_OK)
            return(code);
        if (resource != NULL)
            url = resource;
    }
#endif

    if (xmlParserInputBufferCreateFilenameValue != NULL) {
        buf = xmlParserInputBufferCreateFilenameValue(url,
                XML_CHAR_ENCODING_NONE);
        if (buf == NULL)
            code = XML_IO_ENOENT;
    } else {
        code = xmlParserInputBufferCreateUrl(url, XML_CHAR_ENCODING_NONE,
                                             flags, &buf);
    }

    if (code == XML_ERR_OK) {
        input = xmlNewInputInternal(buf, url);
        if (input == NULL)
            code = XML_ERR_NO_MEMORY;

        *out = input;
    }

    if (resource != NULL)
        xmlFree(resource);
    return(code);
}

/**
 * Create a new input stream based on a file or an URL.
 *
 * Unlike the default external entity loader, this function
 * doesn't use XML catalogs.
 *
 * @deprecated Use #xmlNewInputFromUrl.
 *
 * @param ctxt  an XML parser context
 * @param filename  the filename to use as entity
 * @returns the new input stream or NULL in case of error
 */
xmlParserInput *
xmlNewInputFromFile(xmlParserCtxt *ctxt, const char *filename) {
    xmlParserInputPtr input;
    xmlParserInputFlags flags = 0;
    xmlParserErrors code;

    if ((ctxt == NULL) || (filename == NULL))
        return(NULL);

    if (ctxt->options & XML_PARSE_UNZIP)
        flags |= XML_INPUT_UNZIP;
    if ((ctxt->options & XML_PARSE_NONET) == 0)
        flags |= XML_INPUT_NETWORK;

    code = xmlNewInputFromUrl(filename, flags, &input);
    if (code != XML_ERR_OK) {
        xmlCtxtErrIO(ctxt, code, filename);
        return(NULL);
    }

    return(input);
}

/**
 * By default we don't load external entities, yet.
 *
 * @param url  the URL or system ID for the entity to load
 * @param publicId  the public ID for the entity to load (optional)
 * @param ctxt  the context in which the entity is called or NULL
 * @returns a new allocated xmlParserInput, or NULL.
 */
static xmlParserInputPtr
xmlDefaultExternalEntityLoader(const char *url, const char *publicId,
                               xmlParserCtxtPtr ctxt)
{
    xmlParserInputPtr input = NULL;
    char *resource = NULL;

    (void) publicId;

    if (url == NULL)
        return(NULL);

#ifdef LIBXML_CATALOG_ENABLED
    resource = xmlCtxtResolveFromCatalog(ctxt, url, publicId);
    if (resource != NULL)
	url = resource;
#endif

    /*
     * Several downstream test suites expect this error whenever
     * an http URI is passed and NONET is set.
     */
    if ((ctxt != NULL) &&
        (ctxt->options & XML_PARSE_NONET) &&
        (xmlStrncasecmp(BAD_CAST url, BAD_CAST "http://", 7) == 0)) {
        xmlCtxtErrIO(ctxt, XML_IO_NETWORK_ATTEMPT, url);
    } else {
        input = xmlNewInputFromFile(ctxt, url);
    }

    if (resource != NULL)
	xmlFree(resource);
    return(input);
}

/**
 * A specific entity loader disabling network accesses, though still
 * allowing local catalog accesses for resolution.
 *
 * @deprecated Use XML_PARSE_NONET.
 *
 * @param URL  the URL or system ID for the entity to load
 * @param publicId  the public ID for the entity to load
 * @param ctxt  the context in which the entity is called or NULL
 * @returns a new allocated xmlParserInput, or NULL.
 */
xmlParserInput *
xmlNoNetExternalEntityLoader(const char *URL, const char *publicId,
                             xmlParserCtxt *ctxt) {
    int oldOptions = 0;
    xmlParserInputPtr input;

    if (ctxt != NULL) {
        oldOptions = ctxt->options;
        ctxt->options |= XML_PARSE_NONET;
    }

    input = xmlDefaultExternalEntityLoader(URL, publicId, ctxt);

    if (ctxt != NULL)
        ctxt->options = oldOptions;

    return(input);
}

/*
 * This global has to die eventually
 */
static xmlExternalEntityLoader
xmlCurrentExternalEntityLoader = xmlDefaultExternalEntityLoader;

/**
 * Changes the default external entity resolver function for the
 * application.
 *
 * @deprecated This is a global setting and not thread-safe. Use
 * #xmlCtxtSetResourceLoader or similar functions.
 *
 * @param f  the new entity resolver function
 */
void
xmlSetExternalEntityLoader(xmlExternalEntityLoader f) {
    xmlCurrentExternalEntityLoader = f;
}

/**
 * Get the default external entity resolver function for the application
 *
 * @deprecated See #xmlSetExternalEntityLoader.
 *
 * @returns the #xmlExternalEntityLoader function pointer
 */
xmlExternalEntityLoader
xmlGetExternalEntityLoader(void) {
    return(xmlCurrentExternalEntityLoader);
}

/**
 * Installs a custom callback to load documents, DTDs or external
 * entities.
 *
 * If `vctxt` is NULL, the parser context will be passed.
 *
 * @since 2.14.0
 * @param ctxt  parser context
 * @param loader  callback
 * @param vctxt  user data (optional)
 */
void
xmlCtxtSetResourceLoader(xmlParserCtxt *ctxt, xmlResourceLoader loader,
                         void *vctxt) {
    if (ctxt == NULL)
        return;

    ctxt->resourceLoader = loader;
    ctxt->resourceCtxt = vctxt;
}

/**
 * @param ctxt  parser context
 * @param url  the URL or system ID for the entity to load
 * @param publicId  the public ID for the entity to load (optional)
 * @param type  resource type
 * @returns the xmlParserInput or NULL in case of error.
 */
xmlParserInput *
xmlLoadResource(xmlParserCtxt *ctxt, const char *url, const char *publicId,
                xmlResourceType type) {
    char *canonicFilename;
    xmlParserInputPtr ret;

    if (url == NULL)
        return(NULL);

    if ((ctxt != NULL) && (ctxt->resourceLoader != NULL)) {
        char *resource = NULL;
        void *userData;
        xmlParserInputFlags flags = 0;
        int code;

#ifdef LIBXML_CATALOG_ENABLED
        resource = xmlCtxtResolveFromCatalog(ctxt, url, publicId);
        if (resource != NULL)
            url = resource;
#endif

        if (ctxt->options & XML_PARSE_UNZIP)
            flags |= XML_INPUT_UNZIP;
        if ((ctxt->options & XML_PARSE_NONET) == 0)
            flags |= XML_INPUT_NETWORK;

        userData = ctxt->resourceCtxt;
        if (userData == NULL)
            userData = ctxt;

        code = ctxt->resourceLoader(userData, url, publicId, type,
                                    flags, &ret);
        if (code != XML_ERR_OK) {
            xmlCtxtErrIO(ctxt, code, url);
            ret = NULL;
        }
        if (resource != NULL)
            xmlFree(resource);
        return(ret);
    }

    canonicFilename = (char *) xmlCanonicPath((const xmlChar *) url);
    if (canonicFilename == NULL) {
        xmlCtxtErrMemory(ctxt);
        return(NULL);
    }

    ret = xmlCurrentExternalEntityLoader(canonicFilename, publicId, ctxt);
    xmlFree(canonicFilename);
    return(ret);
}

/**
 * `URL` is a filename or URL. If if contains the substring "://",
 * it is assumed to be a Legacy Extended IRI. Otherwise, it is
 * treated as a filesystem path.
 *
 * `publicId` is an optional XML public ID, typically from a doctype
 * declaration. It is used for catalog lookups.
 *
 * If catalog lookup is enabled (default is yes) and URL or ID are
 * found in system or local XML catalogs, URL is replaced with the
 * result. Then the following resource loaders will be called if
 * they were registered (in order of precedence):
 *
 * - the resource loader set with #xmlCtxtSetResourceLoader
 * - the global external entity loader set with
 *   #xmlSetExternalEntityLoader (without catalog resolution,
 *   deprecated)
 * - the per-thread #xmlParserInputBufferCreateFilenameFunc set with
 *   #xmlParserInputBufferCreateFilenameDefault (deprecated)
 * - the default loader which will return
 *   - the result from a matching global input callback set with
 *     #xmlRegisterInputCallbacks (deprecated)
 *   - a file opened from the filesystem, with automatic detection
 *     of compressed files if support is compiled in.
 *
 * @param URL  the URL or system ID for the entity to load
 * @param publicId  the public ID for the entity to load (optional)
 * @param ctxt  the context in which the entity is called or NULL
 * @returns the xmlParserInput or NULL
 */
xmlParserInput *
xmlLoadExternalEntity(const char *URL, const char *publicId,
                      xmlParserCtxt *ctxt) {
    return(xmlLoadResource(ctxt, URL, publicId, XML_RESOURCE_UNKNOWN));
}

/************************************************************************
 *									*
 *		Commodity functions to handle parser contexts		*
 *									*
 ************************************************************************/

/**
 * Initialize a SAX parser context
 *
 * @param ctxt  XML parser context
 * @param sax  SAX handlert
 * @param userData  user data
 * @returns 0 in case of success and -1 in case of error
 */

static int
xmlInitSAXParserCtxt(xmlParserCtxtPtr ctxt, const xmlSAXHandler *sax,
                     void *userData)
{
    xmlParserInputPtr input;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    size_t initialNodeTabSize = 1;
#else
    size_t initialNodeTabSize = 10;
#endif

    if (ctxt == NULL)
        return(-1);

    if (ctxt->dict == NULL)
	ctxt->dict = xmlDictCreate();
    if (ctxt->dict == NULL)
	return(-1);

    if (ctxt->sax == NULL)
	ctxt->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));
    if (ctxt->sax == NULL)
	return(-1);
    if (sax == NULL) {
	memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
        xmlSAXVersion(ctxt->sax, 2);
        ctxt->userData = ctxt;
    } else {
	if (sax->initialized == XML_SAX2_MAGIC) {
	    memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler));
        } else {
	    memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
	    memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
        }
        ctxt->userData = userData ? userData : ctxt;
    }

    ctxt->maxatts = 0;
    ctxt->atts = NULL;
    /* Allocate the Input stack */
    if (ctxt->inputTab == NULL) {
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
        size_t initialSize = 1;
#else
        size_t initialSize = 5;
#endif

	ctxt->inputTab = xmlMalloc(initialSize * sizeof(xmlParserInputPtr));
	ctxt->inputMax = initialSize;
    }
    if (ctxt->inputTab == NULL)
	return(-1);
    while ((input = xmlCtxtPopInput(ctxt)) != NULL) { /* Non consuming */
        xmlFreeInputStream(input);
    }
    ctxt->inputNr = 0;
    ctxt->input = NULL;

    ctxt->version = NULL;
    ctxt->encoding = NULL;
    ctxt->standalone = -1;
    ctxt->hasExternalSubset = 0;
    ctxt->hasPErefs = 0;
    ctxt->html = 0;
    ctxt->instate = XML_PARSER_START;

    /* Allocate the Node stack */
    if (ctxt->nodeTab == NULL) {
	ctxt->nodeTab = xmlMalloc(initialNodeTabSize * sizeof(xmlNodePtr));
	ctxt->nodeMax = initialNodeTabSize;
    }
    if (ctxt->nodeTab == NULL)
	return(-1);
    ctxt->nodeNr = 0;
    ctxt->node = NULL;

    /* Allocate the Name stack */
    if (ctxt->nameTab == NULL) {
	ctxt->nameTab = xmlMalloc(initialNodeTabSize * sizeof(xmlChar *));
	ctxt->nameMax = initialNodeTabSize;
    }
    if (ctxt->nameTab == NULL)
	return(-1);
    ctxt->nameNr = 0;
    ctxt->name = NULL;

    /* Allocate the space stack */
    if (ctxt->spaceTab == NULL) {
	ctxt->spaceTab = xmlMalloc(initialNodeTabSize * sizeof(int));
	ctxt->spaceMax = initialNodeTabSize;
    }
    if (ctxt->spaceTab == NULL)
	return(-1);
    ctxt->spaceNr = 1;
    ctxt->spaceTab[0] = -1;
    ctxt->space = &ctxt->spaceTab[0];
    ctxt->myDoc = NULL;
    ctxt->wellFormed = 1;
    ctxt->nsWellFormed = 1;
    ctxt->valid = 1;

    ctxt->options = XML_PARSE_NODICT;

    /*
     * Initialize some parser options from deprecated global variables.
     * Note that the "modern" API taking options arguments or
     * xmlCtxtSetOptions will ignore these defaults. They're only
     * relevant if old API functions like xmlParseFile are used.
     */
    ctxt->loadsubset = xmlLoadExtDtdDefaultValue;
    if (ctxt->loadsubset) {
        ctxt->options |= XML_PARSE_DTDLOAD;
    }
    ctxt->validate = xmlDoValidityCheckingDefaultValue;
    if (ctxt->validate) {
        ctxt->options |= XML_PARSE_DTDVALID;
    }
    ctxt->pedantic = xmlPedanticParserDefaultValue;
    if (ctxt->pedantic) {
        ctxt->options |= XML_PARSE_PEDANTIC;
    }
    ctxt->keepBlanks = xmlKeepBlanksDefaultValue;
    if (ctxt->keepBlanks == 0) {
	ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
	ctxt->options |= XML_PARSE_NOBLANKS;
    }
    ctxt->replaceEntities = xmlSubstituteEntitiesDefaultValue;
    if (ctxt->replaceEntities) {
        ctxt->options |= XML_PARSE_NOENT;
    }
    if (xmlGetWarningsDefaultValue == 0)
        ctxt->options |= XML_PARSE_NOWARNING;

    ctxt->vctxt.flags = XML_VCTXT_USE_PCTXT;
    ctxt->vctxt.userData = ctxt;
    ctxt->vctxt.error = xmlParserValidityError;
    ctxt->vctxt.warning = xmlParserValidityWarning;

    ctxt->record_info = 0;
    ctxt->checkIndex = 0;
    ctxt->inSubset = 0;
    ctxt->errNo = XML_ERR_OK;
    ctxt->depth = 0;
    ctxt->catalogs = NULL;
    ctxt->sizeentities = 0;
    ctxt->sizeentcopy = 0;
    ctxt->input_id = 1;
    ctxt->maxAmpl = XML_MAX_AMPLIFICATION_DEFAULT;
    xmlInitNodeInfoSeq(&ctxt->node_seq);

    if (ctxt->nsdb == NULL) {
        ctxt->nsdb = xmlParserNsCreate();
        if (ctxt->nsdb == NULL)
            return(-1);
    }

    return(0);
}

/**
 * Initialize a parser context
 *
 * @deprecated Internal function which will be made private in a future
 * version.
 *
 * @param ctxt  an XML parser context
 * @returns 0 in case of success and -1 in case of error
 */

int
xmlInitParserCtxt(xmlParserCtxt *ctxt)
{
    return(xmlInitSAXParserCtxt(ctxt, NULL, NULL));
}

/**
 * Free all the memory used by a parser context. However the parsed
 * document in ctxt->myDoc is not freed.
 *
 * @param ctxt  an XML parser context
 */

void
xmlFreeParserCtxt(xmlParserCtxt *ctxt)
{
    xmlParserInputPtr input;

    if (ctxt == NULL) return;

    while ((input = xmlCtxtPopInput(ctxt)) != NULL) { /* Non consuming */
        xmlFreeInputStream(input);
    }
    if (ctxt->spaceTab != NULL) xmlFree(ctxt->spaceTab);
    if (ctxt->nameTab != NULL) xmlFree((xmlChar * *)ctxt->nameTab);
    if (ctxt->nodeTab != NULL) xmlFree(ctxt->nodeTab);
    if (ctxt->nodeInfoTab != NULL) xmlFree(ctxt->nodeInfoTab);
    if (ctxt->inputTab != NULL) xmlFree(ctxt->inputTab);
    if (ctxt->version != NULL) xmlFree(ctxt->version);
    if (ctxt->encoding != NULL) xmlFree(ctxt->encoding);
    if (ctxt->extSubURI != NULL) xmlFree(ctxt->extSubURI);
    if (ctxt->extSubSystem != NULL) xmlFree(ctxt->extSubSystem);
#ifdef LIBXML_SAX1_ENABLED
    if ((ctxt->sax != NULL) &&
        (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler))
#else
    if (ctxt->sax != NULL)
#endif /* LIBXML_SAX1_ENABLED */
        xmlFree(ctxt->sax);
    if (ctxt->directory != NULL) xmlFree(ctxt->directory);
    if (ctxt->vctxt.nodeTab != NULL) xmlFree(ctxt->vctxt.nodeTab);
    if (ctxt->atts != NULL) xmlFree((xmlChar * *)ctxt->atts);
    if (ctxt->dict != NULL) xmlDictFree(ctxt->dict);
    if (ctxt->nsTab != NULL) xmlFree(ctxt->nsTab);
    if (ctxt->nsdb != NULL) xmlParserNsFree(ctxt->nsdb);
    if (ctxt->attrHash != NULL) xmlFree(ctxt->attrHash);
    if (ctxt->pushTab != NULL) xmlFree(ctxt->pushTab);
    if (ctxt->attallocs != NULL) xmlFree(ctxt->attallocs);
    if (ctxt->attsDefault != NULL)
        xmlHashFree(ctxt->attsDefault, xmlHashDefaultDeallocator);
    if (ctxt->attsSpecial != NULL)
        xmlHashFree(ctxt->attsSpecial, NULL);
    if (ctxt->freeElems != NULL) {
        xmlNodePtr cur, next;

	cur = ctxt->freeElems;
	while (cur != NULL) {
	    next = cur->next;
	    xmlFree(cur);
	    cur = next;
	}
    }
    if (ctxt->freeAttrs != NULL) {
        xmlAttrPtr cur, next;

	cur = ctxt->freeAttrs;
	while (cur != NULL) {
	    next = cur->next;
	    xmlFree(cur);
	    cur = next;
	}
    }
    /*
     * cleanup the error strings
     */
    if (ctxt->lastError.message != NULL)
        xmlFree(ctxt->lastError.message);
    if (ctxt->lastError.file != NULL)
        xmlFree(ctxt->lastError.file);
    if (ctxt->lastError.str1 != NULL)
        xmlFree(ctxt->lastError.str1);
    if (ctxt->lastError.str2 != NULL)
        xmlFree(ctxt->lastError.str2);
    if (ctxt->lastError.str3 != NULL)
        xmlFree(ctxt->lastError.str3);

#ifdef LIBXML_CATALOG_ENABLED
    if (ctxt->catalogs != NULL)
	xmlCatalogFreeLocal(ctxt->catalogs);
#endif
    xmlFree(ctxt);
}

/**
 * Allocate and initialize a new parser context.
 *
 * @returns the xmlParserCtxt or NULL
 */

xmlParserCtxt *
xmlNewParserCtxt(void)
{
    return(xmlNewSAXParserCtxt(NULL, NULL));
}

/**
 * Allocate and initialize a new SAX parser context. If userData is NULL,
 * the parser context will be passed as user data.
 *
 * @since 2.11.0
 *
 * If you want support older versions,
 * it's best to invoke #xmlNewParserCtxt and set ctxt->sax with
 * struct assignment.
 *
 * @param sax  SAX handler
 * @param userData  user data
 * @returns the xmlParserCtxt or NULL if memory allocation failed.
 */

xmlParserCtxt *
xmlNewSAXParserCtxt(const xmlSAXHandler *sax, void *userData)
{
    xmlParserCtxtPtr ctxt;

    xmlInitParser();

    ctxt = (xmlParserCtxtPtr) xmlMalloc(sizeof(xmlParserCtxt));
    if (ctxt == NULL)
	return(NULL);
    memset(ctxt, 0, sizeof(xmlParserCtxt));
    if (xmlInitSAXParserCtxt(ctxt, sax, userData) < 0) {
        xmlFreeParserCtxt(ctxt);
	return(NULL);
    }
    return(ctxt);
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the private application data.
 */
void *
xmlCtxtGetPrivate(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(ctxt->_private);
}

/**
 * Set the private application data.
 *
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @param priv  private application data
 */
void
xmlCtxtSetPrivate(xmlParserCtxt *ctxt, void *priv) {
    if (ctxt == NULL)
        return;

    ctxt->_private = priv;
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the local catalogs.
 */
void *
xmlCtxtGetCatalogs(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(ctxt->catalogs);
}

/**
 * Set the local catalogs.
 *
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @param catalogs  catalogs pointer
 */
void
xmlCtxtSetCatalogs(xmlParserCtxt *ctxt, void *catalogs) {
    if (ctxt == NULL)
        return;

    ctxt->catalogs = catalogs;
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the dictionary.
 */
xmlDict *
xmlCtxtGetDict(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(ctxt->dict);
}

/**
 * Set the dictionary. This should only be done immediately after
 * creating a parser context.
 *
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @param dict  dictionary
 */
void
xmlCtxtSetDict(xmlParserCtxt *ctxt, xmlDict *dict) {
    if (ctxt == NULL)
        return;

    if (ctxt->dict != NULL)
        xmlDictFree(ctxt->dict);

    xmlDictReference(dict);
    ctxt->dict = dict;
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the SAX handler struct. This is not a copy and must not
 * be freed. Handlers can be updated.
 */
xmlSAXHandler *
xmlCtxtGetSaxHandler(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(ctxt->sax);
}

/**
 * Set the SAX handler struct to a copy of `sax`.
 *
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @param sax  SAX handler
 * @returns 0 on success or -1 if arguments are invalid or a memory
 * allocation failed.
 */
int
xmlCtxtSetSaxHandler(xmlParserCtxt *ctxt, const xmlSAXHandler *sax) {
    xmlSAXHandler *copy;

    if ((ctxt == NULL) || (sax == NULL))
        return(-1);

    copy = xmlMalloc(sizeof(*copy));
    if (copy == NULL)
        return(-1);

    memcpy(copy, sax, sizeof(*copy));
    ctxt->sax = copy;

    return(0);
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the parsed document or NULL if a fatal error occurred when
 * parsing. The document must be freed by the caller. Resets the
 * context's document to NULL.
 */
xmlDoc *
xmlCtxtGetDocument(xmlParserCtxt *ctxt) {
    xmlDocPtr doc;

    if (ctxt == NULL)
        return(NULL);

    if ((ctxt->wellFormed) ||
        (((ctxt->recovery) || (ctxt->html)) &&
         (!xmlCtxtIsCatastrophicError(ctxt)))) {
        doc = ctxt->myDoc;
    } else {
        if (ctxt->errNo == XML_ERR_OK)
            xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "unknown error");
        doc = NULL;
        xmlFreeDoc(ctxt->myDoc);
    }
    ctxt->myDoc = NULL;

    return(doc);
}

/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns 1 if this is a HTML parser context, 0 otherwise.
 */
int
xmlCtxtIsHtml(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(0);

    return(ctxt->html ? 1 : 0);
}

/**
 * Check whether the parser is stopped.
 *
 * The parser is stopped on fatal (non-wellformedness) errors or
 * on user request with #xmlStopParser.
 *
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns 1 if the parser is stopped, 0 otherwise.
 */
int
xmlCtxtIsStopped(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(0);

    return(ctxt->disableSAX != 0);
}

/**
 * Check whether a DTD subset is being parsed.
 *
 * Should only be used by SAX callbacks.
 *
 * Return values are
 *
 * - 0: not in DTD
 * - 1: in internal DTD subset
 * - 2: in external DTD subset
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @returns the subset status
 */
int
xmlCtxtIsInSubset(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(0);

    return(ctxt->inSubset);
}

#ifdef LIBXML_VALID_ENABLED
/**
 * @since 2.14.0
 *
 * @param ctxt  parser context
 * @returns the validation context.
 */
xmlValidCtxt *
xmlCtxtGetValidCtxt(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return(NULL);

    return(&ctxt->vctxt);
}
#endif

/**
 * Return user data.
 *
 * Return user data of a custom SAX parser or the parser context
 * itself if unset.
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @returns the user data.
 */
void *
xmlCtxtGetUserData(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return NULL;

    return ctxt->userData;
}

/**
 * Return the current node being parsed.
 *
 * This is only useful if the default SAX callbacks which build
 * a document tree are intercepted. This mode of operation is
 * fragile and discouraged.
 *
 * Returns the current element node, or the document node if no
 * element was parsed yet.
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @returns the current node.
 */
xmlNode *
xmlCtxtGetNode(xmlParserCtxt *ctxt) {
    if (ctxt == NULL)
        return NULL;

    if (ctxt->node != NULL)
        return ctxt->node;
    return (xmlNode *) ctxt->myDoc;
}

/**
 * Return data from the doctype declaration.
 *
 * Should only be used by SAX callbacks.
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @param name  name of the root element (output)
 * @param systemId  system ID (URI) of the external subset (output)
 * @param publicId  public ID of the external subset (output)
 * @returns 0 on success, -1 if argument is invalid
 */
int
xmlCtxtGetDocTypeDecl(xmlParserCtxt *ctxt,
                      const xmlChar **name,
                      const xmlChar **systemId,
                      const xmlChar **publicId) {
    if (ctxt == NULL)
        return -1;

    if (name != NULL)
        *name = ctxt->intSubName;
    if (systemId != NULL)
        *systemId = ctxt->extSubURI;
    if (publicId != NULL)
        *publicId = ctxt->extSubSystem; /* The member is misnamed */

    return 0;
}

/**
 * Return input position.
 *
 * Should only be used by error handlers or SAX callbacks.
 *
 * Because of entities, there can be multiple inputs. Non-negative
 * values of `inputIndex` (0, 1, 2, ...)  select inputs starting
 * from the outermost input. Negative values (-1, -2, ...) select
 * inputs starting from the innermost input.
 *
 * The byte position is counted in possibly decoded UTF-8 bytes,
 * so it won't match the position in the raw input data.
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @param inputIndex  input index
 * @param filename  filename (output)
 * @param line  line number (output)
 * @param col  column number (output)
 * @param utf8BytePos  byte position (output)
 * @returns 0 on success, -1 if arguments are invalid
 */
int
xmlCtxtGetInputPosition(xmlParserCtxt *ctxt, int inputIndex,
                        const char **filename, int *line, int *col,
                        unsigned long *utf8BytePos) {
    xmlParserInput *input;

    if (ctxt == NULL)
        return -1;

    if (inputIndex < 0) {
        inputIndex += ctxt->inputNr;
        if (inputIndex < 0)
            return -1;
    }
    if (inputIndex >= ctxt->inputNr)
        return -1;

    input = ctxt->inputTab[inputIndex];

    if (filename != NULL)
        *filename = input->filename;
    if (line != NULL)
        *line = input->line;
    if (col != NULL)
        *col = input->col;

    if (utf8BytePos != NULL) {
        unsigned long consumed;

        consumed = input->consumed;
        xmlSaturatedAddSizeT(&consumed, input->cur - input->base);
        *utf8BytePos = consumed;
    }

    return 0;
}

/**
 * Return window into input data.
 *
 * Should only be used by error handlers or SAX callbacks.
 * The returned pointer is only valid until the callback returns.
 *
 * Because of entities, there can be multiple inputs. Non-negative
 * values of `inputIndex` (0, 1, 2, ...)  select inputs starting
 * from the outermost input. Negative values (-1, -2, ...) select
 * inputs starting from the innermost input.
 *
 * @since 2.15.0
 *
 * @param ctxt  parser context
 * @param inputIndex  input index
 * @param startOut  start of window (output)
 * @param sizeInOut  maximum size of window (in)
 *                   actual size of window (out)
 * @param offsetOut  offset of current position inside
 *                   window (out)
 * @returns 0 on success, -1 if arguments are invalid
 */
int
xmlCtxtGetInputWindow(xmlParserCtxt *ctxt, int inputIndex,
                      const xmlChar **startOut,
                      int *sizeInOut, int *offsetOut) {
    xmlParserInput *input;

    if (ctxt == NULL || startOut == NULL || sizeInOut == NULL ||
        offsetOut == NULL)
        return -1;

    if (inputIndex < 0) {
        inputIndex += ctxt->inputNr;
        if (inputIndex < 0)
            return -1;
    }
    if (inputIndex >= ctxt->inputNr)
        return -1;

    input = ctxt->inputTab[inputIndex];

    xmlParserInputGetWindow(input, startOut, sizeInOut, offsetOut);

    return 0;
}

/************************************************************************
 *									*
 *		Handling of node information				*
 *									*
 ************************************************************************/

/**
 * Same as #xmlCtxtReset
 *
 * @deprecated Use #xmlCtxtReset
 *
 * @param ctxt  an XML parser context
 */
void
xmlClearParserCtxt(xmlParserCtxt *ctxt)
{
    xmlCtxtReset(ctxt);
}


/**
 * Find the parser node info struct for a given node
 *
 * @deprecated Don't use.
 *
 * @param ctx  an XML parser context
 * @param node  an XML node within the tree
 * @returns an xmlParserNodeInfo block pointer or NULL
 */
const xmlParserNodeInfo *
xmlParserFindNodeInfo(xmlParserCtxt *ctx, xmlNode *node)
{
    unsigned long pos;

    if ((ctx == NULL) || (node == NULL))
        return (NULL);
    /* Find position where node should be at */
    pos = xmlParserFindNodeInfoIndex(&ctx->node_seq, node);
    if (pos < ctx->node_seq.length
        && ctx->node_seq.buffer[pos].node == node)
        return &ctx->node_seq.buffer[pos];
    else
        return NULL;
}


/**
 * Initialize (set to initial state) node info sequence
 *
 * @deprecated Don't use.
 *
 * @param seq  a node info sequence pointer
 */
void
xmlInitNodeInfoSeq(xmlParserNodeInfoSeq *seq)
{
    if (seq == NULL)
        return;
    seq->length = 0;
    seq->maximum = 0;
    seq->buffer = NULL;
}

/**
 * Clear (release memory and reinitialize) node info sequence
 *
 * @deprecated Don't use.
 *
 * @param seq  a node info sequence pointer
 */
void
xmlClearNodeInfoSeq(xmlParserNodeInfoSeq *seq)
{
    if (seq == NULL)
        return;
    if (seq->buffer != NULL)
        xmlFree(seq->buffer);
    xmlInitNodeInfoSeq(seq);
}

/**
 * Find the index that the info record for the given node is or
 * should be at in a sorted sequence.
 *
 * @deprecated Don't use.
 *
 * @param seq  a node info sequence pointer
 * @param node  an XML node pointer
 * @returns a long indicating the position of the record
 */
unsigned long
xmlParserFindNodeInfoIndex(xmlParserNodeInfoSeq *seq,
                           xmlNode *node)
{
    unsigned long upper, lower, middle;
    int found = 0;

    if ((seq == NULL) || (node == NULL))
        return ((unsigned long) -1);

    /* Do a binary search for the key */
    lower = 1;
    upper = seq->length;
    middle = 0;
    while (lower <= upper && !found) {
        middle = lower + (upper - lower) / 2;
        if (node == seq->buffer[middle - 1].node)
            found = 1;
        else if (node < seq->buffer[middle - 1].node)
            upper = middle - 1;
        else
            lower = middle + 1;
    }

    /* Return position */
    if (middle == 0 || seq->buffer[middle - 1].node < node)
        return middle;
    else
        return middle - 1;
}


/**
 * Insert node info record into the sorted sequence
 *
 * @deprecated Don't use.
 *
 * @param ctxt  an XML parser context
 * @param info  a node info sequence pointer
 */
void
xmlParserAddNodeInfo(xmlParserCtxt *ctxt,
                     xmlParserNodeInfo *info)
{
    unsigned long pos;

    if ((ctxt == NULL) || (info == NULL)) return;

    /* Find pos and check to see if node is already in the sequence */
    pos = xmlParserFindNodeInfoIndex(&ctxt->node_seq, (xmlNodePtr)
                                     info->node);

    if ((pos < ctxt->node_seq.length) &&
        (ctxt->node_seq.buffer != NULL) &&
        (ctxt->node_seq.buffer[pos].node == info->node)) {
        ctxt->node_seq.buffer[pos] = *info;
    }

    /* Otherwise, we need to add new node to buffer */
    else {
        if (ctxt->node_seq.length + 1 > ctxt->node_seq.maximum) {
            xmlParserNodeInfo *tmp;
            int newSize;

            newSize = xmlGrowCapacity(ctxt->node_seq.maximum, sizeof(tmp[0]),
                                      4, XML_MAX_ITEMS);
            if (newSize < 0) {
		xmlCtxtErrMemory(ctxt);
                return;
            }
            tmp = xmlRealloc(ctxt->node_seq.buffer, newSize * sizeof(tmp[0]));
            if (tmp == NULL) {
		xmlCtxtErrMemory(ctxt);
                return;
            }
            ctxt->node_seq.buffer = tmp;
            ctxt->node_seq.maximum = newSize;
        }

        /* If position is not at end, move elements out of the way */
        if (pos != ctxt->node_seq.length) {
            unsigned long i;

            for (i = ctxt->node_seq.length; i > pos; i--)
                ctxt->node_seq.buffer[i] = ctxt->node_seq.buffer[i - 1];
        }

        /* Copy element and increase length */
        ctxt->node_seq.buffer[pos] = *info;
        ctxt->node_seq.length++;
    }
}

/************************************************************************
 *									*
 *		Defaults settings					*
 *									*
 ************************************************************************/
/**
 * Set and return the previous value for enabling pedantic warnings.
 *
 * @deprecated Use the modern options API with XML_PARSE_PEDANTIC.
 *
 * @param val  int 0 or 1
 * @returns the last value for 0 for no substitution, 1 for substitution.
 */

int
xmlPedanticParserDefault(int val) {
    int old = xmlPedanticParserDefaultValue;

    xmlPedanticParserDefaultValue = val;
    return(old);
}

/**
 * Has no effect.
 *
 * @deprecated Line numbers are always enabled.
 *
 * @param val  int 0 or 1
 * @returns 1
 */

int
xmlLineNumbersDefault(int val ATTRIBUTE_UNUSED) {
    return(1);
}

/**
 * Set and return the previous value for default entity support.
 *
 * @deprecated Use the modern options API with XML_PARSE_NOENT.
 *
 * @param val  int 0 or 1
 * @returns the last value for 0 for no substitution, 1 for substitution.
 */

int
xmlSubstituteEntitiesDefault(int val) {
    int old = xmlSubstituteEntitiesDefaultValue;

    xmlSubstituteEntitiesDefaultValue = val;
    return(old);
}

/**
 * Set and return the previous value for default blanks text nodes support.
 *
 * @deprecated Use the modern options API with XML_PARSE_NOBLANKS.
 *
 * @param val  int 0 or 1
 * @returns the last value for 0 for no substitution, 1 for substitution.
 */

int
xmlKeepBlanksDefault(int val) {
    int old = xmlKeepBlanksDefaultValue;

    xmlKeepBlanksDefaultValue = val;
#ifdef LIBXML_OUTPUT_ENABLED
    if (!val)
        xmlIndentTreeOutput = 1;
#endif
    return(old);
}