mod_lua.inl 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  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. if (num_args >= 2 && num_args <= 3) {
  575. char *dst;
  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. /* Allocate dynamically, so there is no internal limit for get_var */
  580. dst = (char *)mg_malloc(data_len + 1);
  581. if (!dst) {
  582. return luaL_error(L, "out of memory in get_var() call");
  583. }
  584. ret = mg_get_var2(data, data_len, var_name, dst, data_len, occurrence);
  585. if (ret >= 0) {
  586. /* Variable found: return value to Lua */
  587. lua_pushstring(L, dst);
  588. } else {
  589. /* Variable not found (TODO (mid): may be string too long) */
  590. lua_pushnil(L);
  591. }
  592. mg_free(dst);
  593. } else {
  594. /* Syntax error */
  595. return luaL_error(L, "invalid get_var() call");
  596. }
  597. return 1;
  598. }
  599. /* mg.get_mime_type */
  600. static int
  601. lsp_get_mime_type(lua_State *L)
  602. {
  603. int num_args = lua_gettop(L);
  604. struct vec mime_type = {0, 0};
  605. struct mg_context *ctx;
  606. const char *text;
  607. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  608. lua_gettable(L, LUA_REGISTRYINDEX);
  609. ctx = (struct mg_context *)lua_touserdata(L, -1);
  610. if (num_args == 1) {
  611. text = lua_tostring(L, 1);
  612. if (text) {
  613. if (ctx) {
  614. get_mime_type(ctx, text, &mime_type);
  615. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  616. } else {
  617. text = mg_get_builtin_mime_type(text);
  618. lua_pushstring(L, text);
  619. }
  620. } else {
  621. /* Syntax error */
  622. return luaL_error(L, "invalid argument for get_mime_type() call");
  623. }
  624. } else {
  625. /* Syntax error */
  626. return luaL_error(L, "invalid get_mime_type() call");
  627. }
  628. return 1;
  629. }
  630. /* mg.get_cookie */
  631. static int
  632. lsp_get_cookie(lua_State *L)
  633. {
  634. int num_args = lua_gettop(L);
  635. const char *cookie;
  636. const char *var_name;
  637. int ret;
  638. if (num_args == 2) {
  639. /* Correct number of arguments */
  640. size_t data_len;
  641. char *dst;
  642. cookie = lua_tolstring(L, 1, &data_len);
  643. var_name = lua_tostring(L, 2);
  644. if (cookie == NULL || var_name == NULL) {
  645. /* Syntax error */
  646. return luaL_error(L, "invalid get_cookie() call");
  647. }
  648. dst = (char *)mg_malloc(data_len + 1);
  649. if (!dst) {
  650. return luaL_error(L, "out of memory in get_cookie() call");
  651. }
  652. ret = mg_get_cookie(cookie, var_name, dst, data_len);
  653. if (ret >= 0) {
  654. lua_pushlstring(L, dst, ret);
  655. } else {
  656. lua_pushnil(L);
  657. }
  658. mg_free(dst);
  659. } else {
  660. /* Syntax error */
  661. return luaL_error(L, "invalid get_cookie() call");
  662. }
  663. return 1;
  664. }
  665. /* mg.md5 */
  666. static int
  667. lsp_md5(lua_State *L)
  668. {
  669. int num_args = lua_gettop(L);
  670. const char *text;
  671. md5_byte_t hash[16];
  672. md5_state_t ctx;
  673. size_t text_len;
  674. char buf[40];
  675. if (num_args == 1) {
  676. text = lua_tolstring(L, 1, &text_len);
  677. if (text) {
  678. md5_init(&ctx);
  679. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  680. md5_finish(&ctx, hash);
  681. bin2str(buf, hash, sizeof(hash));
  682. lua_pushstring(L, buf);
  683. } else {
  684. lua_pushnil(L);
  685. }
  686. } else {
  687. /* Syntax error */
  688. return luaL_error(L, "invalid md5() call");
  689. }
  690. return 1;
  691. }
  692. /* mg.url_encode */
  693. static int
  694. lsp_url_encode(lua_State *L)
  695. {
  696. int num_args = lua_gettop(L);
  697. const char *text;
  698. size_t text_len;
  699. char *dst;
  700. int dst_len;
  701. if (num_args == 1) {
  702. text = lua_tolstring(L, 1, &text_len);
  703. if (text) {
  704. dst_len = 3 * (int)text_len + 1;
  705. dst = ((text_len < 0x2AAAAAAA) ? (char *)mg_malloc(dst_len)
  706. : (char *)NULL);
  707. if (dst) {
  708. mg_url_encode(text, dst, dst_len);
  709. lua_pushstring(L, dst);
  710. mg_free(dst);
  711. } else {
  712. return luaL_error(L, "out of memory in url_decode() call");
  713. }
  714. } else {
  715. lua_pushnil(L);
  716. }
  717. } else {
  718. /* Syntax error */
  719. return luaL_error(L, "invalid url_encode() call");
  720. }
  721. return 1;
  722. }
  723. /* mg.url_decode */
  724. static int
  725. lsp_url_decode(lua_State *L)
  726. {
  727. int num_args = lua_gettop(L);
  728. const char *text;
  729. size_t text_len;
  730. int is_form;
  731. char *dst;
  732. int dst_len;
  733. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  734. text = lua_tolstring(L, 1, &text_len);
  735. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  736. if (text) {
  737. dst_len = (int)text_len + 1;
  738. dst = ((text_len < 0x7FFFFFFF) ? (char *)mg_malloc(dst_len)
  739. : (char *)NULL);
  740. if (dst) {
  741. mg_url_decode(text, (int)text_len, dst, dst_len, is_form);
  742. lua_pushstring(L, dst);
  743. mg_free(dst);
  744. } else {
  745. return luaL_error(L, "out of memory in url_decode() call");
  746. }
  747. } else {
  748. lua_pushnil(L);
  749. }
  750. } else {
  751. /* Syntax error */
  752. return luaL_error(L, "invalid url_decode() call");
  753. }
  754. return 1;
  755. }
  756. /* mg.base64_encode */
  757. static int
  758. lsp_base64_encode(lua_State *L)
  759. {
  760. int num_args = lua_gettop(L);
  761. const char *text;
  762. size_t text_len;
  763. char *dst;
  764. if (num_args == 1) {
  765. text = lua_tolstring(L, 1, &text_len);
  766. if (text) {
  767. dst = (char *)mg_malloc(text_len * 8 / 6 + 4);
  768. if (dst) {
  769. base64_encode((const unsigned char *)text, (int)text_len, dst);
  770. lua_pushstring(L, dst);
  771. mg_free(dst);
  772. } else {
  773. return luaL_error(L, "out of memory in base64_encode() call");
  774. }
  775. } else {
  776. lua_pushnil(L);
  777. }
  778. } else {
  779. /* Syntax error */
  780. return luaL_error(L, "invalid base64_encode() call");
  781. }
  782. return 1;
  783. }
  784. /* mg.base64_encode */
  785. static int
  786. lsp_base64_decode(lua_State *L)
  787. {
  788. int num_args = lua_gettop(L);
  789. const char *text;
  790. size_t text_len, dst_len;
  791. int ret;
  792. char *dst;
  793. if (num_args == 1) {
  794. text = lua_tolstring(L, 1, &text_len);
  795. if (text) {
  796. dst = (char *)mg_malloc(text_len);
  797. if (dst) {
  798. ret = base64_decode((const unsigned char *)text,
  799. (int)text_len,
  800. dst,
  801. &dst_len);
  802. if (ret != -1) {
  803. mg_free(dst);
  804. return luaL_error(
  805. L, "illegal character in lsp_base64_decode() call");
  806. } else {
  807. lua_pushlstring(L, dst, dst_len);
  808. mg_free(dst);
  809. }
  810. } else {
  811. return luaL_error(L,
  812. "out of memory in lsp_base64_decode() call");
  813. }
  814. } else {
  815. lua_pushnil(L);
  816. }
  817. } else {
  818. /* Syntax error */
  819. return luaL_error(L, "invalid lsp_base64_decode() call");
  820. }
  821. return 1;
  822. }
  823. /* mg.get_response_code_text */
  824. static int
  825. lsp_get_response_code_text(lua_State *L)
  826. {
  827. int num_args = lua_gettop(L);
  828. int type1;
  829. double code;
  830. const char *text;
  831. if (num_args == 1) {
  832. type1 = lua_type(L, 1);
  833. if (type1 == LUA_TNUMBER) {
  834. /* If the first argument is a number,
  835. convert it to the corresponding text. */
  836. code = lua_tonumber(L, 1);
  837. text = mg_get_response_code_text(NULL, (int)code);
  838. if (text)
  839. lua_pushstring(L, text);
  840. return text ? 1 : 0;
  841. }
  842. }
  843. /* Syntax error */
  844. return luaL_error(L, "invalid get_response_code_text() call");
  845. }
  846. /* mg.random - might be better than math.random on some systems */
  847. static int
  848. lsp_random(lua_State *L)
  849. {
  850. int num_args = lua_gettop(L);
  851. if (num_args == 0) {
  852. /* The civetweb internal random number generator will generate
  853. * a 64 bit random number. */
  854. uint64_t r = get_random();
  855. /* Lua "number" is a IEEE 754 double precission float:
  856. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  857. * Thus, mask with 2^53-1 to get an integer with the maximum
  858. * precission available. */
  859. r &= ((((uint64_t)1) << 53) - 1);
  860. lua_pushnumber(L, (double)r);
  861. return 1;
  862. }
  863. /* Syntax error */
  864. return luaL_error(L, "invalid random() call");
  865. }
  866. union {
  867. void *p;
  868. void (*f)(unsigned char uuid[16]);
  869. } pf_uuid_generate;
  870. /* mg.uuid */
  871. static int
  872. lsp_uuid(lua_State *L)
  873. {
  874. union {
  875. unsigned char uuid_array[16];
  876. struct uuid_struct_type {
  877. uint32_t data1;
  878. uint16_t data2;
  879. uint16_t data3;
  880. uint8_t data4[8];
  881. } uuid_struct;
  882. } uuid;
  883. char uuid_str[40];
  884. int num_args = lua_gettop(L);
  885. memset(&uuid, 0, sizeof(uuid));
  886. memset(uuid_str, 0, sizeof(uuid_str));
  887. if (num_args == 0) {
  888. pf_uuid_generate.f(uuid.uuid_array);
  889. sprintf(uuid_str,
  890. "{%08lX-%04X-%04X-%02X%02X-"
  891. "%02X%02X%02X%02X%02X%02X}",
  892. (unsigned long)uuid.uuid_struct.data1,
  893. (unsigned)uuid.uuid_struct.data2,
  894. (unsigned)uuid.uuid_struct.data3,
  895. (unsigned)uuid.uuid_struct.data4[0],
  896. (unsigned)uuid.uuid_struct.data4[1],
  897. (unsigned)uuid.uuid_struct.data4[2],
  898. (unsigned)uuid.uuid_struct.data4[3],
  899. (unsigned)uuid.uuid_struct.data4[4],
  900. (unsigned)uuid.uuid_struct.data4[5],
  901. (unsigned)uuid.uuid_struct.data4[6],
  902. (unsigned)uuid.uuid_struct.data4[7]);
  903. lua_pushstring(L, uuid_str);
  904. return 1;
  905. }
  906. /* Syntax error */
  907. return luaL_error(L, "invalid random() call");
  908. }
  909. #ifdef USE_WEBSOCKET
  910. struct lua_websock_data {
  911. lua_State *state;
  912. char *script;
  913. unsigned references;
  914. struct mg_connection *conn[MAX_WORKER_THREADS];
  915. pthread_mutex_t ws_mutex;
  916. };
  917. #endif
  918. /* mg.write for websockets */
  919. static int
  920. lwebsock_write(lua_State *L)
  921. {
  922. #ifdef USE_WEBSOCKET
  923. int num_args = lua_gettop(L);
  924. struct lua_websock_data *ws;
  925. const char *str;
  926. size_t size;
  927. int opcode = -1;
  928. unsigned i;
  929. struct mg_connection *client = NULL;
  930. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  931. lua_gettable(L, LUA_REGISTRYINDEX);
  932. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  933. (void)pthread_mutex_lock(&(ws->ws_mutex));
  934. if (num_args == 1) {
  935. /* just one text: send it to all client */
  936. if (lua_isstring(L, 1)) {
  937. opcode = WEBSOCKET_OPCODE_TEXT;
  938. }
  939. } else if (num_args == 2) {
  940. if (lua_isnumber(L, 1)) {
  941. /* opcode number and message text */
  942. opcode = (int)lua_tointeger(L, 1);
  943. } else if (lua_isstring(L, 1)) {
  944. /* opcode string and message text */
  945. str = lua_tostring(L, 1);
  946. if (!mg_strncasecmp(str, "text", 4))
  947. opcode = WEBSOCKET_OPCODE_TEXT;
  948. else if (!mg_strncasecmp(str, "bin", 3))
  949. opcode = WEBSOCKET_OPCODE_BINARY;
  950. else if (!mg_strncasecmp(str, "close", 5))
  951. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  952. else if (!mg_strncasecmp(str, "ping", 4))
  953. opcode = WEBSOCKET_OPCODE_PING;
  954. else if (!mg_strncasecmp(str, "pong", 4))
  955. opcode = WEBSOCKET_OPCODE_PONG;
  956. else if (!mg_strncasecmp(str, "cont", 4))
  957. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  958. } else if (lua_isuserdata(L, 1)) {
  959. /* client id and message text */
  960. client = (struct mg_connection *)lua_touserdata(L, 1);
  961. opcode = WEBSOCKET_OPCODE_TEXT;
  962. }
  963. } else if (num_args == 3) {
  964. if (lua_isuserdata(L, 1)) {
  965. client = (struct mg_connection *)lua_touserdata(L, 1);
  966. if (lua_isnumber(L, 2)) {
  967. /* client id, opcode number and message text */
  968. opcode = (int)lua_tointeger(L, 2);
  969. } else if (lua_isstring(L, 2)) {
  970. /* client id, opcode string and message text */
  971. str = lua_tostring(L, 2);
  972. if (!mg_strncasecmp(str, "text", 4))
  973. opcode = WEBSOCKET_OPCODE_TEXT;
  974. else if (!mg_strncasecmp(str, "bin", 3))
  975. opcode = WEBSOCKET_OPCODE_BINARY;
  976. else if (!mg_strncasecmp(str, "close", 5))
  977. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  978. else if (!mg_strncasecmp(str, "ping", 4))
  979. opcode = WEBSOCKET_OPCODE_PING;
  980. else if (!mg_strncasecmp(str, "pong", 4))
  981. opcode = WEBSOCKET_OPCODE_PONG;
  982. else if (!mg_strncasecmp(str, "cont", 4))
  983. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  984. }
  985. }
  986. }
  987. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  988. str = lua_tolstring(L, num_args, &size);
  989. if (client) {
  990. for (i = 0; i < ws->references; i++) {
  991. if (client == ws->conn[i]) {
  992. mg_websocket_write(ws->conn[i], opcode, str, size);
  993. }
  994. }
  995. } else {
  996. for (i = 0; i < ws->references; i++) {
  997. mg_websocket_write(ws->conn[i], opcode, str, size);
  998. }
  999. }
  1000. } else {
  1001. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1002. return luaL_error(L, "invalid websocket write() call");
  1003. }
  1004. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1005. #else
  1006. (void)(L); /* unused */
  1007. #endif
  1008. return 0;
  1009. }
  1010. struct laction_arg {
  1011. lua_State *state;
  1012. const char *script;
  1013. pthread_mutex_t *pmutex;
  1014. char txt[1];
  1015. };
  1016. static int
  1017. lua_action(struct laction_arg *arg)
  1018. {
  1019. int err, ok;
  1020. struct mg_context *ctx;
  1021. (void)pthread_mutex_lock(arg->pmutex);
  1022. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  1023. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  1024. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  1025. err = luaL_loadstring(arg->state, arg->txt);
  1026. if (err != 0) {
  1027. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1028. (void)pthread_mutex_unlock(arg->pmutex);
  1029. mg_free(arg);
  1030. return 0;
  1031. }
  1032. err = lua_pcall(arg->state, 0, 1, 0);
  1033. if (err != 0) {
  1034. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1035. (void)pthread_mutex_unlock(arg->pmutex);
  1036. mg_free(arg);
  1037. return 0;
  1038. }
  1039. ok = lua_type(arg->state, -1);
  1040. if (lua_isboolean(arg->state, -1)) {
  1041. ok = lua_toboolean(arg->state, -1);
  1042. } else {
  1043. ok = 0;
  1044. }
  1045. lua_pop(arg->state, 1);
  1046. (void)pthread_mutex_unlock(arg->pmutex);
  1047. if (!ok) {
  1048. mg_free(arg);
  1049. }
  1050. return ok;
  1051. }
  1052. static int
  1053. lua_action_free(struct laction_arg *arg)
  1054. {
  1055. if (lua_action(arg)) {
  1056. mg_free(arg);
  1057. }
  1058. return 0;
  1059. }
  1060. static int
  1061. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1062. {
  1063. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1064. int num_args = lua_gettop(L);
  1065. struct lua_websock_data *ws;
  1066. int type1, type2, ok = 0;
  1067. double timediff;
  1068. struct mg_context *ctx;
  1069. struct laction_arg *arg;
  1070. const char *txt;
  1071. size_t txt_len;
  1072. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1073. lua_gettable(L, LUA_REGISTRYINDEX);
  1074. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1075. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1076. lua_gettable(L, LUA_REGISTRYINDEX);
  1077. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1078. if (num_args < 2) {
  1079. return luaL_error(L,
  1080. "not enough arguments for set_timer/interval() call");
  1081. }
  1082. type1 = lua_type(L, 1);
  1083. type2 = lua_type(L, 2);
  1084. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1085. timediff = (double)lua_tonumber(L, 2);
  1086. txt = lua_tostring(L, 1);
  1087. txt_len = strlen(txt);
  1088. arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg)
  1089. + txt_len + 10);
  1090. arg->state = L;
  1091. arg->script = ws->script;
  1092. arg->pmutex = &(ws->ws_mutex);
  1093. memcpy(arg->txt, "return(", 7);
  1094. memcpy(arg->txt + 7, txt, txt_len);
  1095. arg->txt[txt_len + 7] = ')';
  1096. arg->txt[txt_len + 8] = 0;
  1097. ok =
  1098. (0
  1099. == timer_add(ctx,
  1100. timediff,
  1101. is_periodic,
  1102. 1,
  1103. (taction)(is_periodic ? lua_action : lua_action_free),
  1104. (void *)arg));
  1105. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1106. /* TODO (mid): not implemented yet */
  1107. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1108. } else {
  1109. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1110. }
  1111. lua_pushboolean(L, ok);
  1112. return 1;
  1113. #else
  1114. (void)(L); /* unused */
  1115. (void)(is_periodic); /* unused */
  1116. return 0;
  1117. #endif
  1118. }
  1119. /* mg.set_timeout for websockets */
  1120. static int
  1121. lwebsocket_set_timeout(lua_State *L)
  1122. {
  1123. return lwebsocket_set_timer(L, 0);
  1124. }
  1125. /* mg.set_interval for websockets */
  1126. static int
  1127. lwebsocket_set_interval(lua_State *L)
  1128. {
  1129. return lwebsocket_set_timer(L, 1);
  1130. }
  1131. enum {
  1132. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1133. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1134. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1135. };
  1136. static void
  1137. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1138. {
  1139. const char *s;
  1140. int i;
  1141. /* Export mg.request_info */
  1142. lua_pushstring(L, "request_info");
  1143. lua_newtable(L);
  1144. reg_string(L, "request_method", conn->request_info.request_method);
  1145. reg_string(L, "request_uri", conn->request_info.request_uri);
  1146. reg_string(L, "uri", conn->request_info.local_uri);
  1147. reg_string(L, "http_version", conn->request_info.http_version);
  1148. reg_string(L, "query_string", conn->request_info.query_string);
  1149. #if defined(MG_LEGACY_INTERFACE)
  1150. reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is
  1151. deprecated, use
  1152. remote_addr
  1153. instead */
  1154. #endif
  1155. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1156. /* TODO (high): ip version */
  1157. reg_int(L, "remote_port", conn->request_info.remote_port);
  1158. reg_int(L, "num_headers", conn->request_info.num_headers);
  1159. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1160. if (conn->path_info != NULL) {
  1161. reg_string(L, "path_info", conn->path_info);
  1162. }
  1163. if (conn->request_info.content_length >= 0) {
  1164. /* reg_int64: content_length */
  1165. lua_pushstring(L, "content_length");
  1166. lua_pushnumber(
  1167. L,
  1168. (lua_Number)conn->request_info
  1169. .content_length); /* lua_Number may be used as 52 bit integer */
  1170. lua_rawset(L, -3);
  1171. }
  1172. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1173. reg_string(L, "content_type", s);
  1174. }
  1175. if (conn->request_info.remote_user != NULL) {
  1176. reg_string(L, "remote_user", conn->request_info.remote_user);
  1177. reg_string(L, "auth_type", "Digest");
  1178. }
  1179. reg_boolean(L, "https", conn->ssl != NULL);
  1180. if (conn->status_code > 0) {
  1181. /* Lua error handler should show the status code */
  1182. reg_int(L, "status", conn->status_code);
  1183. }
  1184. lua_pushstring(L, "http_headers");
  1185. lua_newtable(L);
  1186. for (i = 0; i < conn->request_info.num_headers; i++) {
  1187. reg_string(L,
  1188. conn->request_info.http_headers[i].name,
  1189. conn->request_info.http_headers[i].value);
  1190. }
  1191. lua_rawset(L, -3);
  1192. lua_rawset(L, -3);
  1193. }
  1194. void
  1195. civetweb_open_lua_libs(lua_State *L)
  1196. {
  1197. {
  1198. extern void luaL_openlibs(lua_State *);
  1199. luaL_openlibs(L);
  1200. }
  1201. #ifdef USE_LUA_SQLITE3
  1202. {
  1203. extern int luaopen_lsqlite3(lua_State *);
  1204. luaopen_lsqlite3(L);
  1205. }
  1206. #endif
  1207. #ifdef USE_LUA_LUAXML
  1208. {
  1209. extern int luaopen_LuaXML_lib(lua_State *);
  1210. luaopen_LuaXML_lib(L);
  1211. }
  1212. #endif
  1213. #ifdef USE_LUA_FILE_SYSTEM
  1214. {
  1215. extern int luaopen_lfs(lua_State *);
  1216. luaopen_lfs(L);
  1217. }
  1218. #endif
  1219. #ifdef USE_LUA_BINARY
  1220. {
  1221. /* TODO (low): Test if this could be used as a replacement for bit32.
  1222. * Check again with Lua 5.3 later. */
  1223. extern int luaopen_binary(lua_State *);
  1224. luaL_requiref(L, "binary", luaopen_binary, 1);
  1225. lua_pop(L, 1);
  1226. }
  1227. #endif
  1228. }
  1229. static void
  1230. prepare_lua_environment(struct mg_context *ctx,
  1231. struct mg_connection *conn,
  1232. struct lua_websock_data *ws_conn_list,
  1233. lua_State *L,
  1234. const char *script_name,
  1235. int lua_env_type)
  1236. {
  1237. civetweb_open_lua_libs(L);
  1238. #if LUA_VERSION_NUM == 502
  1239. /* Keep the "connect" method for compatibility,
  1240. * but do not backport it to Lua 5.1.
  1241. * TODO: Redesign the interface.
  1242. */
  1243. luaL_newmetatable(L, LUASOCKET);
  1244. lua_pushliteral(L, "__index");
  1245. luaL_newlib(L, luasocket_methods);
  1246. lua_rawset(L, -3);
  1247. lua_pop(L, 1);
  1248. lua_register(L, "connect", lsp_connect);
  1249. #endif
  1250. /* Store context in the registry */
  1251. if (ctx != NULL) {
  1252. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1253. lua_pushlightuserdata(L, (void *)ctx);
  1254. lua_settable(L, LUA_REGISTRYINDEX);
  1255. }
  1256. if (ws_conn_list != NULL) {
  1257. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1258. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1259. lua_settable(L, LUA_REGISTRYINDEX);
  1260. }
  1261. /* Lua server pages store the depth of mg.include, in order
  1262. * to detect recursions and prevent stack overflows. */
  1263. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1264. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_depth);
  1265. lua_pushinteger(L, 0);
  1266. lua_settable(L, LUA_REGISTRYINDEX);
  1267. }
  1268. /* Register mg module */
  1269. lua_newtable(L);
  1270. switch (lua_env_type) {
  1271. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1272. reg_string(L, "lua_type", "page");
  1273. break;
  1274. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1275. reg_string(L, "lua_type", "script");
  1276. break;
  1277. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1278. reg_string(L, "lua_type", "websocket");
  1279. break;
  1280. }
  1281. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1282. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1283. reg_conn_function(L, "cry", lsp_cry, conn);
  1284. reg_conn_function(L, "read", lsp_read, conn);
  1285. reg_conn_function(L, "write", lsp_write, conn);
  1286. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1287. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1288. }
  1289. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1290. reg_conn_function(L, "include", lsp_include, conn);
  1291. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1292. }
  1293. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1294. reg_function(L, "write", lwebsock_write);
  1295. #ifdef USE_TIMERS
  1296. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1297. reg_function(L, "set_interval", lwebsocket_set_interval);
  1298. #endif
  1299. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1300. }
  1301. reg_function(L, "time", lsp_get_time);
  1302. reg_function(L, "get_var", lsp_get_var);
  1303. reg_function(L, "get_mime_type", lsp_get_mime_type);
  1304. reg_function(L, "get_cookie", lsp_get_cookie);
  1305. reg_function(L, "md5", lsp_md5);
  1306. reg_function(L, "url_encode", lsp_url_encode);
  1307. reg_function(L, "url_decode", lsp_url_decode);
  1308. reg_function(L, "base64_encode", lsp_base64_encode);
  1309. reg_function(L, "base64_decode", lsp_base64_decode);
  1310. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1311. reg_function(L, "random", lsp_random);
  1312. if (pf_uuid_generate.f) {
  1313. reg_function(L, "uuid", lsp_uuid);
  1314. }
  1315. reg_string(L, "version", CIVETWEB_VERSION);
  1316. reg_string(L, "script_name", script_name);
  1317. if (ctx != NULL) {
  1318. reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
  1319. reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
  1320. #if defined(USE_WEBSOCKET)
  1321. if (ctx->config[WEBSOCKET_ROOT]) {
  1322. reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
  1323. } else {
  1324. reg_string(L, "websocket_root", ctx->config[DOCUMENT_ROOT]);
  1325. }
  1326. #endif
  1327. if (ctx->systemName != NULL) {
  1328. reg_string(L, "system", ctx->systemName);
  1329. }
  1330. }
  1331. /* Export connection specific info */
  1332. if (conn != NULL) {
  1333. prepare_lua_request_info(conn, L);
  1334. }
  1335. lua_setglobal(L, "mg");
  1336. /* Register default mg.onerror function */
  1337. IGNORE_UNUSED_RESULT(
  1338. luaL_dostring(L,
  1339. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1340. "debug.traceback(e, 1)) end"));
  1341. if (ctx != NULL) {
  1342. /* Preload */
  1343. if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
  1344. IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
  1345. }
  1346. if (ctx->callbacks.init_lua != NULL) {
  1347. ctx->callbacks.init_lua(conn, L);
  1348. }
  1349. }
  1350. }
  1351. static int
  1352. lua_error_handler(lua_State *L)
  1353. {
  1354. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1355. lua_getglobal(L, "mg");
  1356. if (!lua_isnil(L, -1)) {
  1357. lua_getfield(L, -1, "write"); /* call mg.write() */
  1358. lua_pushstring(L, error_msg);
  1359. lua_pushliteral(L, "\n");
  1360. lua_call(L, 2, 0);
  1361. IGNORE_UNUSED_RESULT(
  1362. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1363. } else {
  1364. printf("Lua error: [%s]\n", error_msg);
  1365. IGNORE_UNUSED_RESULT(
  1366. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1367. }
  1368. /* TODO(lsm, low): leave the stack balanced */
  1369. return 0;
  1370. }
  1371. static void *
  1372. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1373. {
  1374. (void)ud;
  1375. (void)osize; /* not used */
  1376. if (nsize == 0) {
  1377. mg_free(ptr);
  1378. return NULL;
  1379. }
  1380. return mg_realloc(ptr, nsize);
  1381. }
  1382. static void
  1383. mg_exec_lua_script(struct mg_connection *conn,
  1384. const char *path,
  1385. const void **exports)
  1386. {
  1387. int i;
  1388. lua_State *L;
  1389. /* Assume the script does not support keep_alive. The script may change this
  1390. * by calling mg.keep_alive(true). */
  1391. conn->must_close = 1;
  1392. /* Execute a plain Lua script. */
  1393. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  1394. prepare_lua_environment(
  1395. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1396. lua_pushcclosure(L, &lua_error_handler, 0);
  1397. if (exports != NULL) {
  1398. #if LUA_VERSION_NUM > 501
  1399. lua_pushglobaltable(L);
  1400. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1401. lua_CFunction func;
  1402. lua_pushstring(L, (const char *)(exports[i]));
  1403. *(const void **)(&func) = exports[i + 1];
  1404. lua_pushcclosure(L, func, 0);
  1405. lua_rawset(L, -3);
  1406. }
  1407. #else
  1408. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1409. lua_CFunction func;
  1410. const char *name = (const char *)(exports[i]);
  1411. *(const void **)(&func) = exports[i + 1];
  1412. lua_register(L, name, func);
  1413. }
  1414. #endif
  1415. }
  1416. if (luaL_loadfile(L, path) != 0) {
  1417. lua_error_handler(L);
  1418. }
  1419. lua_pcall(L, 0, 0, -2);
  1420. lua_close(L);
  1421. }
  1422. }
  1423. static int
  1424. handle_lsp_request(struct mg_connection *conn,
  1425. const char *path,
  1426. struct mg_file *filep,
  1427. struct lua_State *ls)
  1428. {
  1429. void *p = NULL;
  1430. lua_State *L = NULL;
  1431. int error = 1;
  1432. struct mg_file filesize = STRUCT_FILE_INITIALIZER;
  1433. /* Assume the script does not support keep_alive. The script may change this
  1434. * by calling mg.keep_alive(true). */
  1435. conn->must_close = 1;
  1436. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  1437. if (!mg_stat(conn, path, &filesize.stat)) {
  1438. /* File not found */
  1439. if (ls == NULL) {
  1440. send_http_error(conn, 500, "Error: File %s not found", path);
  1441. } else {
  1442. luaL_error(ls, "File [%s] not found", path);
  1443. }
  1444. goto cleanup_handle_lsp_request;
  1445. }
  1446. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  1447. /* File not found or not accessible */
  1448. if (ls == NULL) {
  1449. send_http_error(conn,
  1450. 500,
  1451. "Error: Cannot open script file %s",
  1452. path);
  1453. } else {
  1454. luaL_error(ls, "Cannot [%s] not found", path);
  1455. }
  1456. goto cleanup_handle_lsp_request;
  1457. }
  1458. /* TODO: Operations mg_fopen and mg_stat should do what their names
  1459. * indicate. They should not fill in different members of the same
  1460. * struct mg_file.
  1461. * See Github issue #225 */
  1462. filep->stat.size = filesize.stat.size;
  1463. if (filep->access.membuf == NULL
  1464. && (p = mmap(NULL,
  1465. (size_t)filep->stat.size,
  1466. PROT_READ,
  1467. MAP_PRIVATE,
  1468. fileno(filep->access.fp),
  1469. 0)) == MAP_FAILED) {
  1470. /* mmap failed */
  1471. if (ls == NULL) {
  1472. send_http_error(
  1473. conn,
  1474. 500,
  1475. "Error: Cannot open script\nFile %s can not be mapped",
  1476. path);
  1477. } else {
  1478. luaL_error(ls,
  1479. "mmap(%s, %zu, %d): %s",
  1480. path,
  1481. (size_t)filep->stat.size,
  1482. fileno(filep->access.fp),
  1483. strerror(errno));
  1484. }
  1485. goto cleanup_handle_lsp_request;
  1486. }
  1487. if (ls != NULL) {
  1488. L = ls;
  1489. } else {
  1490. L = lua_newstate(lua_allocator, NULL);
  1491. if (L == NULL) {
  1492. send_http_error(
  1493. conn,
  1494. 500,
  1495. "%s",
  1496. "Error: Cannot execute script\nlua_newstate failed");
  1497. goto cleanup_handle_lsp_request;
  1498. }
  1499. prepare_lua_environment(
  1500. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1501. }
  1502. /* Lua state is ready to use */
  1503. /* We're not sending HTTP headers here, Lua page must do it. */
  1504. error =
  1505. lsp(conn,
  1506. path,
  1507. (filep->access.membuf == NULL) ? (const char *)p
  1508. : (const char *)filep->access.membuf,
  1509. filep->stat.size,
  1510. L);
  1511. cleanup_handle_lsp_request:
  1512. if (L != NULL && ls == NULL)
  1513. lua_close(L);
  1514. if (p != NULL)
  1515. munmap(p, filep->stat.size);
  1516. (void)mg_fclose(&filep->access);
  1517. return error;
  1518. }
  1519. #ifdef USE_WEBSOCKET
  1520. struct mg_shared_lua_websocket_list {
  1521. struct lua_websock_data ws;
  1522. struct mg_shared_lua_websocket_list *next;
  1523. };
  1524. static void *
  1525. lua_websocket_new(const char *script, struct mg_connection *conn)
  1526. {
  1527. struct mg_shared_lua_websocket_list **shared_websock_list =
  1528. &(conn->ctx->shared_lua_websockets);
  1529. struct lua_websock_data *ws;
  1530. int err, ok = 0;
  1531. assert(conn->lua_websocket_state == NULL);
  1532. /* lock list (mg_context global) */
  1533. mg_lock_context(conn->ctx);
  1534. while (*shared_websock_list) {
  1535. /* check if ws already in list */
  1536. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1537. break;
  1538. }
  1539. shared_websock_list = &((*shared_websock_list)->next);
  1540. }
  1541. if (*shared_websock_list == NULL) {
  1542. /* add ws to list */
  1543. *shared_websock_list = (struct mg_shared_lua_websocket_list *)
  1544. mg_calloc(sizeof(struct mg_shared_lua_websocket_list), 1);
  1545. if (*shared_websock_list == NULL) {
  1546. mg_unlock_context(conn->ctx);
  1547. mg_cry(conn, "Cannot create shared websocket struct, OOM");
  1548. return NULL;
  1549. }
  1550. /* init ws list element */
  1551. ws = &(*shared_websock_list)->ws;
  1552. ws->script = mg_strdup(script); /* TODO (low): handle OOM */
  1553. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1554. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1555. ws->state = lua_newstate(lua_allocator, NULL);
  1556. ws->conn[0] = conn;
  1557. ws->references = 1;
  1558. prepare_lua_environment(
  1559. conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  1560. err = luaL_loadfile(ws->state, script);
  1561. if (err != 0) {
  1562. lua_cry(conn, err, ws->state, script, "load");
  1563. }
  1564. err = lua_pcall(ws->state, 0, 0, 0);
  1565. if (err != 0) {
  1566. lua_cry(conn, err, ws->state, script, "init");
  1567. }
  1568. } else {
  1569. /* inc ref count */
  1570. ws = &(*shared_websock_list)->ws;
  1571. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1572. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1573. }
  1574. mg_unlock_context(conn->ctx);
  1575. /* call add */
  1576. lua_getglobal(ws->state, "open");
  1577. lua_newtable(ws->state);
  1578. prepare_lua_request_info(conn, ws->state);
  1579. lua_pushstring(ws->state, "client");
  1580. lua_pushlightuserdata(ws->state, (void *)conn);
  1581. lua_rawset(ws->state, -3);
  1582. err = lua_pcall(ws->state, 1, 1, 0);
  1583. if (err != 0) {
  1584. lua_cry(conn, err, ws->state, script, "open handler");
  1585. } else {
  1586. if (lua_isboolean(ws->state, -1)) {
  1587. ok = lua_toboolean(ws->state, -1);
  1588. }
  1589. lua_pop(ws->state, 1);
  1590. }
  1591. if (!ok) {
  1592. /* Remove from ws connection list. */
  1593. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1594. * (see websocket_close). */
  1595. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1596. }
  1597. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1598. return ok ? (void *)ws : NULL;
  1599. }
  1600. static int
  1601. lua_websocket_data(struct mg_connection *conn,
  1602. int bits,
  1603. char *data,
  1604. size_t data_len,
  1605. void *ws_arg)
  1606. {
  1607. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1608. int err, ok = 0;
  1609. assert(ws != NULL);
  1610. assert(ws->state != NULL);
  1611. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1612. lua_getglobal(ws->state, "data");
  1613. lua_newtable(ws->state);
  1614. lua_pushstring(ws->state, "client");
  1615. lua_pushlightuserdata(ws->state, (void *)conn);
  1616. lua_rawset(ws->state, -3);
  1617. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1618. a meaning according to
  1619. http://tools.ietf.org/html/rfc6455,
  1620. section 5.2 */
  1621. lua_pushnumber(ws->state, bits);
  1622. lua_rawset(ws->state, -3);
  1623. lua_pushstring(ws->state, "data");
  1624. lua_pushlstring(ws->state, data, data_len);
  1625. lua_rawset(ws->state, -3);
  1626. err = lua_pcall(ws->state, 1, 1, 0);
  1627. if (err != 0) {
  1628. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1629. } else {
  1630. if (lua_isboolean(ws->state, -1)) {
  1631. ok = lua_toboolean(ws->state, -1);
  1632. }
  1633. lua_pop(ws->state, 1);
  1634. }
  1635. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1636. return ok;
  1637. }
  1638. static int
  1639. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1640. {
  1641. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1642. int err, ok = 0;
  1643. assert(ws != NULL);
  1644. assert(ws->state != NULL);
  1645. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1646. lua_getglobal(ws->state, "ready");
  1647. lua_newtable(ws->state);
  1648. lua_pushstring(ws->state, "client");
  1649. lua_pushlightuserdata(ws->state, (void *)conn);
  1650. lua_rawset(ws->state, -3);
  1651. err = lua_pcall(ws->state, 1, 1, 0);
  1652. if (err != 0) {
  1653. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1654. } else {
  1655. if (lua_isboolean(ws->state, -1)) {
  1656. ok = lua_toboolean(ws->state, -1);
  1657. }
  1658. lua_pop(ws->state, 1);
  1659. }
  1660. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1661. return ok;
  1662. }
  1663. static void
  1664. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1665. {
  1666. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1667. struct mg_shared_lua_websocket_list **shared_websock_list =
  1668. &(conn->ctx->shared_lua_websockets);
  1669. int err = 0;
  1670. unsigned i;
  1671. assert(ws != NULL);
  1672. assert(ws->state != NULL);
  1673. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1674. lua_getglobal(ws->state, "close");
  1675. lua_newtable(ws->state);
  1676. lua_pushstring(ws->state, "client");
  1677. lua_pushlightuserdata(ws->state, (void *)conn);
  1678. lua_rawset(ws->state, -3);
  1679. err = lua_pcall(ws->state, 1, 0, 0);
  1680. if (err != 0) {
  1681. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1682. }
  1683. for (i = 0; i < ws->references; i++) {
  1684. if (ws->conn[i] == conn) {
  1685. ws->references--;
  1686. ws->conn[i] = ws->conn[ws->references];
  1687. }
  1688. }
  1689. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1690. This must only be done, when all connections are closed, and all
  1691. asynchronous operations and timers are completed/expired. */
  1692. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1693. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1694. }
  1695. #endif
  1696. lua_State *
  1697. mg_prepare_lua_context_script(const char *file_name,
  1698. struct mg_context *ctx,
  1699. char *ebuf,
  1700. size_t ebuf_len)
  1701. {
  1702. struct lua_State *L;
  1703. int lua_ret;
  1704. const char *lua_err_txt;
  1705. L = luaL_newstate();
  1706. if (L == NULL) {
  1707. mg_snprintf(NULL,
  1708. NULL, /* No truncation check for ebuf */
  1709. ebuf,
  1710. ebuf_len,
  1711. "Error: %s",
  1712. "Cannot create Lua state");
  1713. return 0;
  1714. }
  1715. civetweb_open_lua_libs(L);
  1716. lua_ret = luaL_loadfile(L, file_name);
  1717. if (lua_ret != LUA_OK) {
  1718. /* Error when loading the file (e.g. file not found, out of memory, ...)
  1719. */
  1720. lua_err_txt = lua_tostring(L, -1);
  1721. mg_snprintf(NULL,
  1722. NULL, /* No truncation check for ebuf */
  1723. ebuf,
  1724. ebuf_len,
  1725. "Error loading file %s: %s\n",
  1726. file_name,
  1727. lua_err_txt);
  1728. return 0;
  1729. }
  1730. /* The script file is loaded, now call it */
  1731. lua_ret = lua_pcall(L,
  1732. /* no arguments */ 0,
  1733. /* zero or one return value */ 1,
  1734. /* errors as strint return value */ 0);
  1735. if (lua_ret != LUA_OK) {
  1736. /* Error when executing the script */
  1737. lua_err_txt = lua_tostring(L, -1);
  1738. mg_snprintf(NULL,
  1739. NULL, /* No truncation check for ebuf */
  1740. ebuf,
  1741. ebuf_len,
  1742. "Error running file %s: %s\n",
  1743. file_name,
  1744. lua_err_txt);
  1745. return 0;
  1746. }
  1747. /* lua_close(L); must be done somewhere else */
  1748. return L;
  1749. }
  1750. int
  1751. run_lua(const char *file_name)
  1752. {
  1753. int func_ret = EXIT_FAILURE;
  1754. char ebuf[512] = {0};
  1755. lua_State *L =
  1756. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  1757. if (L) {
  1758. /* Script executed */
  1759. if (lua_type(L, -1) == LUA_TNUMBER) {
  1760. func_ret = (int)lua_tonumber(L, -1);
  1761. } else {
  1762. func_ret = EXIT_SUCCESS;
  1763. }
  1764. lua_close(L);
  1765. } else {
  1766. fprintf(stderr, "%s\n", ebuf);
  1767. }
  1768. return func_ret;
  1769. }
  1770. static void *lib_handle_uuid = NULL;
  1771. static void
  1772. lua_init_optional_libraries(void)
  1773. {
  1774. #if !defined(_WIN32)
  1775. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  1776. pf_uuid_generate.p =
  1777. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  1778. #else
  1779. pf_uuid_generate.p = 0;
  1780. #endif
  1781. }
  1782. static void
  1783. lua_exit_optional_libraries(void)
  1784. {
  1785. #if !defined(_WIN32)
  1786. if (lib_handle_uuid) {
  1787. dlclose(lib_handle_uuid);
  1788. }
  1789. #endif
  1790. pf_uuid_generate.p = 0;
  1791. lib_handle_uuid = NULL;
  1792. }