mod_lua.inl 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. int num_args = lua_gettop(L);
  66. if ((num_args == 1) && lua_istable(L, -1)) {
  67. lua_getfield(L, -1, "sock");
  68. closesocket((SOCKET) lua_tonumber(L, -1));
  69. } else {
  70. return luaL_error(L, "invalid :close() call");
  71. }
  72. return 1;
  73. }
  74. static int lsp_sock_recv(lua_State *L)
  75. {
  76. int num_args = lua_gettop(L);
  77. char buf[2000];
  78. int n;
  79. if ((num_args == 1) && lua_istable(L, -1)) {
  80. lua_getfield(L, -1, "sock");
  81. n = recv((SOCKET) lua_tonumber(L, -1), buf, sizeof(buf), 0);
  82. if (n <= 0) {
  83. lua_pushnil(L);
  84. } else {
  85. lua_pushlstring(L, buf, n);
  86. }
  87. } else {
  88. return luaL_error(L, "invalid :close() call");
  89. }
  90. return 1;
  91. }
  92. static int lsp_sock_send(lua_State *L)
  93. {
  94. int num_args = lua_gettop(L);
  95. const char *buf;
  96. size_t len, sent = 0;
  97. int n = 0, sock;
  98. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  99. buf = lua_tolstring(L, -1, &len);
  100. lua_getfield(L, -2, "sock");
  101. sock = (int) lua_tonumber(L, -1);
  102. while (sent < len) {
  103. if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
  104. break;
  105. }
  106. sent += n;
  107. }
  108. lua_pushnumber(L, n);
  109. } else {
  110. return luaL_error(L, "invalid :close() call");
  111. }
  112. return 1;
  113. }
  114. static const struct luaL_Reg luasocket_methods[] = {
  115. {"close", lsp_sock_close},
  116. {"send", lsp_sock_send},
  117. {"recv", lsp_sock_recv},
  118. {NULL, NULL}
  119. };
  120. static int lsp_connect(lua_State *L)
  121. {
  122. int num_args = lua_gettop(L);
  123. char ebuf[100];
  124. SOCKET sock;
  125. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
  126. sock = conn2(NULL, lua_tostring(L, -3), (int) lua_tonumber(L, -2),
  127. (int) lua_tonumber(L, -1), ebuf, sizeof(ebuf));
  128. if (sock == INVALID_SOCKET) {
  129. return luaL_error(L, ebuf);
  130. } else {
  131. lua_newtable(L);
  132. reg_int(L, "sock", (int) sock);
  133. reg_string(L, "host", lua_tostring(L, -4));
  134. luaL_getmetatable(L, LUASOCKET);
  135. lua_setmetatable(L, -2);
  136. }
  137. } else {
  138. return luaL_error(L, "connect(host,port,is_ssl): invalid parameter given.");
  139. }
  140. return 1;
  141. }
  142. static int lsp_error(lua_State *L)
  143. {
  144. lua_getglobal(L, "mg");
  145. lua_getfield(L, -1, "onerror");
  146. lua_pushvalue(L, -3);
  147. lua_pcall(L, 1, 0, 0);
  148. return 0;
  149. }
  150. /* Silently stop processing chunks. */
  151. static void lsp_abort(lua_State *L)
  152. {
  153. int top = lua_gettop(L);
  154. lua_getglobal(L, "mg");
  155. lua_pushnil(L);
  156. lua_setfield(L, -2, "onerror");
  157. lua_settop(L, top);
  158. lua_pushstring(L, "aborting");
  159. lua_error(L);
  160. }
  161. struct lsp_var_reader_data
  162. {
  163. const char * begin;
  164. unsigned len;
  165. unsigned state;
  166. };
  167. static const char * lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  168. {
  169. struct lsp_var_reader_data * reader = (struct lsp_var_reader_data *)ud;
  170. const char * ret;
  171. switch (reader->state) {
  172. case 0:
  173. ret = "mg.write(";
  174. *sz = strlen(ret);
  175. break;
  176. case 1:
  177. ret = reader->begin;
  178. *sz = reader->len;
  179. break;
  180. case 2:
  181. ret = ")";
  182. *sz = strlen(ret);
  183. break;
  184. default:
  185. ret = 0;
  186. *sz = 0;
  187. }
  188. reader->state++;
  189. return ret;
  190. }
  191. static int lsp(struct mg_connection *conn, const char *path,
  192. const char *p, int64_t len, lua_State *L)
  193. {
  194. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  195. char chunkname[MG_BUF_LEN];
  196. struct lsp_var_reader_data data;
  197. for (i = 0; i < len; i++) {
  198. if (p[i] == '\n') lines++;
  199. if ((i + 1) < len && p[i] == '<' && p[i + 1] == '?') {
  200. /* <?= ?> means a variable is enclosed and its value should be printed */
  201. is_var = ((i + 2) < len && p[i + 2] == '=');
  202. if (is_var) j = i + 2;
  203. else j = i + 1;
  204. while (j < len) {
  205. if (p[j] == '\n') lualines++;
  206. if ((j + 1) < len && p[j] == '?' && p[j + 1] == '>') {
  207. mg_write(conn, p + pos, i - pos);
  208. snprintf(chunkname, sizeof(chunkname), "@%s+%i", path, lines);
  209. lua_pushlightuserdata(L, conn);
  210. lua_pushcclosure(L, lsp_error, 1);
  211. if (is_var) {
  212. data.begin = p + (i + 3);
  213. data.len = j - (i + 3);
  214. data.state = 0;
  215. lua_ok = lua_load(L, lsp_var_reader, &data, chunkname, NULL);
  216. } else {
  217. lua_ok = luaL_loadbuffer(L, p + (i + 2), j - (i + 2), chunkname);
  218. }
  219. if (lua_ok) {
  220. /* Syntax error or OOM. Error message is pushed on stack. */
  221. lua_pcall(L, 1, 0, 0);
  222. } else {
  223. /* Success loading chunk. Call it. */
  224. lua_pcall(L, 0, 0, 1);
  225. }
  226. pos = j + 2;
  227. i = pos - 1;
  228. break;
  229. }
  230. j++;
  231. }
  232. if (lualines > 0) {
  233. lines += lualines;
  234. lualines = 0;
  235. }
  236. }
  237. }
  238. if (i > pos) {
  239. mg_write(conn, p + pos, i - pos);
  240. }
  241. return 0;
  242. }
  243. /* mg.write: Send data to the client */
  244. static int lsp_write(lua_State *L)
  245. {
  246. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  247. int num_args = lua_gettop(L);
  248. const char *str;
  249. size_t size;
  250. int i;
  251. for (i = 1; i <= num_args; i++) {
  252. if (lua_isstring(L, i)) {
  253. str = lua_tolstring(L, i, &size);
  254. mg_write(conn, str, size);
  255. }
  256. }
  257. return 0;
  258. }
  259. /* mg.read: Read data from the client (e.g., from a POST request) */
  260. static int lsp_read(lua_State *L)
  261. {
  262. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  263. char buf[1024];
  264. int len = mg_read(conn, buf, sizeof(buf));
  265. if (len <= 0) return 0;
  266. lua_pushlstring(L, buf, len);
  267. return 1;
  268. }
  269. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  270. static int lsp_keep_alive(lua_State *L)
  271. {
  272. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  273. int num_args = lua_gettop(L);
  274. /* This function may be called with one parameter (boolean) to set the keep_alive state.
  275. Or without a parameter to just query the current keep_alive state. */
  276. if ((num_args==1) && lua_isboolean(L, 1)) {
  277. conn->must_close = !lua_toboolean(L, 1);
  278. } else if (num_args != 0) {
  279. /* Syntax error */
  280. return luaL_error(L, "invalid keep_alive() call");
  281. }
  282. /* Return the current "keep_alive" state. This may be false, even it keep_alive(true) has been called. */
  283. lua_pushboolean(L, should_keep_alive(conn));
  284. return 1;
  285. }
  286. /* mg.include: Include another .lp file */
  287. static int lsp_include(lua_State *L)
  288. {
  289. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  290. int num_args = lua_gettop(L);
  291. struct file file = STRUCT_FILE_INITIALIZER;
  292. const char * filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  293. if (filename) {
  294. if (handle_lsp_request(conn, filename, &file, L)) {
  295. /* handle_lsp_request returned an error code, meaning an error occured in
  296. the included page and mg.onerror returned non-zero. Stop processing. */
  297. lsp_abort(L);
  298. }
  299. } else {
  300. /* Syntax error */
  301. return luaL_error(L, "invalid include() call");
  302. }
  303. return 0;
  304. }
  305. /* mg.cry: Log an error. Default value for mg.onerror. */
  306. static int lsp_cry(lua_State *L)
  307. {
  308. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  309. int num_args = lua_gettop(L);
  310. const char * text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  311. if (text) {
  312. mg_cry(conn, "%s", lua_tostring(L, -1));
  313. } else {
  314. /* Syntax error */
  315. return luaL_error(L, "invalid cry() call");
  316. }
  317. return 0;
  318. }
  319. /* mg.redirect: Redirect the request (internally). */
  320. static int lsp_redirect(lua_State *L)
  321. {
  322. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  323. int num_args = lua_gettop(L);
  324. const char * target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  325. if (target) {
  326. conn->request_info.uri = target;
  327. handle_request(conn);
  328. lsp_abort(L);
  329. } else {
  330. /* Syntax error */
  331. return luaL_error(L, "invalid redirect() call");
  332. }
  333. return 0;
  334. }
  335. /* mg.send_file */
  336. static int lsp_send_file(lua_State *L)
  337. {
  338. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  339. int num_args = lua_gettop(L);
  340. const char * filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  341. if (filename) {
  342. mg_send_file(conn, filename);
  343. } else {
  344. /* Syntax error */
  345. return luaL_error(L, "invalid send_file() call");
  346. }
  347. return 0;
  348. }
  349. /* mg.get_var */
  350. static int lsp_get_var(lua_State *L)
  351. {
  352. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  353. int num_args = lua_gettop(L);
  354. const char *data, *var_name;
  355. size_t data_len, occurrence;
  356. int ret;
  357. char dst[512];
  358. if (num_args>=2 && num_args<=3) {
  359. data = lua_tolstring(L, 1, &data_len);
  360. var_name = lua_tostring(L, 2);
  361. occurrence = (num_args>2) ? (long)lua_tonumber(L, 3) : 0;
  362. ret = mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
  363. if (ret>=0) {
  364. /* Variable found: return value to Lua */
  365. lua_pushstring(L, dst);
  366. } else {
  367. /* Variable not found (TODO: may be string too long) */
  368. lua_pushnil(L);
  369. }
  370. } else {
  371. /* Syntax error */
  372. return luaL_error(L, "invalid get_var() call");
  373. }
  374. return 1;
  375. }
  376. /* mg.get_mime_type */
  377. static int lsp_get_mime_type(lua_State *L)
  378. {
  379. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  380. int num_args = lua_gettop(L);
  381. struct vec mime_type = {0};
  382. const char *text;
  383. if (num_args==1) {
  384. text = lua_tostring(L, 1);
  385. if (text) {
  386. get_mime_type(conn->ctx, text, &mime_type);
  387. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  388. } else {
  389. lua_pushnil(L);
  390. }
  391. } else {
  392. /* Syntax error */
  393. return luaL_error(L, "invalid get_mime_type() call");
  394. }
  395. return 1;
  396. }
  397. /* mg.get_cookie */
  398. static int lsp_get_cookie(lua_State *L)
  399. {
  400. int num_args = lua_gettop(L);
  401. struct vec mime_type = {0};
  402. const char *cookie;
  403. const char *var_name;
  404. int ret;
  405. char dst[512];
  406. if (num_args==2) {
  407. cookie = lua_tostring(L, 1);
  408. var_name = lua_tostring(L, 2);
  409. if (cookie!=NULL && var_name!=NULL) {
  410. ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
  411. } else {
  412. ret = -1;
  413. }
  414. if (ret>=0) {
  415. lua_pushlstring(L, dst, ret);
  416. } else {
  417. lua_pushnil(L);
  418. }
  419. } else {
  420. /* Syntax error */
  421. return luaL_error(L, "invalid get_cookie() call");
  422. }
  423. return 1;
  424. }
  425. /* mg.md5 */
  426. static int lsp_md5(lua_State *L)
  427. {
  428. int num_args = lua_gettop(L);
  429. const char *text;
  430. md5_byte_t hash[16];
  431. md5_state_t ctx;
  432. size_t text_len;
  433. char buf[40];
  434. if (num_args==1) {
  435. text = lua_tolstring(L, 1, &text_len);
  436. if (text) {
  437. md5_init(&ctx);
  438. md5_append(&ctx, (const md5_byte_t *) text, text_len);
  439. md5_finish(&ctx, hash);
  440. bin2str(buf, hash, sizeof(hash));
  441. lua_pushstring(L, buf);
  442. } else {
  443. lua_pushnil(L);
  444. }
  445. } else {
  446. /* Syntax error */
  447. return luaL_error(L, "invalid md5() call");
  448. }
  449. return 1;
  450. }
  451. /* mg.url_encode */
  452. static int lsp_url_encode(lua_State *L)
  453. {
  454. int num_args = lua_gettop(L);
  455. const char *text;
  456. size_t text_len;
  457. char dst[512];
  458. if (num_args==1) {
  459. text = lua_tolstring(L, 1, &text_len);
  460. if (text) {
  461. mg_url_encode(text, dst, sizeof(dst));
  462. lua_pushstring(L, dst);
  463. } else {
  464. lua_pushnil(L);
  465. }
  466. } else {
  467. /* Syntax error */
  468. return luaL_error(L, "invalid url_encode() call");
  469. }
  470. return 1;
  471. }
  472. /* mg.url_decode */
  473. static int lsp_url_decode(lua_State *L)
  474. {
  475. int num_args = lua_gettop(L);
  476. const char *text;
  477. size_t text_len;
  478. int is_form;
  479. char dst[512];
  480. if (num_args==1 || (num_args==2 && lua_isboolean(L, 2))) {
  481. text = lua_tolstring(L, 1, &text_len);
  482. is_form = (num_args==2) ? lua_isboolean(L, 2) : 0;
  483. if (text) {
  484. mg_url_decode(text, text_len, dst, sizeof(dst), is_form);
  485. lua_pushstring(L, dst);
  486. } else {
  487. lua_pushnil(L);
  488. }
  489. } else {
  490. /* Syntax error */
  491. return luaL_error(L, "invalid url_decode() call");
  492. }
  493. return 1;
  494. }
  495. /* mg.write for websockets */
  496. static int lwebsock_write(lua_State *L)
  497. {
  498. #ifdef USE_WEBSOCKET
  499. int num_args = lua_gettop(L);
  500. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  501. const char *str;
  502. size_t size;
  503. int opcode = -1;
  504. if (num_args == 1) {
  505. if (lua_isstring(L, 1)) {
  506. str = lua_tolstring(L, 1, &size);
  507. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  508. }
  509. } else if (num_args == 2) {
  510. if (lua_isnumber(L, 1)) {
  511. opcode = (int)lua_tointeger(L, 1);
  512. } else if (lua_isstring(L,1)) {
  513. str = lua_tostring(L, 1);
  514. if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
  515. else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
  516. else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  517. else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
  518. else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
  519. else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
  520. }
  521. if (opcode>=0 && opcode<16 && lua_isstring(L, 2)) {
  522. str = lua_tolstring(L, 2, &size);
  523. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  524. }
  525. }
  526. #endif
  527. return 0;
  528. }
  529. enum {
  530. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  531. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  532. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  533. };
  534. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, const char *script_name, int lua_env_type)
  535. {
  536. const struct mg_request_info *ri = mg_get_request_info(conn);
  537. char src_addr[IP_ADDR_STR_LEN];
  538. const char * preload_file = conn->ctx->config[LUA_PRELOAD_FILE];
  539. int i;
  540. extern void luaL_openlibs(lua_State *);
  541. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  542. luaL_openlibs(L);
  543. #ifdef USE_LUA_SQLITE3
  544. {
  545. extern int luaopen_lsqlite3(lua_State *);
  546. luaopen_lsqlite3(L);
  547. }
  548. #endif
  549. #ifdef USE_LUA_FILE_SYSTEM
  550. {
  551. extern int luaopen_lfs(lua_State *);
  552. luaopen_lfs(L);
  553. }
  554. #endif
  555. luaL_newmetatable(L, LUASOCKET);
  556. lua_pushliteral(L, "__index");
  557. luaL_newlib(L, luasocket_methods);
  558. lua_rawset(L, -3);
  559. lua_pop(L, 1);
  560. lua_register(L, "connect", lsp_connect);
  561. if (conn == NULL) {
  562. /* Do not register any connection specific functions or variables */
  563. return;
  564. }
  565. /* Register mg module */
  566. lua_newtable(L);
  567. reg_function(L, "cry", lsp_cry, conn);
  568. switch (lua_env_type) {
  569. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  570. reg_string(L, "lua_type", "page");
  571. break;
  572. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  573. reg_string(L, "lua_type", "script");
  574. break;
  575. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  576. reg_string(L, "lua_type", "websocket");
  577. break;
  578. }
  579. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  580. reg_function(L, "read", lsp_read, conn);
  581. reg_function(L, "write", lsp_write, conn);
  582. reg_function(L, "keep_alive", lsp_keep_alive, conn);
  583. }
  584. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  585. reg_function(L, "include", lsp_include, conn);
  586. reg_function(L, "redirect", lsp_redirect, conn);
  587. }
  588. if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
  589. reg_function(L, "write", lwebsock_write, conn);
  590. }
  591. reg_function(L, "send_file", lsp_send_file, conn);
  592. reg_function(L, "get_var", lsp_get_var, conn);
  593. reg_function(L, "get_mime_type", lsp_get_mime_type, conn);
  594. reg_function(L, "get_cookie", lsp_get_cookie, conn);
  595. reg_function(L, "md5", lsp_md5, conn);
  596. reg_function(L, "url_encode", lsp_url_encode, conn);
  597. reg_function(L, "url_decode", lsp_url_decode, conn);
  598. reg_string(L, "version", CIVETWEB_VERSION);
  599. reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]);
  600. reg_string(L, "auth_domain", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  601. #if defined(USE_WEBSOCKET)
  602. reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]);
  603. #endif
  604. /* Export request_info */
  605. lua_pushstring(L, "request_info");
  606. lua_newtable(L);
  607. reg_string(L, "request_method", ri->request_method);
  608. reg_string(L, "uri", ri->uri);
  609. reg_string(L, "http_version", ri->http_version);
  610. reg_string(L, "query_string", ri->query_string);
  611. reg_int(L, "remote_ip", ri->remote_ip); /* remote_ip is deprecated, use remote_addr instead */
  612. reg_string(L, "remote_addr", src_addr);
  613. /* TODO: ip version */
  614. reg_int(L, "remote_port", ri->remote_port);
  615. reg_int(L, "num_headers", ri->num_headers);
  616. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  617. if (conn->request_info.remote_user != NULL) {
  618. reg_string(L, "remote_user", conn->request_info.remote_user);
  619. reg_string(L, "auth_type", "Digest");
  620. }
  621. lua_pushstring(L, "http_headers");
  622. lua_newtable(L);
  623. for (i = 0; i < ri->num_headers; i++) {
  624. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  625. }
  626. lua_rawset(L, -3);
  627. reg_boolean(L, "https", conn->ssl != NULL);
  628. reg_string(L, "script_name", script_name);
  629. lua_rawset(L, -3);
  630. lua_setglobal(L, "mg");
  631. /* Register default mg.onerror function */
  632. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  633. "debug.traceback(e, 1)) end"));
  634. /* Preload */
  635. if ((preload_file != NULL) && (*preload_file != 0)) {
  636. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file));
  637. }
  638. }
  639. static int lua_error_handler(lua_State *L)
  640. {
  641. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  642. lua_getglobal(L, "mg");
  643. if (!lua_isnil(L, -1)) {
  644. lua_getfield(L, -1, "write"); /* call mg.write() */
  645. lua_pushstring(L, error_msg);
  646. lua_pushliteral(L, "\n");
  647. lua_call(L, 2, 0);
  648. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  649. } else {
  650. printf("Lua error: [%s]\n", error_msg);
  651. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  652. }
  653. /* TODO(lsm): leave the stack balanced */
  654. return 0;
  655. }
  656. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  657. const void **exports)
  658. {
  659. int i;
  660. lua_State *L;
  661. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  662. conn->must_close=1;
  663. /* Execute a plain Lua script. */
  664. if (path != NULL && (L = luaL_newstate()) != NULL) {
  665. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  666. lua_pushcclosure(L, &lua_error_handler, 0);
  667. if (exports != NULL) {
  668. lua_pushglobaltable(L);
  669. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  670. lua_pushstring(L, exports[i]);
  671. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  672. lua_rawset(L, -3);
  673. }
  674. }
  675. if (luaL_loadfile(L, path) != 0) {
  676. lua_error_handler(L);
  677. }
  678. lua_pcall(L, 0, 0, -2);
  679. lua_close(L);
  680. }
  681. }
  682. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  683. const char *fmt, ...)
  684. {
  685. char buf[MG_BUF_LEN];
  686. va_list ap;
  687. int len;
  688. va_start(ap, fmt);
  689. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  690. va_end(ap);
  691. if (L == NULL) {
  692. send_http_error(conn, 500, http_500_error, "%s", buf);
  693. } else {
  694. lua_pushstring(L, buf);
  695. lua_error(L);
  696. }
  697. }
  698. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  699. struct file *filep, struct lua_State *ls)
  700. {
  701. void *p = NULL;
  702. lua_State *L = NULL;
  703. int error = 1;
  704. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  705. conn->must_close=1;
  706. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  707. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  708. lsp_send_err(conn, ls, "File [%s] not found", path);
  709. } else if (filep->membuf == NULL &&
  710. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  711. fileno(filep->fp), 0)) == MAP_FAILED) {
  712. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  713. fileno(filep->fp), strerror(errno));
  714. } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
  715. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  716. } else {
  717. /* We're not sending HTTP headers here, Lua page must do it. */
  718. if (ls == NULL) {
  719. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  720. if (conn->ctx->callbacks.init_lua != NULL) {
  721. conn->ctx->callbacks.init_lua(conn, L);
  722. }
  723. }
  724. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  725. filep->size, L);
  726. }
  727. if (L != NULL && ls == NULL) lua_close(L);
  728. if (p != NULL) munmap(p, filep->size);
  729. mg_fclose(filep);
  730. return error;
  731. }
  732. #ifdef USE_WEBSOCKET
  733. struct lua_websock_data {
  734. lua_State *main;
  735. lua_State *thread;
  736. struct mg_connection *conn;
  737. };
  738. static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation)
  739. {
  740. switch (err) {
  741. case LUA_OK:
  742. case LUA_YIELD:
  743. break;
  744. case LUA_ERRRUN:
  745. mg_cry(conn, "%s: %s failed: runtime error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  746. break;
  747. case LUA_ERRSYNTAX:
  748. mg_cry(conn, "%s: %s failed: syntax error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  749. break;
  750. case LUA_ERRMEM:
  751. mg_cry(conn, "%s: %s failed: out of memory", ws_operation, lua_operation);
  752. break;
  753. case LUA_ERRGCMM:
  754. mg_cry(conn, "%s: %s failed: error during garbage collection", ws_operation, lua_operation);
  755. break;
  756. case LUA_ERRERR:
  757. mg_cry(conn, "%s: %s failed: error in error handling: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  758. break;
  759. default:
  760. mg_cry(conn, "%s: %s failed: error %i", ws_operation, lua_operation, err);
  761. break;
  762. }
  763. }
  764. static void * lua_websocket_new(const char * script, struct mg_connection *conn, int is_shared)
  765. {
  766. struct lua_websock_data *lws_data;
  767. int ok = 0;
  768. int err, nargs;
  769. assert(conn->lua_websocket_state == NULL);
  770. lws_data = (struct lua_websock_data *) malloc(sizeof(*lws_data));
  771. if (lws_data) {
  772. lws_data->conn = conn;
  773. if (is_shared) {
  774. (void)pthread_mutex_lock(&conn->ctx->mutex);
  775. // TODO: add_to_websocket_list(lws_data);
  776. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  777. }
  778. lws_data->main = luaL_newstate();
  779. if (lws_data->main) {
  780. prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  781. if (conn->ctx->callbacks.init_lua != NULL) {
  782. conn->ctx->callbacks.init_lua(conn, lws_data->main);
  783. }
  784. lws_data->thread = lua_newthread(lws_data->main);
  785. err = luaL_loadfile(lws_data->thread, script);
  786. if (err==LUA_OK) {
  787. /* Activate the Lua script. */
  788. err = lua_resume(lws_data->thread, NULL, 0);
  789. if (err!=LUA_YIELD) {
  790. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  791. } else {
  792. nargs = lua_gettop(lws_data->thread);
  793. ok = (nargs==1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  794. }
  795. } else {
  796. websock_cry(conn, err, lws_data->thread, __func__, "lua_loadfile");
  797. }
  798. } else {
  799. mg_cry(conn, "%s: luaL_newstate failed", __func__);
  800. }
  801. if (!ok) {
  802. if (lws_data->main) lua_close(lws_data->main);
  803. free(lws_data);
  804. lws_data=0;
  805. }
  806. } else {
  807. mg_cry(conn, "%s: out of memory", __func__);
  808. }
  809. return lws_data;
  810. }
  811. static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, size_t data_len)
  812. {
  813. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  814. int err, nargs, ok=0, retry;
  815. lua_Number delay;
  816. assert(lws_data != NULL);
  817. assert(lws_data->main != NULL);
  818. assert(lws_data->thread != NULL);
  819. do {
  820. retry=0;
  821. /* Push the data to Lua, then resume the Lua state. */
  822. /* The data will be available to Lua as the result of the coroutine.yield function. */
  823. lua_pushboolean(lws_data->thread, 1);
  824. if (bits >= 0) {
  825. lua_pushinteger(lws_data->thread, bits);
  826. if (data) {
  827. lua_pushlstring(lws_data->thread, data, data_len);
  828. err = lua_resume(lws_data->thread, NULL, 3);
  829. } else {
  830. err = lua_resume(lws_data->thread, NULL, 2);
  831. }
  832. } else {
  833. err = lua_resume(lws_data->thread, NULL, 1);
  834. }
  835. /* Check if Lua returned by a call to the coroutine.yield function. */
  836. if (err!=LUA_YIELD) {
  837. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  838. } else {
  839. nargs = lua_gettop(lws_data->thread);
  840. ok = (nargs>=1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  841. delay = (nargs>=2) && lua_isnumber(lws_data->thread, 2) ? lua_tonumber(lws_data->thread, 2) : -1.0;
  842. if (ok && delay>0) {
  843. fd_set rfds;
  844. struct timeval tv;
  845. FD_ZERO(&rfds);
  846. FD_SET(conn->client.sock, &rfds);
  847. tv.tv_sec = (unsigned long)delay;
  848. tv.tv_usec = (unsigned long)(((double)delay - (double)((unsigned long)delay))*1000000.0);
  849. retry = (0==select(conn->client.sock+1, &rfds, NULL, NULL, &tv));
  850. }
  851. }
  852. } while (retry);
  853. return ok;
  854. }
  855. static int lua_websocket_ready(struct mg_connection *conn)
  856. {
  857. return lua_websocket_data(conn, -1, NULL, 0);
  858. }
  859. static void lua_websocket_close(struct mg_connection *conn)
  860. {
  861. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  862. int err;
  863. assert(lws_data != NULL);
  864. assert(lws_data->main != NULL);
  865. assert(lws_data->thread != NULL);
  866. lua_pushboolean(lws_data->thread, 0);
  867. err = lua_resume(lws_data->thread, NULL, 1);
  868. lua_close(lws_data->main);
  869. free(lws_data);
  870. conn->lua_websocket_state = NULL;
  871. }
  872. #endif