mod_lua.inl 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. int i;
  539. extern void luaL_openlibs(lua_State *);
  540. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  541. luaL_openlibs(L);
  542. #ifdef USE_LUA_SQLITE3
  543. {
  544. extern int luaopen_lsqlite3(lua_State *);
  545. luaopen_lsqlite3(L);
  546. }
  547. #endif
  548. #ifdef USE_LUA_FILE_SYSTEM
  549. {
  550. extern int luaopen_lfs(lua_State *);
  551. luaopen_lfs(L);
  552. }
  553. #endif
  554. luaL_newmetatable(L, LUASOCKET);
  555. lua_pushliteral(L, "__index");
  556. luaL_newlib(L, luasocket_methods);
  557. lua_rawset(L, -3);
  558. lua_pop(L, 1);
  559. lua_register(L, "connect", lsp_connect);
  560. if (conn == NULL) {
  561. /* Do not register any connection specific functions or variables */
  562. return;
  563. }
  564. /* Register mg module */
  565. lua_newtable(L);
  566. reg_function(L, "cry", lsp_cry, conn);
  567. switch (lua_env_type) {
  568. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  569. reg_string(L, "lua_type", "page");
  570. break;
  571. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  572. reg_string(L, "lua_type", "script");
  573. break;
  574. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  575. reg_string(L, "lua_type", "websocket");
  576. break;
  577. }
  578. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  579. reg_function(L, "read", lsp_read, conn);
  580. reg_function(L, "write", lsp_write, conn);
  581. reg_function(L, "keep_alive", lsp_keep_alive, conn);
  582. }
  583. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  584. reg_function(L, "include", lsp_include, conn);
  585. reg_function(L, "redirect", lsp_redirect, conn);
  586. }
  587. if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
  588. reg_function(L, "write", lwebsock_write, conn);
  589. }
  590. reg_function(L, "send_file", lsp_send_file, conn);
  591. reg_function(L, "get_var", lsp_get_var, conn);
  592. reg_function(L, "get_mime_type", lsp_get_mime_type, conn);
  593. reg_function(L, "get_cookie", lsp_get_cookie, conn);
  594. reg_function(L, "md5", lsp_md5, conn);
  595. reg_function(L, "url_encode", lsp_url_encode, conn);
  596. reg_function(L, "url_decode", lsp_url_decode, conn);
  597. reg_string(L, "version", CIVETWEB_VERSION);
  598. reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]);
  599. reg_string(L, "auth_domain", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  600. #if defined(USE_WEBSOCKET)
  601. reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]);
  602. #endif
  603. /* Export request_info */
  604. lua_pushstring(L, "request_info");
  605. lua_newtable(L);
  606. reg_string(L, "request_method", ri->request_method);
  607. reg_string(L, "uri", ri->uri);
  608. reg_string(L, "http_version", ri->http_version);
  609. reg_string(L, "query_string", ri->query_string);
  610. reg_int(L, "remote_ip", ri->remote_ip); /* remote_ip is deprecated, use remote_addr instead */
  611. reg_string(L, "remote_addr", src_addr);
  612. /* TODO: ip version */
  613. reg_int(L, "remote_port", ri->remote_port);
  614. reg_int(L, "num_headers", ri->num_headers);
  615. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  616. if (conn->request_info.remote_user != NULL) {
  617. reg_string(L, "remote_user", conn->request_info.remote_user);
  618. reg_string(L, "auth_type", "Digest");
  619. }
  620. lua_pushstring(L, "http_headers");
  621. lua_newtable(L);
  622. for (i = 0; i < ri->num_headers; i++) {
  623. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  624. }
  625. lua_rawset(L, -3);
  626. reg_boolean(L, "https", conn->ssl != NULL);
  627. reg_string(L, "script_name", script_name);
  628. lua_rawset(L, -3);
  629. lua_setglobal(L, "mg");
  630. /* Register default mg.onerror function */
  631. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  632. "debug.traceback(e, 1)) end"));
  633. }
  634. static int lua_error_handler(lua_State *L)
  635. {
  636. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  637. lua_getglobal(L, "mg");
  638. if (!lua_isnil(L, -1)) {
  639. lua_getfield(L, -1, "write"); /* call mg.write() */
  640. lua_pushstring(L, error_msg);
  641. lua_pushliteral(L, "\n");
  642. lua_call(L, 2, 0);
  643. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  644. } else {
  645. printf("Lua error: [%s]\n", error_msg);
  646. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  647. }
  648. /* TODO(lsm): leave the stack balanced */
  649. return 0;
  650. }
  651. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  652. const void **exports)
  653. {
  654. int i;
  655. lua_State *L;
  656. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  657. conn->must_close=1;
  658. /* Execute a plain Lua script. */
  659. if (path != NULL && (L = luaL_newstate()) != NULL) {
  660. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  661. lua_pushcclosure(L, &lua_error_handler, 0);
  662. if (exports != NULL) {
  663. lua_pushglobaltable(L);
  664. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  665. lua_pushstring(L, exports[i]);
  666. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  667. lua_rawset(L, -3);
  668. }
  669. }
  670. if (luaL_loadfile(L, path) != 0) {
  671. lua_error_handler(L);
  672. }
  673. lua_pcall(L, 0, 0, -2);
  674. lua_close(L);
  675. }
  676. }
  677. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  678. const char *fmt, ...)
  679. {
  680. char buf[MG_BUF_LEN];
  681. va_list ap;
  682. int len;
  683. va_start(ap, fmt);
  684. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  685. va_end(ap);
  686. if (L == NULL) {
  687. send_http_error(conn, 500, http_500_error, "%s", buf);
  688. } else {
  689. lua_pushstring(L, buf);
  690. lua_error(L);
  691. }
  692. }
  693. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  694. struct file *filep, struct lua_State *ls)
  695. {
  696. void *p = NULL;
  697. lua_State *L = NULL;
  698. int error = 1;
  699. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  700. conn->must_close=1;
  701. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  702. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  703. lsp_send_err(conn, ls, "File [%s] not found", path);
  704. } else if (filep->membuf == NULL &&
  705. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  706. fileno(filep->fp), 0)) == MAP_FAILED) {
  707. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  708. fileno(filep->fp), strerror(errno));
  709. } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
  710. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  711. } else {
  712. /* We're not sending HTTP headers here, Lua page must do it. */
  713. if (ls == NULL) {
  714. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  715. if (conn->ctx->callbacks.init_lua != NULL) {
  716. conn->ctx->callbacks.init_lua(conn, L);
  717. }
  718. }
  719. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  720. filep->size, L);
  721. }
  722. if (L != NULL && ls == NULL) lua_close(L);
  723. if (p != NULL) munmap(p, filep->size);
  724. mg_fclose(filep);
  725. return error;
  726. }
  727. #ifdef USE_WEBSOCKET
  728. struct lua_websock_data {
  729. lua_State *main;
  730. lua_State *thread;
  731. struct mg_connection *conn;
  732. };
  733. static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation)
  734. {
  735. switch (err) {
  736. case LUA_OK:
  737. case LUA_YIELD:
  738. break;
  739. case LUA_ERRRUN:
  740. mg_cry(conn, "%s: %s failed: runtime error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  741. break;
  742. case LUA_ERRSYNTAX:
  743. mg_cry(conn, "%s: %s failed: syntax error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  744. break;
  745. case LUA_ERRMEM:
  746. mg_cry(conn, "%s: %s failed: out of memory", ws_operation, lua_operation);
  747. break;
  748. case LUA_ERRGCMM:
  749. mg_cry(conn, "%s: %s failed: error during garbage collection", ws_operation, lua_operation);
  750. break;
  751. case LUA_ERRERR:
  752. mg_cry(conn, "%s: %s failed: error in error handling: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  753. break;
  754. default:
  755. mg_cry(conn, "%s: %s failed: error %i", ws_operation, lua_operation, err);
  756. break;
  757. }
  758. }
  759. static void * lua_websocket_new(const char * script, struct mg_connection *conn, int is_shared)
  760. {
  761. struct lua_websock_data *lws_data;
  762. int ok = 0;
  763. int err, nargs;
  764. assert(conn->lua_websocket_state == NULL);
  765. lws_data = (struct lua_websock_data *) malloc(sizeof(*lws_data));
  766. if (lws_data) {
  767. lws_data->conn = conn;
  768. if (is_shared) {
  769. (void)pthread_mutex_lock(&conn->ctx->mutex);
  770. // TODO: add_to_websocket_list(lws_data);
  771. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  772. }
  773. lws_data->main = luaL_newstate();
  774. if (lws_data->main) {
  775. prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  776. if (conn->ctx->callbacks.init_lua != NULL) {
  777. conn->ctx->callbacks.init_lua(conn, lws_data->main);
  778. }
  779. lws_data->thread = lua_newthread(lws_data->main);
  780. err = luaL_loadfile(lws_data->thread, script);
  781. if (err==LUA_OK) {
  782. /* Activate the Lua script. */
  783. err = lua_resume(lws_data->thread, NULL, 0);
  784. if (err!=LUA_YIELD) {
  785. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  786. } else {
  787. nargs = lua_gettop(lws_data->thread);
  788. ok = (nargs==1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  789. }
  790. } else {
  791. websock_cry(conn, err, lws_data->thread, __func__, "lua_loadfile");
  792. }
  793. } else {
  794. mg_cry(conn, "%s: luaL_newstate failed", __func__);
  795. }
  796. if (!ok) {
  797. if (lws_data->main) lua_close(lws_data->main);
  798. free(lws_data);
  799. lws_data=0;
  800. }
  801. } else {
  802. mg_cry(conn, "%s: out of memory", __func__);
  803. }
  804. return lws_data;
  805. }
  806. static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, size_t data_len)
  807. {
  808. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  809. int err, nargs, ok=0, retry;
  810. lua_Number delay;
  811. assert(lws_data != NULL);
  812. assert(lws_data->main != NULL);
  813. assert(lws_data->thread != NULL);
  814. do {
  815. retry=0;
  816. /* Push the data to Lua, then resume the Lua state. */
  817. /* The data will be available to Lua as the result of the coroutine.yield function. */
  818. lua_pushboolean(lws_data->thread, 1);
  819. if (bits >= 0) {
  820. lua_pushinteger(lws_data->thread, bits);
  821. if (data) {
  822. lua_pushlstring(lws_data->thread, data, data_len);
  823. err = lua_resume(lws_data->thread, NULL, 3);
  824. } else {
  825. err = lua_resume(lws_data->thread, NULL, 2);
  826. }
  827. } else {
  828. err = lua_resume(lws_data->thread, NULL, 1);
  829. }
  830. /* Check if Lua returned by a call to the coroutine.yield function. */
  831. if (err!=LUA_YIELD) {
  832. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  833. } else {
  834. nargs = lua_gettop(lws_data->thread);
  835. ok = (nargs>=1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  836. delay = (nargs>=2) && lua_isnumber(lws_data->thread, 2) ? lua_tonumber(lws_data->thread, 2) : -1.0;
  837. if (ok && delay>0) {
  838. fd_set rfds;
  839. struct timeval tv;
  840. FD_ZERO(&rfds);
  841. FD_SET(conn->client.sock, &rfds);
  842. tv.tv_sec = (unsigned long)delay;
  843. tv.tv_usec = (unsigned long)(((double)delay - (double)((unsigned long)delay))*1000000.0);
  844. retry = (0==select(conn->client.sock+1, &rfds, NULL, NULL, &tv));
  845. }
  846. }
  847. } while (retry);
  848. return ok;
  849. }
  850. static int lua_websocket_ready(struct mg_connection *conn)
  851. {
  852. return lua_websocket_data(conn, -1, NULL, 0);
  853. }
  854. static void lua_websocket_close(struct mg_connection *conn)
  855. {
  856. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  857. int err;
  858. assert(lws_data != NULL);
  859. assert(lws_data->main != NULL);
  860. assert(lws_data->thread != NULL);
  861. lua_pushboolean(lws_data->thread, 0);
  862. err = lua_resume(lws_data->thread, NULL, 1);
  863. lua_close(lws_data->main);
  864. free(lws_data);
  865. conn->lua_websocket_state = NULL;
  866. }
  867. #endif