mod_lua.inl 24 KB

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