mod_lua.inl 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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.base64_encode */
  496. static int lsp_base64_encode(lua_State *L)
  497. {
  498. int num_args = lua_gettop(L);
  499. const char *text;
  500. size_t text_len;
  501. char *dst;
  502. if (num_args==1) {
  503. text = lua_tolstring(L, 1, &text_len);
  504. if (text) {
  505. dst = mg_malloc(text_len*8/6+4);
  506. if (dst) {
  507. base64_encode(text, text_len, dst);
  508. lua_pushstring(L, dst);
  509. mg_free(dst);
  510. } else {
  511. return luaL_error(L, "out of memory in base64_encode() call");
  512. }
  513. } else {
  514. lua_pushnil(L);
  515. }
  516. } else {
  517. /* Syntax error */
  518. return luaL_error(L, "invalid base64_encode() call");
  519. }
  520. return 1;
  521. }
  522. /* mg.base64_encode */
  523. static int lsp_base64_decode(lua_State *L)
  524. {
  525. int num_args = lua_gettop(L);
  526. const char *text;
  527. size_t text_len, dst_len;
  528. int ret;
  529. char *dst;
  530. if (num_args==1) {
  531. text = lua_tolstring(L, 1, &text_len);
  532. if (text) {
  533. dst = mg_malloc(text_len);
  534. if (dst) {
  535. ret = base64_decode(text, text_len, dst, &dst_len);
  536. if (ret != -1) {
  537. mg_free(dst);
  538. return luaL_error(L, "illegal character in lsp_base64_decode() call");
  539. } else {
  540. lua_pushlstring(L, dst, dst_len);
  541. mg_free(dst);
  542. }
  543. } else {
  544. return luaL_error(L, "out of memory in lsp_base64_decode() call");
  545. }
  546. } else {
  547. lua_pushnil(L);
  548. }
  549. } else {
  550. /* Syntax error */
  551. return luaL_error(L, "invalid lsp_base64_decode() call");
  552. }
  553. return 1;
  554. }
  555. /* mg.write for websockets */
  556. static int lwebsock_write(lua_State *L)
  557. {
  558. #ifdef USE_WEBSOCKET
  559. int num_args = lua_gettop(L);
  560. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  561. const char *str;
  562. size_t size;
  563. int opcode = -1;
  564. if (num_args == 1) {
  565. if (lua_isstring(L, 1)) {
  566. str = lua_tolstring(L, 1, &size);
  567. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  568. }
  569. } else if (num_args == 2) {
  570. if (lua_isnumber(L, 1)) {
  571. opcode = (int)lua_tointeger(L, 1);
  572. } else if (lua_isstring(L,1)) {
  573. str = lua_tostring(L, 1);
  574. if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
  575. else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
  576. else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  577. else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
  578. else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
  579. else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
  580. }
  581. if (opcode>=0 && opcode<16 && lua_isstring(L, 2)) {
  582. str = lua_tolstring(L, 2, &size);
  583. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, str, size);
  584. }
  585. }
  586. #endif
  587. return 0;
  588. }
  589. enum {
  590. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  591. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  592. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  593. };
  594. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, const char *script_name, int lua_env_type)
  595. {
  596. const struct mg_request_info *ri = mg_get_request_info(conn);
  597. char src_addr[IP_ADDR_STR_LEN];
  598. const char * preload_file = conn->ctx->config[LUA_PRELOAD_FILE];
  599. int i;
  600. extern void luaL_openlibs(lua_State *);
  601. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  602. luaL_openlibs(L);
  603. #ifdef USE_LUA_SQLITE3
  604. {
  605. extern int luaopen_lsqlite3(lua_State *);
  606. luaopen_lsqlite3(L);
  607. }
  608. #endif
  609. #ifdef USE_LUA_FILE_SYSTEM
  610. {
  611. extern int luaopen_lfs(lua_State *);
  612. luaopen_lfs(L);
  613. }
  614. #endif
  615. luaL_newmetatable(L, LUASOCKET);
  616. lua_pushliteral(L, "__index");
  617. luaL_newlib(L, luasocket_methods);
  618. lua_rawset(L, -3);
  619. lua_pop(L, 1);
  620. lua_register(L, "connect", lsp_connect);
  621. if (conn == NULL) {
  622. /* Do not register any connection specific functions or variables */
  623. return;
  624. }
  625. /* Register mg module */
  626. lua_newtable(L);
  627. reg_function(L, "cry", lsp_cry, conn);
  628. switch (lua_env_type) {
  629. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  630. reg_string(L, "lua_type", "page");
  631. break;
  632. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  633. reg_string(L, "lua_type", "script");
  634. break;
  635. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  636. reg_string(L, "lua_type", "websocket");
  637. break;
  638. }
  639. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  640. reg_function(L, "read", lsp_read, conn);
  641. reg_function(L, "write", lsp_write, conn);
  642. reg_function(L, "keep_alive", lsp_keep_alive, conn);
  643. }
  644. if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  645. reg_function(L, "include", lsp_include, conn);
  646. reg_function(L, "redirect", lsp_redirect, conn);
  647. }
  648. if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
  649. reg_function(L, "write", lwebsock_write, conn);
  650. }
  651. reg_function(L, "send_file", lsp_send_file, conn);
  652. reg_function(L, "get_var", lsp_get_var, conn);
  653. reg_function(L, "get_mime_type", lsp_get_mime_type, conn);
  654. reg_function(L, "get_cookie", lsp_get_cookie, conn);
  655. reg_function(L, "md5", lsp_md5, conn);
  656. reg_function(L, "url_encode", lsp_url_encode, conn);
  657. reg_function(L, "url_decode", lsp_url_decode, conn);
  658. reg_function(L, "base64_encode", lsp_base64_encode, conn);
  659. reg_function(L, "base64_decode", lsp_base64_decode, conn);
  660. reg_string(L, "version", CIVETWEB_VERSION);
  661. reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]);
  662. reg_string(L, "auth_domain", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  663. #if defined(USE_WEBSOCKET)
  664. reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]);
  665. #endif
  666. if (conn->ctx->systemName) {
  667. reg_string(L, "system", conn->ctx->systemName);
  668. }
  669. /* Export request_info */
  670. lua_pushstring(L, "request_info");
  671. lua_newtable(L);
  672. reg_string(L, "request_method", ri->request_method);
  673. reg_string(L, "uri", ri->uri);
  674. reg_string(L, "http_version", ri->http_version);
  675. reg_string(L, "query_string", ri->query_string);
  676. reg_int(L, "remote_ip", ri->remote_ip); /* remote_ip is deprecated, use remote_addr instead */
  677. reg_string(L, "remote_addr", src_addr);
  678. /* TODO: ip version */
  679. reg_int(L, "remote_port", ri->remote_port);
  680. reg_int(L, "num_headers", ri->num_headers);
  681. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  682. if (conn->request_info.remote_user != NULL) {
  683. reg_string(L, "remote_user", conn->request_info.remote_user);
  684. reg_string(L, "auth_type", "Digest");
  685. }
  686. lua_pushstring(L, "http_headers");
  687. lua_newtable(L);
  688. for (i = 0; i < ri->num_headers; i++) {
  689. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  690. }
  691. lua_rawset(L, -3);
  692. reg_boolean(L, "https", conn->ssl != NULL);
  693. reg_string(L, "script_name", script_name);
  694. lua_rawset(L, -3);
  695. lua_setglobal(L, "mg");
  696. /* Register default mg.onerror function */
  697. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  698. "debug.traceback(e, 1)) end"));
  699. /* Preload */
  700. if ((preload_file != NULL) && (*preload_file != 0)) {
  701. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file));
  702. }
  703. }
  704. static int lua_error_handler(lua_State *L)
  705. {
  706. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  707. lua_getglobal(L, "mg");
  708. if (!lua_isnil(L, -1)) {
  709. lua_getfield(L, -1, "write"); /* call mg.write() */
  710. lua_pushstring(L, error_msg);
  711. lua_pushliteral(L, "\n");
  712. lua_call(L, 2, 0);
  713. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  714. } else {
  715. printf("Lua error: [%s]\n", error_msg);
  716. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  717. }
  718. /* TODO(lsm): leave the stack balanced */
  719. return 0;
  720. }
  721. static void * lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize) {
  722. (void)ud; (void)osize; /* not used */
  723. if (nsize == 0) {
  724. mg_free(ptr);
  725. return NULL;
  726. }
  727. return mg_realloc(ptr, nsize);
  728. }
  729. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  730. const void **exports)
  731. {
  732. int i;
  733. lua_State *L;
  734. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  735. conn->must_close=1;
  736. /* Execute a plain Lua script. */
  737. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  738. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  739. lua_pushcclosure(L, &lua_error_handler, 0);
  740. if (exports != NULL) {
  741. lua_pushglobaltable(L);
  742. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  743. lua_pushstring(L, exports[i]);
  744. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  745. lua_rawset(L, -3);
  746. }
  747. }
  748. if (luaL_loadfile(L, path) != 0) {
  749. lua_error_handler(L);
  750. }
  751. lua_pcall(L, 0, 0, -2);
  752. lua_close(L);
  753. }
  754. }
  755. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  756. const char *fmt, ...)
  757. {
  758. char buf[MG_BUF_LEN];
  759. va_list ap;
  760. int len;
  761. va_start(ap, fmt);
  762. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  763. va_end(ap);
  764. if (L == NULL) {
  765. send_http_error(conn, 500, http_500_error, "%s", buf);
  766. } else {
  767. lua_pushstring(L, buf);
  768. lua_error(L);
  769. }
  770. }
  771. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  772. struct file *filep, struct lua_State *ls)
  773. {
  774. void *p = NULL;
  775. lua_State *L = NULL;
  776. int error = 1;
  777. /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
  778. conn->must_close=1;
  779. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  780. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  781. lsp_send_err(conn, ls, "File [%s] not found", path);
  782. } else if (filep->membuf == NULL &&
  783. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  784. fileno(filep->fp), 0)) == MAP_FAILED) {
  785. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  786. fileno(filep->fp), strerror(errno));
  787. } else if ((L = ls != NULL ? ls : lua_newstate(lua_allocator, NULL)) == NULL) {
  788. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  789. } else {
  790. /* We're not sending HTTP headers here, Lua page must do it. */
  791. if (ls == NULL) {
  792. prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  793. if (conn->ctx->callbacks.init_lua != NULL) {
  794. conn->ctx->callbacks.init_lua(conn, L);
  795. }
  796. }
  797. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  798. filep->size, L);
  799. }
  800. if (L != NULL && ls == NULL) lua_close(L);
  801. if (p != NULL) munmap(p, filep->size);
  802. mg_fclose(filep);
  803. return error;
  804. }
  805. #ifdef USE_WEBSOCKET
  806. struct lua_websock_data {
  807. lua_State *main;
  808. lua_State *thread;
  809. char * script;
  810. unsigned shared;
  811. struct mg_connection *conn;
  812. pthread_mutex_t mutex;
  813. };
  814. struct mg_shared_lua_websocket {
  815. struct lua_websock_data *sock;
  816. struct mg_shared_lua_websocket *next;
  817. };
  818. static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation)
  819. {
  820. switch (err) {
  821. case LUA_OK:
  822. case LUA_YIELD:
  823. break;
  824. case LUA_ERRRUN:
  825. mg_cry(conn, "%s: %s failed: runtime error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  826. break;
  827. case LUA_ERRSYNTAX:
  828. mg_cry(conn, "%s: %s failed: syntax error: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  829. break;
  830. case LUA_ERRMEM:
  831. mg_cry(conn, "%s: %s failed: out of memory", ws_operation, lua_operation);
  832. break;
  833. case LUA_ERRGCMM:
  834. mg_cry(conn, "%s: %s failed: error during garbage collection", ws_operation, lua_operation);
  835. break;
  836. case LUA_ERRERR:
  837. mg_cry(conn, "%s: %s failed: error in error handling: %s", ws_operation, lua_operation, lua_tostring(L, -1));
  838. break;
  839. default:
  840. mg_cry(conn, "%s: %s failed: error %i", ws_operation, lua_operation, err);
  841. break;
  842. }
  843. }
  844. static void * lua_websocket_new(const char * script, struct mg_connection *conn, int is_shared)
  845. {
  846. struct lua_websock_data *lws_data;
  847. struct mg_shared_lua_websocket **shared_websock_list = &(conn->ctx->shared_lua_websockets);
  848. int ok = 0;
  849. int found = 0;
  850. int err, nargs;
  851. assert(conn->lua_websocket_state == NULL);
  852. /*
  853. lock list (mg_context global)
  854. check if in list
  855. yes: inc rec counter
  856. no: create state, add to list
  857. lock list element
  858. unlock list (mg_context global)
  859. call add
  860. unlock list element
  861. */
  862. if (is_shared) {
  863. (void)pthread_mutex_lock(&conn->ctx->mutex);
  864. while (*shared_websock_list) {
  865. if (!strcmp((*shared_websock_list)->sock->script, script)) {
  866. lws_data = (*shared_websock_list)->sock;
  867. lws_data->shared++;
  868. found = 1;
  869. }
  870. shared_websock_list = &((*shared_websock_list)->next);
  871. }
  872. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  873. }
  874. if (!found) {
  875. lws_data = (struct lua_websock_data *) mg_malloc(sizeof(*lws_data));
  876. }
  877. if (lws_data) {
  878. if (!found) {
  879. lws_data->shared = is_shared;
  880. lws_data->conn = conn;
  881. lws_data->script = mg_strdup(script);
  882. lws_data->main = lua_newstate(lua_allocator, NULL);
  883. if (is_shared) {
  884. (void)pthread_mutex_lock(&conn->ctx->mutex);
  885. shared_websock_list = &(conn->ctx->shared_lua_websockets);
  886. while (*shared_websock_list) {
  887. shared_websock_list = &((*shared_websock_list)->next);
  888. }
  889. *shared_websock_list = (struct mg_shared_lua_websocket *)mg_malloc(sizeof(struct mg_shared_lua_websocket));
  890. if (*shared_websock_list) {
  891. (*shared_websock_list)->sock = lws_data;
  892. (*shared_websock_list)->next = 0;
  893. }
  894. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  895. }
  896. }
  897. if (lws_data->main) {
  898. prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  899. if (conn->ctx->callbacks.init_lua != NULL) {
  900. conn->ctx->callbacks.init_lua(conn, lws_data->main);
  901. }
  902. lws_data->thread = lua_newthread(lws_data->main);
  903. err = luaL_loadfile(lws_data->thread, script);
  904. if (err==LUA_OK) {
  905. /* Activate the Lua script. */
  906. err = lua_resume(lws_data->thread, NULL, 0);
  907. if (err!=LUA_YIELD) {
  908. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  909. } else {
  910. nargs = lua_gettop(lws_data->thread);
  911. ok = (nargs==1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  912. }
  913. } else {
  914. websock_cry(conn, err, lws_data->thread, __func__, "lua_loadfile");
  915. }
  916. } else {
  917. mg_cry(conn, "%s: luaL_newstate failed", __func__);
  918. }
  919. if (!ok) {
  920. if (lws_data->main) lua_close(lws_data->main);
  921. mg_free(lws_data->script);
  922. mg_free(lws_data);
  923. lws_data=0;
  924. }
  925. } else {
  926. mg_cry(conn, "%s: out of memory", __func__);
  927. }
  928. return lws_data;
  929. }
  930. static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, size_t data_len)
  931. {
  932. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  933. int err, nargs, ok=0, retry;
  934. lua_Number delay;
  935. assert(lws_data != NULL);
  936. assert(lws_data->main != NULL);
  937. assert(lws_data->thread != NULL);
  938. /*
  939. lock list element
  940. call data
  941. unlock list element
  942. */
  943. do {
  944. retry=0;
  945. /* Push the data to Lua, then resume the Lua state. */
  946. /* The data will be available to Lua as the result of the coroutine.yield function. */
  947. lua_pushboolean(lws_data->thread, 1);
  948. if (bits >= 0) {
  949. lua_pushinteger(lws_data->thread, bits);
  950. if (data) {
  951. lua_pushlstring(lws_data->thread, data, data_len);
  952. err = lua_resume(lws_data->thread, NULL, 3);
  953. } else {
  954. err = lua_resume(lws_data->thread, NULL, 2);
  955. }
  956. } else {
  957. err = lua_resume(lws_data->thread, NULL, 1);
  958. }
  959. /* Check if Lua returned by a call to the coroutine.yield function. */
  960. if (err!=LUA_YIELD) {
  961. websock_cry(conn, err, lws_data->thread, __func__, "lua_resume");
  962. } else {
  963. nargs = lua_gettop(lws_data->thread);
  964. ok = (nargs>=1) && lua_isboolean(lws_data->thread, 1) && lua_toboolean(lws_data->thread, 1);
  965. delay = (nargs>=2) && lua_isnumber(lws_data->thread, 2) ? lua_tonumber(lws_data->thread, 2) : -1.0;
  966. if (ok && delay>0) {
  967. fd_set rfds;
  968. struct timeval tv;
  969. FD_ZERO(&rfds);
  970. FD_SET(conn->client.sock, &rfds);
  971. tv.tv_sec = (unsigned long)delay;
  972. tv.tv_usec = (unsigned long)(((double)delay - (double)((unsigned long)delay))*1000000.0);
  973. retry = (0==select(conn->client.sock+1, &rfds, NULL, NULL, &tv));
  974. }
  975. }
  976. } while (retry);
  977. return ok;
  978. }
  979. static int lua_websocket_ready(struct mg_connection *conn)
  980. {
  981. return lua_websocket_data(conn, -1, NULL, 0);
  982. }
  983. static void lua_websocket_close(struct mg_connection *conn)
  984. {
  985. struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state);
  986. struct mg_shared_lua_websocket **shared_websock_list;
  987. int err;
  988. assert(lws_data != NULL);
  989. assert(lws_data->main != NULL);
  990. assert(lws_data->thread != NULL);
  991. /*
  992. lock list element
  993. lock list (mg_context global)
  994. call remove
  995. dec ref counter
  996. if ref counter == 0 close state and remove from list
  997. unlock list element
  998. unlock list (mg_context global)
  999. */
  1000. lua_pushboolean(lws_data->thread, 0);
  1001. err = lua_resume(lws_data->thread, NULL, 1);
  1002. if (lws_data->shared) {
  1003. (void)pthread_mutex_lock(&conn->ctx->mutex);
  1004. lws_data->shared--;
  1005. if (lws_data->shared==0) {
  1006. /*
  1007. shared_websock_list = &(conn->ctx->shared_lua_websockets);
  1008. while (*shared_websock_list) {
  1009. if ((*shared_websock_list)->sock == lws_data) {
  1010. *shared_websock_list = (*shared_websock_list)->next;
  1011. } else {
  1012. shared_websock_list = &((*shared_websock_list)->next);
  1013. }
  1014. }
  1015. lua_close(lws_data->main);
  1016. mg_free(lws_data->script);
  1017. lws_data->script=0;
  1018. mg_free(lws_data);
  1019. */
  1020. }
  1021. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  1022. } else {
  1023. lua_close(lws_data->main);
  1024. mg_free(lws_data->script);
  1025. mg_free(lws_data);
  1026. }
  1027. conn->lua_websocket_state = NULL;
  1028. }
  1029. #endif