mod_lua.inl 39 KB

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