LuaXML_lib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /**
  2. LuaXML License
  3. LuaXml is licensed under the terms of the MIT license reproduced below,
  4. the same as Lua itself. This means that LuaXml is free software and can be
  5. used for both academic and commercial purposes at absolutely no cost.
  6. Copyright (C) 2007-2013 Gerald Franz, eludi.net
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. */
  23. #if defined __WIN32__ || defined WIN32
  24. # include <windows.h>
  25. # define _EXPORT __declspec(dllexport)
  26. #else
  27. # define _EXPORT
  28. #endif
  29. #ifdef __cplusplus
  30. extern "C" {
  31. #endif
  32. #include "civetweb_lua.h"
  33. #ifdef __cplusplus
  34. } // extern "C"
  35. #endif
  36. #include <stdio.h>
  37. #include <string.h>
  38. #include <ctype.h>
  39. #include <stdlib.h>
  40. static const char ESC=27;
  41. static const char OPN=28;
  42. static const char CLS=29;
  43. //--- auxliary functions -------------------------------------------
  44. static const char* char2code(unsigned char ch, char buf[8]) {
  45. unsigned char i=0;
  46. buf[i++]='&';
  47. buf[i++]='#';
  48. if(ch>99) buf[i++]=ch/100+48;
  49. if(ch>9) buf[i++]=(ch%100)/10+48;
  50. buf[i++]=ch%10+48;
  51. buf[i++]=';';
  52. buf[i]=0;
  53. return buf;
  54. }
  55. static size_t find(const char* s, const char* pattern, size_t start) {
  56. const char* found =strstr(s+start, pattern);
  57. return found ? found-s : strlen(s);
  58. }
  59. //--- internal tokenizer -------------------------------------------
  60. typedef struct Tokenizer_s {
  61. /// stores string to be tokenized
  62. const char* s;
  63. /// stores size of string to be tokenized
  64. size_t s_size;
  65. /// stores current read position
  66. size_t i;
  67. /// stores current read context
  68. int tagMode;
  69. /// stores next token, if already determined
  70. const char* m_next;
  71. /// size of next token
  72. size_t m_next_size;
  73. /// pointer to current token
  74. char* m_token;
  75. /// size of current token
  76. size_t m_token_size;
  77. /// capacity of current token
  78. size_t m_token_capacity;
  79. } Tokenizer;
  80. Tokenizer* Tokenizer_new(const char* str, size_t str_size) {
  81. Tokenizer *tok = (Tokenizer*)malloc(sizeof(Tokenizer));
  82. memset(tok, 0, sizeof(Tokenizer));
  83. tok->s_size = str_size;
  84. tok->s = str;
  85. return tok;
  86. }
  87. void Tokenizer_delete(Tokenizer* tok) {
  88. free(tok->m_token);
  89. free(tok);
  90. }
  91. //void Tokenizer_print(Tokenizer* tok) { printf(" @%u %s\n", tok->i, !tok->m_token ? "(null)" : (tok->m_token[0]==ESC)?"(esc)" : (tok->m_token[0]==OPN)?"(open)": (tok->m_token[0]==CLS)?"(close)" : tok->m_token); fflush(stdout); }
  92. static const char* Tokenizer_set(Tokenizer* tok, const char* s, size_t size) {
  93. if(!size||!s) return 0;
  94. free(tok->m_token);
  95. tok->m_token = (char*)malloc(size+1);
  96. strncpy(tok->m_token,s, size);
  97. tok->m_token[size] = 0;
  98. tok->m_token_size = tok->m_token_capacity = size;
  99. //Tokenizer_print(tok);
  100. return tok->m_token;
  101. }
  102. static void Tokenizer_append(Tokenizer* tok, char ch) {
  103. if(tok->m_token_size+1>=tok->m_token_capacity) {
  104. tok->m_token_capacity = (tok->m_token_capacity==0) ? 16 : tok->m_token_capacity*2;
  105. tok->m_token = (char*)realloc(tok->m_token, tok->m_token_capacity);
  106. }
  107. tok->m_token[tok->m_token_size]=ch;
  108. tok->m_token[++tok->m_token_size]=0;
  109. }
  110. const char* Tokenizer_next(Tokenizer* tok) {
  111. const char* ESC_str = "\033";
  112. const char* OPEN_str = "\034";
  113. const char* CLOSE_str = "\035";
  114. int quotMode=0;
  115. int tokenComplete = 0;
  116. if(tok->m_token) {
  117. free(tok->m_token);
  118. tok->m_token = 0;
  119. tok->m_token_size=tok->m_token_capacity = 0;
  120. }
  121. while(tok->m_next_size || (tok->i < tok->s_size)) {
  122. if(tok->m_next_size) {
  123. Tokenizer_set(tok, tok->m_next, tok->m_next_size);
  124. tok->m_next=0;
  125. tok->m_next_size=0;
  126. return tok->m_token;
  127. }
  128. switch(tok->s[tok->i]) {
  129. case '"':
  130. case '\'':
  131. if(tok->tagMode) {
  132. if(!quotMode) quotMode=tok->s[tok->i];
  133. else if(quotMode==tok->s[tok->i]) quotMode=0;
  134. }
  135. Tokenizer_append(tok, tok->s[tok->i]);
  136. break;
  137. case '<':
  138. if(!quotMode&&(tok->i+4<tok->s_size)&&(strncmp(tok->s+tok->i,"<!--",4)==0)) // strip comments
  139. tok->i=find(tok->s, "-->", tok->i+4)+2;
  140. else if(!quotMode&&(tok->i+9<tok->s_size)&&(strncmp(tok->s+tok->i,"<![CDATA[",9)==0)) { // interpet CDATA
  141. size_t b=tok->i+9;
  142. tok->i=find(tok->s, "]]>",b)+3;
  143. if(!tok->m_token_size) return Tokenizer_set(tok, tok->s+b, tok->i-b-3);
  144. tokenComplete = 1;
  145. tok->m_next = tok->s+b;
  146. tok->m_next_size = tok->i-b-3;
  147. --tok->i;
  148. }
  149. else if(!quotMode&&(tok->i+1<tok->s_size)&&((tok->s[tok->i+1]=='?')||(tok->s[tok->i+1]=='!'))) // strip meta information
  150. tok->i=find(tok->s, ">", tok->i+2);
  151. else if(!quotMode&&!tok->tagMode) {
  152. if((tok->i+1<tok->s_size)&&(tok->s[tok->i+1]=='/')) {
  153. tok->m_next=ESC_str;
  154. tok->m_next_size = 1;
  155. tok->i=find(tok->s, ">", tok->i+2);
  156. }
  157. else {
  158. tok->m_next = OPEN_str;
  159. tok->m_next_size = 1;
  160. tok->tagMode=1;
  161. }
  162. tokenComplete = 1;
  163. }
  164. else Tokenizer_append(tok, tok->s[tok->i]);
  165. break;
  166. case '/':
  167. if(tok->tagMode&&!quotMode) {
  168. tokenComplete = 1;
  169. if((tok->i+1 < tok->s_size) && (tok->s[tok->i+1]=='>')) {
  170. tok->tagMode=0;
  171. tok->m_next=ESC_str;
  172. tok->m_next_size = 1;
  173. ++tok->i;
  174. }
  175. else Tokenizer_append(tok, tok->s[tok->i]);
  176. }
  177. else Tokenizer_append(tok, tok->s[tok->i]);
  178. break;
  179. case '>':
  180. if(!quotMode&&tok->tagMode) {
  181. tok->tagMode=0;
  182. tokenComplete = 1;
  183. tok->m_next = CLOSE_str;
  184. tok->m_next_size = 1;
  185. }
  186. else Tokenizer_append(tok, tok->s[tok->i]);
  187. break;
  188. case ' ':
  189. case '\r':
  190. case '\n':
  191. case '\t':
  192. if(tok->tagMode&&!quotMode) {
  193. if(tok->m_token_size) tokenComplete=1;
  194. }
  195. else if(tok->m_token_size) Tokenizer_append(tok, tok->s[tok->i]);
  196. break;
  197. default: Tokenizer_append(tok, tok->s[tok->i]);
  198. }
  199. ++tok->i;
  200. if((tok->i>=tok->s_size)||(tokenComplete&&tok->m_token_size)) {
  201. tokenComplete=0;
  202. while(tok->m_token_size&&isspace(tok->m_token[tok->m_token_size-1])) // trim whitespace
  203. tok->m_token[--tok->m_token_size]=0;
  204. if(tok->m_token_size) break;
  205. }
  206. }
  207. //Tokenizer_print(tok);
  208. return tok->m_token;
  209. }
  210. //--- local variables ----------------------------------------------
  211. /// stores number of special character codes
  212. static size_t sv_code_size=0;
  213. /// stores currently allocated capacity for special character codes
  214. static size_t sv_code_capacity=16;
  215. /// stores code table for special characters
  216. static char** sv_code=0;
  217. //--- public methods -----------------------------------------------
  218. static void Xml_pushDecode(lua_State* L, const char* s, size_t s_size) {
  219. luaL_Buffer b;
  220. const char* found = strstr(s, "&#");
  221. size_t start=0, pos, i;
  222. if(!s_size)
  223. s_size=strlen(s);
  224. luaL_buffinit(L, &b);
  225. found = strstr(s, "&#");
  226. pos = found ? found-s : s_size;
  227. while(found) {
  228. char ch = 0;
  229. size_t i=0;
  230. for(found += 2; i<3; ++i, ++found)
  231. if(isdigit(*found))
  232. ch = ch * 10 + (*found - 48);
  233. else break;
  234. if(*found == ';') {
  235. if(pos>start)
  236. luaL_addlstring(&b, s+start, pos-start);
  237. luaL_addchar(&b, ch);
  238. start = pos + 3 + i;
  239. }
  240. found = strstr(found+1, "&#");
  241. pos = found ? found-s : s_size;
  242. }
  243. if(pos>start)
  244. luaL_addlstring(&b,s+start, pos-start);
  245. luaL_pushresult(&b);
  246. for(i=sv_code_size-1; i<sv_code_size; i-=2) {
  247. luaL_gsub(L, lua_tostring(L,-1), sv_code[i], sv_code[i-1]);
  248. lua_remove(L,-2);
  249. }
  250. }
  251. int Xml_eval(lua_State *L) {
  252. char* str = 0;
  253. size_t str_size=0;
  254. Tokenizer* tok;
  255. const char* token=0;
  256. int firstStatement = 1;
  257. if(lua_isuserdata(L,1))
  258. str = (char*)lua_touserdata(L,1);
  259. else {
  260. const char * sTmp = luaL_checklstring(L,1,&str_size);
  261. str = (char*)malloc(str_size+1);
  262. memcpy(str, sTmp, str_size);
  263. str[str_size]=0;
  264. }
  265. tok = Tokenizer_new(str, str_size ? str_size : strlen(str));
  266. lua_settop(L,0);
  267. while((token=Tokenizer_next(tok))!=0) if(token[0]==OPN) { // new tag found
  268. if(lua_gettop(L)) {
  269. int newIndex=lua_rawlen(L,-1)+1;
  270. lua_pushnumber(L,newIndex);
  271. lua_newtable(L);
  272. lua_settable(L, -3);
  273. lua_pushnumber(L,newIndex);
  274. lua_gettable(L,-2);
  275. }
  276. else {
  277. if (firstStatement) {
  278. lua_newtable(L);
  279. firstStatement = 0;
  280. }
  281. else return lua_gettop(L);
  282. }
  283. // set metatable:
  284. lua_newtable(L);
  285. lua_pushliteral(L, "__index");
  286. lua_getglobal(L, "xml");
  287. lua_settable(L, -3);
  288. lua_pushliteral(L, "__tostring"); // set __tostring metamethod
  289. lua_getglobal(L, "xml");
  290. lua_pushliteral(L,"str");
  291. lua_gettable(L, -2);
  292. lua_remove(L, -2);
  293. lua_settable(L, -3);
  294. lua_setmetatable(L, -2);
  295. // parse tag and content:
  296. lua_pushnumber(L,0); // use index 0 for storing the tag
  297. lua_pushstring(L, Tokenizer_next(tok));
  298. lua_settable(L, -3);
  299. while(((token = Tokenizer_next(tok))!=0)&&(token[0]!=CLS)&&(token[0]!=ESC)) { // parse tag header
  300. size_t sepPos=find(token, "=", 0);
  301. if(token[sepPos]) { // regular attribute
  302. const char* aVal =token+sepPos+2;
  303. size_t lenVal;
  304. lua_pushlstring(L, token, sepPos);
  305. lenVal = strlen(aVal)-1;
  306. if(!lenVal) Xml_pushDecode(L, "", 0);
  307. else Xml_pushDecode(L, aVal, lenVal);
  308. lua_settable(L, -3);
  309. }
  310. }
  311. if(!token||(token[0]==ESC)) {
  312. if(lua_gettop(L)>1) lua_settop(L,-2); // this tag has no content, only attributes
  313. else break;
  314. }
  315. }
  316. else if(token[0]==ESC) { // previous tag is over
  317. if(lua_gettop(L)>1) lua_settop(L,-2); // pop current table
  318. else break;
  319. }
  320. else { // read elements
  321. lua_pushnumber(L,lua_rawlen(L,-1)+1);
  322. Xml_pushDecode(L, token, 0);
  323. lua_settable(L, -3);
  324. }
  325. Tokenizer_delete(tok);
  326. free(str);
  327. return lua_gettop(L);
  328. }
  329. int Xml_load (lua_State *L) {
  330. const char * filename = luaL_checkstring(L,1);
  331. FILE * file=fopen(filename,"r");
  332. char* buffer;
  333. size_t sz;
  334. if(!file)
  335. return luaL_error(L,"LuaXml ERROR: \"%s\" file error or file not found!",filename);
  336. fseek (file , 0 , SEEK_END);
  337. sz = ftell (file);
  338. rewind (file);
  339. buffer = (char*)malloc(sz+1);
  340. sz = fread (buffer,1,sz,file);
  341. fclose(file);
  342. buffer[sz]=0;
  343. lua_pushlightuserdata(L,buffer);
  344. lua_replace(L,1);
  345. return Xml_eval(L);
  346. };
  347. int Xml_registerCode(lua_State *L) {
  348. const char * decoded = luaL_checkstring(L,1);
  349. const char * encoded = luaL_checkstring(L,2);
  350. size_t i;
  351. for(i=0; i<sv_code_size; i+=2)
  352. if(strcmp(sv_code[i],decoded)==0)
  353. return luaL_error(L,"LuaXml ERROR: code already exists.");
  354. if(sv_code_size+2>sv_code_capacity) {
  355. sv_code_capacity*=2;
  356. sv_code = (char**)realloc(sv_code, sv_code_capacity*sizeof(char*));
  357. }
  358. sv_code[sv_code_size]=(char*)malloc(strlen(decoded)+1);
  359. strcpy(sv_code[sv_code_size++], decoded);
  360. sv_code[sv_code_size]=(char*)malloc(strlen(encoded)+1);
  361. strcpy(sv_code[sv_code_size++],encoded);
  362. return 0;
  363. }
  364. int Xml_encode(lua_State *L) {
  365. char buf[8];
  366. size_t start, pos;
  367. luaL_Buffer b;
  368. const char* s;
  369. size_t i;
  370. if(lua_gettop(L)!=1)
  371. return 0;
  372. luaL_checkstring(L,-1);
  373. for(i=0; i<sv_code_size; i+=2) {
  374. luaL_gsub(L, lua_tostring(L,-1), sv_code[i], sv_code[i+1]);
  375. lua_remove(L,-2);
  376. }
  377. s=lua_tostring(L,1);
  378. luaL_buffinit(L, &b);
  379. for(start=pos=0; s[pos]!=0; ++pos) if(s[pos]<0) {
  380. if(pos>start) luaL_addlstring(&b,s+start, pos-start);
  381. luaL_addstring(&b,char2code((unsigned char)(s[pos]),buf));
  382. start=pos+1;
  383. }
  384. if(pos>start)
  385. luaL_addlstring(&b,s+start, pos-start);
  386. luaL_pushresult(&b);
  387. lua_remove(L,-2);
  388. return 1;
  389. }
  390. #ifdef __cplusplus
  391. extern "C" {
  392. #endif
  393. int _EXPORT luaopen_LuaXML_lib (lua_State* L) {
  394. static const struct luaL_Reg funcs[] = {
  395. {"load", Xml_load},
  396. {"eval", Xml_eval},
  397. {"encode", Xml_encode},
  398. {"registerCode", Xml_registerCode},
  399. {NULL, NULL}
  400. };
  401. luaL_newlibtable(L, funcs);
  402. luaL_setfuncs(L, funcs, 0);
  403. lua_setglobal(L, "xml");
  404. // register default codes:
  405. if(!sv_code) {
  406. sv_code=(char**)malloc(sv_code_capacity*sizeof(char*));
  407. sv_code[sv_code_size++]="&";
  408. sv_code[sv_code_size++]="&amp;";
  409. sv_code[sv_code_size++]="<";
  410. sv_code[sv_code_size++]="&lt;";
  411. sv_code[sv_code_size++]=">";
  412. sv_code[sv_code_size++]="&gt;";
  413. sv_code[sv_code_size++]="\"";
  414. sv_code[sv_code_size++]="&quot;";
  415. sv_code[sv_code_size++]="'";
  416. sv_code[sv_code_size++]="&apos;";
  417. }
  418. return 1;
  419. }
  420. #ifdef __cplusplus
  421. } // extern "C"
  422. #endif