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
|
/**********************************************************************
*
* Project: CPL - Common Portability Library
* Purpose: Implementation of MiniXML Parser and handling.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
**********************************************************************
* Copyright (c) 2001, Frank Warmerdam
* Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************
*
* Independent Security Audit 2003/04/05 Andrey Kiselev:
* Completed audit of this module. Any documents may be parsed without
* buffer overflows and stack corruptions.
*
* Security Audit 2003/03/28 warmerda:
* Completed security audit. I believe that this module may be safely used
* to parse, and serialize arbitrary documents provided by a potentially
* hostile source.
*
*/
#include "cpl_minixml.h"
#include <cctype>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
typedef enum
{
TNone,
TString,
TOpen,
TClose,
TEqual,
TToken,
TSlashClose,
TQuestionClose,
TComment,
TLiteral
} XMLTokenType;
typedef struct
{
CPLXMLNode *psFirstNode;
CPLXMLNode *psLastChild;
} StackContext;
typedef struct
{
const char *pszInput;
int nInputOffset;
int nInputLine;
bool bInElement;
XMLTokenType eTokenType;
char *pszToken;
size_t nTokenMaxSize;
size_t nTokenSize;
int nStackMaxSize;
int nStackSize;
StackContext *papsStack;
CPLXMLNode *psFirstNode;
CPLXMLNode *psLastNode;
} ParseContext;
static CPLXMLNode *_CPLCreateXMLNode(CPLXMLNode *poParent, CPLXMLNodeType eType,
const char *pszText);
/************************************************************************/
/* ReadChar() */
/************************************************************************/
static CPL_INLINE char ReadChar(ParseContext *psContext)
{
const char chReturn = psContext->pszInput[psContext->nInputOffset++];
if (chReturn == '\0')
psContext->nInputOffset--;
else if (chReturn == 10)
psContext->nInputLine++;
return chReturn;
}
/************************************************************************/
/* UnreadChar() */
/************************************************************************/
static CPL_INLINE void UnreadChar(ParseContext *psContext, char chToUnread)
{
if (chToUnread == '\0')
return;
CPLAssert(chToUnread == psContext->pszInput[psContext->nInputOffset - 1]);
psContext->nInputOffset--;
if (chToUnread == 10)
psContext->nInputLine--;
}
/************************************************************************/
/* ReallocToken() */
/************************************************************************/
static bool ReallocToken(ParseContext *psContext)
{
if (psContext->nTokenMaxSize > INT_MAX / 2)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Out of memory allocating %d*2 bytes",
static_cast<int>(psContext->nTokenMaxSize));
VSIFree(psContext->pszToken);
psContext->pszToken = nullptr;
return false;
}
psContext->nTokenMaxSize *= 2;
char *pszToken = static_cast<char *>(
VSIRealloc(psContext->pszToken, psContext->nTokenMaxSize));
if (pszToken == nullptr)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Out of memory allocating %d bytes",
static_cast<int>(psContext->nTokenMaxSize));
VSIFree(psContext->pszToken);
psContext->pszToken = nullptr;
return false;
}
psContext->pszToken = pszToken;
return true;
}
/************************************************************************/
/* AddToToken() */
/************************************************************************/
static CPL_INLINE bool _AddToToken(ParseContext *psContext, char chNewChar)
{
if (psContext->nTokenSize >= psContext->nTokenMaxSize - 2)
{
if (!ReallocToken(psContext))
return false;
}
psContext->pszToken[psContext->nTokenSize++] = chNewChar;
psContext->pszToken[psContext->nTokenSize] = '\0';
return true;
}
// TODO(schwehr): Remove the goto.
#define AddToToken(psContext, chNewChar) \
if (!_AddToToken(psContext, chNewChar)) \
goto fail;
/************************************************************************/
/* ReadToken() */
/************************************************************************/
static XMLTokenType ReadToken(ParseContext *psContext, CPLErr &eLastErrorType)
{
psContext->nTokenSize = 0;
psContext->pszToken[0] = '\0';
char chNext = ReadChar(psContext);
while (isspace(static_cast<unsigned char>(chNext)))
chNext = ReadChar(psContext);
/* -------------------------------------------------------------------- */
/* Handle comments. */
/* -------------------------------------------------------------------- */
if (chNext == '<' &&
STARTS_WITH_CI(psContext->pszInput + psContext->nInputOffset, "!--"))
{
psContext->eTokenType = TComment;
// Skip "!--" characters.
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
while (!STARTS_WITH_CI(psContext->pszInput + psContext->nInputOffset,
"-->") &&
(chNext = ReadChar(psContext)) != '\0')
AddToToken(psContext, chNext);
// Skip "-->" characters.
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
}
/* -------------------------------------------------------------------- */
/* Handle DOCTYPE. */
/* -------------------------------------------------------------------- */
else if (chNext == '<' &&
STARTS_WITH_CI(psContext->pszInput + psContext->nInputOffset,
"!DOCTYPE"))
{
bool bInQuotes = false;
psContext->eTokenType = TLiteral;
AddToToken(psContext, '<');
do
{
chNext = ReadChar(psContext);
if (chNext == '\0')
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Parse error in DOCTYPE on or before line %d, "
"reached end of file without '>'.",
psContext->nInputLine);
break;
}
/* The markup declaration block within a DOCTYPE tag consists of:
* - a left square bracket [
* - a list of declarations
* - a right square bracket ]
* Example:
* <!DOCTYPE RootElement [ ...declarations... ]>
*/
if (chNext == '[')
{
AddToToken(psContext, chNext);
do
{
chNext = ReadChar(psContext);
if (chNext == ']')
break;
AddToToken(psContext, chNext);
} while (chNext != '\0' &&
!STARTS_WITH_CI(psContext->pszInput +
psContext->nInputOffset,
"]>"));
if (chNext == '\0')
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Parse error in DOCTYPE on or before line %d, "
"reached end of file without ']'.",
psContext->nInputLine);
break;
}
if (chNext != ']')
{
chNext = ReadChar(psContext);
AddToToken(psContext, chNext);
// Skip ">" character, will be consumed below.
chNext = ReadChar(psContext);
}
}
if (chNext == '\"')
bInQuotes = !bInQuotes;
if (chNext == '>' && !bInQuotes)
{
AddToToken(psContext, '>');
break;
}
AddToToken(psContext, chNext);
} while (true);
}
/* -------------------------------------------------------------------- */
/* Handle CDATA. */
/* -------------------------------------------------------------------- */
else if (chNext == '<' &&
STARTS_WITH_CI(psContext->pszInput + psContext->nInputOffset,
"![CDATA["))
{
psContext->eTokenType = TString;
// Skip !CDATA[
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
while (!STARTS_WITH_CI(psContext->pszInput + psContext->nInputOffset,
"]]>") &&
(chNext = ReadChar(psContext)) != '\0')
AddToToken(psContext, chNext);
// Skip "]]>" characters.
ReadChar(psContext);
ReadChar(psContext);
ReadChar(psContext);
}
/* -------------------------------------------------------------------- */
/* Simple single tokens of interest. */
/* -------------------------------------------------------------------- */
else if (chNext == '<' && !psContext->bInElement)
{
psContext->eTokenType = TOpen;
psContext->bInElement = true;
}
else if (chNext == '>' && psContext->bInElement)
{
psContext->eTokenType = TClose;
psContext->bInElement = false;
}
else if (chNext == '=' && psContext->bInElement)
{
psContext->eTokenType = TEqual;
}
else if (chNext == '\0')
{
psContext->eTokenType = TNone;
}
/* -------------------------------------------------------------------- */
/* Handle the /> token terminator. */
/* -------------------------------------------------------------------- */
else if (chNext == '/' && psContext->bInElement &&
psContext->pszInput[psContext->nInputOffset] == '>')
{
chNext = ReadChar(psContext);
(void)chNext;
CPLAssert(chNext == '>');
psContext->eTokenType = TSlashClose;
psContext->bInElement = false;
}
/* -------------------------------------------------------------------- */
/* Handle the ?> token terminator. */
/* -------------------------------------------------------------------- */
else if (chNext == '?' && psContext->bInElement &&
psContext->pszInput[psContext->nInputOffset] == '>')
{
chNext = ReadChar(psContext);
(void)chNext;
CPLAssert(chNext == '>');
psContext->eTokenType = TQuestionClose;
psContext->bInElement = false;
}
/* -------------------------------------------------------------------- */
/* Collect a quoted string. */
/* -------------------------------------------------------------------- */
else if (psContext->bInElement && chNext == '"')
{
psContext->eTokenType = TString;
while ((chNext = ReadChar(psContext)) != '"' && chNext != '\0')
AddToToken(psContext, chNext);
if (chNext != '"')
{
psContext->eTokenType = TNone;
eLastErrorType = CE_Failure;
CPLError(
eLastErrorType, CPLE_AppDefined,
"Parse error on line %d, reached EOF before closing quote.",
psContext->nInputLine);
}
// Do we need to unescape it?
if (strchr(psContext->pszToken, '&') != nullptr)
{
int nLength = 0;
char *pszUnescaped =
CPLUnescapeString(psContext->pszToken, &nLength, CPLES_XML);
strcpy(psContext->pszToken, pszUnescaped);
CPLFree(pszUnescaped);
psContext->nTokenSize = strlen(psContext->pszToken);
}
}
else if (psContext->bInElement && chNext == '\'')
{
psContext->eTokenType = TString;
while ((chNext = ReadChar(psContext)) != '\'' && chNext != '\0')
AddToToken(psContext, chNext);
if (chNext != '\'')
{
psContext->eTokenType = TNone;
eLastErrorType = CE_Failure;
CPLError(
eLastErrorType, CPLE_AppDefined,
"Parse error on line %d, reached EOF before closing quote.",
psContext->nInputLine);
}
// Do we need to unescape it?
if (strchr(psContext->pszToken, '&') != nullptr)
{
int nLength = 0;
char *pszUnescaped =
CPLUnescapeString(psContext->pszToken, &nLength, CPLES_XML);
strcpy(psContext->pszToken, pszUnescaped);
CPLFree(pszUnescaped);
psContext->nTokenSize = strlen(psContext->pszToken);
}
}
/* -------------------------------------------------------------------- */
/* Collect an unquoted string, terminated by a open angle */
/* bracket. */
/* -------------------------------------------------------------------- */
else if (!psContext->bInElement)
{
psContext->eTokenType = TString;
AddToToken(psContext, chNext);
while ((chNext = ReadChar(psContext)) != '<' && chNext != '\0')
AddToToken(psContext, chNext);
UnreadChar(psContext, chNext);
// Do we need to unescape it?
if (strchr(psContext->pszToken, '&') != nullptr)
{
int nLength = 0;
char *pszUnescaped =
CPLUnescapeString(psContext->pszToken, &nLength, CPLES_XML);
strcpy(psContext->pszToken, pszUnescaped);
CPLFree(pszUnescaped);
psContext->nTokenSize = strlen(psContext->pszToken);
}
}
/* -------------------------------------------------------------------- */
/* Collect a regular token terminated by white space, or */
/* special character(s) like an equal sign. */
/* -------------------------------------------------------------------- */
else
{
psContext->eTokenType = TToken;
// Add the first character to the token regardless of what it is.
AddToToken(psContext, chNext);
for (chNext = ReadChar(psContext);
(chNext >= 'A' && chNext <= 'Z') ||
(chNext >= 'a' && chNext <= 'z') || chNext == '-' ||
chNext == '_' || chNext == '.' || chNext == ':' ||
(chNext >= '0' && chNext <= '9');
chNext = ReadChar(psContext))
{
AddToToken(psContext, chNext);
}
UnreadChar(psContext, chNext);
}
return psContext->eTokenType;
fail:
psContext->eTokenType = TNone;
return TNone;
}
/************************************************************************/
/* PushNode() */
/************************************************************************/
static bool PushNode(ParseContext *psContext, CPLXMLNode *psNode,
CPLErr &eLastErrorType)
{
if (psContext->nStackMaxSize <= psContext->nStackSize)
{
// Somewhat arbitrary number.
if (psContext->nStackMaxSize >= 10000)
{
eLastErrorType = CE_Failure;
CPLError(CE_Failure, CPLE_NotSupported,
"XML element depth beyond 10000. Giving up");
VSIFree(psContext->papsStack);
psContext->papsStack = nullptr;
return false;
}
psContext->nStackMaxSize += 10;
StackContext *papsStack = static_cast<StackContext *>(
VSIRealloc(psContext->papsStack,
sizeof(StackContext) * psContext->nStackMaxSize));
if (papsStack == nullptr)
{
eLastErrorType = CE_Failure;
CPLError(CE_Failure, CPLE_OutOfMemory,
"Out of memory allocating %d bytes",
static_cast<int>(sizeof(StackContext)) *
psContext->nStackMaxSize);
VSIFree(psContext->papsStack);
psContext->papsStack = nullptr;
return false;
}
psContext->papsStack = papsStack;
}
#ifdef DEBUG
// To make Coverity happy, but cannot happen.
if (psContext->papsStack == nullptr)
return false;
#endif
psContext->papsStack[psContext->nStackSize].psFirstNode = psNode;
psContext->papsStack[psContext->nStackSize].psLastChild = nullptr;
psContext->nStackSize++;
return true;
}
/************************************************************************/
/* AttachNode() */
/* */
/* Attach the passed node as a child of the current node. */
/* Special handling exists for adding siblings to psFirst if */
/* there is nothing on the stack. */
/************************************************************************/
static void AttachNode(ParseContext *psContext, CPLXMLNode *psNode)
{
if (psContext->psFirstNode == nullptr)
{
psContext->psFirstNode = psNode;
psContext->psLastNode = psNode;
}
else if (psContext->nStackSize == 0)
{
psContext->psLastNode->psNext = psNode;
psContext->psLastNode = psNode;
}
else
{
if (psContext->papsStack[psContext->nStackSize - 1]
.psFirstNode->psChild == nullptr)
{
psContext->papsStack[psContext->nStackSize - 1]
.psFirstNode->psChild = psNode;
}
else
{
psContext->papsStack[psContext->nStackSize - 1]
.psLastChild->psNext = psNode;
}
psContext->papsStack[psContext->nStackSize - 1].psLastChild = psNode;
}
}
/************************************************************************/
/* CPLParseXMLString() */
/************************************************************************/
/**
* \brief Parse an XML string into tree form.
*
* The passed document is parsed into a CPLXMLNode tree representation.
* If the document is not well formed XML then NULL is returned, and errors
* are reported via CPLError(). No validation beyond wellformedness is
* done. The CPLParseXMLFile() convenience function can be used to parse
* from a file.
*
* The returned document tree is owned by the caller and should be freed
* with CPLDestroyXMLNode() when no longer needed.
*
* If the document has more than one "root level" element then those after the
* first will be attached to the first as siblings (via the psNext pointers)
* even though there is no common parent. A document with no XML structure
* (no angle brackets for instance) would be considered well formed, and
* returned as a single CXT_Text node.
*
* @param pszString the document to parse.
*
* @return parsed tree or NULL on error.
*/
CPLXMLNode *CPLParseXMLString(const char *pszString)
{
if (pszString == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPLParseXMLString() called with NULL pointer.");
return nullptr;
}
// Save back error context.
const CPLErr eErrClass = CPLGetLastErrorType();
const CPLErrorNum nErrNum = CPLGetLastErrorNo();
const CPLString osErrMsg = CPLGetLastErrorMsg();
// Reset it now.
CPLErrorReset();
/* -------------------------------------------------------------------- */
/* Check for a UTF-8 BOM and skip if found */
/* */
/* TODO: BOM is variable-length parameter and depends on encoding. */
/* Add BOM detection for other encodings. */
/* -------------------------------------------------------------------- */
// Used to skip to actual beginning of XML data.
if ((static_cast<unsigned char>(pszString[0]) == 0xEF) &&
(static_cast<unsigned char>(pszString[1]) == 0xBB) &&
(static_cast<unsigned char>(pszString[2]) == 0xBF))
{
pszString += 3;
}
/* -------------------------------------------------------------------- */
/* Initialize parse context. */
/* -------------------------------------------------------------------- */
ParseContext sContext;
sContext.pszInput = pszString;
sContext.nInputOffset = 0;
sContext.nInputLine = 0;
sContext.bInElement = false;
sContext.nTokenMaxSize = 10;
sContext.pszToken = static_cast<char *>(VSIMalloc(sContext.nTokenMaxSize));
if (sContext.pszToken == nullptr)
return nullptr;
sContext.nTokenSize = 0;
sContext.eTokenType = TNone;
sContext.nStackMaxSize = 0;
sContext.nStackSize = 0;
sContext.papsStack = nullptr;
sContext.psFirstNode = nullptr;
sContext.psLastNode = nullptr;
#ifdef DEBUG
bool bRecoverableError = true;
#endif
CPLErr eLastErrorType = CE_None;
/* ==================================================================== */
/* Loop reading tokens. */
/* ==================================================================== */
while (ReadToken(&sContext, eLastErrorType) != TNone)
{
loop_beginning:
/* --------------------------------------------------------------------
*/
/* Create a new element. */
/* --------------------------------------------------------------------
*/
if (sContext.eTokenType == TOpen)
{
if (ReadToken(&sContext, eLastErrorType) != TToken)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Didn't find element token after "
"open angle bracket.",
sContext.nInputLine);
break;
}
CPLXMLNode *psElement = nullptr;
if (sContext.pszToken[0] != '/')
{
psElement =
_CPLCreateXMLNode(nullptr, CXT_Element, sContext.pszToken);
if (!psElement)
break;
AttachNode(&sContext, psElement);
if (!PushNode(&sContext, psElement, eLastErrorType))
break;
}
else
{
if (sContext.nStackSize == 0 ||
!EQUAL(sContext.pszToken + 1,
sContext.papsStack[sContext.nStackSize - 1]
.psFirstNode->pszValue))
{
#ifdef DEBUG
// Makes life of fuzzers easier if we accept somewhat
// corrupted XML like <foo> ... </not_foo>.
if (CPLTestBool(
CPLGetConfigOption("CPL_MINIXML_RELAXED", "FALSE")))
{
eLastErrorType = CE_Warning;
CPLError(
eLastErrorType, CPLE_AppDefined,
"Line %d: <%.500s> doesn't have matching <%.500s>.",
sContext.nInputLine, sContext.pszToken,
sContext.pszToken + 1);
if (sContext.nStackSize == 0)
break;
goto end_processing_close;
}
else
#endif
{
eLastErrorType = CE_Failure;
CPLError(
eLastErrorType, CPLE_AppDefined,
"Line %d: <%.500s> doesn't have matching <%.500s>.",
sContext.nInputLine, sContext.pszToken,
sContext.pszToken + 1);
break;
}
}
else
{
if (strcmp(sContext.pszToken + 1,
sContext.papsStack[sContext.nStackSize - 1]
.psFirstNode->pszValue) != 0)
{
// TODO: At some point we could just error out like any
// other sane XML parser would do.
eLastErrorType = CE_Warning;
CPLError(
eLastErrorType, CPLE_AppDefined,
"Line %d: <%.500s> matches <%.500s>, but the case "
"isn't the same. Going on, but this is invalid "
"XML that might be rejected in future versions.",
sContext.nInputLine,
sContext.papsStack[sContext.nStackSize - 1]
.psFirstNode->pszValue,
sContext.pszToken);
}
#ifdef DEBUG
end_processing_close:
#endif
if (ReadToken(&sContext, eLastErrorType) != TClose)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Missing close angle bracket "
"after <%.500s.",
sContext.nInputLine, sContext.pszToken);
break;
}
// Pop element off stack
sContext.nStackSize--;
}
}
}
/* --------------------------------------------------------------------
*/
/* Add an attribute to a token. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TToken)
{
CPLXMLNode *psAttr =
_CPLCreateXMLNode(nullptr, CXT_Attribute, sContext.pszToken);
if (!psAttr)
break;
AttachNode(&sContext, psAttr);
XMLTokenType nextToken = ReadToken(&sContext, eLastErrorType);
if (nextToken != TEqual)
{
// Parse stuff like <?valbuddy_schematron
// ../wmtsSimpleGetCapabilities.sch?>
if (sContext.nStackSize > 0 &&
sContext.papsStack[sContext.nStackSize - 1]
.psFirstNode->pszValue[0] == '?')
{
psAttr->eType = CXT_Text;
if (nextToken == TNone)
break;
goto loop_beginning;
}
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Didn't find expected '=' for value of "
"attribute '%.500s'.",
sContext.nInputLine, psAttr->pszValue);
#ifdef DEBUG
// Accepting an attribute without child text
// would break too much assumptions in driver code
bRecoverableError = false;
#endif
break;
}
if (ReadToken(&sContext, eLastErrorType) == TToken)
{
/* TODO: at some point we could just error out like any other */
/* sane XML parser would do */
eLastErrorType = CE_Warning;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Attribute value should be single or double "
"quoted. Going on, but this is invalid XML that "
"might be rejected in future versions.",
sContext.nInputLine);
}
else if (sContext.eTokenType != TString)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Didn't find expected attribute value.",
sContext.nInputLine);
#ifdef DEBUG
// Accepting an attribute without child text
// would break too much assumptions in driver code
bRecoverableError = false;
#endif
break;
}
if (!_CPLCreateXMLNode(psAttr, CXT_Text, sContext.pszToken))
break;
}
/* --------------------------------------------------------------------
*/
/* Close the start section of an element. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TClose)
{
if (sContext.nStackSize == 0)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Found unbalanced '>'.", sContext.nInputLine);
break;
}
}
/* --------------------------------------------------------------------
*/
/* Close the start section of an element, and pop it */
/* immediately. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TSlashClose)
{
if (sContext.nStackSize == 0)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Found unbalanced '/>'.",
sContext.nInputLine);
break;
}
sContext.nStackSize--;
}
/* --------------------------------------------------------------------
*/
/* Close the start section of a <?...?> element, and pop it */
/* immediately. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TQuestionClose)
{
if (sContext.nStackSize == 0)
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Found unbalanced '?>'.",
sContext.nInputLine);
break;
}
else if (sContext.papsStack[sContext.nStackSize - 1]
.psFirstNode->pszValue[0] != '?')
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Line %d: Found '?>' without matching '<?'.",
sContext.nInputLine);
break;
}
sContext.nStackSize--;
}
/* --------------------------------------------------------------------
*/
/* Handle comments. They are returned as a whole token with the */
/* prefix and postfix omitted. No processing of white space */
/* will be done. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TComment)
{
CPLXMLNode *psValue =
_CPLCreateXMLNode(nullptr, CXT_Comment, sContext.pszToken);
if (!psValue)
break;
AttachNode(&sContext, psValue);
}
/* --------------------------------------------------------------------
*/
/* Handle literals. They are returned without processing. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TLiteral)
{
CPLXMLNode *psValue =
_CPLCreateXMLNode(nullptr, CXT_Literal, sContext.pszToken);
if (!psValue)
break;
AttachNode(&sContext, psValue);
}
/* --------------------------------------------------------------------
*/
/* Add a text value node as a child of the current element. */
/* --------------------------------------------------------------------
*/
else if (sContext.eTokenType == TString && !sContext.bInElement)
{
CPLXMLNode *psValue =
_CPLCreateXMLNode(nullptr, CXT_Text, sContext.pszToken);
if (!psValue)
break;
AttachNode(&sContext, psValue);
}
/* --------------------------------------------------------------------
*/
/* Anything else is an error. */
/* --------------------------------------------------------------------
*/
else
{
eLastErrorType = CE_Failure;
CPLError(eLastErrorType, CPLE_AppDefined,
"Parse error at line %d, unexpected token:%.500s",
sContext.nInputLine, sContext.pszToken);
break;
}
}
/* -------------------------------------------------------------------- */
/* Did we pop all the way out of our stack? */
/* -------------------------------------------------------------------- */
if (CPLGetLastErrorType() != CE_Failure && sContext.nStackSize > 0 &&
sContext.papsStack != nullptr)
{
#ifdef DEBUG
// Makes life of fuzzers easier if we accept somewhat corrupted XML
// like <x> ...
if (bRecoverableError &&
CPLTestBool(CPLGetConfigOption("CPL_MINIXML_RELAXED", "FALSE")))
{
eLastErrorType = CE_Warning;
}
else
#endif
{
eLastErrorType = CE_Failure;
}
CPLError(
eLastErrorType, CPLE_AppDefined,
"Parse error at EOF, not all elements have been closed, "
"starting with %.500s",
sContext.papsStack[sContext.nStackSize - 1].psFirstNode->pszValue);
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
CPLFree(sContext.pszToken);
if (sContext.papsStack != nullptr)
CPLFree(sContext.papsStack);
// We do not trust CPLGetLastErrorType() as if CPLTurnFailureIntoWarning()
// has been set we would never get failures
if (eLastErrorType == CE_Failure)
{
CPLDestroyXMLNode(sContext.psFirstNode);
sContext.psFirstNode = nullptr;
sContext.psLastNode = nullptr;
}
if (eLastErrorType == CE_None)
{
// Restore initial error state.
CPLErrorSetState(eErrClass, nErrNum, osErrMsg);
}
return sContext.psFirstNode;
}
/************************************************************************/
/* _GrowBuffer() */
/************************************************************************/
static bool _GrowBuffer(size_t nNeeded, char **ppszText, size_t *pnMaxLength)
{
if (nNeeded + 1 >= *pnMaxLength)
{
*pnMaxLength = std::max(*pnMaxLength * 2, nNeeded + 1);
char *pszTextNew =
static_cast<char *>(VSIRealloc(*ppszText, *pnMaxLength));
if (pszTextNew == nullptr)
return false;
*ppszText = pszTextNew;
}
return true;
}
/************************************************************************/
/* CPLSerializeXMLNode() */
/************************************************************************/
// TODO(schwehr): Rewrite this whole thing using C++ string.
// CPLSerializeXMLNode has buffer overflows.
static bool CPLSerializeXMLNode(const CPLXMLNode *psNode, int nIndent,
char **ppszText, size_t *pnLength,
size_t *pnMaxLength)
{
if (psNode == nullptr)
return true;
/* -------------------------------------------------------------------- */
/* Ensure the buffer is plenty large to hold this additional */
/* string. */
/* -------------------------------------------------------------------- */
*pnLength += strlen(*ppszText + *pnLength);
if (!_GrowBuffer(strlen(psNode->pszValue) + *pnLength + 40 + nIndent,
ppszText, pnMaxLength))
return false;
/* -------------------------------------------------------------------- */
/* Text is just directly emitted. */
/* -------------------------------------------------------------------- */
if (psNode->eType == CXT_Text)
{
char *pszEscaped =
CPLEscapeString(psNode->pszValue, -1, CPLES_XML_BUT_QUOTES);
CPLAssert(psNode->psChild == nullptr);
// Escaped text might be bigger than expected.
if (!_GrowBuffer(strlen(pszEscaped) + *pnLength, ppszText, pnMaxLength))
{
CPLFree(pszEscaped);
return false;
}
strcat(*ppszText + *pnLength, pszEscaped);
CPLFree(pszEscaped);
}
/* -------------------------------------------------------------------- */
/* Attributes require a little formatting. */
/* -------------------------------------------------------------------- */
else if (psNode->eType == CXT_Attribute)
{
CPLAssert(psNode->psChild != nullptr &&
psNode->psChild->eType == CXT_Text);
snprintf(*ppszText + *pnLength, *pnMaxLength - *pnLength, " %s=\"",
psNode->pszValue);
*pnLength += strlen(*ppszText + *pnLength);
char *pszEscaped =
CPLEscapeString(psNode->psChild->pszValue, -1, CPLES_XML);
if (!_GrowBuffer(strlen(pszEscaped) + *pnLength, ppszText, pnMaxLength))
{
CPLFree(pszEscaped);
return false;
}
strcat(*ppszText + *pnLength, pszEscaped);
CPLFree(pszEscaped);
*pnLength += strlen(*ppszText + *pnLength);
if (!_GrowBuffer(3 + *pnLength, ppszText, pnMaxLength))
return false;
strcat(*ppszText + *pnLength, "\"");
}
/* -------------------------------------------------------------------- */
/* Handle comment output. */
/* -------------------------------------------------------------------- */
else if (psNode->eType == CXT_Comment)
{
CPLAssert(psNode->psChild == nullptr);
for (int i = 0; i < nIndent; i++)
(*ppszText)[(*pnLength)++] = ' ';
snprintf(*ppszText + *pnLength, *pnMaxLength - *pnLength, "<!--%s-->\n",
psNode->pszValue);
}
/* -------------------------------------------------------------------- */
/* Handle literal output (like <!DOCTYPE...>) */
/* -------------------------------------------------------------------- */
else if (psNode->eType == CXT_Literal)
{
CPLAssert(psNode->psChild == nullptr);
for (int i = 0; i < nIndent; i++)
(*ppszText)[(*pnLength)++] = ' ';
strcpy(*ppszText + *pnLength, psNode->pszValue);
strcat(*ppszText + *pnLength, "\n");
}
/* -------------------------------------------------------------------- */
/* Elements actually have to deal with general children, and */
/* various formatting issues. */
/* -------------------------------------------------------------------- */
else if (psNode->eType == CXT_Element)
{
if (nIndent)
memset(*ppszText + *pnLength, ' ', nIndent);
*pnLength += nIndent;
(*ppszText)[*pnLength] = '\0';
snprintf(*ppszText + *pnLength, *pnMaxLength - *pnLength, "<%s",
psNode->pszValue);
if (psNode->pszValue[0] == '?')
{
for (const CPLXMLNode *psChild = psNode->psChild;
psChild != nullptr; psChild = psChild->psNext)
{
if (psChild->eType == CXT_Text)
{
*pnLength += strlen(*ppszText + *pnLength);
if (!_GrowBuffer(1 + *pnLength, ppszText, pnMaxLength))
return false;
strcat(*ppszText + *pnLength, " ");
}
if (!CPLSerializeXMLNode(psChild, 0, ppszText, pnLength,
pnMaxLength))
{
return false;
}
}
if (!_GrowBuffer(*pnLength + 40, ppszText, pnMaxLength))
return false;
strcat(*ppszText + *pnLength, "?>\n");
}
else
{
bool bHasNonAttributeChildren = false;
// Serialize *all* the attribute children, regardless of order
for (const CPLXMLNode *psChild = psNode->psChild;
psChild != nullptr; psChild = psChild->psNext)
{
if (psChild->eType == CXT_Attribute)
{
if (!CPLSerializeXMLNode(psChild, 0, ppszText, pnLength,
pnMaxLength))
return false;
}
else
bHasNonAttributeChildren = true;
}
if (!bHasNonAttributeChildren)
{
if (!_GrowBuffer(*pnLength + 40, ppszText, pnMaxLength))
return false;
strcat(*ppszText + *pnLength, " />\n");
}
else
{
bool bJustText = true;
strcat(*ppszText + *pnLength, ">");
for (const CPLXMLNode *psChild = psNode->psChild;
psChild != nullptr; psChild = psChild->psNext)
{
if (psChild->eType == CXT_Attribute)
continue;
if (psChild->eType != CXT_Text && bJustText)
{
bJustText = false;
*pnLength += strlen(*ppszText + *pnLength);
if (!_GrowBuffer(1 + *pnLength, ppszText, pnMaxLength))
return false;
strcat(*ppszText + *pnLength, "\n");
}
if (!CPLSerializeXMLNode(psChild, nIndent + 2, ppszText,
pnLength, pnMaxLength))
return false;
}
*pnLength += strlen(*ppszText + *pnLength);
if (!_GrowBuffer(strlen(psNode->pszValue) + *pnLength + 40 +
nIndent,
ppszText, pnMaxLength))
return false;
if (!bJustText)
{
if (nIndent)
memset(*ppszText + *pnLength, ' ', nIndent);
*pnLength += nIndent;
(*ppszText)[*pnLength] = '\0';
}
*pnLength += strlen(*ppszText + *pnLength);
snprintf(*ppszText + *pnLength, *pnMaxLength - *pnLength,
"</%s>\n", psNode->pszValue);
}
}
}
return true;
}
/************************************************************************/
/* CPLSerializeXMLTree() */
/************************************************************************/
/**
* \brief Convert tree into string document.
*
* This function converts a CPLXMLNode tree representation of a document
* into a flat string representation. White space indentation is used
* visually preserve the tree structure of the document. The returned
* document becomes owned by the caller and should be freed with CPLFree()
* when no longer needed.
*
* @param psNode the node to serialize.
*
* @return the document on success or NULL on failure.
*/
char *CPLSerializeXMLTree(const CPLXMLNode *psNode)
{
size_t nMaxLength = 100;
char *pszText = static_cast<char *>(CPLCalloc(nMaxLength, sizeof(char)));
if (pszText == nullptr)
return nullptr;
size_t nLength = 0;
for (const CPLXMLNode *psThis = psNode; psThis != nullptr;
psThis = psThis->psNext)
{
if (!CPLSerializeXMLNode(psThis, 0, &pszText, &nLength, &nMaxLength))
{
VSIFree(pszText);
return nullptr;
}
}
return pszText;
}
/************************************************************************/
/* CPLCreateXMLNode() */
/************************************************************************/
#ifdef DEBUG
static CPLXMLNode *psDummyStaticNode;
#endif
/**
* \brief Create an document tree item.
*
* Create a single CPLXMLNode object with the desired value and type, and
* attach it as a child of the indicated parent.
*
* @param poParent the parent to which this node should be attached as a
* child. May be NULL to keep as free standing.
* @param eType the type of the newly created node
* @param pszText the value of the newly created node
*
* @return the newly created node, now owned by the caller (or parent node).
*/
CPLXMLNode *CPLCreateXMLNode(CPLXMLNode *poParent, CPLXMLNodeType eType,
const char *pszText)
{
auto ret = _CPLCreateXMLNode(poParent, eType, pszText);
if (!ret)
{
CPLError(CE_Fatal, CPLE_OutOfMemory, "CPLCreateXMLNode() failed");
}
return ret;
}
/************************************************************************/
/* _CPLCreateXMLNode() */
/************************************************************************/
/* Same as CPLCreateXMLNode() but can return NULL in case of out-of-memory */
/* situation */
static CPLXMLNode *_CPLCreateXMLNode(CPLXMLNode *poParent, CPLXMLNodeType eType,
const char *pszText)
{
/* -------------------------------------------------------------------- */
/* Create new node. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psNode =
static_cast<CPLXMLNode *>(VSICalloc(sizeof(CPLXMLNode), 1));
if (psNode == nullptr)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate CPLXMLNode");
return nullptr;
}
psNode->eType = eType;
psNode->pszValue = VSIStrdup(pszText ? pszText : "");
if (psNode->pszValue == nullptr)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot allocate psNode->pszValue");
VSIFree(psNode);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Attach to parent, if provided. */
/* -------------------------------------------------------------------- */
if (poParent != nullptr)
{
if (poParent->psChild == nullptr)
poParent->psChild = psNode;
else
{
CPLXMLNode *psLink = poParent->psChild;
if (psLink->psNext == nullptr && eType == CXT_Attribute &&
psLink->eType == CXT_Text)
{
psNode->psNext = psLink;
poParent->psChild = psNode;
}
else
{
while (psLink->psNext != nullptr)
{
if (eType == CXT_Attribute &&
psLink->psNext->eType == CXT_Text)
{
psNode->psNext = psLink->psNext;
break;
}
psLink = psLink->psNext;
}
psLink->psNext = psNode;
}
}
}
#ifdef DEBUG
else
{
// Coverity sometimes doesn't realize that this function is passed
// with a non NULL parent and thinks that this branch is taken, leading
// to creating object being leak by caller. This ugly hack hopefully
// makes it believe that someone will reference it.
psDummyStaticNode = psNode;
}
#endif
return psNode;
}
/************************************************************************/
/* CPLDestroyXMLNode() */
/************************************************************************/
/**
* \brief Destroy a tree.
*
* This function frees resources associated with a CPLXMLNode and all its
* children nodes.
*
* @param psNode the tree to free.
*/
void CPLDestroyXMLNode(CPLXMLNode *psNode)
{
while (psNode != nullptr)
{
if (psNode->pszValue != nullptr)
CPLFree(psNode->pszValue);
if (psNode->psChild != nullptr)
{
CPLXMLNode *psNext = psNode->psNext;
psNode->psNext = psNode->psChild;
// Move the child and its siblings as the next
// siblings of the current node.
if (psNext != nullptr)
{
CPLXMLNode *psIter = psNode->psChild;
while (psIter->psNext != nullptr)
psIter = psIter->psNext;
psIter->psNext = psNext;
}
}
CPLXMLNode *psNext = psNode->psNext;
CPLFree(psNode);
psNode = psNext;
}
}
/************************************************************************/
/* CPLSearchXMLNode() */
/************************************************************************/
/**
* \brief Search for a node in document.
*
* Searches the children (and potentially siblings) of the documented
* passed in for the named element or attribute. To search following
* siblings as well as children, prefix the pszElement name with an equal
* sign. This function does an in-order traversal of the document tree.
* So it will first match against the current node, then its first child,
* that child's first child, and so on.
*
* Use CPLGetXMLNode() to find a specific child, or along a specific
* node path.
*
* @param psRoot the subtree to search. This should be a node of type
* CXT_Element. NULL is safe.
*
* @param pszElement the name of the element or attribute to search for.
*
* @return The matching node or NULL on failure.
*/
CPLXMLNode *CPLSearchXMLNode(CPLXMLNode *psRoot, const char *pszElement)
{
if (psRoot == nullptr || pszElement == nullptr)
return nullptr;
bool bSideSearch = false;
if (*pszElement == '=')
{
bSideSearch = true;
pszElement++;
}
/* -------------------------------------------------------------------- */
/* Does this node match? */
/* -------------------------------------------------------------------- */
if ((psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute) &&
EQUAL(pszElement, psRoot->pszValue))
return psRoot;
/* -------------------------------------------------------------------- */
/* Search children. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psChild = nullptr;
for (psChild = psRoot->psChild; psChild != nullptr;
psChild = psChild->psNext)
{
if ((psChild->eType == CXT_Element ||
psChild->eType == CXT_Attribute) &&
EQUAL(pszElement, psChild->pszValue))
return psChild;
if (psChild->psChild != nullptr)
{
CPLXMLNode *psResult = CPLSearchXMLNode(psChild, pszElement);
if (psResult != nullptr)
return psResult;
}
}
/* -------------------------------------------------------------------- */
/* Search siblings if we are in side search mode. */
/* -------------------------------------------------------------------- */
if (bSideSearch)
{
for (psRoot = psRoot->psNext; psRoot != nullptr;
psRoot = psRoot->psNext)
{
CPLXMLNode *psResult = CPLSearchXMLNode(psRoot, pszElement);
if (psResult != nullptr)
return psResult;
}
}
return nullptr;
}
/************************************************************************/
/* CPLGetXMLNode() */
/************************************************************************/
/**
* \brief Find node by path.
*
* Searches the document or subdocument indicated by psRoot for an element
* (or attribute) with the given path. The path should consist of a set of
* element names separated by dots, not including the name of the root
* element (psRoot). If the requested element is not found NULL is returned.
*
* Attribute names may only appear as the last item in the path.
*
* The search is done from the root nodes children, but all intermediate
* nodes in the path must be specified. Searching for "name" would only find
* a name element or attribute if it is a direct child of the root, not at any
* level in the subdocument.
*
* If the pszPath is prefixed by "=" then the search will begin with the
* root node, and its siblings, instead of the root nodes children. This
* is particularly useful when searching within a whole document which is
* often prefixed by one or more "junk" nodes like the <?xml> declaration.
*
* @param psRoot the subtree in which to search. This should be a node of
* type CXT_Element. NULL is safe.
*
* @param pszPath the list of element names in the path (dot separated).
*
* @return the requested element node, or NULL if not found.
*/
CPLXMLNode *CPLGetXMLNode(CPLXMLNode *psRoot, const char *pszPath)
{
if (psRoot == nullptr || pszPath == nullptr)
return nullptr;
bool bSideSearch = false;
if (*pszPath == '=')
{
bSideSearch = true;
pszPath++;
}
const char *const apszTokens[2] = {pszPath, nullptr};
// Slight optimization: avoid using CSLTokenizeStringComplex that
// does memory allocations when it is not really necessary.
bool bFreeTokens = false;
char **papszTokensToFree = nullptr;
const char *const *papszTokens;
if (strchr(pszPath, '.'))
{
papszTokensToFree =
CSLTokenizeStringComplex(pszPath, ".", FALSE, FALSE);
papszTokens = papszTokensToFree;
bFreeTokens = true;
}
else
{
papszTokens = apszTokens;
}
int iToken = 0;
while (papszTokens[iToken] != nullptr && psRoot != nullptr)
{
CPLXMLNode *psChild = nullptr;
if (bSideSearch)
{
psChild = psRoot;
bSideSearch = false;
}
else
psChild = psRoot->psChild;
for (; psChild != nullptr; psChild = psChild->psNext)
{
if (psChild->eType != CXT_Text &&
EQUAL(papszTokens[iToken], psChild->pszValue))
break;
}
if (psChild == nullptr)
{
psRoot = nullptr;
break;
}
psRoot = psChild;
iToken++;
}
if (bFreeTokens)
CSLDestroy(papszTokensToFree);
return psRoot;
}
/************************************************************************/
/* CPLGetXMLValue() */
/************************************************************************/
/**
* \brief Fetch element/attribute value.
*
* Searches the document for the element/attribute value associated with
* the path. The corresponding node is internally found with CPLGetXMLNode()
* (see there for details on path handling). Once found, the value is
* considered to be the first CXT_Text child of the node.
*
* If the attribute/element search fails, or if the found node has no
* value then the passed default value is returned.
*
* The returned value points to memory within the document tree, and should
* not be altered or freed.
*
* @param psRoot the subtree in which to search. This should be a node of
* type CXT_Element. NULL is safe.
*
* @param pszPath the list of element names in the path (dot separated). An
* empty path means get the value of the psRoot node.
*
* @param pszDefault the value to return if a corresponding value is not
* found, may be NULL.
*
* @return the requested value or pszDefault if not found.
*/
const char *CPLGetXMLValue(const CPLXMLNode *psRoot, const char *pszPath,
const char *pszDefault)
{
const CPLXMLNode *psTarget = nullptr;
if (pszPath == nullptr || *pszPath == '\0')
psTarget = psRoot;
else
psTarget = CPLGetXMLNode(psRoot, pszPath);
if (psTarget == nullptr)
return pszDefault;
if (psTarget->eType == CXT_Attribute)
{
CPLAssert(psTarget->psChild != nullptr &&
psTarget->psChild->eType == CXT_Text);
return psTarget->psChild->pszValue;
}
if (psTarget->eType == CXT_Element)
{
// Find first non-attribute child, and verify it is a single text
// with no siblings.
psTarget = psTarget->psChild;
while (psTarget != nullptr && psTarget->eType == CXT_Attribute)
psTarget = psTarget->psNext;
if (psTarget != nullptr && psTarget->eType == CXT_Text &&
psTarget->psNext == nullptr)
return psTarget->pszValue;
}
return pszDefault;
}
/************************************************************************/
/* CPLAddXMLChild() */
/************************************************************************/
/**
* \brief Add child node to parent.
*
* The passed child is added to the list of children of the indicated
* parent. Normally the child is added at the end of the parents child
* list, but attributes (CXT_Attribute) will be inserted after any other
* attributes but before any other element type. Ownership of the child
* node is effectively assumed by the parent node. If the child has
* siblings (its psNext is not NULL) they will be trimmed, but if the child
* has children they are carried with it.
*
* @param psParent the node to attach the child to. May not be NULL.
*
* @param psChild the child to add to the parent. May not be NULL. Should
* not be a child of any other parent.
*/
void CPLAddXMLChild(CPLXMLNode *psParent, CPLXMLNode *psChild)
{
if (psParent->psChild == nullptr)
{
psParent->psChild = psChild;
return;
}
// Insert at head of list if first child is not attribute.
if (psChild->eType == CXT_Attribute &&
psParent->psChild->eType != CXT_Attribute)
{
psChild->psNext = psParent->psChild;
psParent->psChild = psChild;
return;
}
// Search for end of list.
CPLXMLNode *psSib = nullptr;
for (psSib = psParent->psChild; psSib->psNext != nullptr;
psSib = psSib->psNext)
{
// Insert attributes if the next node is not an attribute.
if (psChild->eType == CXT_Attribute && psSib->psNext != nullptr &&
psSib->psNext->eType != CXT_Attribute)
{
psChild->psNext = psSib->psNext;
psSib->psNext = psChild;
return;
}
}
psSib->psNext = psChild;
}
/************************************************************************/
/* CPLRemoveXMLChild() */
/************************************************************************/
/**
* \brief Remove child node from parent.
*
* The passed child is removed from the child list of the passed parent,
* but the child is not destroyed. The child retains ownership of its
* own children, but is cleanly removed from the child list of the parent.
*
* @param psParent the node to the child is attached to.
*
* @param psChild the child to remove.
*
* @return TRUE on success or FALSE if the child was not found.
*/
int CPLRemoveXMLChild(CPLXMLNode *psParent, CPLXMLNode *psChild)
{
if (psParent == nullptr)
return FALSE;
CPLXMLNode *psLast = nullptr;
CPLXMLNode *psThis = nullptr;
for (psThis = psParent->psChild; psThis != nullptr; psThis = psThis->psNext)
{
if (psThis == psChild)
{
if (psLast == nullptr)
psParent->psChild = psThis->psNext;
else
psLast->psNext = psThis->psNext;
psThis->psNext = nullptr;
return TRUE;
}
psLast = psThis;
}
return FALSE;
}
/************************************************************************/
/* CPLAddXMLSibling() */
/************************************************************************/
/**
* \brief Add new sibling.
*
* The passed psNewSibling is added to the end of siblings of the
* psOlderSibling node. That is, it is added to the end of the psNext
* chain. There is no special handling if psNewSibling is an attribute.
* If this is required, use CPLAddXMLChild().
*
* @param psOlderSibling the node to attach the sibling after.
*
* @param psNewSibling the node to add at the end of psOlderSiblings psNext
* chain.
*/
void CPLAddXMLSibling(CPLXMLNode *psOlderSibling, CPLXMLNode *psNewSibling)
{
if (psOlderSibling == nullptr)
return;
while (psOlderSibling->psNext != nullptr)
psOlderSibling = psOlderSibling->psNext;
psOlderSibling->psNext = psNewSibling;
}
/************************************************************************/
/* CPLCreateXMLElementAndValue() */
/************************************************************************/
/**
* \brief Create an element and text value.
*
* This is function is a convenient short form for:
*
* \code
* CPLXMLNode *psTextNode;
* CPLXMLNode *psElementNode;
*
* psElementNode = CPLCreateXMLNode( psParent, CXT_Element, pszName );
* psTextNode = CPLCreateXMLNode( psElementNode, CXT_Text, pszValue );
*
* return psElementNode;
* \endcode
*
* It creates a CXT_Element node, with a CXT_Text child, and
* attaches the element to the passed parent.
*
* @param psParent the parent node to which the resulting node should
* be attached. May be NULL to keep as freestanding.
*
* @param pszName the element name to create.
* @param pszValue the text to attach to the element. Must not be NULL.
*
* @return the pointer to the new element node.
*/
CPLXMLNode *CPLCreateXMLElementAndValue(CPLXMLNode *psParent,
const char *pszName,
const char *pszValue)
{
CPLXMLNode *psElementNode =
CPLCreateXMLNode(psParent, CXT_Element, pszName);
CPLCreateXMLNode(psElementNode, CXT_Text, pszValue);
return psElementNode;
}
/************************************************************************/
/* CPLCreateXMLElementAndValue() */
/************************************************************************/
/**
* \brief Create an attribute and text value.
*
* This is function is a convenient short form for:
*
* \code
* CPLXMLNode *psAttributeNode;
*
* psAttributeNode = CPLCreateXMLNode( psParent, CXT_Attribute, pszName );
* CPLCreateXMLNode( psAttributeNode, CXT_Text, pszValue );
* \endcode
*
* It creates a CXT_Attribute node, with a CXT_Text child, and
* attaches the element to the passed parent.
*
* @param psParent the parent node to which the resulting node should
* be attached. Must not be NULL.
* @param pszName the attribute name to create.
* @param pszValue the text to attach to the attribute. Must not be NULL.
*
* @since GDAL 2.0
*/
void CPLAddXMLAttributeAndValue(CPLXMLNode *psParent, const char *pszName,
const char *pszValue)
{
CPLAssert(psParent != nullptr);
CPLXMLNode *psAttributeNode =
CPLCreateXMLNode(psParent, CXT_Attribute, pszName);
CPLCreateXMLNode(psAttributeNode, CXT_Text, pszValue);
}
/************************************************************************/
/* CPLCloneXMLTree() */
/************************************************************************/
/**
* \brief Copy tree.
*
* Creates a deep copy of a CPLXMLNode tree.
*
* @param psTree the tree to duplicate.
*
* @return a copy of the whole tree.
*/
CPLXMLNode *CPLCloneXMLTree(const CPLXMLNode *psTree)
{
CPLXMLNode *psPrevious = nullptr;
CPLXMLNode *psReturn = nullptr;
while (psTree != nullptr)
{
CPLXMLNode *psCopy =
CPLCreateXMLNode(nullptr, psTree->eType, psTree->pszValue);
if (psReturn == nullptr)
psReturn = psCopy;
if (psPrevious != nullptr)
psPrevious->psNext = psCopy;
if (psTree->psChild != nullptr)
psCopy->psChild = CPLCloneXMLTree(psTree->psChild);
psPrevious = psCopy;
psTree = psTree->psNext;
}
return psReturn;
}
/************************************************************************/
/* CPLSetXMLValue() */
/************************************************************************/
/**
* \brief Set element value by path.
*
* Find (or create) the target element or attribute specified in the
* path, and assign it the indicated value.
*
* Any path elements that do not already exist will be created. The target
* nodes value (the first CXT_Text child) will be replaced with the provided
* value.
*
* If the target node is an attribute instead of an element, the name
* should be prefixed with a #.
*
* Example:
* CPLSetXMLValue( "Citation.Id.Description", "DOQ dataset" );
* CPLSetXMLValue( "Citation.Id.Description.#name", "doq" );
*
* @param psRoot the subdocument to be updated.
*
* @param pszPath the dot separated path to the target element/attribute.
*
* @param pszValue the text value to assign.
*
* @return TRUE on success.
*/
int CPLSetXMLValue(CPLXMLNode *psRoot, const char *pszPath,
const char *pszValue)
{
char **papszTokens = CSLTokenizeStringComplex(pszPath, ".", FALSE, FALSE);
int iToken = 0;
while (papszTokens[iToken] != nullptr)
{
bool bIsAttribute = false;
const char *pszName = papszTokens[iToken];
if (pszName[0] == '#')
{
bIsAttribute = true;
pszName++;
}
if (psRoot->eType != CXT_Element)
{
CSLDestroy(papszTokens);
return FALSE;
}
CPLXMLNode *psChild = nullptr;
for (psChild = psRoot->psChild; psChild != nullptr;
psChild = psChild->psNext)
{
if (psChild->eType != CXT_Text && EQUAL(pszName, psChild->pszValue))
break;
}
if (psChild == nullptr)
{
if (bIsAttribute)
psChild = CPLCreateXMLNode(psRoot, CXT_Attribute, pszName);
else
psChild = CPLCreateXMLNode(psRoot, CXT_Element, pszName);
}
psRoot = psChild;
iToken++;
}
CSLDestroy(papszTokens);
/* -------------------------------------------------------------------- */
/* Find the "text" child if there is one. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psTextChild = psRoot->psChild;
while (psTextChild != nullptr && psTextChild->eType != CXT_Text)
psTextChild = psTextChild->psNext;
/* -------------------------------------------------------------------- */
/* Now set a value node under this node. */
/* -------------------------------------------------------------------- */
if (psTextChild == nullptr)
CPLCreateXMLNode(psRoot, CXT_Text, pszValue);
else
{
CPLFree(psTextChild->pszValue);
psTextChild->pszValue = CPLStrdup(pszValue);
}
return TRUE;
}
/************************************************************************/
/* CPLStripXMLNamespace() */
/************************************************************************/
/**
* \brief Strip indicated namespaces.
*
* The subdocument (psRoot) is recursively examined, and any elements
* with the indicated namespace prefix will have the namespace prefix
* stripped from the element names. If the passed namespace is NULL, then
* all namespace prefixes will be stripped.
*
* Nodes other than elements should remain unaffected. The changes are
* made "in place", and should not alter any node locations, only the
* pszValue field of affected nodes.
*
* @param psRoot the document to operate on.
* @param pszNamespace the name space prefix (not including colon), or NULL.
* @param bRecurse TRUE to recurse over whole document, or FALSE to only
* operate on the passed node.
*/
void CPLStripXMLNamespace(CPLXMLNode *psRoot, const char *pszNamespace,
int bRecurse)
{
size_t nNameSpaceLen = (pszNamespace) ? strlen(pszNamespace) : 0;
while (psRoot != nullptr)
{
if (psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute)
{
if (pszNamespace != nullptr)
{
if (EQUALN(pszNamespace, psRoot->pszValue, nNameSpaceLen) &&
psRoot->pszValue[nNameSpaceLen] == ':')
{
memmove(psRoot->pszValue,
psRoot->pszValue + nNameSpaceLen + 1,
strlen(psRoot->pszValue + nNameSpaceLen + 1) + 1);
}
}
else
{
for (const char *pszCheck = psRoot->pszValue; *pszCheck != '\0';
pszCheck++)
{
if (*pszCheck == ':')
{
memmove(psRoot->pszValue, pszCheck + 1,
strlen(pszCheck + 1) + 1);
break;
}
}
}
}
if (bRecurse)
{
if (psRoot->psChild != nullptr)
CPLStripXMLNamespace(psRoot->psChild, pszNamespace, 1);
psRoot = psRoot->psNext;
}
else
{
break;
}
}
}
/************************************************************************/
/* CPLParseXMLFile() */
/************************************************************************/
/**
* \brief Parse XML file into tree.
*
* The named file is opened, loaded into memory as a big string, and
* parsed with CPLParseXMLString(). Errors in reading the file or parsing
* the XML will be reported by CPLError().
*
* The "large file" API is used, so XML files can come from virtualized
* files.
*
* @param pszFilename the file to open.
*
* @return NULL on failure, or the document tree on success.
*/
CPLXMLNode *CPLParseXMLFile(const char *pszFilename)
{
/* -------------------------------------------------------------------- */
/* Ingest the file. */
/* -------------------------------------------------------------------- */
GByte *pabyOut = nullptr;
if (!VSIIngestFile(nullptr, pszFilename, &pabyOut, nullptr, -1))
return nullptr;
char *pszDoc = reinterpret_cast<char *>(pabyOut);
/* -------------------------------------------------------------------- */
/* Parse it. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psTree = CPLParseXMLString(pszDoc);
CPLFree(pszDoc);
return psTree;
}
/************************************************************************/
/* CPLSerializeXMLTreeToFile() */
/************************************************************************/
/**
* \brief Write document tree to a file.
*
* The passed document tree is converted into one big string (with
* CPLSerializeXMLTree()) and then written to the named file. Errors writing
* the file will be reported by CPLError(). The source document tree is
* not altered. If the output file already exists it will be overwritten.
*
* @param psTree the document tree to write.
* @param pszFilename the name of the file to write to.
* @return TRUE on success, FALSE otherwise.
*/
int CPLSerializeXMLTreeToFile(const CPLXMLNode *psTree, const char *pszFilename)
{
/* -------------------------------------------------------------------- */
/* Serialize document. */
/* -------------------------------------------------------------------- */
char *pszDoc = CPLSerializeXMLTree(psTree);
if (pszDoc == nullptr)
return FALSE;
const vsi_l_offset nLength = strlen(pszDoc);
/* -------------------------------------------------------------------- */
/* Create file. */
/* -------------------------------------------------------------------- */
VSILFILE *fp = VSIFOpenL(pszFilename, "wt");
if (fp == nullptr)
{
CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open %.500s to write.",
pszFilename);
CPLFree(pszDoc);
return FALSE;
}
/* -------------------------------------------------------------------- */
/* Write file. */
/* -------------------------------------------------------------------- */
if (VSIFWriteL(pszDoc, 1, static_cast<size_t>(nLength), fp) != nLength)
{
CPLError(CE_Failure, CPLE_FileIO,
"Failed to write whole XML document (%.500s).", pszFilename);
CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
CPLFree(pszDoc);
return FALSE;
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
const bool bRet = VSIFCloseL(fp) == 0;
if (!bRet)
{
CPLError(CE_Failure, CPLE_FileIO,
"Failed to write whole XML document (%.500s).", pszFilename);
}
CPLFree(pszDoc);
return bRet;
}
/************************************************************************/
/* CPLCleanXMLElementName() */
/************************************************************************/
/**
* \brief Make string into safe XML token.
*
* Modifies a string in place to try and make it into a legal
* XML token that can be used as an element name. This is accomplished
* by changing any characters not legal in a token into an underscore.
*
* NOTE: This function should implement the rules in section 2.3 of
* http://www.w3.org/TR/xml11/ but it doesn't yet do that properly. We
* only do a rough approximation of that.
*
* @param pszTarget the string to be adjusted. It is altered in place.
*/
void CPLCleanXMLElementName(char *pszTarget)
{
if (pszTarget == nullptr)
return;
for (; *pszTarget != '\0'; pszTarget++)
{
if ((*(reinterpret_cast<unsigned char *>(pszTarget)) & 0x80) ||
isalnum(*pszTarget) || *pszTarget == '_' || *pszTarget == '.')
{
// Ok.
}
else
{
*pszTarget = '_';
}
}
}
/************************************************************************/
/* CPLXMLTreeCloser::getDocumentElement() */
/************************************************************************/
CPLXMLNode *CPLXMLTreeCloser::getDocumentElement()
{
CPLXMLNode *doc = get();
// skip the Declaration and assume the next is the root element
while (doc != nullptr &&
(doc->eType != CXT_Element || doc->pszValue[0] == '?'))
{
doc = doc->psNext;
}
return doc;
}
|