mod_lua.inl 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  1. /* This file is part of the CivetWeb web server.
  2. * See https://github.com/civetweb/civetweb/
  3. */
  4. #include "civetweb_lua.h"
  5. #include "civetweb_private_lua.h"
  6. #ifdef _WIN32
  7. static void *
  8. mmap(void *addr, int64_t len, int prot, int flags, int fd, int offset)
  9. {
  10. /* TODO (low): This is an incomplete implementation of mmap for windows.
  11. * Currently it is sufficient, but there are a lot of unused parameters.
  12. * Better use a function "mg_map" which only has the required parameters,
  13. * and implement it using mmap in Linux and CreateFileMapping in Windows.
  14. * Noone should expect a full mmap for Windows here.
  15. */
  16. HANDLE fh = (HANDLE)_get_osfhandle(fd);
  17. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  18. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
  19. CloseHandle(mh);
  20. /* unused parameters */
  21. (void)addr;
  22. (void)prot;
  23. (void)flags;
  24. (void)offset;
  25. return p;
  26. }
  27. static void
  28. munmap(void *addr, int64_t length)
  29. {
  30. /* unused parameters */
  31. (void)length;
  32. UnmapViewOfFile(addr);
  33. }
  34. #define MAP_FAILED (NULL)
  35. #define MAP_PRIVATE (0)
  36. #define PROT_READ (0)
  37. #else
  38. #include <sys/mman.h>
  39. #endif
  40. static const char *LUASOCKET = "luasocket";
  41. static const char lua_regkey_ctx = 1;
  42. static const char lua_regkey_connlist = 2;
  43. static const char lua_regkey_lsp_include_depth = 3;
  44. #ifndef LSP_INCLUDE_MAX_DEPTH
  45. #define LSP_INCLUDE_MAX_DEPTH (32)
  46. #endif
  47. /* Forward declarations */
  48. static void handle_request(struct mg_connection *);
  49. static int handle_lsp_request(struct mg_connection *,
  50. const char *,
  51. struct mg_file *,
  52. struct lua_State *);
  53. static void
  54. reg_lstring(struct lua_State *L,
  55. const char *name,
  56. const void *buffer,
  57. size_t buflen)
  58. {
  59. if (name != NULL && buffer != NULL) {
  60. lua_pushstring(L, name);
  61. lua_pushlstring(L, (const char *)buffer, buflen);
  62. lua_rawset(L, -3);
  63. }
  64. }
  65. #define reg_string(L, name, val) \
  66. reg_lstring(L, name, val, val ? strlen(val) : 0)
  67. static void
  68. reg_int(struct lua_State *L, const char *name, int val)
  69. {
  70. if (name != NULL) {
  71. lua_pushstring(L, name);
  72. lua_pushinteger(L, val);
  73. lua_rawset(L, -3);
  74. }
  75. }
  76. static void
  77. reg_boolean(struct lua_State *L, const char *name, int val)
  78. {
  79. if (name != NULL) {
  80. lua_pushstring(L, name);
  81. lua_pushboolean(L, val != 0);
  82. lua_rawset(L, -3);
  83. }
  84. }
  85. static void
  86. reg_conn_function(struct lua_State *L,
  87. const char *name,
  88. lua_CFunction func,
  89. struct mg_connection *conn)
  90. {
  91. if (name != NULL && func != NULL && conn != NULL) {
  92. lua_pushstring(L, name);
  93. lua_pushlightuserdata(L, conn);
  94. lua_pushcclosure(L, func, 1);
  95. lua_rawset(L, -3);
  96. }
  97. }
  98. static void
  99. reg_function(struct lua_State *L, const char *name, lua_CFunction func)
  100. {
  101. if (name != NULL && func != NULL) {
  102. lua_pushstring(L, name);
  103. lua_pushcclosure(L, func, 0);
  104. lua_rawset(L, -3);
  105. }
  106. }
  107. static void
  108. lua_cry(struct mg_connection *conn,
  109. int err,
  110. lua_State *L,
  111. const char *lua_title,
  112. const char *lua_operation)
  113. {
  114. switch (err) {
  115. case LUA_OK:
  116. case LUA_YIELD:
  117. break;
  118. case LUA_ERRRUN:
  119. mg_cry(conn,
  120. "%s: %s failed: runtime error: %s",
  121. lua_title,
  122. lua_operation,
  123. lua_tostring(L, -1));
  124. break;
  125. case LUA_ERRSYNTAX:
  126. mg_cry(conn,
  127. "%s: %s failed: syntax error: %s",
  128. lua_title,
  129. lua_operation,
  130. lua_tostring(L, -1));
  131. break;
  132. case LUA_ERRMEM:
  133. mg_cry(conn, "%s: %s failed: out of memory", lua_title, lua_operation);
  134. break;
  135. case LUA_ERRGCMM:
  136. mg_cry(conn,
  137. "%s: %s failed: error during garbage collection",
  138. lua_title,
  139. lua_operation);
  140. break;
  141. case LUA_ERRERR:
  142. mg_cry(conn,
  143. "%s: %s failed: error in error handling: %s",
  144. lua_title,
  145. lua_operation,
  146. lua_tostring(L, -1));
  147. break;
  148. default:
  149. mg_cry(conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
  150. break;
  151. }
  152. }
  153. static int
  154. lsp_sock_close(lua_State *L)
  155. {
  156. int num_args = lua_gettop(L);
  157. size_t s;
  158. SOCKET *psock;
  159. if ((num_args == 1) && lua_istable(L, -1)) {
  160. lua_getfield(L, -1, "sock");
  161. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  162. if (s != sizeof(SOCKET)) {
  163. return luaL_error(L, "invalid internal state in :close() call");
  164. }
  165. /* Do not closesocket(*psock); here, close it in __gc */
  166. (void)psock;
  167. } else {
  168. return luaL_error(L, "invalid :close() call");
  169. }
  170. return 0;
  171. }
  172. static int
  173. lsp_sock_recv(lua_State *L)
  174. {
  175. int num_args = lua_gettop(L);
  176. char buf[2000];
  177. int n;
  178. size_t s;
  179. SOCKET *psock;
  180. if ((num_args == 1) && lua_istable(L, -1)) {
  181. lua_getfield(L, -1, "sock");
  182. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  183. if (s != sizeof(SOCKET)) {
  184. return luaL_error(L, "invalid internal state in :recv() call");
  185. }
  186. n = recv(*psock, buf, sizeof(buf), 0);
  187. if (n <= 0) {
  188. lua_pushnil(L);
  189. } else {
  190. lua_pushlstring(L, buf, n);
  191. }
  192. } else {
  193. return luaL_error(L, "invalid :recv() call");
  194. }
  195. return 1;
  196. }
  197. static int
  198. lsp_sock_send(lua_State *L)
  199. {
  200. int num_args = lua_gettop(L);
  201. const char *buf;
  202. size_t len, sent = 0;
  203. int n = 0;
  204. size_t s;
  205. SOCKET *psock;
  206. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  207. buf = lua_tolstring(L, -1, &len);
  208. lua_getfield(L, -2, "sock");
  209. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  210. if (s != sizeof(SOCKET)) {
  211. return luaL_error(L, "invalid internal state in :close() call");
  212. }
  213. while (sent < len) {
  214. if ((n = send(*psock, buf + sent, (int)(len - sent), 0)) <= 0) {
  215. break;
  216. }
  217. sent += n;
  218. }
  219. lua_pushnumber(L, n);
  220. } else {
  221. return luaL_error(L, "invalid :close() call");
  222. }
  223. return 1;
  224. }
  225. static int
  226. lsp_sock_gc(lua_State *L)
  227. {
  228. int num_args = lua_gettop(L);
  229. size_t s;
  230. SOCKET *psock;
  231. if ((num_args == 1) && lua_istable(L, -1)) {
  232. lua_getfield(L, -1, "sock");
  233. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  234. if (s != sizeof(SOCKET)) {
  235. return luaL_error(
  236. L,
  237. "invalid internal state in __gc for object created by connect");
  238. }
  239. closesocket(*psock);
  240. } else {
  241. return luaL_error(L, "__gc for object created by connect failed");
  242. }
  243. return 0;
  244. }
  245. /* Methods and meta-methods supported by the object returned by connect.
  246. * For meta-methods, see http://lua-users.org/wiki/MetatableEvents */
  247. static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
  248. {"send", lsp_sock_send},
  249. {"recv", lsp_sock_recv},
  250. {"__gc", lsp_sock_gc},
  251. {NULL, NULL}};
  252. static int
  253. lsp_connect(lua_State *L)
  254. {
  255. int num_args = lua_gettop(L);
  256. char ebuf[100];
  257. SOCKET sock;
  258. union usa sa;
  259. int ok;
  260. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2)
  261. && lua_isnumber(L, -1)) {
  262. ok = connect_socket(NULL,
  263. lua_tostring(L, -3),
  264. (int)lua_tonumber(L, -2),
  265. (int)lua_tonumber(L, -1),
  266. ebuf,
  267. sizeof(ebuf),
  268. &sock,
  269. &sa);
  270. if (!ok) {
  271. return luaL_error(L, ebuf);
  272. } else {
  273. lua_newtable(L);
  274. reg_lstring(L, "sock", (const char *)&sock, sizeof(SOCKET));
  275. reg_string(L, "host", lua_tostring(L, -4));
  276. luaL_getmetatable(L, LUASOCKET);
  277. lua_setmetatable(L, -2);
  278. }
  279. } else {
  280. return luaL_error(
  281. L, "connect(host,port,is_ssl): invalid parameter given.");
  282. }
  283. return 1;
  284. }
  285. static int
  286. lsp_error(lua_State *L)
  287. {
  288. lua_getglobal(L, "mg");
  289. lua_getfield(L, -1, "onerror");
  290. lua_pushvalue(L, -3);
  291. lua_pcall(L, 1, 0, 0);
  292. return 0;
  293. }
  294. /* Silently stop processing chunks. */
  295. static void
  296. lsp_abort(lua_State *L)
  297. {
  298. int top = lua_gettop(L);
  299. lua_getglobal(L, "mg");
  300. lua_pushnil(L);
  301. lua_setfield(L, -2, "onerror");
  302. lua_settop(L, top);
  303. lua_pushstring(L, "aborting");
  304. lua_error(L);
  305. }
  306. struct lsp_var_reader_data {
  307. const char *begin;
  308. unsigned len;
  309. unsigned state;
  310. };
  311. static const char *
  312. lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  313. {
  314. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  315. const char *ret;
  316. (void)(L); /* unused */
  317. switch (reader->state) {
  318. case 0:
  319. ret = "mg.write(";
  320. *sz = strlen(ret);
  321. break;
  322. case 1:
  323. ret = reader->begin;
  324. *sz = reader->len;
  325. break;
  326. case 2:
  327. ret = ")";
  328. *sz = strlen(ret);
  329. break;
  330. default:
  331. ret = 0;
  332. *sz = 0;
  333. }
  334. reader->state++;
  335. return ret;
  336. }
  337. static int
  338. lsp(struct mg_connection *conn,
  339. const char *path,
  340. const char *p,
  341. int64_t len,
  342. lua_State *L)
  343. {
  344. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  345. char chunkname[MG_BUF_LEN];
  346. struct lsp_var_reader_data data;
  347. for (i = 0; i < len; i++) {
  348. if (p[i] == '\n')
  349. lines++;
  350. if (((i + 1) < len) && (p[i] == '<') && (p[i + 1] == '?')) {
  351. /* <?= ?> means a variable is enclosed and its value should be
  352. * printed */
  353. is_var = (((i + 2) < len) && (p[i + 2] == '='));
  354. if (is_var)
  355. j = i + 2;
  356. else
  357. j = i + 1;
  358. while (j < len) {
  359. if (p[j] == '\n')
  360. lualines++;
  361. if (((j + 1) < len) && (p[j] == '?') && (p[j + 1] == '>')) {
  362. mg_write(conn, p + pos, i - pos);
  363. mg_snprintf(conn,
  364. NULL, /* name only used for debugging */
  365. chunkname,
  366. sizeof(chunkname),
  367. "@%s+%i",
  368. path,
  369. lines);
  370. lua_pushlightuserdata(L, conn);
  371. lua_pushcclosure(L, lsp_error, 1);
  372. if (is_var) {
  373. data.begin = p + (i + 3);
  374. data.len = j - (i + 3);
  375. data.state = 0;
  376. lua_ok = mg_lua_load(
  377. L, lsp_var_reader, &data, chunkname, NULL);
  378. } else {
  379. lua_ok = luaL_loadbuffer(L,
  380. p + (i + 2),
  381. j - (i + 2),
  382. chunkname);
  383. }
  384. if (lua_ok) {
  385. /* Syntax error or OOM. Error message is pushed on
  386. * stack. */
  387. lua_pcall(L, 1, 0, 0);
  388. } else {
  389. /* Success loading chunk. Call it. */
  390. lua_pcall(L, 0, 0, 1);
  391. }
  392. pos = j + 2;
  393. i = pos - 1;
  394. break;
  395. }
  396. j++;
  397. }
  398. if (lualines > 0) {
  399. lines += lualines;
  400. lualines = 0;
  401. }
  402. }
  403. }
  404. if (i > pos) {
  405. mg_write(conn, p + pos, i - pos);
  406. }
  407. return 0;
  408. }
  409. /* mg.write: Send data to the client */
  410. static int
  411. lsp_write(lua_State *L)
  412. {
  413. struct mg_connection *conn =
  414. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  415. int num_args = lua_gettop(L);
  416. const char *str;
  417. size_t size;
  418. int i;
  419. int rv = 1;
  420. for (i = 1; i <= num_args; i++) {
  421. if (lua_isstring(L, i)) {
  422. str = lua_tolstring(L, i, &size);
  423. if (mg_write(conn, str, size) != (int)size) {
  424. rv = 0;
  425. }
  426. }
  427. }
  428. lua_pushboolean(L, rv);
  429. return 1;
  430. }
  431. /* mg.read: Read data from the client (e.g., from a POST request) */
  432. static int
  433. lsp_read(lua_State *L)
  434. {
  435. struct mg_connection *conn =
  436. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  437. char buf[1024];
  438. int len = mg_read(conn, buf, sizeof(buf));
  439. if (len <= 0)
  440. return 0;
  441. lua_pushlstring(L, buf, len);
  442. return 1;
  443. }
  444. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  445. static int
  446. lsp_keep_alive(lua_State *L)
  447. {
  448. struct mg_connection *conn =
  449. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  450. int num_args = lua_gettop(L);
  451. /* This function may be called with one parameter (boolean) to set the
  452. keep_alive state.
  453. Or without a parameter to just query the current keep_alive state. */
  454. if ((num_args == 1) && lua_isboolean(L, 1)) {
  455. conn->must_close = !lua_toboolean(L, 1);
  456. } else if (num_args != 0) {
  457. /* Syntax error */
  458. return luaL_error(L, "invalid keep_alive() call");
  459. }
  460. /* Return the current "keep_alive" state. This may be false, even it
  461. * keep_alive(true) has been called. */
  462. lua_pushboolean(L, should_keep_alive(conn));
  463. return 1;
  464. }
  465. /* mg.include: Include another .lp file */
  466. static int
  467. lsp_include(lua_State *L)
  468. {
  469. struct mg_connection *conn =
  470. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  471. int num_args = lua_gettop(L);
  472. struct mg_file file = STRUCT_FILE_INITIALIZER;
  473. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  474. if (filename) {
  475. int depth;
  476. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_depth);
  477. lua_gettable(L, LUA_REGISTRYINDEX);
  478. depth = lua_tointeger(L, -1);
  479. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_depth);
  480. lua_pushinteger(L, depth + 1);
  481. lua_settable(L, LUA_REGISTRYINDEX);
  482. if (depth >= ((int)(LSP_INCLUDE_MAX_DEPTH))) {
  483. mg_cry(conn,
  484. "lsp max include depth of %i reached while including %s",
  485. (int)(LSP_INCLUDE_MAX_DEPTH),
  486. filename);
  487. } else if (handle_lsp_request(conn, filename, &file, L)) {
  488. /* handle_lsp_request returned an error code, meaning an error
  489. * occured in the included page and mg.onerror returned non-zero.
  490. * Stop processing.
  491. */
  492. lsp_abort(L);
  493. }
  494. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_depth);
  495. lua_pushinteger(L, depth);
  496. lua_settable(L, LUA_REGISTRYINDEX);
  497. } else {
  498. /* Syntax error */
  499. return luaL_error(L, "invalid include() call");
  500. }
  501. return 0;
  502. }
  503. /* mg.cry: Log an error. Default value for mg.onerror. */
  504. static int
  505. lsp_cry(lua_State *L)
  506. {
  507. struct mg_connection *conn =
  508. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  509. int num_args = lua_gettop(L);
  510. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  511. if (text) {
  512. mg_cry(conn, "%s", lua_tostring(L, -1));
  513. } else {
  514. /* Syntax error */
  515. return luaL_error(L, "invalid cry() call");
  516. }
  517. return 0;
  518. }
  519. /* mg.redirect: Redirect the request (internally). */
  520. static int
  521. lsp_redirect(lua_State *L)
  522. {
  523. struct mg_connection *conn =
  524. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  525. int num_args = lua_gettop(L);
  526. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  527. if (target) {
  528. conn->request_info.local_uri = target;
  529. handle_request(conn);
  530. lsp_abort(L);
  531. } else {
  532. /* Syntax error */
  533. return luaL_error(L, "invalid redirect() call");
  534. }
  535. return 0;
  536. }
  537. /* mg.send_file */
  538. static int
  539. lsp_send_file(lua_State *L)
  540. {
  541. struct mg_connection *conn =
  542. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  543. int num_args = lua_gettop(L);
  544. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  545. if (filename) {
  546. mg_send_file(conn, filename);
  547. } else {
  548. /* Syntax error */
  549. return luaL_error(L, "invalid send_file() call");
  550. }
  551. return 0;
  552. }
  553. /* mg.get_time */
  554. static int
  555. lsp_get_time(lua_State *L)
  556. {
  557. int num_args = lua_gettop(L);
  558. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  559. struct timespec ts;
  560. double d;
  561. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  562. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  563. lua_pushnumber(L, d);
  564. return 1;
  565. }
  566. /* mg.get_var */
  567. static int
  568. lsp_get_var(lua_State *L)
  569. {
  570. int num_args = lua_gettop(L);
  571. const char *data, *var_name;
  572. size_t data_len, occurrence;
  573. int ret;
  574. char dst[512];
  575. if (num_args >= 2 && num_args <= 3) {
  576. data = lua_tolstring(L, 1, &data_len);
  577. var_name = lua_tostring(L, 2);
  578. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  579. ret =
  580. mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
  581. if (ret >= 0) {
  582. /* Variable found: return value to Lua */
  583. lua_pushstring(L, dst);
  584. } else {
  585. /* Variable not found (TODO (mid): may be string too long) */
  586. lua_pushnil(L);
  587. }
  588. } else {
  589. /* Syntax error */
  590. return luaL_error(L, "invalid get_var() call");
  591. }
  592. return 1;
  593. }
  594. /* mg.get_mime_type */
  595. static int
  596. lsp_get_mime_type(lua_State *L)
  597. {
  598. int num_args = lua_gettop(L);
  599. struct vec mime_type = {0, 0};
  600. struct mg_context *ctx;
  601. const char *text;
  602. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  603. lua_gettable(L, LUA_REGISTRYINDEX);
  604. ctx = (struct mg_context *)lua_touserdata(L, -1);
  605. if (num_args == 1) {
  606. text = lua_tostring(L, 1);
  607. if (text) {
  608. if (ctx) {
  609. get_mime_type(ctx, text, &mime_type);
  610. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  611. } else {
  612. text = mg_get_builtin_mime_type(text);
  613. lua_pushstring(L, text);
  614. }
  615. } else {
  616. /* Syntax error */
  617. return luaL_error(L, "invalid argument for get_mime_type() call");
  618. }
  619. } else {
  620. /* Syntax error */
  621. return luaL_error(L, "invalid get_mime_type() call");
  622. }
  623. return 1;
  624. }
  625. /* mg.get_cookie */
  626. static int
  627. lsp_get_cookie(lua_State *L)
  628. {
  629. int num_args = lua_gettop(L);
  630. const char *cookie;
  631. const char *var_name;
  632. int ret;
  633. char dst[512];
  634. if (num_args == 2) {
  635. cookie = lua_tostring(L, 1);
  636. var_name = lua_tostring(L, 2);
  637. if (cookie != NULL && var_name != NULL) {
  638. ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
  639. } else {
  640. ret = -1;
  641. }
  642. if (ret >= 0) {
  643. lua_pushlstring(L, dst, ret);
  644. } else {
  645. lua_pushnil(L);
  646. }
  647. } else {
  648. /* Syntax error */
  649. return luaL_error(L, "invalid get_cookie() call");
  650. }
  651. return 1;
  652. }
  653. /* mg.md5 */
  654. static int
  655. lsp_md5(lua_State *L)
  656. {
  657. int num_args = lua_gettop(L);
  658. const char *text;
  659. md5_byte_t hash[16];
  660. md5_state_t ctx;
  661. size_t text_len;
  662. char buf[40];
  663. if (num_args == 1) {
  664. text = lua_tolstring(L, 1, &text_len);
  665. if (text) {
  666. md5_init(&ctx);
  667. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  668. md5_finish(&ctx, hash);
  669. bin2str(buf, hash, sizeof(hash));
  670. lua_pushstring(L, buf);
  671. } else {
  672. lua_pushnil(L);
  673. }
  674. } else {
  675. /* Syntax error */
  676. return luaL_error(L, "invalid md5() call");
  677. }
  678. return 1;
  679. }
  680. /* mg.url_encode */
  681. static int
  682. lsp_url_encode(lua_State *L)
  683. {
  684. int num_args = lua_gettop(L);
  685. const char *text;
  686. size_t text_len;
  687. char dst[512 * 3];
  688. if (num_args == 1) {
  689. text = lua_tolstring(L, 1, &text_len);
  690. if (text) {
  691. mg_url_encode(text, dst, sizeof(dst));
  692. lua_pushstring(L, dst);
  693. } else {
  694. lua_pushnil(L);
  695. }
  696. } else {
  697. /* Syntax error */
  698. return luaL_error(L, "invalid url_encode() call");
  699. }
  700. return 1;
  701. }
  702. /* mg.url_decode */
  703. static int
  704. lsp_url_decode(lua_State *L)
  705. {
  706. int num_args = lua_gettop(L);
  707. const char *text;
  708. size_t text_len;
  709. int is_form;
  710. char dst[512];
  711. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  712. text = lua_tolstring(L, 1, &text_len);
  713. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  714. if (text) {
  715. mg_url_decode(text, (int)text_len, dst, (int)sizeof(dst), is_form);
  716. lua_pushstring(L, dst);
  717. } else {
  718. lua_pushnil(L);
  719. }
  720. } else {
  721. /* Syntax error */
  722. return luaL_error(L, "invalid url_decode() call");
  723. }
  724. return 1;
  725. }
  726. /* mg.base64_encode */
  727. static int
  728. lsp_base64_encode(lua_State *L)
  729. {
  730. int num_args = lua_gettop(L);
  731. const char *text;
  732. size_t text_len;
  733. char *dst;
  734. if (num_args == 1) {
  735. text = lua_tolstring(L, 1, &text_len);
  736. if (text) {
  737. dst = (char *)mg_malloc(text_len * 8 / 6 + 4);
  738. if (dst) {
  739. base64_encode((const unsigned char *)text, (int)text_len, dst);
  740. lua_pushstring(L, dst);
  741. mg_free(dst);
  742. } else {
  743. return luaL_error(L, "out of memory in base64_encode() call");
  744. }
  745. } else {
  746. lua_pushnil(L);
  747. }
  748. } else {
  749. /* Syntax error */
  750. return luaL_error(L, "invalid base64_encode() call");
  751. }
  752. return 1;
  753. }
  754. /* mg.base64_encode */
  755. static int
  756. lsp_base64_decode(lua_State *L)
  757. {
  758. int num_args = lua_gettop(L);
  759. const char *text;
  760. size_t text_len, dst_len;
  761. int ret;
  762. char *dst;
  763. if (num_args == 1) {
  764. text = lua_tolstring(L, 1, &text_len);
  765. if (text) {
  766. dst = (char *)mg_malloc(text_len);
  767. if (dst) {
  768. ret = base64_decode((const unsigned char *)text,
  769. (int)text_len,
  770. dst,
  771. &dst_len);
  772. if (ret != -1) {
  773. mg_free(dst);
  774. return luaL_error(
  775. L, "illegal character in lsp_base64_decode() call");
  776. } else {
  777. lua_pushlstring(L, dst, dst_len);
  778. mg_free(dst);
  779. }
  780. } else {
  781. return luaL_error(L,
  782. "out of memory in lsp_base64_decode() call");
  783. }
  784. } else {
  785. lua_pushnil(L);
  786. }
  787. } else {
  788. /* Syntax error */
  789. return luaL_error(L, "invalid lsp_base64_decode() call");
  790. }
  791. return 1;
  792. }
  793. /* mg.get_response_code_text */
  794. static int
  795. lsp_get_response_code_text(lua_State *L)
  796. {
  797. int num_args = lua_gettop(L);
  798. int type1;
  799. double code;
  800. const char *text;
  801. if (num_args == 1) {
  802. type1 = lua_type(L, 1);
  803. if (type1 == LUA_TNUMBER) {
  804. /* If the first argument is a number,
  805. convert it to the corresponding text. */
  806. code = lua_tonumber(L, 1);
  807. text = mg_get_response_code_text(NULL, (int)code);
  808. if (text)
  809. lua_pushstring(L, text);
  810. return text ? 1 : 0;
  811. }
  812. }
  813. /* Syntax error */
  814. return luaL_error(L, "invalid get_response_code_text() call");
  815. }
  816. /* mg.random - might be better than math.random on some systems */
  817. static int
  818. lsp_random(lua_State *L)
  819. {
  820. int num_args = lua_gettop(L);
  821. if (num_args == 0) {
  822. /* The civetweb internal random number generator will generate
  823. * a 64 bit random number. */
  824. uint64_t r = get_random();
  825. /* Lua "number" is a IEEE 754 double precission float:
  826. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  827. * Thus, mask with 2^53-1 to get an integer with the maximum
  828. * precission available. */
  829. r &= ((((uint64_t)1) << 53) - 1);
  830. lua_pushnumber(L, (double)r);
  831. return 1;
  832. }
  833. /* Syntax error */
  834. return luaL_error(L, "invalid random() call");
  835. }
  836. union {
  837. void *p;
  838. void (*f)(unsigned char uuid[16]);
  839. } pf_uuid_generate;
  840. /* mg.uuid */
  841. static int
  842. lsp_uuid(lua_State *L)
  843. {
  844. union {
  845. unsigned char uuid_array[16];
  846. struct uuid_struct_type {
  847. uint32_t data1;
  848. uint16_t data2;
  849. uint16_t data3;
  850. uint8_t data4[8];
  851. } uuid_struct;
  852. } uuid;
  853. char uuid_str[40];
  854. int num_args = lua_gettop(L);
  855. memset(&uuid, 0, sizeof(uuid));
  856. memset(uuid_str, 0, sizeof(uuid_str));
  857. if (num_args == 0) {
  858. pf_uuid_generate.f(uuid.uuid_array);
  859. sprintf(uuid_str,
  860. "{%08lX-%04X-%04X-%02X%02X-"
  861. "%02X%02X%02X%02X%02X%02X}",
  862. (unsigned long)uuid.uuid_struct.data1,
  863. (unsigned)uuid.uuid_struct.data2,
  864. (unsigned)uuid.uuid_struct.data3,
  865. (unsigned)uuid.uuid_struct.data4[0],
  866. (unsigned)uuid.uuid_struct.data4[1],
  867. (unsigned)uuid.uuid_struct.data4[2],
  868. (unsigned)uuid.uuid_struct.data4[3],
  869. (unsigned)uuid.uuid_struct.data4[4],
  870. (unsigned)uuid.uuid_struct.data4[5],
  871. (unsigned)uuid.uuid_struct.data4[6],
  872. (unsigned)uuid.uuid_struct.data4[7]);
  873. lua_pushstring(L, uuid_str);
  874. return 1;
  875. }
  876. /* Syntax error */
  877. return luaL_error(L, "invalid random() call");
  878. }
  879. #ifdef USE_WEBSOCKET
  880. struct lua_websock_data {
  881. lua_State *state;
  882. char *script;
  883. unsigned references;
  884. struct mg_connection *conn[MAX_WORKER_THREADS];
  885. pthread_mutex_t ws_mutex;
  886. };
  887. #endif
  888. /* mg.write for websockets */
  889. static int
  890. lwebsock_write(lua_State *L)
  891. {
  892. #ifdef USE_WEBSOCKET
  893. int num_args = lua_gettop(L);
  894. struct lua_websock_data *ws;
  895. const char *str;
  896. size_t size;
  897. int opcode = -1;
  898. unsigned i;
  899. struct mg_connection *client = NULL;
  900. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  901. lua_gettable(L, LUA_REGISTRYINDEX);
  902. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  903. (void)pthread_mutex_lock(&(ws->ws_mutex));
  904. if (num_args == 1) {
  905. /* just one text: send it to all client */
  906. if (lua_isstring(L, 1)) {
  907. opcode = WEBSOCKET_OPCODE_TEXT;
  908. }
  909. } else if (num_args == 2) {
  910. if (lua_isnumber(L, 1)) {
  911. /* opcode number and message text */
  912. opcode = (int)lua_tointeger(L, 1);
  913. } else if (lua_isstring(L, 1)) {
  914. /* opcode string and message text */
  915. str = lua_tostring(L, 1);
  916. if (!mg_strncasecmp(str, "text", 4))
  917. opcode = WEBSOCKET_OPCODE_TEXT;
  918. else if (!mg_strncasecmp(str, "bin", 3))
  919. opcode = WEBSOCKET_OPCODE_BINARY;
  920. else if (!mg_strncasecmp(str, "close", 5))
  921. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  922. else if (!mg_strncasecmp(str, "ping", 4))
  923. opcode = WEBSOCKET_OPCODE_PING;
  924. else if (!mg_strncasecmp(str, "pong", 4))
  925. opcode = WEBSOCKET_OPCODE_PONG;
  926. else if (!mg_strncasecmp(str, "cont", 4))
  927. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  928. } else if (lua_isuserdata(L, 1)) {
  929. /* client id and message text */
  930. client = (struct mg_connection *)lua_touserdata(L, 1);
  931. opcode = WEBSOCKET_OPCODE_TEXT;
  932. }
  933. } else if (num_args == 3) {
  934. if (lua_isuserdata(L, 1)) {
  935. client = (struct mg_connection *)lua_touserdata(L, 1);
  936. if (lua_isnumber(L, 2)) {
  937. /* client id, opcode number and message text */
  938. opcode = (int)lua_tointeger(L, 2);
  939. } else if (lua_isstring(L, 2)) {
  940. /* client id, opcode string and message text */
  941. str = lua_tostring(L, 2);
  942. if (!mg_strncasecmp(str, "text", 4))
  943. opcode = WEBSOCKET_OPCODE_TEXT;
  944. else if (!mg_strncasecmp(str, "bin", 3))
  945. opcode = WEBSOCKET_OPCODE_BINARY;
  946. else if (!mg_strncasecmp(str, "close", 5))
  947. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  948. else if (!mg_strncasecmp(str, "ping", 4))
  949. opcode = WEBSOCKET_OPCODE_PING;
  950. else if (!mg_strncasecmp(str, "pong", 4))
  951. opcode = WEBSOCKET_OPCODE_PONG;
  952. else if (!mg_strncasecmp(str, "cont", 4))
  953. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  954. }
  955. }
  956. }
  957. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  958. str = lua_tolstring(L, num_args, &size);
  959. if (client) {
  960. for (i = 0; i < ws->references; i++) {
  961. if (client == ws->conn[i]) {
  962. mg_websocket_write(ws->conn[i], opcode, str, size);
  963. }
  964. }
  965. } else {
  966. for (i = 0; i < ws->references; i++) {
  967. mg_websocket_write(ws->conn[i], opcode, str, size);
  968. }
  969. }
  970. } else {
  971. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  972. return luaL_error(L, "invalid websocket write() call");
  973. }
  974. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  975. #else
  976. (void)(L); /* unused */
  977. #endif
  978. return 0;
  979. }
  980. struct laction_arg {
  981. lua_State *state;
  982. const char *script;
  983. pthread_mutex_t *pmutex;
  984. char txt[1];
  985. };
  986. static int
  987. lua_action(struct laction_arg *arg)
  988. {
  989. int err, ok;
  990. struct mg_context *ctx;
  991. (void)pthread_mutex_lock(arg->pmutex);
  992. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  993. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  994. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  995. err = luaL_loadstring(arg->state, arg->txt);
  996. if (err != 0) {
  997. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  998. (void)pthread_mutex_unlock(arg->pmutex);
  999. mg_free(arg);
  1000. return 0;
  1001. }
  1002. err = lua_pcall(arg->state, 0, 1, 0);
  1003. if (err != 0) {
  1004. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1005. (void)pthread_mutex_unlock(arg->pmutex);
  1006. mg_free(arg);
  1007. return 0;
  1008. }
  1009. ok = lua_type(arg->state, -1);
  1010. if (lua_isboolean(arg->state, -1)) {
  1011. ok = lua_toboolean(arg->state, -1);
  1012. } else {
  1013. ok = 0;
  1014. }
  1015. lua_pop(arg->state, 1);
  1016. (void)pthread_mutex_unlock(arg->pmutex);
  1017. if (!ok) {
  1018. mg_free(arg);
  1019. }
  1020. return ok;
  1021. }
  1022. static int
  1023. lua_action_free(struct laction_arg *arg)
  1024. {
  1025. if (lua_action(arg)) {
  1026. mg_free(arg);
  1027. }
  1028. return 0;
  1029. }
  1030. static int
  1031. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1032. {
  1033. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1034. int num_args = lua_gettop(L);
  1035. struct lua_websock_data *ws;
  1036. int type1, type2, ok = 0;
  1037. double timediff;
  1038. struct mg_context *ctx;
  1039. struct laction_arg *arg;
  1040. const char *txt;
  1041. size_t txt_len;
  1042. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1043. lua_gettable(L, LUA_REGISTRYINDEX);
  1044. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1045. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1046. lua_gettable(L, LUA_REGISTRYINDEX);
  1047. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1048. if (num_args < 2) {
  1049. return luaL_error(L,
  1050. "not enough arguments for set_timer/interval() call");
  1051. }
  1052. type1 = lua_type(L, 1);
  1053. type2 = lua_type(L, 2);
  1054. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1055. timediff = (double)lua_tonumber(L, 2);
  1056. txt = lua_tostring(L, 1);
  1057. txt_len = strlen(txt);
  1058. arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg)
  1059. + txt_len + 10);
  1060. arg->state = L;
  1061. arg->script = ws->script;
  1062. arg->pmutex = &(ws->ws_mutex);
  1063. memcpy(arg->txt, "return(", 7);
  1064. memcpy(arg->txt + 7, txt, txt_len);
  1065. arg->txt[txt_len + 7] = ')';
  1066. arg->txt[txt_len + 8] = 0;
  1067. ok =
  1068. (0
  1069. == timer_add(ctx,
  1070. timediff,
  1071. is_periodic,
  1072. 1,
  1073. (taction)(is_periodic ? lua_action : lua_action_free),
  1074. (void *)arg));
  1075. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1076. /* TODO (mid): not implemented yet */
  1077. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1078. } else {
  1079. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1080. }
  1081. lua_pushboolean(L, ok);
  1082. return 1;
  1083. #else
  1084. (void)(L); /* unused */
  1085. (void)(is_periodic); /* unused */
  1086. return 0;
  1087. #endif
  1088. }
  1089. /* mg.set_timeout for websockets */
  1090. static int
  1091. lwebsocket_set_timeout(lua_State *L)
  1092. {
  1093. return lwebsocket_set_timer(L, 0);
  1094. }
  1095. /* mg.set_interval for websockets */
  1096. static int
  1097. lwebsocket_set_interval(lua_State *L)
  1098. {
  1099. return lwebsocket_set_timer(L, 1);
  1100. }
  1101. enum {
  1102. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1103. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1104. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1105. };
  1106. static void
  1107. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1108. {
  1109. const char *s;
  1110. int i;
  1111. /* Export mg.request_info */
  1112. lua_pushstring(L, "request_info");
  1113. lua_newtable(L);
  1114. reg_string(L, "request_method", conn->request_info.request_method);
  1115. reg_string(L, "request_uri", conn->request_info.request_uri);
  1116. reg_string(L, "uri", conn->request_info.local_uri);
  1117. reg_string(L, "http_version", conn->request_info.http_version);
  1118. reg_string(L, "query_string", conn->request_info.query_string);
  1119. #if defined(MG_LEGACY_INTERFACE)
  1120. reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is
  1121. deprecated, use
  1122. remote_addr
  1123. instead */
  1124. #endif
  1125. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1126. /* TODO (high): ip version */
  1127. reg_int(L, "remote_port", conn->request_info.remote_port);
  1128. reg_int(L, "num_headers", conn->request_info.num_headers);
  1129. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1130. if (conn->path_info != NULL) {
  1131. reg_string(L, "path_info", conn->path_info);
  1132. }
  1133. if (conn->request_info.content_length >= 0) {
  1134. /* reg_int64: content_length */
  1135. lua_pushstring(L, "content_length");
  1136. lua_pushnumber(
  1137. L,
  1138. (lua_Number)conn->request_info
  1139. .content_length); /* lua_Number may be used as 52 bit integer */
  1140. lua_rawset(L, -3);
  1141. }
  1142. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1143. reg_string(L, "content_type", s);
  1144. }
  1145. if (conn->request_info.remote_user != NULL) {
  1146. reg_string(L, "remote_user", conn->request_info.remote_user);
  1147. reg_string(L, "auth_type", "Digest");
  1148. }
  1149. reg_boolean(L, "https", conn->ssl != NULL);
  1150. if (conn->status_code > 0) {
  1151. /* Lua error handler should show the status code */
  1152. reg_int(L, "status", conn->status_code);
  1153. }
  1154. lua_pushstring(L, "http_headers");
  1155. lua_newtable(L);
  1156. for (i = 0; i < conn->request_info.num_headers; i++) {
  1157. reg_string(L,
  1158. conn->request_info.http_headers[i].name,
  1159. conn->request_info.http_headers[i].value);
  1160. }
  1161. lua_rawset(L, -3);
  1162. lua_rawset(L, -3);
  1163. }
  1164. void
  1165. civetweb_open_lua_libs(lua_State *L)
  1166. {
  1167. {
  1168. extern void luaL_openlibs(lua_State *);
  1169. luaL_openlibs(L);
  1170. }
  1171. #ifdef USE_LUA_SQLITE3
  1172. {
  1173. extern int luaopen_lsqlite3(lua_State *);
  1174. luaopen_lsqlite3(L);
  1175. }
  1176. #endif
  1177. #ifdef USE_LUA_LUAXML
  1178. {
  1179. extern int luaopen_LuaXML_lib(lua_State *);
  1180. luaopen_LuaXML_lib(L);
  1181. }
  1182. #endif
  1183. #ifdef USE_LUA_FILE_SYSTEM
  1184. {
  1185. extern int luaopen_lfs(lua_State *);
  1186. luaopen_lfs(L);
  1187. }
  1188. #endif
  1189. #ifdef USE_LUA_BINARY
  1190. {
  1191. /* TODO (low): Test if this could be used as a replacement for bit32.
  1192. * Check again with Lua 5.3 later. */
  1193. extern int luaopen_binary(lua_State *);
  1194. luaL_requiref(L, "binary", luaopen_binary, 1);
  1195. lua_pop(L, 1);
  1196. }
  1197. #endif
  1198. }
  1199. static void
  1200. prepare_lua_environment(struct mg_context *ctx,
  1201. struct mg_connection *conn,
  1202. struct lua_websock_data *ws_conn_list,
  1203. lua_State *L,
  1204. const char *script_name,
  1205. int lua_env_type)
  1206. {
  1207. civetweb_open_lua_libs(L);
  1208. #if LUA_VERSION_NUM == 502
  1209. /* Keep the "connect" method for compatibility,
  1210. * but do not backport it to Lua 5.1.
  1211. * TODO: Redesign the interface.
  1212. */
  1213. luaL_newmetatable(L, LUASOCKET);
  1214. lua_pushliteral(L, "__index");
  1215. luaL_newlib(L, luasocket_methods);
  1216. lua_rawset(L, -3);
  1217. lua_pop(L, 1);
  1218. lua_register(L, "connect", lsp_connect);
  1219. #endif
  1220. /* Store context in the registry */
  1221. if (ctx != NULL) {
  1222. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1223. lua_pushlightuserdata(L, (void *)ctx);
  1224. lua_settable(L, LUA_REGISTRYINDEX);
  1225. }
  1226. if (ws_conn_list != NULL) {
  1227. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1228. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1229. lua_settable(L, LUA_REGISTRYINDEX);
  1230. }
  1231. /* Lua server pages store the depth of mg.include, in order
  1232. * to detect recursions and prevent stack overflows. */
  1233. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1234. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_depth);
  1235. lua_pushinteger(L, 0);
  1236. lua_settable(L, LUA_REGISTRYINDEX);
  1237. }
  1238. /* Register mg module */
  1239. lua_newtable(L);
  1240. switch (lua_env_type) {
  1241. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1242. reg_string(L, "lua_type", "page");
  1243. break;
  1244. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1245. reg_string(L, "lua_type", "script");
  1246. break;
  1247. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1248. reg_string(L, "lua_type", "websocket");
  1249. break;
  1250. }
  1251. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1252. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1253. reg_conn_function(L, "cry", lsp_cry, conn);
  1254. reg_conn_function(L, "read", lsp_read, conn);
  1255. reg_conn_function(L, "write", lsp_write, conn);
  1256. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1257. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1258. }
  1259. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1260. reg_conn_function(L, "include", lsp_include, conn);
  1261. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1262. }
  1263. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1264. reg_function(L, "write", lwebsock_write);
  1265. #ifdef USE_TIMERS
  1266. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1267. reg_function(L, "set_interval", lwebsocket_set_interval);
  1268. #endif
  1269. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1270. }
  1271. reg_function(L, "time", lsp_get_time);
  1272. reg_function(L, "get_var", lsp_get_var);
  1273. reg_function(L, "get_mime_type", lsp_get_mime_type);
  1274. reg_function(L, "get_cookie", lsp_get_cookie);
  1275. reg_function(L, "md5", lsp_md5);
  1276. reg_function(L, "url_encode", lsp_url_encode);
  1277. reg_function(L, "url_decode", lsp_url_decode);
  1278. reg_function(L, "base64_encode", lsp_base64_encode);
  1279. reg_function(L, "base64_decode", lsp_base64_decode);
  1280. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1281. reg_function(L, "random", lsp_random);
  1282. if (pf_uuid_generate.f) {
  1283. reg_function(L, "uuid", lsp_uuid);
  1284. }
  1285. reg_string(L, "version", CIVETWEB_VERSION);
  1286. reg_string(L, "script_name", script_name);
  1287. if (ctx != NULL) {
  1288. reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
  1289. reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
  1290. #if defined(USE_WEBSOCKET)
  1291. if (ctx->config[WEBSOCKET_ROOT]) {
  1292. reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
  1293. } else {
  1294. reg_string(L, "websocket_root", ctx->config[DOCUMENT_ROOT]);
  1295. }
  1296. #endif
  1297. if (ctx->systemName != NULL) {
  1298. reg_string(L, "system", ctx->systemName);
  1299. }
  1300. }
  1301. /* Export connection specific info */
  1302. if (conn != NULL) {
  1303. prepare_lua_request_info(conn, L);
  1304. }
  1305. lua_setglobal(L, "mg");
  1306. /* Register default mg.onerror function */
  1307. IGNORE_UNUSED_RESULT(
  1308. luaL_dostring(L,
  1309. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1310. "debug.traceback(e, 1)) end"));
  1311. if (ctx != NULL) {
  1312. /* Preload */
  1313. if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
  1314. IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
  1315. }
  1316. if (ctx->callbacks.init_lua != NULL) {
  1317. ctx->callbacks.init_lua(conn, L);
  1318. }
  1319. }
  1320. }
  1321. static int
  1322. lua_error_handler(lua_State *L)
  1323. {
  1324. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1325. lua_getglobal(L, "mg");
  1326. if (!lua_isnil(L, -1)) {
  1327. lua_getfield(L, -1, "write"); /* call mg.write() */
  1328. lua_pushstring(L, error_msg);
  1329. lua_pushliteral(L, "\n");
  1330. lua_call(L, 2, 0);
  1331. IGNORE_UNUSED_RESULT(
  1332. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1333. } else {
  1334. printf("Lua error: [%s]\n", error_msg);
  1335. IGNORE_UNUSED_RESULT(
  1336. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1337. }
  1338. /* TODO(lsm, low): leave the stack balanced */
  1339. return 0;
  1340. }
  1341. static void *
  1342. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1343. {
  1344. (void)ud;
  1345. (void)osize; /* not used */
  1346. if (nsize == 0) {
  1347. mg_free(ptr);
  1348. return NULL;
  1349. }
  1350. return mg_realloc(ptr, nsize);
  1351. }
  1352. static void
  1353. mg_exec_lua_script(struct mg_connection *conn,
  1354. const char *path,
  1355. const void **exports)
  1356. {
  1357. int i;
  1358. lua_State *L;
  1359. /* Assume the script does not support keep_alive. The script may change this
  1360. * by calling mg.keep_alive(true). */
  1361. conn->must_close = 1;
  1362. /* Execute a plain Lua script. */
  1363. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  1364. prepare_lua_environment(
  1365. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1366. lua_pushcclosure(L, &lua_error_handler, 0);
  1367. if (exports != NULL) {
  1368. #if LUA_VERSION_NUM > 501
  1369. lua_pushglobaltable(L);
  1370. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1371. lua_CFunction func;
  1372. lua_pushstring(L, (const char *)(exports[i]));
  1373. *(const void **)(&func) = exports[i + 1];
  1374. lua_pushcclosure(L, func, 0);
  1375. lua_rawset(L, -3);
  1376. }
  1377. #else
  1378. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1379. lua_CFunction func;
  1380. const char *name = (const char *)(exports[i]);
  1381. *(const void **)(&func) = exports[i + 1];
  1382. lua_register(L, name, func);
  1383. }
  1384. #endif
  1385. }
  1386. if (luaL_loadfile(L, path) != 0) {
  1387. lua_error_handler(L);
  1388. }
  1389. lua_pcall(L, 0, 0, -2);
  1390. lua_close(L);
  1391. }
  1392. }
  1393. static int
  1394. handle_lsp_request(struct mg_connection *conn,
  1395. const char *path,
  1396. struct mg_file *filep,
  1397. struct lua_State *ls)
  1398. {
  1399. void *p = NULL;
  1400. lua_State *L = NULL;
  1401. int error = 1;
  1402. struct mg_file filesize = STRUCT_FILE_INITIALIZER;
  1403. /* Assume the script does not support keep_alive. The script may change this
  1404. * by calling mg.keep_alive(true). */
  1405. conn->must_close = 1;
  1406. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  1407. if (!mg_stat(conn, path, &filesize.stat)) {
  1408. /* File not found */
  1409. if (ls == NULL) {
  1410. send_http_error(conn, 500, "Error: File %s not found", path);
  1411. } else {
  1412. luaL_error(ls, "File [%s] not found", path);
  1413. }
  1414. goto cleanup_handle_lsp_request;
  1415. }
  1416. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  1417. /* File not found or not accessible */
  1418. if (ls == NULL) {
  1419. send_http_error(conn,
  1420. 500,
  1421. "Error: Cannot open script file %s",
  1422. path);
  1423. } else {
  1424. luaL_error(ls, "Cannot [%s] not found", path);
  1425. }
  1426. goto cleanup_handle_lsp_request;
  1427. }
  1428. /* TODO: Operations mg_fopen and mg_stat should do what their names
  1429. * indicate. They should not fill in different members of the same
  1430. * struct mg_file.
  1431. * See Github issue #225 */
  1432. filep->stat.size = filesize.stat.size;
  1433. if (filep->access.membuf == NULL
  1434. && (p = mmap(NULL,
  1435. (size_t)filep->stat.size,
  1436. PROT_READ,
  1437. MAP_PRIVATE,
  1438. fileno(filep->access.fp),
  1439. 0)) == MAP_FAILED) {
  1440. /* mmap failed */
  1441. if (ls == NULL) {
  1442. send_http_error(
  1443. conn,
  1444. 500,
  1445. "Error: Cannot open script\nFile %s can not be mapped",
  1446. path);
  1447. } else {
  1448. luaL_error(ls,
  1449. "mmap(%s, %zu, %d): %s",
  1450. path,
  1451. (size_t)filep->stat.size,
  1452. fileno(filep->access.fp),
  1453. strerror(errno));
  1454. }
  1455. goto cleanup_handle_lsp_request;
  1456. }
  1457. if (ls != NULL) {
  1458. L = ls;
  1459. } else {
  1460. L = lua_newstate(lua_allocator, NULL);
  1461. if (L == NULL) {
  1462. send_http_error(
  1463. conn,
  1464. 500,
  1465. "%s",
  1466. "Error: Cannot execute script\nlua_newstate failed");
  1467. goto cleanup_handle_lsp_request;
  1468. }
  1469. prepare_lua_environment(
  1470. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1471. }
  1472. /* Lua state is ready to use */
  1473. /* We're not sending HTTP headers here, Lua page must do it. */
  1474. error =
  1475. lsp(conn,
  1476. path,
  1477. (filep->access.membuf == NULL) ? (const char *)p
  1478. : (const char *)filep->access.membuf,
  1479. filep->stat.size,
  1480. L);
  1481. cleanup_handle_lsp_request:
  1482. if (L != NULL && ls == NULL)
  1483. lua_close(L);
  1484. if (p != NULL)
  1485. munmap(p, filep->stat.size);
  1486. (void)mg_fclose(&filep->access);
  1487. return error;
  1488. }
  1489. #ifdef USE_WEBSOCKET
  1490. struct mg_shared_lua_websocket_list {
  1491. struct lua_websock_data ws;
  1492. struct mg_shared_lua_websocket_list *next;
  1493. };
  1494. static void *
  1495. lua_websocket_new(const char *script, struct mg_connection *conn)
  1496. {
  1497. struct mg_shared_lua_websocket_list **shared_websock_list =
  1498. &(conn->ctx->shared_lua_websockets);
  1499. struct lua_websock_data *ws;
  1500. int err, ok = 0;
  1501. assert(conn->lua_websocket_state == NULL);
  1502. /* lock list (mg_context global) */
  1503. mg_lock_context(conn->ctx);
  1504. while (*shared_websock_list) {
  1505. /* check if ws already in list */
  1506. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1507. break;
  1508. }
  1509. shared_websock_list = &((*shared_websock_list)->next);
  1510. }
  1511. if (*shared_websock_list == NULL) {
  1512. /* add ws to list */
  1513. *shared_websock_list = (struct mg_shared_lua_websocket_list *)
  1514. mg_calloc(sizeof(struct mg_shared_lua_websocket_list), 1);
  1515. if (*shared_websock_list == NULL) {
  1516. mg_unlock_context(conn->ctx);
  1517. mg_cry(conn, "Cannot create shared websocket struct, OOM");
  1518. return NULL;
  1519. }
  1520. /* init ws list element */
  1521. ws = &(*shared_websock_list)->ws;
  1522. ws->script = mg_strdup(script); /* TODO (low): handle OOM */
  1523. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1524. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1525. ws->state = lua_newstate(lua_allocator, NULL);
  1526. ws->conn[0] = conn;
  1527. ws->references = 1;
  1528. prepare_lua_environment(
  1529. conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  1530. err = luaL_loadfile(ws->state, script);
  1531. if (err != 0) {
  1532. lua_cry(conn, err, ws->state, script, "load");
  1533. }
  1534. err = lua_pcall(ws->state, 0, 0, 0);
  1535. if (err != 0) {
  1536. lua_cry(conn, err, ws->state, script, "init");
  1537. }
  1538. } else {
  1539. /* inc ref count */
  1540. ws = &(*shared_websock_list)->ws;
  1541. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1542. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1543. }
  1544. mg_unlock_context(conn->ctx);
  1545. /* call add */
  1546. lua_getglobal(ws->state, "open");
  1547. lua_newtable(ws->state);
  1548. prepare_lua_request_info(conn, ws->state);
  1549. lua_pushstring(ws->state, "client");
  1550. lua_pushlightuserdata(ws->state, (void *)conn);
  1551. lua_rawset(ws->state, -3);
  1552. err = lua_pcall(ws->state, 1, 1, 0);
  1553. if (err != 0) {
  1554. lua_cry(conn, err, ws->state, script, "open handler");
  1555. } else {
  1556. if (lua_isboolean(ws->state, -1)) {
  1557. ok = lua_toboolean(ws->state, -1);
  1558. }
  1559. lua_pop(ws->state, 1);
  1560. }
  1561. if (!ok) {
  1562. /* Remove from ws connection list. */
  1563. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1564. * (see websocket_close). */
  1565. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1566. }
  1567. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1568. return ok ? (void *)ws : NULL;
  1569. }
  1570. static int
  1571. lua_websocket_data(struct mg_connection *conn,
  1572. int bits,
  1573. char *data,
  1574. size_t data_len,
  1575. void *ws_arg)
  1576. {
  1577. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1578. int err, ok = 0;
  1579. assert(ws != NULL);
  1580. assert(ws->state != NULL);
  1581. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1582. lua_getglobal(ws->state, "data");
  1583. lua_newtable(ws->state);
  1584. lua_pushstring(ws->state, "client");
  1585. lua_pushlightuserdata(ws->state, (void *)conn);
  1586. lua_rawset(ws->state, -3);
  1587. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1588. a meaning according to
  1589. http://tools.ietf.org/html/rfc6455,
  1590. section 5.2 */
  1591. lua_pushnumber(ws->state, bits);
  1592. lua_rawset(ws->state, -3);
  1593. lua_pushstring(ws->state, "data");
  1594. lua_pushlstring(ws->state, data, data_len);
  1595. lua_rawset(ws->state, -3);
  1596. err = lua_pcall(ws->state, 1, 1, 0);
  1597. if (err != 0) {
  1598. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1599. } else {
  1600. if (lua_isboolean(ws->state, -1)) {
  1601. ok = lua_toboolean(ws->state, -1);
  1602. }
  1603. lua_pop(ws->state, 1);
  1604. }
  1605. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1606. return ok;
  1607. }
  1608. static int
  1609. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1610. {
  1611. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1612. int err, ok = 0;
  1613. assert(ws != NULL);
  1614. assert(ws->state != NULL);
  1615. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1616. lua_getglobal(ws->state, "ready");
  1617. lua_newtable(ws->state);
  1618. lua_pushstring(ws->state, "client");
  1619. lua_pushlightuserdata(ws->state, (void *)conn);
  1620. lua_rawset(ws->state, -3);
  1621. err = lua_pcall(ws->state, 1, 1, 0);
  1622. if (err != 0) {
  1623. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1624. } else {
  1625. if (lua_isboolean(ws->state, -1)) {
  1626. ok = lua_toboolean(ws->state, -1);
  1627. }
  1628. lua_pop(ws->state, 1);
  1629. }
  1630. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1631. return ok;
  1632. }
  1633. static void
  1634. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1635. {
  1636. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1637. struct mg_shared_lua_websocket_list **shared_websock_list =
  1638. &(conn->ctx->shared_lua_websockets);
  1639. int err = 0;
  1640. unsigned i;
  1641. assert(ws != NULL);
  1642. assert(ws->state != NULL);
  1643. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1644. lua_getglobal(ws->state, "close");
  1645. lua_newtable(ws->state);
  1646. lua_pushstring(ws->state, "client");
  1647. lua_pushlightuserdata(ws->state, (void *)conn);
  1648. lua_rawset(ws->state, -3);
  1649. err = lua_pcall(ws->state, 1, 0, 0);
  1650. if (err != 0) {
  1651. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1652. }
  1653. for (i = 0; i < ws->references; i++) {
  1654. if (ws->conn[i] == conn) {
  1655. ws->references--;
  1656. ws->conn[i] = ws->conn[ws->references];
  1657. }
  1658. }
  1659. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1660. This must only be done, when all connections are closed, and all
  1661. asynchronous operations and timers are completed/expired. */
  1662. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1663. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1664. }
  1665. #endif
  1666. lua_State *
  1667. mg_prepare_lua_context_script(const char *file_name,
  1668. struct mg_context *ctx,
  1669. char *ebuf,
  1670. size_t ebuf_len)
  1671. {
  1672. struct lua_State *L;
  1673. int lua_ret;
  1674. const char *lua_err_txt;
  1675. L = luaL_newstate();
  1676. if (L == NULL) {
  1677. mg_snprintf(NULL,
  1678. NULL, /* No truncation check for ebuf */
  1679. ebuf,
  1680. ebuf_len,
  1681. "Error: %s",
  1682. "Cannot create Lua state");
  1683. return 0;
  1684. }
  1685. civetweb_open_lua_libs(L);
  1686. lua_ret = luaL_loadfile(L, file_name);
  1687. if (lua_ret != LUA_OK) {
  1688. /* Error when loading the file (e.g. file not found, out of memory, ...)
  1689. */
  1690. lua_err_txt = lua_tostring(L, -1);
  1691. mg_snprintf(NULL,
  1692. NULL, /* No truncation check for ebuf */
  1693. ebuf,
  1694. ebuf_len,
  1695. "Error loading file %s: %s\n",
  1696. file_name,
  1697. lua_err_txt);
  1698. return 0;
  1699. }
  1700. /* The script file is loaded, now call it */
  1701. lua_ret = lua_pcall(L,
  1702. /* no arguments */ 0,
  1703. /* zero or one return value */ 1,
  1704. /* errors as strint return value */ 0);
  1705. if (lua_ret != LUA_OK) {
  1706. /* Error when executing the script */
  1707. lua_err_txt = lua_tostring(L, -1);
  1708. mg_snprintf(NULL,
  1709. NULL, /* No truncation check for ebuf */
  1710. ebuf,
  1711. ebuf_len,
  1712. "Error running file %s: %s\n",
  1713. file_name,
  1714. lua_err_txt);
  1715. return 0;
  1716. }
  1717. /* lua_close(L); must be done somewhere else */
  1718. return L;
  1719. }
  1720. int
  1721. run_lua(const char *file_name)
  1722. {
  1723. int func_ret = EXIT_FAILURE;
  1724. char ebuf[512] = {0};
  1725. lua_State *L =
  1726. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  1727. if (L) {
  1728. /* Script executed */
  1729. if (lua_type(L, -1) == LUA_TNUMBER) {
  1730. func_ret = (int)lua_tonumber(L, -1);
  1731. } else {
  1732. func_ret = EXIT_SUCCESS;
  1733. }
  1734. lua_close(L);
  1735. } else {
  1736. fprintf(stderr, "%s\n", ebuf);
  1737. }
  1738. return func_ret;
  1739. }
  1740. static void *lib_handle_uuid = NULL;
  1741. static void
  1742. lua_init_optional_libraries(void)
  1743. {
  1744. #if !defined(_WIN32)
  1745. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  1746. pf_uuid_generate.p =
  1747. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  1748. #else
  1749. pf_uuid_generate.p = 0;
  1750. #endif
  1751. }
  1752. static void
  1753. lua_exit_optional_libraries(void)
  1754. {
  1755. #if !defined(_WIN32)
  1756. if (lib_handle_uuid) {
  1757. dlclose(lib_handle_uuid);
  1758. }
  1759. #endif
  1760. pf_uuid_generate.p = 0;
  1761. lib_handle_uuid = NULL;
  1762. }