mod_lua.inl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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.write for websockets */
  300. static int lwebsock_write(lua_State *L)
  301. {
  302. #ifdef USE_WEBSOCKET
  303. int num_args = lua_gettop(L);
  304. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  305. const char *str;
  306. size_t size;
  307. int opcode = -1;
  308. if (num_args == 1) {
  309. if (lua_isstring(L, 1)) {
  310. str = lua_tolstring(L, 1, &size);
  311. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  312. }
  313. } else if (num_args == 2) {
  314. if (lua_isnumber(L, 1)) {
  315. opcode = (int)lua_tointeger(L, 1);
  316. } else if (lua_isstring(L,1)) {
  317. str = lua_tostring(L, 1);
  318. if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
  319. else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
  320. else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  321. else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
  322. else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
  323. else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
  324. }
  325. if (opcode>=0 && opcode<16 && lua_isstring(L, 2)) {
  326. str = lua_tolstring(L, 2, &size);
  327. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  328. }
  329. }
  330. #endif
  331. return 0;
  332. }
  333. enum {
  334. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  335. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  336. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  337. };
  338. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, const char *script_name, int lua_env_type)
  339. {
  340. const struct mg_request_info *ri = mg_get_request_info(conn);
  341. char src_addr[IP_ADDR_STR_LEN];
  342. int i;
  343. extern void luaL_openlibs(lua_State *);
  344. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  345. luaL_openlibs(L);
  346. #ifdef USE_LUA_SQLITE3
  347. {
  348. extern int luaopen_lsqlite3(lua_State *);
  349. luaopen_lsqlite3(L);
  350. }
  351. #endif
  352. #ifdef USE_LUA_FILE_SYSTEM
  353. {
  354. extern int luaopen_lfs(lua_State *);
  355. luaopen_lfs(L);
  356. }
  357. #endif
  358. luaL_newmetatable(L, LUASOCKET);
  359. lua_pushliteral(L, "__index");
  360. luaL_newlib(L, luasocket_methods);
  361. lua_rawset(L, -3);
  362. lua_pop(L, 1);
  363. lua_register(L, "connect", lsp_connect);
  364. if (conn == NULL) {
  365. /* Do not register any connection specific functions or variables */
  366. return;
  367. }
  368. /* Register mg module */
  369. lua_newtable(L);
  370. reg_function(L, "cry", lsp_cry, conn);
  371. switch (lua_env_type) {
  372. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  373. reg_string(L, "lua_type", "page");
  374. break;
  375. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  376. reg_string(L, "lua_type", "script");
  377. break;
  378. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  379. reg_string(L, "lua_type", "websocket");
  380. break;
  381. }
  382. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  383. reg_function(L, "read", lsp_read, conn);
  384. reg_function(L, "write", lsp_write, conn);
  385. }
  386. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  387. reg_function(L, "include", lsp_include, conn);
  388. reg_function(L, "redirect", lsp_redirect, conn);
  389. }
  390. if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
  391. reg_function(L, "write", lwebsock_write, conn);
  392. }
  393. reg_function(L, "send_file", lsp_send_file, conn);
  394. reg_string(L, "version", CIVETWEB_VERSION);
  395. reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]);
  396. reg_string(L, "auth_domain", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  397. #if defined(USE_WEBSOCKET)
  398. reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]);
  399. #endif
  400. /* Export request_info */
  401. lua_pushstring(L, "request_info");
  402. lua_newtable(L);
  403. reg_string(L, "request_method", ri->request_method);
  404. reg_string(L, "uri", ri->uri);
  405. reg_string(L, "http_version", ri->http_version);
  406. reg_string(L, "query_string", ri->query_string);
  407. reg_int(L, "remote_ip", ri->remote_ip); /* remote_ip is deprecated, use remote_addr instead */
  408. reg_string(L, "remote_addr", src_addr);
  409. /* TODO: ip version */
  410. reg_int(L, "remote_port", ri->remote_port);
  411. reg_int(L, "num_headers", ri->num_headers);
  412. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  413. if (conn->request_info.remote_user != NULL) {
  414. reg_string(L, "remote_user", conn->request_info.remote_user);
  415. reg_string(L, "auth_type", "Digest");
  416. }
  417. lua_pushstring(L, "http_headers");
  418. lua_newtable(L);
  419. for (i = 0; i < ri->num_headers; i++) {
  420. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  421. }
  422. lua_rawset(L, -3);
  423. reg_boolean(L, "https", conn->ssl != NULL);
  424. reg_string(L, "script_name", script_name);
  425. lua_rawset(L, -3);
  426. lua_setglobal(L, "mg");
  427. /* Register default mg.onerror function */
  428. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  429. "debug.traceback(e, 1)) end"));
  430. }
  431. static int lua_error_handler(lua_State *L)
  432. {
  433. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  434. lua_getglobal(L, "mg");
  435. if (!lua_isnil(L, -1)) {
  436. lua_getfield(L, -1, "write"); /* call mg.write() */
  437. lua_pushstring(L, error_msg);
  438. lua_pushliteral(L, "\n");
  439. lua_call(L, 2, 0);
  440. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  441. } else {
  442. printf("Lua error: [%s]\n", error_msg);
  443. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  444. }
  445. /* TODO(lsm): leave the stack balanced */
  446. return 0;
  447. }
  448. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  449. const void **exports)
  450. {
  451. int i;
  452. lua_State *L;
  453. if (path != NULL && (L = luaL_newstate()) != NULL) {
  454. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  455. lua_pushcclosure(L, &lua_error_handler, 0);
  456. if (exports != NULL) {
  457. lua_pushglobaltable(L);
  458. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  459. lua_pushstring(L, exports[i]);
  460. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  461. lua_rawset(L, -3);
  462. }
  463. }
  464. if (luaL_loadfile(L, path) != 0) {
  465. lua_error_handler(L);
  466. }
  467. lua_pcall(L, 0, 0, -2);
  468. lua_close(L);
  469. }
  470. conn->must_close=1;
  471. }
  472. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  473. const char *fmt, ...)
  474. {
  475. char buf[MG_BUF_LEN];
  476. va_list ap;
  477. int len;
  478. va_start(ap, fmt);
  479. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  480. va_end(ap);
  481. if (L == NULL) {
  482. send_http_error(conn, 500, http_500_error, "%s", buf);
  483. } else {
  484. lua_pushstring(L, buf);
  485. lua_error(L);
  486. }
  487. }
  488. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  489. struct file *filep, struct lua_State *ls)
  490. {
  491. void *p = NULL;
  492. lua_State *L = NULL;
  493. int error = 1;
  494. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  495. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  496. lsp_send_err(conn, ls, "File [%s] not found", path);
  497. } else if (filep->membuf == NULL &&
  498. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  499. fileno(filep->fp), 0)) == MAP_FAILED) {
  500. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  501. fileno(filep->fp), strerror(errno));
  502. } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
  503. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  504. } else {
  505. /* We're not sending HTTP headers here, Lua page must do it. */
  506. if (ls == NULL) {
  507. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  508. if (conn->ctx->callbacks.init_lua != NULL) {
  509. conn->ctx->callbacks.init_lua(conn, L);
  510. }
  511. }
  512. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  513. filep->size, L);
  514. }
  515. if (L != NULL && ls == NULL) lua_close(L);
  516. if (p != NULL) munmap(p, filep->size);
  517. mg_fclose(filep);
  518. conn->must_close=1;
  519. return error;
  520. }
  521. #ifdef USE_WEBSOCKET
  522. struct lua_websock_data {
  523. lua_State *main;
  524. lua_State *thread;
  525. };
  526. static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation)
  527. {
  528. switch (err) {
  529. case LUA_OK:
  530. case LUA_YIELD:
  531. break;
  532. case LUA_ERRRUN:
  533. mg_cry(conn, "%s: %s failed: runtime error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  534. break;
  535. case LUA_ERRSYNTAX:
  536. mg_cry(conn, "%s: %s failed: syntax error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  537. break;
  538. case LUA_ERRMEM:
  539. mg_cry(conn, "%s: %s failed: out of memory", ws_operation, lua_operation);
  540. break;
  541. case LUA_ERRGCMM:
  542. mg_cry(conn, "%s: %s failed: error during garbage collection", ws_operation, lua_operation);
  543. break;
  544. case LUA_ERRERR:
  545. mg_cry(conn, "%s: %s failed: error in error handling: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  546. break;
  547. default:
  548. mg_cry(conn, "%s: %s failed: error %i", ws_operation, lua_operation, err);
  549. break;
  550. }
  551. }
  552. static void * new_lua_websocket(const char * script, struct mg_connection *conn)
  553. {
  554. struct lua_websock_data *lws_data;
  555. int ok = 0;
  556. int err, nargs;
  557. assert(conn->lua_websocket_state == NULL);
  558. lws_data = (struct lua_websock_data *) malloc(sizeof(*lws_data));
  559. if (lws_data) {
  560. lws_data->main = luaL_newstate();
  561. if (lws_data->main) {
  562. prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  563. if (conn->ctx->callbacks.init_lua != NULL) {
  564. conn->ctx->callbacks.init_lua(conn, lws_data->main);
  565. }
  566. lws_data->thread = lua_newthread(lws_data->main);
  567. err = luaL_loadfile(lws_data->thread, script);
  568. if (err==LUA_OK) {
  569. /* Activate the Lua script. */
  570. err = lua_resume(lws_data->thread, NULL, 0);
  571. if (err!=LUA_YIELD) {
  572. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  573. } else {
  574. nargs = lua_gettop(lws_data->thread);
  575. ok = (nargs==1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  576. }
  577. } else {
  578. websock_cry(conn, err, lws_data->thread, __func__, "lua_loadfile");
  579. }
  580. } else {
  581. mg_cry(conn, "%s: luaL_newstate failed", __func__);
  582. }
  583. if (!ok) {
  584. if (lws_data->main) lua_close(lws_data->main);
  585. free(lws_data);
  586. lws_data=0;
  587. }
  588. } else {
  589. mg_cry(conn, "%s: out of memory", __func__);
  590. }
  591. return lws_data;
  592. }
  593. static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, size_t data_len)
  594. {
  595. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  596. int err, nargs, ok=0, retry;
  597. lua_Number delay;
  598. assert(lws_data != NULL);
  599. assert(lws_data->main != NULL);
  600. assert(lws_data->thread != NULL);
  601. do {
  602. retry=0;
  603. /* Push the data to Lua, then resume the Lua state. */
  604. /* The data will be available to Lua as the result of the coroutine.yield function. */
  605. lua_pushboolean(lws_data->thread, 1);
  606. if (bits >= 0) {
  607. lua_pushinteger(lws_data->thread, bits);
  608. if (data) {
  609. lua_pushlstring(lws_data->thread, data, data_len);
  610. err = lua_resume(lws_data->thread, NULL, 3);
  611. } else {
  612. err = lua_resume(lws_data->thread, NULL, 2);
  613. }
  614. } else {
  615. err = lua_resume(lws_data->thread, NULL, 1);
  616. }
  617. /* Check if Lua returned by a call to the coroutine.yield function. */
  618. if (err!=LUA_YIELD) {
  619. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  620. } else {
  621. nargs = lua_gettop(lws_data->thread);
  622. ok = (nargs>=1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  623. delay = (nargs>=2) && lua_isnumber(lws_data->thread, 2) ? lua_tonumber(lws_data->thread, 2) : -1.0;
  624. if (ok && delay>0) {
  625. fd_set rfds;
  626. struct timeval tv;
  627. FD_ZERO(&rfds);
  628. FD_SET(conn->client.sock, &rfds);
  629. tv.tv_sec = (unsigned long)delay;
  630. tv.tv_usec = (unsigned long)(((double)delay - (double)((unsigned long)delay))*1000000.0);
  631. retry = (0==select(conn->client.sock+1, &rfds, NULL, NULL, &tv));
  632. }
  633. }
  634. } while (retry);
  635. return ok;
  636. }
  637. static int lua_websocket_ready(struct mg_connection *conn)
  638. {
  639. return lua_websocket_data(conn, -1, NULL, 0);
  640. }
  641. static void lua_websocket_close(struct mg_connection *conn)
  642. {
  643. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  644. int err;
  645. assert(lws_data != NULL);
  646. assert(lws_data->main != NULL);
  647. assert(lws_data->thread != NULL);
  648. lua_pushboolean(lws_data->thread, 0);
  649. err = lua_resume(lws_data->thread, NULL, 1);
  650. lua_close(lws_data->main);
  651. free(lws_data);
  652. conn->lua_websocket_state = NULL;
  653. }
  654. #endif