mod_lua.inl 38 KB

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