mod_lua.inl 42 KB

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