mod_lua.inl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. /* Forward declarations */
  26. static void handle_request(struct mg_connection *);
  27. static int handle_lsp_request(struct mg_connection *, const char *,
  28. struct file *, struct lua_State *);
  29. static void reg_string(struct lua_State *L, const char *name, const char *val)
  30. {
  31. if (name!=NULL && val!=NULL) {
  32. lua_pushstring(L, name);
  33. lua_pushstring(L, val);
  34. lua_rawset(L, -3);
  35. }
  36. }
  37. static void reg_int(struct lua_State *L, const char *name, int val)
  38. {
  39. if (name!=NULL) {
  40. lua_pushstring(L, name);
  41. lua_pushinteger(L, val);
  42. lua_rawset(L, -3);
  43. }
  44. }
  45. static void reg_boolean(struct lua_State *L, const char *name, int val)
  46. {
  47. if (name!=NULL) {
  48. lua_pushstring(L, name);
  49. lua_pushboolean(L, val != 0);
  50. lua_rawset(L, -3);
  51. }
  52. }
  53. static void reg_function(struct lua_State *L, const char *name,
  54. lua_CFunction func, struct mg_connection *conn)
  55. {
  56. if (name!=NULL && func!=NULL) {
  57. lua_pushstring(L, name);
  58. lua_pushlightuserdata(L, conn);
  59. lua_pushcclosure(L, func, 1);
  60. lua_rawset(L, -3);
  61. }
  62. }
  63. static int lsp_sock_close(lua_State *L)
  64. {
  65. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  66. lua_getfield(L, -1, "sock");
  67. closesocket((SOCKET) lua_tonumber(L, -1));
  68. } else {
  69. return luaL_error(L, "invalid :close() call");
  70. }
  71. return 1;
  72. }
  73. static int lsp_sock_recv(lua_State *L)
  74. {
  75. char buf[2000];
  76. int n;
  77. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  78. lua_getfield(L, -1, "sock");
  79. n = recv((SOCKET) lua_tonumber(L, -1), buf, sizeof(buf), 0);
  80. if (n <= 0) {
  81. lua_pushnil(L);
  82. } else {
  83. lua_pushlstring(L, buf, n);
  84. }
  85. } else {
  86. return luaL_error(L, "invalid :close() call");
  87. }
  88. return 1;
  89. }
  90. static int lsp_sock_send(lua_State *L)
  91. {
  92. const char *buf;
  93. size_t len, sent = 0;
  94. int n = 0, sock;
  95. if (lua_gettop(L) > 1 && lua_istable(L, -2) && lua_isstring(L, -1)) {
  96. buf = lua_tolstring(L, -1, &len);
  97. lua_getfield(L, -2, "sock");
  98. sock = (int) lua_tonumber(L, -1);
  99. while (sent < len) {
  100. if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
  101. break;
  102. }
  103. sent += n;
  104. }
  105. lua_pushnumber(L, n);
  106. } else {
  107. return luaL_error(L, "invalid :close() call");
  108. }
  109. return 1;
  110. }
  111. static const struct luaL_Reg luasocket_methods[] = {
  112. {"close", lsp_sock_close},
  113. {"send", lsp_sock_send},
  114. {"recv", lsp_sock_recv},
  115. {NULL, NULL}
  116. };
  117. static int lsp_connect(lua_State *L)
  118. {
  119. char ebuf[100];
  120. SOCKET sock;
  121. if (lua_isstring(L, -3) && lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
  122. sock = conn2(NULL, lua_tostring(L, -3), (int) lua_tonumber(L, -2),
  123. (int) lua_tonumber(L, -1), ebuf, sizeof(ebuf));
  124. if (sock == INVALID_SOCKET) {
  125. return luaL_error(L, ebuf);
  126. } else {
  127. lua_newtable(L);
  128. reg_int(L, "sock", (int) sock);
  129. reg_string(L, "host", lua_tostring(L, -4));
  130. luaL_getmetatable(L, LUASOCKET);
  131. lua_setmetatable(L, -2);
  132. }
  133. } else {
  134. return luaL_error(L, "connect(host,port,is_ssl): invalid parameter given.");
  135. }
  136. return 1;
  137. }
  138. static int lsp_error(lua_State *L)
  139. {
  140. lua_getglobal(L, "mg");
  141. lua_getfield(L, -1, "onerror");
  142. lua_pushvalue(L, -3);
  143. lua_pcall(L, 1, 0, 0);
  144. return 0;
  145. }
  146. /* Silently stop processing chunks. */
  147. static void lsp_abort(lua_State *L)
  148. {
  149. int top = lua_gettop(L);
  150. lua_getglobal(L, "mg");
  151. lua_pushnil(L);
  152. lua_setfield(L, -2, "onerror");
  153. lua_settop(L, top);
  154. lua_pushstring(L, "aborting");
  155. lua_error(L);
  156. }
  157. struct lsp_var_reader_data
  158. {
  159. const char * begin;
  160. unsigned len;
  161. unsigned state;
  162. };
  163. static const char * lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  164. {
  165. struct lsp_var_reader_data * reader = (struct lsp_var_reader_data *)ud;
  166. const char * ret;
  167. switch (reader->state) {
  168. case 0:
  169. ret = "mg.write(";
  170. *sz = strlen(ret);
  171. break;
  172. case 1:
  173. ret = reader->begin;
  174. *sz = reader->len;
  175. break;
  176. case 2:
  177. ret = ")";
  178. *sz = strlen(ret);
  179. break;
  180. default:
  181. ret = 0;
  182. *sz = 0;
  183. }
  184. reader->state++;
  185. return ret;
  186. }
  187. static int lsp(struct mg_connection *conn, const char *path,
  188. const char *p, int64_t len, lua_State *L)
  189. {
  190. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  191. char chunkname[MG_BUF_LEN];
  192. struct lsp_var_reader_data data;
  193. for (i = 0; i < len; i++) {
  194. if (p[i] == '\n') lines++;
  195. if ((i + 1) < len && p[i] == '<' && p[i + 1] == '?') {
  196. /* <?= ?> means a variable is enclosed and its value should be printed */
  197. is_var = ((i + 2) < len && p[i + 2] == '=');
  198. if (is_var) j = i + 2;
  199. else j = i + 1;
  200. while (j < len) {
  201. if (p[j] == '\n') lualines++;
  202. if ((j + 1) < len && p[j] == '?' && p[j + 1] == '>') {
  203. mg_write(conn, p + pos, i - pos);
  204. snprintf(chunkname, sizeof(chunkname), "@%s+%i", path, lines);
  205. lua_pushlightuserdata(L, conn);
  206. lua_pushcclosure(L, lsp_error, 1);
  207. if (is_var) {
  208. data.begin = p + (i + 3);
  209. data.len = j - (i + 3);
  210. data.state = 0;
  211. lua_ok = lua_load(L, lsp_var_reader, &data, chunkname, NULL);
  212. } else {
  213. lua_ok = luaL_loadbuffer(L, p + (i + 2), j - (i + 2), chunkname);
  214. }
  215. if (lua_ok) {
  216. /* Syntax error or OOM. Error message is pushed on stack. */
  217. lua_pcall(L, 1, 0, 0);
  218. } else {
  219. /* Success loading chunk. Call it. */
  220. lua_pcall(L, 0, 0, 1);
  221. }
  222. pos = j + 2;
  223. i = pos - 1;
  224. break;
  225. }
  226. j++;
  227. }
  228. if (lualines > 0) {
  229. lines += lualines;
  230. lualines = 0;
  231. }
  232. }
  233. }
  234. if (i > pos) {
  235. mg_write(conn, p + pos, i - pos);
  236. }
  237. return 0;
  238. }
  239. static int lsp_write(lua_State *L)
  240. {
  241. int i, num_args;
  242. const char *str;
  243. size_t size;
  244. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  245. num_args = lua_gettop(L);
  246. for (i = 1; i <= num_args; i++) {
  247. if (lua_isstring(L, i)) {
  248. str = lua_tolstring(L, i, &size);
  249. mg_write(conn, str, size);
  250. }
  251. }
  252. return 0;
  253. }
  254. static int lsp_read(lua_State *L)
  255. {
  256. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  257. char buf[1024];
  258. int len = mg_read(conn, buf, sizeof(buf));
  259. if (len <= 0) return 0;
  260. lua_pushlstring(L, buf, len);
  261. return 1;
  262. }
  263. /* mg.include: Include another .lp file */
  264. static int lsp_include(lua_State *L)
  265. {
  266. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  267. struct file file = STRUCT_FILE_INITIALIZER;
  268. if (handle_lsp_request(conn, lua_tostring(L, -1), &file, L)) {
  269. /* handle_lsp_request returned an error code, meaning an error occured in
  270. the included page and mg.onerror returned non-zero. Stop processing. */
  271. lsp_abort(L);
  272. }
  273. return 0;
  274. }
  275. /* mg.cry: Log an error. Default value for mg.onerror. */
  276. static int lsp_cry(lua_State *L)
  277. {
  278. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  279. mg_cry(conn, "%s", lua_tostring(L, -1));
  280. return 0;
  281. }
  282. /* mg.redirect: Redirect the request (internally). */
  283. static int lsp_redirect(lua_State *L)
  284. {
  285. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  286. conn->request_info.uri = lua_tostring(L, -1);
  287. handle_request(conn);
  288. lsp_abort(L);
  289. return 0;
  290. }
  291. /* mg.send_file */
  292. static int lsp_send_file(lua_State *L)
  293. {
  294. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  295. const char * filename = lua_tostring(L, -1);
  296. mg_send_file(conn, filename);
  297. return 0;
  298. }
  299. /* mg.get_var */
  300. static int lsp_get_var(lua_State *L)
  301. {
  302. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  303. int params = lua_gettop(L);
  304. const char *data, *var_name;
  305. size_t data_len, occurrence;
  306. int ret;
  307. char dst[512];
  308. data = lua_tolstring(L, 1, &data_len);
  309. var_name = lua_tostring(L, 2);
  310. occurrence = (params>2) ? (long)lua_tonumber(L, 3) : 0;
  311. ret = mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
  312. if (ret>=0) {
  313. lua_pushstring(L, dst);
  314. } else {
  315. lua_pushnil(L);
  316. }
  317. return 1;
  318. }
  319. /* TODO: Other functions in civetweb.h that should be available to Lua too:
  320. mg_get_cookie
  321. mg_get_builtin_mime_type
  322. mg_url_decode
  323. mg_url_encode
  324. mg_md5
  325. */
  326. /* mg.write for websockets */
  327. static int lwebsock_write(lua_State *L)
  328. {
  329. #ifdef USE_WEBSOCKET
  330. int num_args = lua_gettop(L);
  331. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  332. const char *str;
  333. size_t size;
  334. int opcode = -1;
  335. if (num_args == 1) {
  336. if (lua_isstring(L, 1)) {
  337. str = lua_tolstring(L, 1, &size);
  338. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  339. }
  340. } else if (num_args == 2) {
  341. if (lua_isnumber(L, 1)) {
  342. opcode = (int)lua_tointeger(L, 1);
  343. } else if (lua_isstring(L,1)) {
  344. str = lua_tostring(L, 1);
  345. if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
  346. else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
  347. else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  348. else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
  349. else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
  350. else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
  351. }
  352. if (opcode>=0 && opcode<16 && lua_isstring(L, 2)) {
  353. str = lua_tolstring(L, 2, &size);
  354. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  355. }
  356. }
  357. #endif
  358. return 0;
  359. }
  360. enum {
  361. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  362. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  363. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  364. };
  365. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, const char *script_name, int lua_env_type)
  366. {
  367. const struct mg_request_info *ri = mg_get_request_info(conn);
  368. char src_addr[IP_ADDR_STR_LEN];
  369. int i;
  370. extern void luaL_openlibs(lua_State *);
  371. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  372. luaL_openlibs(L);
  373. #ifdef USE_LUA_SQLITE3
  374. {
  375. extern int luaopen_lsqlite3(lua_State *);
  376. luaopen_lsqlite3(L);
  377. }
  378. #endif
  379. #ifdef USE_LUA_FILE_SYSTEM
  380. {
  381. extern int luaopen_lfs(lua_State *);
  382. luaopen_lfs(L);
  383. }
  384. #endif
  385. luaL_newmetatable(L, LUASOCKET);
  386. lua_pushliteral(L, "__index");
  387. luaL_newlib(L, luasocket_methods);
  388. lua_rawset(L, -3);
  389. lua_pop(L, 1);
  390. lua_register(L, "connect", lsp_connect);
  391. if (conn == NULL) {
  392. /* Do not register any connection specific functions or variables */
  393. return;
  394. }
  395. /* Register mg module */
  396. lua_newtable(L);
  397. reg_function(L, "cry", lsp_cry, conn);
  398. switch (lua_env_type) {
  399. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  400. reg_string(L, "lua_type", "page");
  401. break;
  402. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  403. reg_string(L, "lua_type", "script");
  404. break;
  405. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  406. reg_string(L, "lua_type", "websocket");
  407. break;
  408. }
  409. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  410. reg_function(L, "read", lsp_read, conn);
  411. reg_function(L, "write", lsp_write, conn);
  412. }
  413. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  414. reg_function(L, "include", lsp_include, conn);
  415. reg_function(L, "redirect", lsp_redirect, conn);
  416. }
  417. if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
  418. reg_function(L, "write", lwebsock_write, conn);
  419. }
  420. reg_function(L, "send_file", lsp_send_file, conn);
  421. reg_function(L, "get_var", lsp_get_var, conn);
  422. reg_string(L, "version", CIVETWEB_VERSION);
  423. reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]);
  424. reg_string(L, "auth_domain", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  425. #if defined(USE_WEBSOCKET)
  426. reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]);
  427. #endif
  428. /* Export request_info */
  429. lua_pushstring(L, "request_info");
  430. lua_newtable(L);
  431. reg_string(L, "request_method", ri->request_method);
  432. reg_string(L, "uri", ri->uri);
  433. reg_string(L, "http_version", ri->http_version);
  434. reg_string(L, "query_string", ri->query_string);
  435. reg_int(L, "remote_ip", ri->remote_ip); /* remote_ip is deprecated, use remote_addr instead */
  436. reg_string(L, "remote_addr", src_addr);
  437. /* TODO: ip version */
  438. reg_int(L, "remote_port", ri->remote_port);
  439. reg_int(L, "num_headers", ri->num_headers);
  440. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  441. if (conn->request_info.remote_user != NULL) {
  442. reg_string(L, "remote_user", conn->request_info.remote_user);
  443. reg_string(L, "auth_type", "Digest");
  444. }
  445. lua_pushstring(L, "http_headers");
  446. lua_newtable(L);
  447. for (i = 0; i < ri->num_headers; i++) {
  448. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  449. }
  450. lua_rawset(L, -3);
  451. reg_boolean(L, "https", conn->ssl != NULL);
  452. reg_string(L, "script_name", script_name);
  453. lua_rawset(L, -3);
  454. lua_setglobal(L, "mg");
  455. /* Register default mg.onerror function */
  456. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  457. "debug.traceback(e, 1)) end"));
  458. }
  459. static int lua_error_handler(lua_State *L)
  460. {
  461. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  462. lua_getglobal(L, "mg");
  463. if (!lua_isnil(L, -1)) {
  464. lua_getfield(L, -1, "write"); /* call mg.write() */
  465. lua_pushstring(L, error_msg);
  466. lua_pushliteral(L, "\n");
  467. lua_call(L, 2, 0);
  468. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  469. } else {
  470. printf("Lua error: [%s]\n", error_msg);
  471. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  472. }
  473. /* TODO(lsm): leave the stack balanced */
  474. return 0;
  475. }
  476. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  477. const void **exports)
  478. {
  479. int i;
  480. lua_State *L;
  481. if (path != NULL && (L = luaL_newstate()) != NULL) {
  482. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  483. lua_pushcclosure(L, &lua_error_handler, 0);
  484. if (exports != NULL) {
  485. lua_pushglobaltable(L);
  486. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  487. lua_pushstring(L, exports[i]);
  488. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  489. lua_rawset(L, -3);
  490. }
  491. }
  492. if (luaL_loadfile(L, path) != 0) {
  493. lua_error_handler(L);
  494. }
  495. lua_pcall(L, 0, 0, -2);
  496. lua_close(L);
  497. }
  498. conn->must_close=1;
  499. }
  500. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  501. const char *fmt, ...)
  502. {
  503. char buf[MG_BUF_LEN];
  504. va_list ap;
  505. int len;
  506. va_start(ap, fmt);
  507. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  508. va_end(ap);
  509. if (L == NULL) {
  510. send_http_error(conn, 500, http_500_error, "%s", buf);
  511. } else {
  512. lua_pushstring(L, buf);
  513. lua_error(L);
  514. }
  515. }
  516. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  517. struct file *filep, struct lua_State *ls)
  518. {
  519. void *p = NULL;
  520. lua_State *L = NULL;
  521. int error = 1;
  522. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  523. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  524. lsp_send_err(conn, ls, "File [%s] not found", path);
  525. } else if (filep->membuf == NULL &&
  526. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  527. fileno(filep->fp), 0)) == MAP_FAILED) {
  528. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  529. fileno(filep->fp), strerror(errno));
  530. } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
  531. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  532. } else {
  533. /* We're not sending HTTP headers here, Lua page must do it. */
  534. if (ls == NULL) {
  535. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  536. if (conn->ctx->callbacks.init_lua != NULL) {
  537. conn->ctx->callbacks.init_lua(conn, L);
  538. }
  539. }
  540. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  541. filep->size, L);
  542. }
  543. if (L != NULL && ls == NULL) lua_close(L);
  544. if (p != NULL) munmap(p, filep->size);
  545. mg_fclose(filep);
  546. conn->must_close=1;
  547. return error;
  548. }
  549. #ifdef USE_WEBSOCKET
  550. struct lua_websock_data {
  551. lua_State *main;
  552. lua_State *thread;
  553. };
  554. static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation)
  555. {
  556. switch (err) {
  557. case LUA_OK:
  558. case LUA_YIELD:
  559. break;
  560. case LUA_ERRRUN:
  561. mg_cry(conn, "%s: %s failed: runtime error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  562. break;
  563. case LUA_ERRSYNTAX:
  564. mg_cry(conn, "%s: %s failed: syntax error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  565. break;
  566. case LUA_ERRMEM:
  567. mg_cry(conn, "%s: %s failed: out of memory", ws_operation, lua_operation);
  568. break;
  569. case LUA_ERRGCMM:
  570. mg_cry(conn, "%s: %s failed: error during garbage collection", ws_operation, lua_operation);
  571. break;
  572. case LUA_ERRERR:
  573. mg_cry(conn, "%s: %s failed: error in error handling: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  574. break;
  575. default:
  576. mg_cry(conn, "%s: %s failed: error %i", ws_operation, lua_operation, err);
  577. break;
  578. }
  579. }
  580. static void * new_lua_websocket(const char * script, struct mg_connection *conn)
  581. {
  582. struct lua_websock_data *lws_data;
  583. int ok = 0;
  584. int err, nargs;
  585. assert(conn->lua_websocket_state == NULL);
  586. lws_data = (struct lua_websock_data *) malloc(sizeof(*lws_data));
  587. if (lws_data) {
  588. lws_data->main = luaL_newstate();
  589. if (lws_data->main) {
  590. prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  591. if (conn->ctx->callbacks.init_lua != NULL) {
  592. conn->ctx->callbacks.init_lua(conn, lws_data->main);
  593. }
  594. lws_data->thread = lua_newthread(lws_data->main);
  595. err = luaL_loadfile(lws_data->thread, script);
  596. if (err==LUA_OK) {
  597. /* Activate the Lua script. */
  598. err = lua_resume(lws_data->thread, NULL, 0);
  599. if (err!=LUA_YIELD) {
  600. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  601. } else {
  602. nargs = lua_gettop(lws_data->thread);
  603. ok = (nargs==1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  604. }
  605. } else {
  606. websock_cry(conn, err, lws_data->thread, __func__, "lua_loadfile");
  607. }
  608. } else {
  609. mg_cry(conn, "%s: luaL_newstate failed", __func__);
  610. }
  611. if (!ok) {
  612. if (lws_data->main) lua_close(lws_data->main);
  613. free(lws_data);
  614. lws_data=0;
  615. }
  616. } else {
  617. mg_cry(conn, "%s: out of memory", __func__);
  618. }
  619. return lws_data;
  620. }
  621. static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, size_t data_len)
  622. {
  623. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  624. int err, nargs, ok=0, retry;
  625. lua_Number delay;
  626. assert(lws_data != NULL);
  627. assert(lws_data->main != NULL);
  628. assert(lws_data->thread != NULL);
  629. do {
  630. retry=0;
  631. /* Push the data to Lua, then resume the Lua state. */
  632. /* The data will be available to Lua as the result of the coroutine.yield function. */
  633. lua_pushboolean(lws_data->thread, 1);
  634. if (bits >= 0) {
  635. lua_pushinteger(lws_data->thread, bits);
  636. if (data) {
  637. lua_pushlstring(lws_data->thread, data, data_len);
  638. err = lua_resume(lws_data->thread, NULL, 3);
  639. } else {
  640. err = lua_resume(lws_data->thread, NULL, 2);
  641. }
  642. } else {
  643. err = lua_resume(lws_data->thread, NULL, 1);
  644. }
  645. /* Check if Lua returned by a call to the coroutine.yield function. */
  646. if (err!=LUA_YIELD) {
  647. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  648. } else {
  649. nargs = lua_gettop(lws_data->thread);
  650. ok = (nargs>=1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  651. delay = (nargs>=2) && lua_isnumber(lws_data->thread, 2) ? lua_tonumber(lws_data->thread, 2) : -1.0;
  652. if (ok && delay>0) {
  653. fd_set rfds;
  654. struct timeval tv;
  655. FD_ZERO(&rfds);
  656. FD_SET(conn->client.sock, &rfds);
  657. tv.tv_sec = (unsigned long)delay;
  658. tv.tv_usec = (unsigned long)(((double)delay - (double)((unsigned long)delay))*1000000.0);
  659. retry = (0==select(conn->client.sock+1, &rfds, NULL, NULL, &tv));
  660. }
  661. }
  662. } while (retry);
  663. return ok;
  664. }
  665. static int lua_websocket_ready(struct mg_connection *conn)
  666. {
  667. return lua_websocket_data(conn, -1, NULL, 0);
  668. }
  669. static void lua_websocket_close(struct mg_connection *conn)
  670. {
  671. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  672. int err;
  673. assert(lws_data != NULL);
  674. assert(lws_data->main != NULL);
  675. assert(lws_data->thread != NULL);
  676. lua_pushboolean(lws_data->thread, 0);
  677. err = lua_resume(lws_data->thread, NULL, 1);
  678. lua_close(lws_data->main);
  679. free(lws_data);
  680. conn->lua_websocket_state = NULL;
  681. }
  682. #endif