xmlwf.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. /*
  2. __ __ _
  3. ___\ \/ /_ __ __ _| |_
  4. / _ \\ /| '_ \ / _` | __|
  5. | __// \| |_) | (_| | |_
  6. \___/_/\_\ .__/ \__,_|\__|
  7. |_| XML parser
  8. Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
  9. Copyright (c) 2000 Clark Cooper <[email protected]>
  10. Copyright (c) 2001-2003 Fred L. Drake, Jr. <[email protected]>
  11. Copyright (c) 2004-2009 Karl Waclawek <[email protected]>
  12. Copyright (c) 2005-2007 Steven Solie <[email protected]>
  13. Copyright (c) 2016-2025 Sebastian Pipping <[email protected]>
  14. Copyright (c) 2017 Rhodri James <[email protected]>
  15. Copyright (c) 2019 David Loffredo <[email protected]>
  16. Copyright (c) 2020 Joe Orton <[email protected]>
  17. Copyright (c) 2020 Kleber Tarcísio <[email protected]>
  18. Copyright (c) 2021 Tim Bray <[email protected]>
  19. Copyright (c) 2022 Martin Ettl <[email protected]>
  20. Copyright (c) 2022 Sean McBride <[email protected]>
  21. Licensed under the MIT license:
  22. Permission is hereby granted, free of charge, to any person obtaining
  23. a copy of this software and associated documentation files (the
  24. "Software"), to deal in the Software without restriction, including
  25. without limitation the rights to use, copy, modify, merge, publish,
  26. distribute, sublicense, and/or sell copies of the Software, and to permit
  27. persons to whom the Software is furnished to do so, subject to the
  28. following conditions:
  29. The above copyright notice and this permission notice shall be included
  30. in all copies or substantial portions of the Software.
  31. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  32. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  34. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  35. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  36. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  37. USE OR OTHER DEALINGS IN THE SOFTWARE.
  38. */
  39. #include "expat_config.h"
  40. #include <assert.h>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <stddef.h>
  44. #include <string.h>
  45. #include <math.h> /* for isnan */
  46. #include <errno.h>
  47. #include "expat.h"
  48. #include "codepage.h"
  49. #include "internal.h" /* for UNUSED_P only */
  50. #include "xmlfile.h"
  51. #include "xmltchar.h"
  52. #ifdef _MSC_VER
  53. # include <crtdbg.h>
  54. #endif
  55. #ifdef XML_UNICODE
  56. # include <wchar.h>
  57. #endif
  58. enum ExitCode {
  59. XMLWF_EXIT_SUCCESS = 0,
  60. XMLWF_EXIT_INTERNAL_ERROR = 1,
  61. XMLWF_EXIT_NOT_WELLFORMED = 2,
  62. XMLWF_EXIT_OUTPUT_ERROR = 3,
  63. XMLWF_EXIT_USAGE_ERROR = 4,
  64. };
  65. /* Structures for handler user data */
  66. typedef struct NotationList {
  67. struct NotationList *next;
  68. const XML_Char *notationName;
  69. const XML_Char *systemId;
  70. const XML_Char *publicId;
  71. } NotationList;
  72. typedef struct xmlwfUserData {
  73. FILE *fp;
  74. NotationList *notationListHead;
  75. const XML_Char *currentDoctypeName;
  76. } XmlwfUserData;
  77. /* This ensures proper sorting. */
  78. #define NSSEP T('\001')
  79. static void XMLCALL
  80. characterData(void *userData, const XML_Char *s, int len) {
  81. FILE *fp = ((XmlwfUserData *)userData)->fp;
  82. for (; len > 0; --len, ++s) {
  83. switch (*s) {
  84. case T('&'):
  85. fputts(T("&amp;"), fp);
  86. break;
  87. case T('<'):
  88. fputts(T("&lt;"), fp);
  89. break;
  90. case T('>'):
  91. fputts(T("&gt;"), fp);
  92. break;
  93. #ifdef W3C14N
  94. case 13:
  95. fputts(T("&#xD;"), fp);
  96. break;
  97. #else
  98. case T('"'):
  99. fputts(T("&quot;"), fp);
  100. break;
  101. case 9:
  102. case 10:
  103. case 13:
  104. ftprintf(fp, T("&#%d;"), *s);
  105. break;
  106. #endif
  107. default:
  108. puttc(*s, fp);
  109. break;
  110. }
  111. }
  112. }
  113. static void
  114. attributeValue(FILE *fp, const XML_Char *s) {
  115. puttc(T('='), fp);
  116. puttc(T('"'), fp);
  117. assert(s);
  118. for (;;) {
  119. switch (*s) {
  120. case 0:
  121. case NSSEP:
  122. puttc(T('"'), fp);
  123. return;
  124. case T('&'):
  125. fputts(T("&amp;"), fp);
  126. break;
  127. case T('<'):
  128. fputts(T("&lt;"), fp);
  129. break;
  130. case T('"'):
  131. fputts(T("&quot;"), fp);
  132. break;
  133. #ifdef W3C14N
  134. case 9:
  135. fputts(T("&#x9;"), fp);
  136. break;
  137. case 10:
  138. fputts(T("&#xA;"), fp);
  139. break;
  140. case 13:
  141. fputts(T("&#xD;"), fp);
  142. break;
  143. #else
  144. case T('>'):
  145. fputts(T("&gt;"), fp);
  146. break;
  147. case 9:
  148. case 10:
  149. case 13:
  150. ftprintf(fp, T("&#%d;"), *s);
  151. break;
  152. #endif
  153. default:
  154. puttc(*s, fp);
  155. break;
  156. }
  157. s++;
  158. }
  159. }
  160. /* Lexicographically comparing UTF-8 encoded attribute values,
  161. is equivalent to lexicographically comparing based on the character number. */
  162. static int
  163. attcmp(const void *att1, const void *att2) {
  164. return tcscmp(*(const XML_Char *const *)att1, *(const XML_Char *const *)att2);
  165. }
  166. static void XMLCALL
  167. startElement(void *userData, const XML_Char *name, const XML_Char **atts) {
  168. int nAtts;
  169. const XML_Char **p;
  170. FILE *fp = ((XmlwfUserData *)userData)->fp;
  171. puttc(T('<'), fp);
  172. fputts(name, fp);
  173. p = atts;
  174. while (*p)
  175. ++p;
  176. nAtts = (int)((p - atts) >> 1);
  177. if (nAtts > 1)
  178. qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, attcmp);
  179. while (*atts) {
  180. puttc(T(' '), fp);
  181. fputts(*atts++, fp);
  182. attributeValue(fp, *atts);
  183. atts++;
  184. }
  185. puttc(T('>'), fp);
  186. }
  187. static void XMLCALL
  188. endElement(void *userData, const XML_Char *name) {
  189. FILE *fp = ((XmlwfUserData *)userData)->fp;
  190. puttc(T('<'), fp);
  191. puttc(T('/'), fp);
  192. fputts(name, fp);
  193. puttc(T('>'), fp);
  194. }
  195. static int
  196. nsattcmp(const void *p1, const void *p2) {
  197. const XML_Char *att1 = *(const XML_Char *const *)p1;
  198. const XML_Char *att2 = *(const XML_Char *const *)p2;
  199. int sep1 = (tcsrchr(att1, NSSEP) != 0);
  200. int sep2 = (tcsrchr(att2, NSSEP) != 0);
  201. if (sep1 != sep2)
  202. return sep1 - sep2;
  203. return tcscmp(att1, att2);
  204. }
  205. static void XMLCALL
  206. startElementNS(void *userData, const XML_Char *name, const XML_Char **atts) {
  207. int nAtts;
  208. int nsi;
  209. const XML_Char **p;
  210. FILE *fp = ((XmlwfUserData *)userData)->fp;
  211. const XML_Char *sep;
  212. puttc(T('<'), fp);
  213. sep = tcsrchr(name, NSSEP);
  214. if (sep) {
  215. fputts(T("n1:"), fp);
  216. fputts(sep + 1, fp);
  217. fputts(T(" xmlns:n1"), fp);
  218. attributeValue(fp, name);
  219. nsi = 2;
  220. } else {
  221. fputts(name, fp);
  222. nsi = 1;
  223. }
  224. p = atts;
  225. while (*p)
  226. ++p;
  227. nAtts = (int)((p - atts) >> 1);
  228. if (nAtts > 1)
  229. qsort((void *)atts, nAtts, sizeof(XML_Char *) * 2, nsattcmp);
  230. while (*atts) {
  231. name = *atts++;
  232. sep = tcsrchr(name, NSSEP);
  233. puttc(T(' '), fp);
  234. if (sep) {
  235. ftprintf(fp, T("n%d:"), nsi);
  236. fputts(sep + 1, fp);
  237. } else
  238. fputts(name, fp);
  239. attributeValue(fp, *atts);
  240. if (sep) {
  241. ftprintf(fp, T(" xmlns:n%d"), nsi++);
  242. attributeValue(fp, name);
  243. }
  244. atts++;
  245. }
  246. puttc(T('>'), fp);
  247. }
  248. static void XMLCALL
  249. endElementNS(void *userData, const XML_Char *name) {
  250. FILE *fp = ((XmlwfUserData *)userData)->fp;
  251. const XML_Char *sep;
  252. puttc(T('<'), fp);
  253. puttc(T('/'), fp);
  254. sep = tcsrchr(name, NSSEP);
  255. if (sep) {
  256. fputts(T("n1:"), fp);
  257. fputts(sep + 1, fp);
  258. } else
  259. fputts(name, fp);
  260. puttc(T('>'), fp);
  261. }
  262. #ifndef W3C14N
  263. static void XMLCALL
  264. processingInstruction(void *userData, const XML_Char *target,
  265. const XML_Char *data) {
  266. FILE *fp = ((XmlwfUserData *)userData)->fp;
  267. puttc(T('<'), fp);
  268. puttc(T('?'), fp);
  269. fputts(target, fp);
  270. puttc(T(' '), fp);
  271. fputts(data, fp);
  272. puttc(T('?'), fp);
  273. puttc(T('>'), fp);
  274. }
  275. static XML_Char *
  276. xcsdup(const XML_Char *s) {
  277. XML_Char *result;
  278. int count = 0;
  279. size_t numBytes;
  280. /* Get the length of the string, including terminator */
  281. while (s[count++] != 0) {
  282. /* Do nothing */
  283. }
  284. numBytes = count * sizeof(XML_Char);
  285. result = malloc(numBytes);
  286. if (result == NULL)
  287. return NULL;
  288. memcpy(result, s, numBytes);
  289. return result;
  290. }
  291. static void XMLCALL
  292. startDoctypeDecl(void *userData, const XML_Char *doctypeName,
  293. const XML_Char *sysid, const XML_Char *publid,
  294. int has_internal_subset) {
  295. XmlwfUserData *data = (XmlwfUserData *)userData;
  296. UNUSED_P(sysid);
  297. UNUSED_P(publid);
  298. UNUSED_P(has_internal_subset);
  299. data->currentDoctypeName = xcsdup(doctypeName);
  300. }
  301. static void
  302. freeNotations(XmlwfUserData *data) {
  303. NotationList *notationListHead = data->notationListHead;
  304. while (notationListHead != NULL) {
  305. NotationList *next = notationListHead->next;
  306. free((void *)notationListHead->notationName);
  307. free((void *)notationListHead->systemId);
  308. free((void *)notationListHead->publicId);
  309. free(notationListHead);
  310. notationListHead = next;
  311. }
  312. data->notationListHead = NULL;
  313. }
  314. static void
  315. cleanupUserData(XmlwfUserData *userData) {
  316. free((void *)userData->currentDoctypeName);
  317. userData->currentDoctypeName = NULL;
  318. freeNotations(userData);
  319. }
  320. static int
  321. xcscmp(const XML_Char *xs, const XML_Char *xt) {
  322. while (*xs != 0 && *xt != 0) {
  323. if (*xs < *xt)
  324. return -1;
  325. if (*xs > *xt)
  326. return 1;
  327. xs++;
  328. xt++;
  329. }
  330. if (*xs < *xt)
  331. return -1;
  332. if (*xs > *xt)
  333. return 1;
  334. return 0;
  335. }
  336. static int
  337. notationCmp(const void *a, const void *b) {
  338. const NotationList *const n1 = *(const NotationList *const *)a;
  339. const NotationList *const n2 = *(const NotationList *const *)b;
  340. return xcscmp(n1->notationName, n2->notationName);
  341. }
  342. static void XMLCALL
  343. endDoctypeDecl(void *userData) {
  344. XmlwfUserData *data = (XmlwfUserData *)userData;
  345. NotationList **notations;
  346. int notationCount = 0;
  347. NotationList *p;
  348. int i;
  349. /* How many notations do we have? */
  350. for (p = data->notationListHead; p != NULL; p = p->next)
  351. notationCount++;
  352. if (notationCount == 0) {
  353. /* Nothing to report */
  354. free((void *)data->currentDoctypeName);
  355. data->currentDoctypeName = NULL;
  356. return;
  357. }
  358. notations = malloc(notationCount * sizeof(NotationList *));
  359. if (notations == NULL) {
  360. fprintf(stderr, "Unable to sort notations");
  361. freeNotations(data);
  362. return;
  363. }
  364. for (p = data->notationListHead, i = 0; i < notationCount; p = p->next, i++) {
  365. notations[i] = p;
  366. }
  367. qsort(notations, notationCount, sizeof(NotationList *), notationCmp);
  368. /* Output the DOCTYPE header */
  369. fputts(T("<!DOCTYPE "), data->fp);
  370. fputts(data->currentDoctypeName, data->fp);
  371. fputts(T(" [\n"), data->fp);
  372. /* Now the NOTATIONs */
  373. for (i = 0; i < notationCount; i++) {
  374. fputts(T("<!NOTATION "), data->fp);
  375. fputts(notations[i]->notationName, data->fp);
  376. if (notations[i]->publicId != NULL) {
  377. fputts(T(" PUBLIC '"), data->fp);
  378. fputts(notations[i]->publicId, data->fp);
  379. puttc(T('\''), data->fp);
  380. if (notations[i]->systemId != NULL) {
  381. puttc(T(' '), data->fp);
  382. puttc(T('\''), data->fp);
  383. fputts(notations[i]->systemId, data->fp);
  384. puttc(T('\''), data->fp);
  385. }
  386. } else if (notations[i]->systemId != NULL) {
  387. fputts(T(" SYSTEM '"), data->fp);
  388. fputts(notations[i]->systemId, data->fp);
  389. puttc(T('\''), data->fp);
  390. }
  391. puttc(T('>'), data->fp);
  392. puttc(T('\n'), data->fp);
  393. }
  394. /* Finally end the DOCTYPE */
  395. fputts(T("]>\n"), data->fp);
  396. free(notations);
  397. freeNotations(data);
  398. free((void *)data->currentDoctypeName);
  399. data->currentDoctypeName = NULL;
  400. }
  401. static void XMLCALL
  402. notationDecl(void *userData, const XML_Char *notationName, const XML_Char *base,
  403. const XML_Char *systemId, const XML_Char *publicId) {
  404. XmlwfUserData *data = (XmlwfUserData *)userData;
  405. NotationList *entry = malloc(sizeof(NotationList));
  406. const char *errorMessage = "Unable to store NOTATION for output\n";
  407. UNUSED_P(base);
  408. if (entry == NULL) {
  409. fputs(errorMessage, stderr);
  410. return; /* Nothing we can really do about this */
  411. }
  412. entry->notationName = xcsdup(notationName);
  413. if (entry->notationName == NULL) {
  414. fputs(errorMessage, stderr);
  415. free(entry);
  416. return;
  417. }
  418. if (systemId != NULL) {
  419. entry->systemId = xcsdup(systemId);
  420. if (entry->systemId == NULL) {
  421. fputs(errorMessage, stderr);
  422. free((void *)entry->notationName);
  423. free(entry);
  424. return;
  425. }
  426. } else {
  427. entry->systemId = NULL;
  428. }
  429. if (publicId != NULL) {
  430. entry->publicId = xcsdup(publicId);
  431. if (entry->publicId == NULL) {
  432. fputs(errorMessage, stderr);
  433. free((void *)entry->systemId); /* Safe if it's NULL */
  434. free((void *)entry->notationName);
  435. free(entry);
  436. return;
  437. }
  438. } else {
  439. entry->publicId = NULL;
  440. }
  441. entry->next = data->notationListHead;
  442. data->notationListHead = entry;
  443. }
  444. #endif /* not W3C14N */
  445. static void XMLCALL
  446. defaultCharacterData(void *userData, const XML_Char *s, int len) {
  447. UNUSED_P(s);
  448. UNUSED_P(len);
  449. XML_DefaultCurrent((XML_Parser)userData);
  450. }
  451. static void XMLCALL
  452. defaultStartElement(void *userData, const XML_Char *name,
  453. const XML_Char **atts) {
  454. UNUSED_P(name);
  455. UNUSED_P(atts);
  456. XML_DefaultCurrent((XML_Parser)userData);
  457. }
  458. static void XMLCALL
  459. defaultEndElement(void *userData, const XML_Char *name) {
  460. UNUSED_P(name);
  461. XML_DefaultCurrent((XML_Parser)userData);
  462. }
  463. static void XMLCALL
  464. defaultProcessingInstruction(void *userData, const XML_Char *target,
  465. const XML_Char *data) {
  466. UNUSED_P(target);
  467. UNUSED_P(data);
  468. XML_DefaultCurrent((XML_Parser)userData);
  469. }
  470. static void XMLCALL
  471. nopCharacterData(void *userData, const XML_Char *s, int len) {
  472. UNUSED_P(userData);
  473. UNUSED_P(s);
  474. UNUSED_P(len);
  475. }
  476. static void XMLCALL
  477. nopStartElement(void *userData, const XML_Char *name, const XML_Char **atts) {
  478. UNUSED_P(userData);
  479. UNUSED_P(name);
  480. UNUSED_P(atts);
  481. }
  482. static void XMLCALL
  483. nopEndElement(void *userData, const XML_Char *name) {
  484. UNUSED_P(userData);
  485. UNUSED_P(name);
  486. }
  487. static void XMLCALL
  488. nopProcessingInstruction(void *userData, const XML_Char *target,
  489. const XML_Char *data) {
  490. UNUSED_P(userData);
  491. UNUSED_P(target);
  492. UNUSED_P(data);
  493. }
  494. static void XMLCALL
  495. markup(void *userData, const XML_Char *s, int len) {
  496. FILE *fp = ((XmlwfUserData *)XML_GetUserData((XML_Parser)userData))->fp;
  497. for (; len > 0; --len, ++s)
  498. puttc(*s, fp);
  499. }
  500. static void
  501. metaLocation(XML_Parser parser) {
  502. const XML_Char *uri = XML_GetBase(parser);
  503. FILE *fp = ((XmlwfUserData *)XML_GetUserData(parser))->fp;
  504. if (uri)
  505. ftprintf(fp, T(" uri=\"%s\""), uri);
  506. ftprintf(fp,
  507. T(" byte=\"%") T(XML_FMT_INT_MOD) T("d\"") T(" nbytes=\"%d\"")
  508. T(" line=\"%") T(XML_FMT_INT_MOD) T("u\"") T(" col=\"%")
  509. T(XML_FMT_INT_MOD) T("u\""),
  510. XML_GetCurrentByteIndex(parser), XML_GetCurrentByteCount(parser),
  511. XML_GetCurrentLineNumber(parser),
  512. XML_GetCurrentColumnNumber(parser));
  513. }
  514. static void
  515. metaStartDocument(void *userData) {
  516. fputts(T("<document>\n"),
  517. ((XmlwfUserData *)XML_GetUserData((XML_Parser)userData))->fp);
  518. }
  519. static void
  520. metaEndDocument(void *userData) {
  521. fputts(T("</document>\n"),
  522. ((XmlwfUserData *)XML_GetUserData((XML_Parser)userData))->fp);
  523. }
  524. static void XMLCALL
  525. metaStartElement(void *userData, const XML_Char *name, const XML_Char **atts) {
  526. XML_Parser parser = (XML_Parser)userData;
  527. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  528. FILE *fp = data->fp;
  529. const XML_Char **specifiedAttsEnd
  530. = atts + XML_GetSpecifiedAttributeCount(parser);
  531. const XML_Char **idAttPtr;
  532. int idAttIndex = XML_GetIdAttributeIndex(parser);
  533. if (idAttIndex < 0)
  534. idAttPtr = 0;
  535. else
  536. idAttPtr = atts + idAttIndex;
  537. ftprintf(fp, T("<starttag name=\"%s\""), name);
  538. metaLocation(parser);
  539. if (*atts) {
  540. fputts(T(">\n"), fp);
  541. do {
  542. ftprintf(fp, T("<attribute name=\"%s\" value=\""), atts[0]);
  543. characterData(data, atts[1], (int)tcslen(atts[1]));
  544. if (atts >= specifiedAttsEnd)
  545. fputts(T("\" defaulted=\"yes\"/>\n"), fp);
  546. else if (atts == idAttPtr)
  547. fputts(T("\" id=\"yes\"/>\n"), fp);
  548. else
  549. fputts(T("\"/>\n"), fp);
  550. } while (*(atts += 2));
  551. fputts(T("</starttag>\n"), fp);
  552. } else
  553. fputts(T("/>\n"), fp);
  554. }
  555. static void XMLCALL
  556. metaEndElement(void *userData, const XML_Char *name) {
  557. XML_Parser parser = (XML_Parser)userData;
  558. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  559. FILE *fp = data->fp;
  560. ftprintf(fp, T("<endtag name=\"%s\""), name);
  561. metaLocation(parser);
  562. fputts(T("/>\n"), fp);
  563. }
  564. static void XMLCALL
  565. metaProcessingInstruction(void *userData, const XML_Char *target,
  566. const XML_Char *data) {
  567. XML_Parser parser = (XML_Parser)userData;
  568. XmlwfUserData *usrData = (XmlwfUserData *)XML_GetUserData(parser);
  569. FILE *fp = usrData->fp;
  570. ftprintf(fp, T("<pi target=\"%s\" data=\""), target);
  571. characterData(usrData, data, (int)tcslen(data));
  572. puttc(T('"'), fp);
  573. metaLocation(parser);
  574. fputts(T("/>\n"), fp);
  575. }
  576. static void XMLCALL
  577. metaComment(void *userData, const XML_Char *data) {
  578. XML_Parser parser = (XML_Parser)userData;
  579. XmlwfUserData *usrData = (XmlwfUserData *)XML_GetUserData(parser);
  580. FILE *fp = usrData->fp;
  581. fputts(T("<comment data=\""), fp);
  582. characterData(usrData, data, (int)tcslen(data));
  583. puttc(T('"'), fp);
  584. metaLocation(parser);
  585. fputts(T("/>\n"), fp);
  586. }
  587. static void XMLCALL
  588. metaStartCdataSection(void *userData) {
  589. XML_Parser parser = (XML_Parser)userData;
  590. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  591. FILE *fp = data->fp;
  592. fputts(T("<startcdata"), fp);
  593. metaLocation(parser);
  594. fputts(T("/>\n"), fp);
  595. }
  596. static void XMLCALL
  597. metaEndCdataSection(void *userData) {
  598. XML_Parser parser = (XML_Parser)userData;
  599. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  600. FILE *fp = data->fp;
  601. fputts(T("<endcdata"), fp);
  602. metaLocation(parser);
  603. fputts(T("/>\n"), fp);
  604. }
  605. static void XMLCALL
  606. metaCharacterData(void *userData, const XML_Char *s, int len) {
  607. XML_Parser parser = (XML_Parser)userData;
  608. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  609. FILE *fp = data->fp;
  610. fputts(T("<chars str=\""), fp);
  611. characterData(data, s, len);
  612. puttc(T('"'), fp);
  613. metaLocation(parser);
  614. fputts(T("/>\n"), fp);
  615. }
  616. static void XMLCALL
  617. metaStartDoctypeDecl(void *userData, const XML_Char *doctypeName,
  618. const XML_Char *sysid, const XML_Char *pubid,
  619. int has_internal_subset) {
  620. XML_Parser parser = (XML_Parser)userData;
  621. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  622. FILE *fp = data->fp;
  623. UNUSED_P(sysid);
  624. UNUSED_P(pubid);
  625. UNUSED_P(has_internal_subset);
  626. ftprintf(fp, T("<startdoctype name=\"%s\""), doctypeName);
  627. metaLocation(parser);
  628. fputts(T("/>\n"), fp);
  629. }
  630. static void XMLCALL
  631. metaEndDoctypeDecl(void *userData) {
  632. XML_Parser parser = (XML_Parser)userData;
  633. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  634. FILE *fp = data->fp;
  635. fputts(T("<enddoctype"), fp);
  636. metaLocation(parser);
  637. fputts(T("/>\n"), fp);
  638. }
  639. static void XMLCALL
  640. metaNotationDecl(void *userData, const XML_Char *notationName,
  641. const XML_Char *base, const XML_Char *systemId,
  642. const XML_Char *publicId) {
  643. XML_Parser parser = (XML_Parser)userData;
  644. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  645. FILE *fp = data->fp;
  646. UNUSED_P(base);
  647. ftprintf(fp, T("<notation name=\"%s\""), notationName);
  648. if (publicId)
  649. ftprintf(fp, T(" public=\"%s\""), publicId);
  650. if (systemId) {
  651. fputts(T(" system=\""), fp);
  652. characterData(data, systemId, (int)tcslen(systemId));
  653. puttc(T('"'), fp);
  654. }
  655. metaLocation(parser);
  656. fputts(T("/>\n"), fp);
  657. }
  658. static void XMLCALL
  659. metaEntityDecl(void *userData, const XML_Char *entityName, int is_param,
  660. const XML_Char *value, int value_length, const XML_Char *base,
  661. const XML_Char *systemId, const XML_Char *publicId,
  662. const XML_Char *notationName) {
  663. XML_Parser parser = (XML_Parser)userData;
  664. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  665. FILE *fp = data->fp;
  666. UNUSED_P(is_param);
  667. UNUSED_P(base);
  668. if (value) {
  669. ftprintf(fp, T("<entity name=\"%s\""), entityName);
  670. metaLocation(parser);
  671. puttc(T('>'), fp);
  672. characterData(data, value, value_length);
  673. fputts(T("</entity/>\n"), fp);
  674. } else if (notationName) {
  675. ftprintf(fp, T("<entity name=\"%s\""), entityName);
  676. if (publicId)
  677. ftprintf(fp, T(" public=\"%s\""), publicId);
  678. fputts(T(" system=\""), fp);
  679. characterData(data, systemId, (int)tcslen(systemId));
  680. puttc(T('"'), fp);
  681. ftprintf(fp, T(" notation=\"%s\""), notationName);
  682. metaLocation(parser);
  683. fputts(T("/>\n"), fp);
  684. } else {
  685. ftprintf(fp, T("<entity name=\"%s\""), entityName);
  686. if (publicId)
  687. ftprintf(fp, T(" public=\"%s\""), publicId);
  688. fputts(T(" system=\""), fp);
  689. characterData(data, systemId, (int)tcslen(systemId));
  690. puttc(T('"'), fp);
  691. metaLocation(parser);
  692. fputts(T("/>\n"), fp);
  693. }
  694. }
  695. static void XMLCALL
  696. metaStartNamespaceDecl(void *userData, const XML_Char *prefix,
  697. const XML_Char *uri) {
  698. XML_Parser parser = (XML_Parser)userData;
  699. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  700. FILE *fp = data->fp;
  701. fputts(T("<startns"), fp);
  702. if (prefix)
  703. ftprintf(fp, T(" prefix=\"%s\""), prefix);
  704. if (uri) {
  705. fputts(T(" ns=\""), fp);
  706. characterData(data, uri, (int)tcslen(uri));
  707. fputts(T("\"/>\n"), fp);
  708. } else
  709. fputts(T("/>\n"), fp);
  710. }
  711. static void XMLCALL
  712. metaEndNamespaceDecl(void *userData, const XML_Char *prefix) {
  713. XML_Parser parser = (XML_Parser)userData;
  714. XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
  715. FILE *fp = data->fp;
  716. if (! prefix)
  717. fputts(T("<endns/>\n"), fp);
  718. else
  719. ftprintf(fp, T("<endns prefix=\"%s\"/>\n"), prefix);
  720. }
  721. static int XMLCALL
  722. unknownEncodingConvert(void *data, const char *p) {
  723. return codepageConvert(*(int *)data, p);
  724. }
  725. static int XMLCALL
  726. unknownEncoding(void *userData, const XML_Char *name, XML_Encoding *info) {
  727. int cp;
  728. static const XML_Char prefixL[] = T("windows-");
  729. static const XML_Char prefixU[] = T("WINDOWS-");
  730. int i;
  731. UNUSED_P(userData);
  732. for (i = 0; prefixU[i]; i++)
  733. if (name[i] != prefixU[i] && name[i] != prefixL[i])
  734. return 0;
  735. cp = 0;
  736. for (; name[i]; i++) {
  737. static const XML_Char digits[] = T("0123456789");
  738. const XML_Char *s = tcschr(digits, name[i]);
  739. if (! s)
  740. return 0;
  741. cp *= 10;
  742. cp += (int)(s - digits);
  743. if (cp >= 0x10000)
  744. return 0;
  745. }
  746. if (! codepageMap(cp, info->map))
  747. return 0;
  748. info->convert = unknownEncodingConvert;
  749. /* We could just cast the code page integer to a void *,
  750. and avoid the use of release. */
  751. info->release = free;
  752. info->data = malloc(sizeof(int));
  753. if (! info->data)
  754. return 0;
  755. *(int *)info->data = cp;
  756. return 1;
  757. }
  758. static int XMLCALL
  759. notStandalone(void *userData) {
  760. UNUSED_P(userData);
  761. return 0;
  762. }
  763. static void
  764. showVersion(XML_Char *prog) {
  765. XML_Char *s = prog;
  766. XML_Char ch;
  767. const XML_Feature *features = XML_GetFeatureList();
  768. while ((ch = *s) != 0) {
  769. if (ch == '/'
  770. #if defined(_WIN32)
  771. || ch == '\\'
  772. #endif
  773. )
  774. prog = s + 1;
  775. ++s;
  776. }
  777. ftprintf(stdout, T("%s using %s\n"), prog, XML_ExpatVersion());
  778. if (features != NULL && features[0].feature != XML_FEATURE_END) {
  779. int i = 1;
  780. ftprintf(stdout, T("%s"), features[0].name);
  781. if (features[0].value)
  782. ftprintf(stdout, T("=%ld"), features[0].value);
  783. while (features[i].feature != XML_FEATURE_END) {
  784. ftprintf(stdout, T(", %s"), features[i].name);
  785. if (features[i].value)
  786. ftprintf(stdout, T("=%ld"), features[i].value);
  787. ++i;
  788. }
  789. ftprintf(stdout, T("\n"));
  790. }
  791. }
  792. #if defined(__GNUC__)
  793. __attribute__((noreturn))
  794. #endif
  795. static void
  796. usage(const XML_Char *prog, int rc) {
  797. ftprintf(
  798. stderr,
  799. /* Generated with:
  800. * $ xmlwf/xmlwf_helpgen.sh
  801. * To update, change xmlwf/xmlwf_helpgen.py, then paste the output of
  802. * xmlwf/xmlwf_helpgen.sh in here.
  803. */
  804. /* clang-format off */
  805. T("usage:\n")
  806. T(" %s [OPTIONS] [FILE ...]\n")
  807. T(" %s -h|--help\n")
  808. T(" %s -v|--version\n")
  809. T("\n")
  810. T("xmlwf - Determines if an XML document is well-formed\n")
  811. T("\n")
  812. T("positional arguments:\n")
  813. T(" FILE file to process (default: STDIN)\n")
  814. T("\n")
  815. T("input control arguments:\n")
  816. T(" -s print an error if the document is not [s]tandalone\n")
  817. T(" -n enable [n]amespace processing\n")
  818. T(" -p enable processing of external DTDs and [p]arameter entities\n")
  819. T(" -x enable processing of e[x]ternal entities\n")
  820. T(" -e ENCODING override any in-document [e]ncoding declaration\n")
  821. T(" -w enable support for [W]indows code pages\n")
  822. T(" -r disable memory-mapping and use [r]ead calls instead\n")
  823. T(" -g BYTES buffer size to request per call pair to XML_[G]etBuffer and read (default: 8 KiB)\n")
  824. T(" -k when processing multiple files, [k]eep processing after first file with error\n")
  825. T("\n")
  826. T("output control arguments:\n")
  827. T(" -d DIRECTORY output [d]estination directory\n")
  828. T(" -c write a [c]opy of input XML, not canonical XML\n")
  829. T(" -m write [m]eta XML, not canonical XML\n")
  830. T(" -t write no XML output for [t]iming of plain parsing\n")
  831. T(" -N enable adding doctype and [n]otation declarations\n")
  832. T("\n")
  833. T("amplification attack protection (e.g. billion laughs):\n")
  834. T(" NOTE: If you ever need to increase these values for non-attack payload, please file a bug report.\n")
  835. T("\n")
  836. T(" -a FACTOR set maximum tolerated [a]mplification factor (default: 100.0)\n")
  837. T(" -b BYTES set number of output [b]ytes needed to activate (default: 8 MiB/64 MiB)\n")
  838. T("\n")
  839. T("reparse deferral:\n")
  840. T(" -q disable reparse deferral, and allow [q]uadratic parse runtime with large tokens\n")
  841. T("\n")
  842. T("info arguments:\n")
  843. T(" -h, --help show this [h]elp message and exit\n")
  844. T(" -v, --version show program's [v]ersion number and exit\n")
  845. T("\n")
  846. T("environment variables:\n")
  847. T(" EXPAT_ACCOUNTING_DEBUG=(0|1|2|3)\n")
  848. T(" Control verbosity of accounting debugging (default: 0)\n")
  849. T(" EXPAT_ENTITY_DEBUG=(0|1)\n")
  850. T(" Control verbosity of entity debugging (default: 0)\n")
  851. T(" EXPAT_ENTROPY_DEBUG=(0|1)\n")
  852. T(" Control verbosity of entropy debugging (default: 0)\n")
  853. T(" EXPAT_MALLOC_DEBUG=(0|1|2)\n")
  854. T(" Control verbosity of allocation tracker (default: 0)\n")
  855. T("\n")
  856. T("exit status:\n")
  857. T(" 0 the input files are well-formed and the output (if requested) was written successfully\n")
  858. T(" 1 could not allocate data structures, signals a serious problem with execution environment\n")
  859. T(" 2 one or more input files were not well-formed\n")
  860. T(" 3 could not create an output file\n")
  861. T(" 4 command-line argument error\n")
  862. T("\n")
  863. T("xmlwf of libexpat is software libre, licensed under the MIT license.\n")
  864. T("Please report bugs at https://github.com/libexpat/libexpat/issues -- thank you!\n")
  865. , /* clang-format on */
  866. prog, prog, prog);
  867. exit(rc);
  868. }
  869. #if defined(__MINGW32__) && defined(XML_UNICODE)
  870. /* Silence warning about missing prototype */
  871. int wmain(int argc, XML_Char **argv);
  872. #endif
  873. #define XMLWF_SHIFT_ARG_INTO(constCharStarTarget, argc, argv, i, j) \
  874. { \
  875. if (argv[i][j + 1] == T('\0')) { \
  876. if (++i == argc) { \
  877. usage(argv[0], XMLWF_EXIT_USAGE_ERROR); \
  878. /* usage called exit(..), never gets here */ \
  879. } \
  880. constCharStarTarget = argv[i]; \
  881. } else { \
  882. constCharStarTarget = argv[i] + j + 1; \
  883. } \
  884. i++; \
  885. j = 0; \
  886. }
  887. int
  888. tmain(int argc, XML_Char **argv) {
  889. int i, j;
  890. const XML_Char *outputDir = NULL;
  891. const XML_Char *encoding = NULL;
  892. unsigned processFlags = XML_MAP_FILE;
  893. int windowsCodePages = 0;
  894. int outputType = 0;
  895. int useNamespaces = 0;
  896. int requireStandalone = 0;
  897. int requiresNotations = 0;
  898. int continueOnError = 0;
  899. float attackMaximumAmplification = -1.0f; /* signaling "not set" */
  900. unsigned long long attackThresholdBytes = 0;
  901. XML_Bool attackThresholdGiven = XML_FALSE;
  902. XML_Bool disableDeferral = XML_FALSE;
  903. int exitCode = XMLWF_EXIT_SUCCESS;
  904. enum XML_ParamEntityParsing paramEntityParsing
  905. = XML_PARAM_ENTITY_PARSING_NEVER;
  906. int useStdin = 0;
  907. XmlwfUserData userData = {NULL, NULL, NULL};
  908. #ifdef _MSC_VER
  909. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  910. #endif
  911. i = 1;
  912. j = 0;
  913. while (i < argc) {
  914. if (j == 0) {
  915. if (argv[i][0] != T('-'))
  916. break;
  917. if (argv[i][1] == T('-')) {
  918. if (argv[i][2] == T('\0')) {
  919. i++;
  920. break;
  921. } else if (tcscmp(argv[i] + 2, T("help")) == 0) {
  922. usage(argv[0], XMLWF_EXIT_SUCCESS);
  923. // usage called exit(..), never gets here
  924. } else if (tcscmp(argv[i] + 2, T("version")) == 0) {
  925. showVersion(argv[0]);
  926. return XMLWF_EXIT_SUCCESS;
  927. }
  928. }
  929. j++;
  930. }
  931. switch (argv[i][j]) {
  932. case T('r'):
  933. processFlags &= ~XML_MAP_FILE;
  934. j++;
  935. break;
  936. case T('s'):
  937. requireStandalone = 1;
  938. j++;
  939. break;
  940. case T('n'):
  941. useNamespaces = 1;
  942. j++;
  943. break;
  944. case T('p'):
  945. paramEntityParsing = XML_PARAM_ENTITY_PARSING_ALWAYS;
  946. /* fall through */
  947. case T('x'):
  948. processFlags |= XML_EXTERNAL_ENTITIES;
  949. j++;
  950. break;
  951. case T('w'):
  952. windowsCodePages = 1;
  953. j++;
  954. break;
  955. case T('m'):
  956. outputType = 'm';
  957. j++;
  958. break;
  959. case T('c'):
  960. outputType = 'c';
  961. useNamespaces = 0;
  962. j++;
  963. break;
  964. case T('t'):
  965. outputType = 't';
  966. j++;
  967. break;
  968. case T('N'):
  969. requiresNotations = 1;
  970. j++;
  971. break;
  972. case T('d'):
  973. XMLWF_SHIFT_ARG_INTO(outputDir, argc, argv, i, j);
  974. break;
  975. case T('e'):
  976. XMLWF_SHIFT_ARG_INTO(encoding, argc, argv, i, j);
  977. break;
  978. case T('h'):
  979. usage(argv[0], XMLWF_EXIT_SUCCESS);
  980. // usage called exit(..), never gets here
  981. case T('v'):
  982. showVersion(argv[0]);
  983. return XMLWF_EXIT_SUCCESS;
  984. case T('g'): {
  985. const XML_Char *valueText = NULL;
  986. XMLWF_SHIFT_ARG_INTO(valueText, argc, argv, i, j);
  987. errno = 0;
  988. XML_Char *afterValueText = (XML_Char *)valueText;
  989. const long long read_size_bytes_candidate
  990. = tcstoull(valueText, &afterValueText, 10);
  991. if ((errno != 0) || (afterValueText[0] != T('\0'))
  992. || (read_size_bytes_candidate < 1)
  993. || (read_size_bytes_candidate > (INT_MAX / 2 + 1))) {
  994. // This prevents tperror(..) from reporting misleading "[..]: Success"
  995. errno = ERANGE;
  996. tperror(T("invalid buffer size") T(
  997. " (needs an integer from 1 to INT_MAX/2+1 i.e. 1,073,741,824 on most platforms)"));
  998. exit(XMLWF_EXIT_USAGE_ERROR);
  999. }
  1000. g_read_size_bytes = (int)read_size_bytes_candidate;
  1001. break;
  1002. }
  1003. case T('k'):
  1004. continueOnError = 1;
  1005. j++;
  1006. break;
  1007. case T('a'): {
  1008. const XML_Char *valueText = NULL;
  1009. XMLWF_SHIFT_ARG_INTO(valueText, argc, argv, i, j);
  1010. errno = 0;
  1011. XML_Char *afterValueText = NULL;
  1012. attackMaximumAmplification = tcstof(valueText, &afterValueText);
  1013. if ((errno != 0) || (afterValueText[0] != T('\0'))
  1014. || isnan(attackMaximumAmplification)
  1015. || (attackMaximumAmplification < 1.0f)) {
  1016. // This prevents tperror(..) from reporting misleading "[..]: Success"
  1017. errno = ERANGE;
  1018. tperror(T("invalid amplification limit") T(
  1019. " (needs a floating point number greater or equal than 1.0)"));
  1020. exit(XMLWF_EXIT_USAGE_ERROR);
  1021. }
  1022. #if XML_GE == 0
  1023. ftprintf(stderr,
  1024. T("Warning: Given amplification limit ignored")
  1025. T(", xmlwf has been compiled without DTD/GE support.\n"));
  1026. #endif
  1027. break;
  1028. }
  1029. case T('b'): {
  1030. const XML_Char *valueText = NULL;
  1031. XMLWF_SHIFT_ARG_INTO(valueText, argc, argv, i, j);
  1032. errno = 0;
  1033. XML_Char *afterValueText = (XML_Char *)valueText;
  1034. attackThresholdBytes = tcstoull(valueText, &afterValueText, 10);
  1035. if ((errno != 0) || (afterValueText[0] != T('\0'))) {
  1036. // This prevents tperror(..) from reporting misleading "[..]: Success"
  1037. errno = ERANGE;
  1038. tperror(T("invalid ignore threshold")
  1039. T(" (needs an integer from 0 to 2^64-1)"));
  1040. exit(XMLWF_EXIT_USAGE_ERROR);
  1041. }
  1042. attackThresholdGiven = XML_TRUE;
  1043. #if XML_GE == 0
  1044. ftprintf(stderr,
  1045. T("Warning: Given attack threshold ignored")
  1046. T(", xmlwf has been compiled without DTD/GE support.\n"));
  1047. #endif
  1048. break;
  1049. }
  1050. case T('q'): {
  1051. disableDeferral = XML_TRUE;
  1052. j++;
  1053. break;
  1054. }
  1055. case T('\0'):
  1056. if (j > 1) {
  1057. i++;
  1058. j = 0;
  1059. break;
  1060. }
  1061. /* fall through */
  1062. default:
  1063. usage(argv[0], XMLWF_EXIT_USAGE_ERROR);
  1064. // usage called exit(..), never gets here
  1065. }
  1066. }
  1067. if (i == argc) {
  1068. useStdin = 1;
  1069. processFlags &= ~XML_MAP_FILE;
  1070. i--;
  1071. }
  1072. for (; i < argc; i++) {
  1073. XML_Char *outName = 0;
  1074. int result;
  1075. XML_Parser parser;
  1076. if (useNamespaces)
  1077. parser = XML_ParserCreateNS(encoding, NSSEP);
  1078. else
  1079. parser = XML_ParserCreate(encoding);
  1080. if (! parser) {
  1081. tperror(T("Could not instantiate parser"));
  1082. exit(XMLWF_EXIT_INTERNAL_ERROR);
  1083. }
  1084. if (attackMaximumAmplification != -1.0f) {
  1085. #if XML_GE == 1
  1086. XML_SetBillionLaughsAttackProtectionMaximumAmplification(
  1087. parser, attackMaximumAmplification);
  1088. XML_SetAllocTrackerMaximumAmplification(parser,
  1089. attackMaximumAmplification);
  1090. #endif
  1091. }
  1092. if (attackThresholdGiven) {
  1093. #if XML_GE == 1
  1094. XML_SetBillionLaughsAttackProtectionActivationThreshold(
  1095. parser, attackThresholdBytes);
  1096. XML_SetAllocTrackerActivationThreshold(parser, attackThresholdBytes);
  1097. #else
  1098. (void)attackThresholdBytes; // silence -Wunused-but-set-variable
  1099. #endif
  1100. }
  1101. if (disableDeferral) {
  1102. const XML_Bool success = XML_SetReparseDeferralEnabled(parser, XML_FALSE);
  1103. if (! success) {
  1104. // This prevents tperror(..) from reporting misleading "[..]: Success"
  1105. errno = EINVAL;
  1106. tperror(T("Failed to disable reparse deferral"));
  1107. exit(XMLWF_EXIT_INTERNAL_ERROR);
  1108. }
  1109. }
  1110. if (requireStandalone)
  1111. XML_SetNotStandaloneHandler(parser, notStandalone);
  1112. XML_SetParamEntityParsing(parser, paramEntityParsing);
  1113. if (outputType == 't') {
  1114. /* This is for doing timings; this gives a more realistic estimate of
  1115. the parsing time. */
  1116. outputDir = 0;
  1117. XML_SetElementHandler(parser, nopStartElement, nopEndElement);
  1118. XML_SetCharacterDataHandler(parser, nopCharacterData);
  1119. XML_SetProcessingInstructionHandler(parser, nopProcessingInstruction);
  1120. } else if (outputDir) {
  1121. const XML_Char *delim = T("/");
  1122. const XML_Char *file = useStdin ? T("STDIN") : argv[i];
  1123. if (! useStdin) {
  1124. /* Jump after last (back)slash */
  1125. const XML_Char *lastDelim = tcsrchr(file, delim[0]);
  1126. if (lastDelim)
  1127. file = lastDelim + 1;
  1128. #if defined(_WIN32)
  1129. else {
  1130. const XML_Char *winDelim = T("\\");
  1131. lastDelim = tcsrchr(file, winDelim[0]);
  1132. if (lastDelim) {
  1133. file = lastDelim + 1;
  1134. delim = winDelim;
  1135. }
  1136. }
  1137. #endif
  1138. }
  1139. outName = (XML_Char *)malloc((tcslen(outputDir) + tcslen(file) + 2)
  1140. * sizeof(XML_Char));
  1141. if (! outName) {
  1142. tperror(T("Could not allocate memory"));
  1143. exit(XMLWF_EXIT_INTERNAL_ERROR);
  1144. }
  1145. tcscpy(outName, outputDir);
  1146. tcscat(outName, delim);
  1147. tcscat(outName, file);
  1148. userData.fp = tfopen(outName, T("wb"));
  1149. if (! userData.fp) {
  1150. tperror(outName);
  1151. exitCode = XMLWF_EXIT_OUTPUT_ERROR;
  1152. free(outName);
  1153. XML_ParserFree(parser);
  1154. if (continueOnError) {
  1155. continue;
  1156. } else {
  1157. break;
  1158. }
  1159. }
  1160. setvbuf(userData.fp, NULL, _IOFBF, 16384);
  1161. #ifdef XML_UNICODE
  1162. puttc(0xFEFF, userData.fp);
  1163. #endif
  1164. XML_SetUserData(parser, &userData);
  1165. switch (outputType) {
  1166. case 'm':
  1167. XML_UseParserAsHandlerArg(parser);
  1168. XML_SetElementHandler(parser, metaStartElement, metaEndElement);
  1169. XML_SetProcessingInstructionHandler(parser, metaProcessingInstruction);
  1170. XML_SetCommentHandler(parser, metaComment);
  1171. XML_SetCdataSectionHandler(parser, metaStartCdataSection,
  1172. metaEndCdataSection);
  1173. XML_SetCharacterDataHandler(parser, metaCharacterData);
  1174. XML_SetDoctypeDeclHandler(parser, metaStartDoctypeDecl,
  1175. metaEndDoctypeDecl);
  1176. XML_SetEntityDeclHandler(parser, metaEntityDecl);
  1177. XML_SetNotationDeclHandler(parser, metaNotationDecl);
  1178. XML_SetNamespaceDeclHandler(parser, metaStartNamespaceDecl,
  1179. metaEndNamespaceDecl);
  1180. metaStartDocument(parser);
  1181. break;
  1182. case 'c':
  1183. XML_UseParserAsHandlerArg(parser);
  1184. XML_SetDefaultHandler(parser, markup);
  1185. XML_SetElementHandler(parser, defaultStartElement, defaultEndElement);
  1186. XML_SetCharacterDataHandler(parser, defaultCharacterData);
  1187. XML_SetProcessingInstructionHandler(parser,
  1188. defaultProcessingInstruction);
  1189. break;
  1190. default:
  1191. if (useNamespaces)
  1192. XML_SetElementHandler(parser, startElementNS, endElementNS);
  1193. else
  1194. XML_SetElementHandler(parser, startElement, endElement);
  1195. XML_SetCharacterDataHandler(parser, characterData);
  1196. #ifndef W3C14N
  1197. XML_SetProcessingInstructionHandler(parser, processingInstruction);
  1198. if (requiresNotations) {
  1199. XML_SetDoctypeDeclHandler(parser, startDoctypeDecl, endDoctypeDecl);
  1200. XML_SetNotationDeclHandler(parser, notationDecl);
  1201. }
  1202. #endif /* not W3C14N */
  1203. break;
  1204. }
  1205. }
  1206. if (windowsCodePages)
  1207. XML_SetUnknownEncodingHandler(parser, unknownEncoding, 0);
  1208. result = XML_ProcessFile(parser, useStdin ? NULL : argv[i], processFlags);
  1209. if (outputDir) {
  1210. if (outputType == 'm')
  1211. metaEndDocument(parser);
  1212. fclose(userData.fp);
  1213. if (! result) {
  1214. tremove(outName);
  1215. }
  1216. free(outName);
  1217. }
  1218. XML_ParserFree(parser);
  1219. if (! result) {
  1220. exitCode = XMLWF_EXIT_NOT_WELLFORMED;
  1221. cleanupUserData(&userData);
  1222. if (! continueOnError) {
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. return exitCode;
  1228. }