mod_lua.inl 41 KB

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