mod_lua.inl 47 KB

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