mod_lua.inl 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. #include <lua.h>
  2. #include <lauxlib.h>
  3. #include "lua_civet.h"
  4. #ifdef _WIN32
  5. static void *
  6. mmap(void *addr, int64_t len, int prot, int flags, int fd, int offset)
  7. {
  8. /* TODO (low): This is an incomplete implementation of mmap for windows.
  9. * Currently it is sufficient, but there are a lot of unused parameters.
  10. * Better use a function "mg_map" which only has the required parameters,
  11. * and implement it using mmap in Linux and CreateFileMapping in Windows.
  12. * Noone should expect a full mmap for Windows here.
  13. */
  14. HANDLE fh = (HANDLE)_get_osfhandle(fd);
  15. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  16. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
  17. CloseHandle(mh);
  18. /* unused parameters */
  19. (void)addr;
  20. (void)prot;
  21. (void)flags;
  22. (void)offset;
  23. return p;
  24. }
  25. static void munmap(void *addr, int64_t length)
  26. {
  27. /* unused parameters */
  28. (void)length;
  29. UnmapViewOfFile(addr);
  30. }
  31. #define MAP_FAILED (NULL)
  32. #define MAP_PRIVATE (0)
  33. #define PROT_READ (0)
  34. #else
  35. #include <sys/mman.h>
  36. #endif
  37. static const char *LUASOCKET = "luasocket";
  38. static const char lua_regkey_ctx = 1;
  39. static const char lua_regkey_connlist = 2;
  40. /* Forward declarations */
  41. static void handle_request(struct mg_connection *);
  42. static int handle_lsp_request(struct mg_connection *,
  43. const char *,
  44. struct file *,
  45. struct lua_State *);
  46. static void reg_string(struct lua_State *L, const char *name, const char *val)
  47. {
  48. if (name != NULL && val != NULL) {
  49. lua_pushstring(L, name);
  50. lua_pushstring(L, val);
  51. lua_rawset(L, -3);
  52. }
  53. }
  54. static void reg_int(struct lua_State *L, const char *name, int val)
  55. {
  56. if (name != NULL) {
  57. lua_pushstring(L, name);
  58. lua_pushinteger(L, val);
  59. lua_rawset(L, -3);
  60. }
  61. }
  62. static void reg_boolean(struct lua_State *L, const char *name, int val)
  63. {
  64. if (name != NULL) {
  65. lua_pushstring(L, name);
  66. lua_pushboolean(L, val != 0);
  67. lua_rawset(L, -3);
  68. }
  69. }
  70. static void reg_conn_function(struct lua_State *L,
  71. const char *name,
  72. lua_CFunction func,
  73. struct mg_connection *conn)
  74. {
  75. if (name != NULL && func != NULL && conn != NULL) {
  76. lua_pushstring(L, name);
  77. lua_pushlightuserdata(L, conn);
  78. lua_pushcclosure(L, func, 1);
  79. lua_rawset(L, -3);
  80. }
  81. }
  82. static void
  83. reg_function(struct lua_State *L, const char *name, lua_CFunction func)
  84. {
  85. if (name != NULL && func != NULL) {
  86. lua_pushstring(L, name);
  87. lua_pushcclosure(L, func, 0);
  88. lua_rawset(L, -3);
  89. }
  90. }
  91. static void lua_cry(struct mg_connection *conn,
  92. int err,
  93. lua_State *L,
  94. const char *lua_title,
  95. const char *lua_operation)
  96. {
  97. switch (err) {
  98. case LUA_OK:
  99. case LUA_YIELD:
  100. break;
  101. case LUA_ERRRUN:
  102. mg_cry(conn,
  103. "%s: %s failed: runtime error: %s",
  104. lua_title,
  105. lua_operation,
  106. lua_tostring(L, -1));
  107. break;
  108. case LUA_ERRSYNTAX:
  109. mg_cry(conn,
  110. "%s: %s failed: syntax error: %s",
  111. lua_title,
  112. lua_operation,
  113. lua_tostring(L, -1));
  114. break;
  115. case LUA_ERRMEM:
  116. mg_cry(conn, "%s: %s failed: out of memory", lua_title, lua_operation);
  117. break;
  118. case LUA_ERRGCMM:
  119. mg_cry(conn,
  120. "%s: %s failed: error during garbage collection",
  121. lua_title,
  122. lua_operation);
  123. break;
  124. case LUA_ERRERR:
  125. mg_cry(conn,
  126. "%s: %s failed: error in error handling: %s",
  127. lua_title,
  128. lua_operation,
  129. lua_tostring(L, -1));
  130. break;
  131. default:
  132. mg_cry(conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
  133. break;
  134. }
  135. }
  136. static int lsp_sock_close(lua_State *L)
  137. {
  138. int num_args = lua_gettop(L);
  139. if ((num_args == 1) && lua_istable(L, -1)) {
  140. lua_getfield(L, -1, "sock");
  141. closesocket((SOCKET)lua_tonumber(L, -1));
  142. } else {
  143. return luaL_error(L, "invalid :close() call");
  144. }
  145. return 1;
  146. }
  147. static int lsp_sock_recv(lua_State *L)
  148. {
  149. int num_args = lua_gettop(L);
  150. char buf[2000];
  151. int n;
  152. if ((num_args == 1) && lua_istable(L, -1)) {
  153. lua_getfield(L, -1, "sock");
  154. n = recv((SOCKET)lua_tonumber(L, -1), buf, sizeof(buf), 0);
  155. if (n <= 0) {
  156. lua_pushnil(L);
  157. } else {
  158. lua_pushlstring(L, buf, n);
  159. }
  160. } else {
  161. return luaL_error(L, "invalid :close() call");
  162. }
  163. return 1;
  164. }
  165. static int lsp_sock_send(lua_State *L)
  166. {
  167. int num_args = lua_gettop(L);
  168. const char *buf;
  169. size_t len, sent = 0;
  170. int n = 0, sock;
  171. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  172. buf = lua_tolstring(L, -1, &len);
  173. lua_getfield(L, -2, "sock");
  174. sock = (int)lua_tonumber(L, -1);
  175. while (sent < len) {
  176. if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
  177. break;
  178. }
  179. sent += n;
  180. }
  181. lua_pushnumber(L, n);
  182. } else {
  183. return luaL_error(L, "invalid :close() call");
  184. }
  185. return 1;
  186. }
  187. static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
  188. {"send", lsp_sock_send},
  189. {"recv", lsp_sock_recv},
  190. {NULL, NULL}};
  191. static int lsp_connect(lua_State *L)
  192. {
  193. int num_args = lua_gettop(L);
  194. char ebuf[100];
  195. SOCKET sock;
  196. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2) &&
  197. lua_isnumber(L, -1)) {
  198. sock = conn2(NULL,
  199. lua_tostring(L, -3),
  200. (int)lua_tonumber(L, -2),
  201. (int)lua_tonumber(L, -1),
  202. ebuf,
  203. sizeof(ebuf));
  204. if (sock == INVALID_SOCKET) {
  205. return luaL_error(L, ebuf);
  206. } else {
  207. lua_newtable(L);
  208. reg_int(L, "sock", (int)sock);
  209. reg_string(L, "host", lua_tostring(L, -4));
  210. luaL_getmetatable(L, LUASOCKET);
  211. lua_setmetatable(L, -2);
  212. }
  213. } else {
  214. return luaL_error(
  215. L, "connect(host,port,is_ssl): invalid parameter given.");
  216. }
  217. return 1;
  218. }
  219. static int lsp_error(lua_State *L)
  220. {
  221. lua_getglobal(L, "mg");
  222. lua_getfield(L, -1, "onerror");
  223. lua_pushvalue(L, -3);
  224. lua_pcall(L, 1, 0, 0);
  225. return 0;
  226. }
  227. /* Silently stop processing chunks. */
  228. static void lsp_abort(lua_State *L)
  229. {
  230. int top = lua_gettop(L);
  231. lua_getglobal(L, "mg");
  232. lua_pushnil(L);
  233. lua_setfield(L, -2, "onerror");
  234. lua_settop(L, top);
  235. lua_pushstring(L, "aborting");
  236. lua_error(L);
  237. }
  238. struct lsp_var_reader_data {
  239. const char *begin;
  240. unsigned len;
  241. unsigned state;
  242. };
  243. static const char *lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  244. {
  245. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  246. const char *ret;
  247. (void)(L); /* unused */
  248. switch (reader->state) {
  249. case 0:
  250. ret = "mg.write(";
  251. *sz = strlen(ret);
  252. break;
  253. case 1:
  254. ret = reader->begin;
  255. *sz = reader->len;
  256. break;
  257. case 2:
  258. ret = ")";
  259. *sz = strlen(ret);
  260. break;
  261. default:
  262. ret = 0;
  263. *sz = 0;
  264. }
  265. reader->state++;
  266. return ret;
  267. }
  268. static int lsp(struct mg_connection *conn,
  269. const char *path,
  270. const char *p,
  271. int64_t len,
  272. lua_State *L)
  273. {
  274. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  275. char chunkname[MG_BUF_LEN];
  276. struct lsp_var_reader_data data;
  277. for (i = 0; i < len; i++) {
  278. if (p[i] == '\n')
  279. lines++;
  280. if ((i + 1) < len && p[i] == '<' && p[i + 1] == '?') {
  281. /* <?= ?> means a variable is enclosed and its value should be
  282. * printed */
  283. is_var = ((i + 2) < len && p[i + 2] == '=');
  284. if (is_var)
  285. j = i + 2;
  286. else
  287. j = i + 1;
  288. while (j < len) {
  289. if (p[j] == '\n')
  290. lualines++;
  291. if ((j + 1) < len && p[j] == '?' && p[j + 1] == '>') {
  292. mg_write(conn, p + pos, i - pos);
  293. snprintf(
  294. chunkname, sizeof(chunkname), "@%s+%i", path, lines);
  295. lua_pushlightuserdata(L, conn);
  296. lua_pushcclosure(L, lsp_error, 1);
  297. if (is_var) {
  298. data.begin = p + (i + 3);
  299. data.len = j - (i + 3);
  300. data.state = 0;
  301. lua_ok =
  302. lua_load(L, lsp_var_reader, &data, chunkname, NULL);
  303. } else {
  304. lua_ok = luaL_loadbuffer(
  305. L, p + (i + 2), j - (i + 2), chunkname);
  306. }
  307. if (lua_ok) {
  308. /* Syntax error or OOM. Error message is pushed on
  309. * stack. */
  310. lua_pcall(L, 1, 0, 0);
  311. } else {
  312. /* Success loading chunk. Call it. */
  313. lua_pcall(L, 0, 0, 1);
  314. }
  315. pos = j + 2;
  316. i = pos - 1;
  317. break;
  318. }
  319. j++;
  320. }
  321. if (lualines > 0) {
  322. lines += lualines;
  323. lualines = 0;
  324. }
  325. }
  326. }
  327. if (i > pos) {
  328. mg_write(conn, p + pos, i - pos);
  329. }
  330. return 0;
  331. }
  332. /* mg.write: Send data to the client */
  333. static int lsp_write(lua_State *L)
  334. {
  335. struct mg_connection *conn =
  336. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  337. int num_args = lua_gettop(L);
  338. const char *str;
  339. size_t size;
  340. int i;
  341. for (i = 1; i <= num_args; i++) {
  342. if (lua_isstring(L, i)) {
  343. str = lua_tolstring(L, i, &size);
  344. mg_write(conn, str, size);
  345. }
  346. }
  347. return 0;
  348. }
  349. /* mg.read: Read data from the client (e.g., from a POST request) */
  350. static int lsp_read(lua_State *L)
  351. {
  352. struct mg_connection *conn =
  353. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  354. char buf[1024];
  355. int len = mg_read(conn, buf, sizeof(buf));
  356. if (len <= 0)
  357. return 0;
  358. lua_pushlstring(L, buf, len);
  359. return 1;
  360. }
  361. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  362. static int lsp_keep_alive(lua_State *L)
  363. {
  364. struct mg_connection *conn =
  365. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  366. int num_args = lua_gettop(L);
  367. /* This function may be called with one parameter (boolean) to set the
  368. keep_alive state.
  369. Or without a parameter to just query the current keep_alive state. */
  370. if ((num_args == 1) && lua_isboolean(L, 1)) {
  371. conn->must_close = !lua_toboolean(L, 1);
  372. } else if (num_args != 0) {
  373. /* Syntax error */
  374. return luaL_error(L, "invalid keep_alive() call");
  375. }
  376. /* Return the current "keep_alive" state. This may be false, even it
  377. * keep_alive(true) has been called. */
  378. lua_pushboolean(L, should_keep_alive(conn));
  379. return 1;
  380. }
  381. /* mg.include: Include another .lp file */
  382. static int lsp_include(lua_State *L)
  383. {
  384. struct mg_connection *conn =
  385. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  386. int num_args = lua_gettop(L);
  387. struct file file = STRUCT_FILE_INITIALIZER;
  388. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  389. if (filename) {
  390. if (handle_lsp_request(conn, filename, &file, L)) {
  391. /* handle_lsp_request returned an error code, meaning an error
  392. occured in
  393. the included page and mg.onerror returned non-zero. Stop processing.
  394. */
  395. lsp_abort(L);
  396. }
  397. } else {
  398. /* Syntax error */
  399. return luaL_error(L, "invalid include() call");
  400. }
  401. return 0;
  402. }
  403. /* mg.cry: Log an error. Default value for mg.onerror. */
  404. static int lsp_cry(lua_State *L)
  405. {
  406. struct mg_connection *conn =
  407. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  408. int num_args = lua_gettop(L);
  409. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  410. if (text) {
  411. mg_cry(conn, "%s", lua_tostring(L, -1));
  412. } else {
  413. /* Syntax error */
  414. return luaL_error(L, "invalid cry() call");
  415. }
  416. return 0;
  417. }
  418. /* mg.redirect: Redirect the request (internally). */
  419. static int lsp_redirect(lua_State *L)
  420. {
  421. struct mg_connection *conn =
  422. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  423. int num_args = lua_gettop(L);
  424. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  425. if (target) {
  426. conn->request_info.uri = target;
  427. handle_request(conn);
  428. lsp_abort(L);
  429. } else {
  430. /* Syntax error */
  431. return luaL_error(L, "invalid redirect() call");
  432. }
  433. return 0;
  434. }
  435. /* mg.send_file */
  436. static int lsp_send_file(lua_State *L)
  437. {
  438. struct mg_connection *conn =
  439. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  440. int num_args = lua_gettop(L);
  441. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  442. if (filename) {
  443. mg_send_file(conn, filename);
  444. } else {
  445. /* Syntax error */
  446. return luaL_error(L, "invalid send_file() call");
  447. }
  448. return 0;
  449. }
  450. /* mg.get_time */
  451. static int lsp_get_time(lua_State *L)
  452. {
  453. int num_args = lua_gettop(L);
  454. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  455. struct timespec ts;
  456. double d;
  457. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  458. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  459. lua_pushnumber(L, d);
  460. return 1;
  461. }
  462. /* mg.get_var */
  463. static int lsp_get_var(lua_State *L)
  464. {
  465. int num_args = lua_gettop(L);
  466. const char *data, *var_name;
  467. size_t data_len, occurrence;
  468. int ret;
  469. char dst[512];
  470. if (num_args >= 2 && num_args <= 3) {
  471. data = lua_tolstring(L, 1, &data_len);
  472. var_name = lua_tostring(L, 2);
  473. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  474. ret =
  475. mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
  476. if (ret >= 0) {
  477. /* Variable found: return value to Lua */
  478. lua_pushstring(L, dst);
  479. } else {
  480. /* Variable not found (TODO (mid): may be string too long) */
  481. lua_pushnil(L);
  482. }
  483. } else {
  484. /* Syntax error */
  485. return luaL_error(L, "invalid get_var() call");
  486. }
  487. return 1;
  488. }
  489. /* mg.get_mime_type */
  490. static int lsp_get_mime_type(lua_State *L)
  491. {
  492. int num_args = lua_gettop(L);
  493. struct vec mime_type = {0, 0};
  494. struct mg_context *ctx;
  495. const char *text;
  496. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  497. lua_gettable(L, LUA_REGISTRYINDEX);
  498. ctx = (struct mg_context *)lua_touserdata(L, -1);
  499. if (num_args == 1) {
  500. text = lua_tostring(L, 1);
  501. if (text) {
  502. if (ctx) {
  503. get_mime_type(ctx, text, &mime_type);
  504. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  505. } else {
  506. text = mg_get_builtin_mime_type(text);
  507. lua_pushstring(L, text);
  508. }
  509. } else {
  510. /* Syntax error */
  511. return luaL_error(L, "invalid argument for get_mime_type() call");
  512. }
  513. } else {
  514. /* Syntax error */
  515. return luaL_error(L, "invalid get_mime_type() call");
  516. }
  517. return 1;
  518. }
  519. /* mg.get_cookie */
  520. static int lsp_get_cookie(lua_State *L)
  521. {
  522. int num_args = lua_gettop(L);
  523. const char *cookie;
  524. const char *var_name;
  525. int ret;
  526. char dst[512];
  527. if (num_args == 2) {
  528. cookie = lua_tostring(L, 1);
  529. var_name = lua_tostring(L, 2);
  530. if (cookie != NULL && var_name != NULL) {
  531. ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
  532. } else {
  533. ret = -1;
  534. }
  535. if (ret >= 0) {
  536. lua_pushlstring(L, dst, ret);
  537. } else {
  538. lua_pushnil(L);
  539. }
  540. } else {
  541. /* Syntax error */
  542. return luaL_error(L, "invalid get_cookie() call");
  543. }
  544. return 1;
  545. }
  546. /* mg.md5 */
  547. static int lsp_md5(lua_State *L)
  548. {
  549. int num_args = lua_gettop(L);
  550. const char *text;
  551. md5_byte_t hash[16];
  552. md5_state_t ctx;
  553. size_t text_len;
  554. char buf[40];
  555. if (num_args == 1) {
  556. text = lua_tolstring(L, 1, &text_len);
  557. if (text) {
  558. md5_init(&ctx);
  559. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  560. md5_finish(&ctx, hash);
  561. bin2str(buf, hash, sizeof(hash));
  562. lua_pushstring(L, buf);
  563. } else {
  564. lua_pushnil(L);
  565. }
  566. } else {
  567. /* Syntax error */
  568. return luaL_error(L, "invalid md5() call");
  569. }
  570. return 1;
  571. }
  572. /* mg.url_encode */
  573. static int lsp_url_encode(lua_State *L)
  574. {
  575. int num_args = lua_gettop(L);
  576. const char *text;
  577. size_t text_len;
  578. char dst[512];
  579. if (num_args == 1) {
  580. text = lua_tolstring(L, 1, &text_len);
  581. if (text) {
  582. mg_url_encode(text, dst, sizeof(dst));
  583. lua_pushstring(L, dst);
  584. } else {
  585. lua_pushnil(L);
  586. }
  587. } else {
  588. /* Syntax error */
  589. return luaL_error(L, "invalid url_encode() call");
  590. }
  591. return 1;
  592. }
  593. /* mg.url_decode */
  594. static int lsp_url_decode(lua_State *L)
  595. {
  596. int num_args = lua_gettop(L);
  597. const char *text;
  598. size_t text_len;
  599. int is_form;
  600. char dst[512];
  601. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  602. text = lua_tolstring(L, 1, &text_len);
  603. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  604. if (text) {
  605. mg_url_decode(text, text_len, dst, sizeof(dst), is_form);
  606. lua_pushstring(L, dst);
  607. } else {
  608. lua_pushnil(L);
  609. }
  610. } else {
  611. /* Syntax error */
  612. return luaL_error(L, "invalid url_decode() call");
  613. }
  614. return 1;
  615. }
  616. /* mg.base64_encode */
  617. static int lsp_base64_encode(lua_State *L)
  618. {
  619. int num_args = lua_gettop(L);
  620. const char *text;
  621. size_t text_len;
  622. char *dst;
  623. if (num_args == 1) {
  624. text = lua_tolstring(L, 1, &text_len);
  625. if (text) {
  626. dst = (char *)mg_malloc(text_len * 8 / 6 + 4);
  627. if (dst) {
  628. base64_encode((const unsigned char *)text, text_len, dst);
  629. lua_pushstring(L, dst);
  630. mg_free(dst);
  631. } else {
  632. return luaL_error(L, "out of memory in base64_encode() call");
  633. }
  634. } else {
  635. lua_pushnil(L);
  636. }
  637. } else {
  638. /* Syntax error */
  639. return luaL_error(L, "invalid base64_encode() call");
  640. }
  641. return 1;
  642. }
  643. /* mg.base64_encode */
  644. static int lsp_base64_decode(lua_State *L)
  645. {
  646. int num_args = lua_gettop(L);
  647. const char *text;
  648. size_t text_len, dst_len;
  649. int ret;
  650. char *dst;
  651. if (num_args == 1) {
  652. text = lua_tolstring(L, 1, &text_len);
  653. if (text) {
  654. dst = (char *)mg_malloc(text_len);
  655. if (dst) {
  656. ret = base64_decode(
  657. (const unsigned char *)text, text_len, dst, &dst_len);
  658. if (ret != -1) {
  659. mg_free(dst);
  660. return luaL_error(
  661. L, "illegal character in lsp_base64_decode() call");
  662. } else {
  663. lua_pushlstring(L, dst, dst_len);
  664. mg_free(dst);
  665. }
  666. } else {
  667. return luaL_error(L,
  668. "out of memory in lsp_base64_decode() call");
  669. }
  670. } else {
  671. lua_pushnil(L);
  672. }
  673. } else {
  674. /* Syntax error */
  675. return luaL_error(L, "invalid lsp_base64_decode() call");
  676. }
  677. return 1;
  678. }
  679. /* mg.get_response_code_text */
  680. static int lsp_get_response_code_text(lua_State *L)
  681. {
  682. int num_args = lua_gettop(L);
  683. int type1;
  684. double code;
  685. const char *text;
  686. if (num_args == 1) {
  687. type1 = lua_type(L, 1);
  688. if (type1 == LUA_TNUMBER) {
  689. /* If the first argument is a number,
  690. convert it to the corresponding text. */
  691. code = lua_tonumber(L, 1);
  692. text = mg_get_response_code_text((int)code, NULL);
  693. if (text)
  694. lua_pushstring(L, text);
  695. return text ? 1 : 0;
  696. }
  697. }
  698. /* Syntax error */
  699. return luaL_error(L, "invalid get_response_code_text() call");
  700. }
  701. #ifdef USE_WEBSOCKET
  702. struct lua_websock_data {
  703. lua_State *state;
  704. char *script;
  705. unsigned references;
  706. struct mg_connection *conn[MAX_WORKER_THREADS];
  707. pthread_mutex_t ws_mutex;
  708. };
  709. #endif
  710. /* mg.write for websockets */
  711. static int lwebsock_write(lua_State *L)
  712. {
  713. #ifdef USE_WEBSOCKET
  714. int num_args = lua_gettop(L);
  715. struct lua_websock_data *ws;
  716. const char *str;
  717. size_t size;
  718. int opcode = -1;
  719. unsigned i;
  720. struct mg_connection *client = NULL;
  721. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  722. lua_gettable(L, LUA_REGISTRYINDEX);
  723. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  724. if (num_args == 1) {
  725. /* just one text: send it to all client */
  726. if (lua_isstring(L, 1)) {
  727. opcode = WEBSOCKET_OPCODE_TEXT;
  728. }
  729. } else if (num_args == 2) {
  730. if (lua_isnumber(L, 1)) {
  731. /* opcode number and message text */
  732. opcode = (int)lua_tointeger(L, 1);
  733. } else if (lua_isstring(L, 1)) {
  734. /* opcode string and message text */
  735. str = lua_tostring(L, 1);
  736. if (!mg_strncasecmp(str, "text", 4))
  737. opcode = WEBSOCKET_OPCODE_TEXT;
  738. else if (!mg_strncasecmp(str, "bin", 3))
  739. opcode = WEBSOCKET_OPCODE_BINARY;
  740. else if (!mg_strncasecmp(str, "close", 5))
  741. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  742. else if (!mg_strncasecmp(str, "ping", 4))
  743. opcode = WEBSOCKET_OPCODE_PING;
  744. else if (!mg_strncasecmp(str, "pong", 4))
  745. opcode = WEBSOCKET_OPCODE_PONG;
  746. else if (!mg_strncasecmp(str, "cont", 4))
  747. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  748. } else if (lua_isuserdata(L, 1)) {
  749. /* client id and message text */
  750. client = (struct mg_connection *)lua_touserdata(L, 1);
  751. opcode = WEBSOCKET_OPCODE_TEXT;
  752. }
  753. } else if (num_args == 3) {
  754. if (lua_isuserdata(L, 1)) {
  755. client = (struct mg_connection *)lua_touserdata(L, 1);
  756. if (lua_isnumber(L, 2)) {
  757. /* client id, opcode number and message text */
  758. opcode = (int)lua_tointeger(L, 2);
  759. } else if (lua_isstring(L, 2)) {
  760. /* client id, opcode string and message text */
  761. str = lua_tostring(L, 2);
  762. if (!mg_strncasecmp(str, "text", 4))
  763. opcode = WEBSOCKET_OPCODE_TEXT;
  764. else if (!mg_strncasecmp(str, "bin", 3))
  765. opcode = WEBSOCKET_OPCODE_BINARY;
  766. else if (!mg_strncasecmp(str, "close", 5))
  767. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  768. else if (!mg_strncasecmp(str, "ping", 4))
  769. opcode = WEBSOCKET_OPCODE_PING;
  770. else if (!mg_strncasecmp(str, "pong", 4))
  771. opcode = WEBSOCKET_OPCODE_PONG;
  772. else if (!mg_strncasecmp(str, "cont", 4))
  773. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  774. }
  775. }
  776. }
  777. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  778. str = lua_tolstring(L, num_args, &size);
  779. if (client) {
  780. for (i = 0; i < ws->references; i++) {
  781. if (client == ws->conn[i]) {
  782. mg_websocket_write(ws->conn[i], opcode, str, size);
  783. }
  784. }
  785. } else {
  786. for (i = 0; i < ws->references; i++) {
  787. mg_websocket_write(ws->conn[i], opcode, str, size);
  788. }
  789. }
  790. } else {
  791. return luaL_error(L, "invalid websocket write() call");
  792. }
  793. #else
  794. (void)(L); /* unused */
  795. #endif
  796. return 0;
  797. }
  798. struct laction_arg {
  799. lua_State *state;
  800. const char *script;
  801. pthread_mutex_t *pmutex;
  802. char txt[1];
  803. };
  804. static int lua_action(struct laction_arg *arg)
  805. {
  806. int err, ok;
  807. struct mg_context *ctx;
  808. (void)pthread_mutex_lock(arg->pmutex);
  809. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  810. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  811. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  812. err = luaL_loadstring(arg->state, arg->txt);
  813. if (err != 0) {
  814. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  815. (void)pthread_mutex_unlock(arg->pmutex);
  816. mg_free(arg);
  817. return 0;
  818. }
  819. err = lua_pcall(arg->state, 0, 1, 0);
  820. if (err != 0) {
  821. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  822. (void)pthread_mutex_unlock(arg->pmutex);
  823. mg_free(arg);
  824. return 0;
  825. }
  826. ok = lua_type(arg->state, -1);
  827. if (lua_isboolean(arg->state, -1)) {
  828. ok = lua_toboolean(arg->state, -1);
  829. } else {
  830. ok = 0;
  831. }
  832. lua_pop(arg->state, 1);
  833. (void)pthread_mutex_unlock(arg->pmutex);
  834. if (!ok) {
  835. mg_free(arg);
  836. }
  837. return ok;
  838. }
  839. static int lua_action_free(struct laction_arg *arg)
  840. {
  841. if (lua_action(arg)) {
  842. mg_free(arg);
  843. }
  844. return 0;
  845. }
  846. static int lwebsocket_set_timer(lua_State *L, int is_periodic)
  847. {
  848. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  849. int num_args = lua_gettop(L);
  850. struct lua_websock_data *ws;
  851. int type1, type2, ok = 0;
  852. double timediff;
  853. struct mg_context *ctx;
  854. struct laction_arg *arg;
  855. const char *txt;
  856. size_t txt_len;
  857. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  858. lua_gettable(L, LUA_REGISTRYINDEX);
  859. ctx = (struct mg_context *)lua_touserdata(L, -1);
  860. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  861. lua_gettable(L, LUA_REGISTRYINDEX);
  862. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  863. if (num_args < 2) {
  864. return luaL_error(L,
  865. "not enough arguments for set_timer/interval() call");
  866. }
  867. type1 = lua_type(L, 1);
  868. type2 = lua_type(L, 2);
  869. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  870. timediff = (double)lua_tonumber(L, 2);
  871. txt = lua_tostring(L, 1);
  872. txt_len = strlen(txt);
  873. arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg) +
  874. txt_len + 10);
  875. arg->state = L;
  876. arg->script = ws->script;
  877. arg->pmutex = &(ws->ws_mutex);
  878. memcpy(arg->txt, "return(", 7);
  879. memcpy(arg->txt + 7, txt, txt_len);
  880. arg->txt[txt_len + 7] = ')';
  881. arg->txt[txt_len + 8] = 0;
  882. ok = (0 ==
  883. timer_add(ctx,
  884. timediff,
  885. is_periodic,
  886. 1,
  887. (taction)(is_periodic ? lua_action : lua_action_free),
  888. (void *)arg));
  889. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  890. /* TODO (mid): not implemented yet */
  891. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  892. } else {
  893. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  894. }
  895. lua_pushboolean(L, ok);
  896. return 1;
  897. #else
  898. (void)(L); /* unused */
  899. (void)(is_periodic); /* unused */
  900. return 0;
  901. #endif
  902. }
  903. /* mg.set_timeout for websockets */
  904. static int lwebsocket_set_timeout(lua_State *L)
  905. {
  906. return lwebsocket_set_timer(L, 0);
  907. }
  908. /* mg.set_interval for websockets */
  909. static int lwebsocket_set_interval(lua_State *L)
  910. {
  911. return lwebsocket_set_timer(L, 1);
  912. }
  913. enum {
  914. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  915. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  916. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  917. };
  918. static void prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  919. {
  920. const char *s;
  921. int i;
  922. /* Export mg.request_info */
  923. lua_pushstring(L, "request_info");
  924. lua_newtable(L);
  925. reg_string(L, "request_method", conn->request_info.request_method);
  926. reg_string(L, "uri", conn->request_info.uri);
  927. reg_string(L, "http_version", conn->request_info.http_version);
  928. reg_string(L, "query_string", conn->request_info.query_string);
  929. #if defined(MG_LEGACY_INTERFACE)
  930. reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is
  931. deprecated, use
  932. remote_addr
  933. instead */
  934. #endif
  935. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  936. /* TODO (high): ip version */
  937. reg_int(L, "remote_port", conn->request_info.remote_port);
  938. reg_int(L, "num_headers", conn->request_info.num_headers);
  939. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  940. if (conn->request_info.content_length >= 0) {
  941. /* reg_int64: content_length */
  942. lua_pushstring(L, "content_length");
  943. lua_pushnumber(
  944. L,
  945. (lua_Number)conn->request_info
  946. .content_length); /* lua_Number may be used as 52 bit integer */
  947. lua_rawset(L, -3);
  948. }
  949. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  950. reg_string(L, "content_type", s);
  951. }
  952. if (conn->request_info.remote_user != NULL) {
  953. reg_string(L, "remote_user", conn->request_info.remote_user);
  954. reg_string(L, "auth_type", "Digest");
  955. }
  956. reg_boolean(L, "https", conn->ssl != NULL);
  957. if (conn->status_code > 0) {
  958. /* Lua error handler should show the status code */
  959. reg_int(L, "status", conn->status_code);
  960. }
  961. lua_pushstring(L, "http_headers");
  962. lua_newtable(L);
  963. for (i = 0; i < conn->request_info.num_headers; i++) {
  964. reg_string(L,
  965. conn->request_info.http_headers[i].name,
  966. conn->request_info.http_headers[i].value);
  967. }
  968. lua_rawset(L, -3);
  969. lua_rawset(L, -3);
  970. }
  971. void lua_civet_open_all_libs(lua_State *L)
  972. {
  973. {
  974. extern void luaL_openlibs(lua_State *);
  975. luaL_openlibs(L);
  976. }
  977. #ifdef USE_LUA_SQLITE3
  978. {
  979. extern int luaopen_lsqlite3(lua_State *);
  980. luaopen_lsqlite3(L);
  981. }
  982. #endif
  983. #ifdef USE_LUA_LUAXML
  984. {
  985. extern int luaopen_LuaXML_lib(lua_State *);
  986. luaopen_LuaXML_lib(L);
  987. }
  988. #endif
  989. #ifdef USE_LUA_FILE_SYSTEM
  990. {
  991. extern int luaopen_lfs(lua_State *);
  992. luaopen_lfs(L);
  993. }
  994. #endif
  995. #ifdef USE_LUA_BINARY
  996. {
  997. /* TODO (low): Test if this could be used as a replacement for bit32.
  998. * Check again with Lua 5.3 later. */
  999. extern int luaopen_binary(lua_State *);
  1000. luaL_requiref(L, "binary", luaopen_binary, 1);
  1001. lua_pop(L, 1);
  1002. }
  1003. #endif
  1004. }
  1005. static void prepare_lua_environment(struct mg_context *ctx,
  1006. struct mg_connection *conn,
  1007. struct lua_websock_data *conn_list,
  1008. lua_State *L,
  1009. const char *script_name,
  1010. int lua_env_type)
  1011. {
  1012. lua_civet_open_all_libs(L);
  1013. luaL_newmetatable(L, LUASOCKET);
  1014. lua_pushliteral(L, "__index");
  1015. luaL_newlib(L, luasocket_methods);
  1016. lua_rawset(L, -3);
  1017. lua_pop(L, 1);
  1018. lua_register(L, "connect", lsp_connect);
  1019. /* Store context in the registry */
  1020. if (ctx) {
  1021. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1022. lua_pushlightuserdata(L, (void *)ctx);
  1023. lua_settable(L, LUA_REGISTRYINDEX);
  1024. }
  1025. if (conn_list) {
  1026. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1027. lua_pushlightuserdata(L, (void *)conn_list);
  1028. lua_settable(L, LUA_REGISTRYINDEX);
  1029. }
  1030. /* Register mg module */
  1031. lua_newtable(L);
  1032. switch (lua_env_type) {
  1033. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1034. reg_string(L, "lua_type", "page");
  1035. break;
  1036. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1037. reg_string(L, "lua_type", "script");
  1038. break;
  1039. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1040. reg_string(L, "lua_type", "websocket");
  1041. break;
  1042. }
  1043. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE ||
  1044. lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1045. reg_conn_function(L, "cry", lsp_cry, conn);
  1046. reg_conn_function(L, "read", lsp_read, conn);
  1047. reg_conn_function(L, "write", lsp_write, conn);
  1048. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1049. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1050. }
  1051. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1052. reg_conn_function(L, "include", lsp_include, conn);
  1053. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1054. }
  1055. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1056. reg_function(L, "write", lwebsock_write);
  1057. #ifdef USE_TIMERS
  1058. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1059. reg_function(L, "set_interval", lwebsocket_set_interval);
  1060. #endif
  1061. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1062. }
  1063. reg_function(L, "time", lsp_get_time);
  1064. reg_function(L, "get_var", lsp_get_var);
  1065. reg_function(L, "get_mime_type", lsp_get_mime_type);
  1066. reg_function(L, "get_cookie", lsp_get_cookie);
  1067. reg_function(L, "md5", lsp_md5);
  1068. reg_function(L, "url_encode", lsp_url_encode);
  1069. reg_function(L, "url_decode", lsp_url_decode);
  1070. reg_function(L, "base64_encode", lsp_base64_encode);
  1071. reg_function(L, "base64_decode", lsp_base64_decode);
  1072. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1073. reg_string(L, "version", CIVETWEB_VERSION);
  1074. reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
  1075. reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
  1076. #if defined(USE_WEBSOCKET)
  1077. reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
  1078. #endif
  1079. reg_string(L, "script_name", script_name);
  1080. if (ctx->systemName != NULL) {
  1081. reg_string(L, "system", ctx->systemName);
  1082. }
  1083. /* Export connection specific info */
  1084. if (conn != NULL) {
  1085. prepare_lua_request_info(conn, L);
  1086. }
  1087. lua_setglobal(L, "mg");
  1088. /* Register default mg.onerror function */
  1089. IGNORE_UNUSED_RESULT(
  1090. luaL_dostring(L,
  1091. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1092. "debug.traceback(e, 1)) end"));
  1093. /* Preload */
  1094. if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
  1095. IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
  1096. }
  1097. if (ctx->callbacks.init_lua != NULL) {
  1098. ctx->callbacks.init_lua(conn, L);
  1099. }
  1100. }
  1101. static int lua_error_handler(lua_State *L)
  1102. {
  1103. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1104. lua_getglobal(L, "mg");
  1105. if (!lua_isnil(L, -1)) {
  1106. lua_getfield(L, -1, "write"); /* call mg.write() */
  1107. lua_pushstring(L, error_msg);
  1108. lua_pushliteral(L, "\n");
  1109. lua_call(L, 2, 0);
  1110. IGNORE_UNUSED_RESULT(
  1111. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1112. } else {
  1113. printf("Lua error: [%s]\n", error_msg);
  1114. IGNORE_UNUSED_RESULT(
  1115. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1116. }
  1117. /* TODO(lsm, low): leave the stack balanced */
  1118. return 0;
  1119. }
  1120. static void *lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1121. {
  1122. (void)ud;
  1123. (void)osize; /* not used */
  1124. if (nsize == 0) {
  1125. mg_free(ptr);
  1126. return NULL;
  1127. }
  1128. return mg_realloc(ptr, nsize);
  1129. }
  1130. static void mg_exec_lua_script(struct mg_connection *conn,
  1131. const char *path,
  1132. const void **exports)
  1133. {
  1134. int i;
  1135. lua_State *L;
  1136. /* Assume the script does not support keep_alive. The script may change this
  1137. * by calling mg.keep_alive(true). */
  1138. conn->must_close = 1;
  1139. /* Execute a plain Lua script. */
  1140. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  1141. prepare_lua_environment(
  1142. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1143. lua_pushcclosure(L, &lua_error_handler, 0);
  1144. if (exports != NULL) {
  1145. lua_pushglobaltable(L);
  1146. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1147. lua_CFunction func;
  1148. lua_pushstring(L, (const char *)(exports[i]));
  1149. *(const void **)(&func) = exports[i + 1];
  1150. lua_pushcclosure(L, func, 0);
  1151. lua_rawset(L, -3);
  1152. }
  1153. }
  1154. if (luaL_loadfile(L, path) != 0) {
  1155. lua_error_handler(L);
  1156. }
  1157. lua_pcall(L, 0, 0, -2);
  1158. lua_close(L);
  1159. }
  1160. }
  1161. static int handle_lsp_request(struct mg_connection *conn,
  1162. const char *path,
  1163. struct file *filep,
  1164. struct lua_State *ls)
  1165. {
  1166. void *p = NULL;
  1167. lua_State *L = NULL;
  1168. int error = 1;
  1169. /* Assume the script does not support keep_alive. The script may change this
  1170. * by calling mg.keep_alive(true). */
  1171. conn->must_close = 1;
  1172. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  1173. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  1174. /* File not found or not accessible */
  1175. if (ls == NULL) {
  1176. send_http_error(
  1177. conn,
  1178. 500,
  1179. "Error: Cannot open script\nFile %s can not be read",
  1180. path);
  1181. } else {
  1182. luaL_error(ls, "File [%s] not found", path);
  1183. }
  1184. } else if (filep->membuf == NULL &&
  1185. (p = mmap(NULL,
  1186. (size_t)filep->size,
  1187. PROT_READ,
  1188. MAP_PRIVATE,
  1189. fileno(filep->fp),
  1190. 0)) == MAP_FAILED) {
  1191. /* mmap failed */
  1192. if (ls == NULL) {
  1193. send_http_error(
  1194. conn,
  1195. 500,
  1196. "Error: Cannot open script\nFile %s can not be mapped",
  1197. path);
  1198. } else {
  1199. luaL_error(ls,
  1200. "mmap(%s, %zu, %d): %s",
  1201. path,
  1202. (size_t)filep->size,
  1203. fileno(filep->fp),
  1204. strerror(errno));
  1205. }
  1206. } else if ((L = (ls != NULL ? ls : lua_newstate(lua_allocator, NULL))) ==
  1207. NULL) {
  1208. send_http_error(conn,
  1209. 500,
  1210. "%s",
  1211. "Error: Cannot execute script\nlua_newstate failed");
  1212. } else {
  1213. /* We're not sending HTTP headers here, Lua page must do it. */
  1214. if (ls == NULL) {
  1215. prepare_lua_environment(
  1216. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1217. }
  1218. error = lsp(conn,
  1219. path,
  1220. (filep->membuf == NULL) ? (const char *)p
  1221. : (const char *)filep->membuf,
  1222. filep->size,
  1223. L);
  1224. }
  1225. if (L != NULL && ls == NULL)
  1226. lua_close(L);
  1227. if (p != NULL)
  1228. munmap(p, filep->size);
  1229. mg_fclose(filep);
  1230. return error;
  1231. }
  1232. #ifdef USE_WEBSOCKET
  1233. struct mg_shared_lua_websocket_list {
  1234. struct lua_websock_data ws;
  1235. struct mg_shared_lua_websocket_list *next;
  1236. };
  1237. static void *lua_websocket_new(const char *script, struct mg_connection *conn)
  1238. {
  1239. struct mg_shared_lua_websocket_list **shared_websock_list =
  1240. &(conn->ctx->shared_lua_websockets);
  1241. struct lua_websock_data *ws;
  1242. int err, ok = 0;
  1243. assert(conn->lua_websocket_state == NULL);
  1244. /* lock list (mg_context global) */
  1245. mg_lock_context(conn->ctx);
  1246. while (*shared_websock_list) {
  1247. /* check if ws already in list */
  1248. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1249. break;
  1250. }
  1251. shared_websock_list = &((*shared_websock_list)->next);
  1252. }
  1253. if (*shared_websock_list == NULL) {
  1254. /* add ws to list */
  1255. *shared_websock_list = (struct mg_shared_lua_websocket_list *)mg_calloc(
  1256. sizeof(struct mg_shared_lua_websocket_list), 1);
  1257. if (*shared_websock_list == NULL) {
  1258. mg_unlock_context(conn->ctx);
  1259. mg_cry(conn, "Cannot create shared websocket struct, OOM");
  1260. return NULL;
  1261. }
  1262. /* init ws list element */
  1263. ws = &(*shared_websock_list)->ws;
  1264. ws->script = mg_strdup(script); /* TODO (low): handle OOM */
  1265. pthread_mutex_init(&(ws->ws_mutex), NULL);
  1266. ws->state = lua_newstate(lua_allocator, NULL);
  1267. ws->conn[0] = conn;
  1268. ws->references = 1;
  1269. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1270. prepare_lua_environment(
  1271. conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  1272. err = luaL_loadfile(ws->state, script);
  1273. if (err != 0) {
  1274. lua_cry(conn, err, ws->state, script, "load");
  1275. }
  1276. err = lua_pcall(ws->state, 0, 0, 0);
  1277. if (err != 0) {
  1278. lua_cry(conn, err, ws->state, script, "init");
  1279. }
  1280. } else {
  1281. /* inc ref count */
  1282. ws = &(*shared_websock_list)->ws;
  1283. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1284. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1285. }
  1286. mg_unlock_context(conn->ctx);
  1287. /* call add */
  1288. lua_getglobal(ws->state, "open");
  1289. lua_newtable(ws->state);
  1290. prepare_lua_request_info(conn, ws->state);
  1291. lua_pushstring(ws->state, "client");
  1292. lua_pushlightuserdata(ws->state, (void *)conn);
  1293. lua_rawset(ws->state, -3);
  1294. err = lua_pcall(ws->state, 1, 1, 0);
  1295. if (err != 0) {
  1296. lua_cry(conn, err, ws->state, script, "open handler");
  1297. } else {
  1298. if (lua_isboolean(ws->state, -1)) {
  1299. ok = lua_toboolean(ws->state, -1);
  1300. }
  1301. lua_pop(ws->state, 1);
  1302. }
  1303. if (!ok) {
  1304. /* Remove from ws connection list. */
  1305. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1306. * (see websocket_close). */
  1307. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1308. }
  1309. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1310. return ok ? (void *)ws : NULL;
  1311. }
  1312. static int lua_websocket_data(struct mg_connection *conn,
  1313. int bits,
  1314. char *data,
  1315. size_t data_len,
  1316. void *ws_arg)
  1317. {
  1318. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1319. int err, ok = 0;
  1320. assert(ws != NULL);
  1321. assert(ws->state != NULL);
  1322. (void)pthread_mutex_lock(&ws->ws_mutex);
  1323. lua_getglobal(ws->state, "data");
  1324. lua_newtable(ws->state);
  1325. lua_pushstring(ws->state, "client");
  1326. lua_pushlightuserdata(ws->state, (void *)conn);
  1327. lua_rawset(ws->state, -3);
  1328. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1329. a meaning according to
  1330. http://tools.ietf.org/html/rfc6455,
  1331. section 5.2 */
  1332. lua_pushnumber(ws->state, bits);
  1333. lua_rawset(ws->state, -3);
  1334. lua_pushstring(ws->state, "data");
  1335. lua_pushlstring(ws->state, data, data_len);
  1336. lua_rawset(ws->state, -3);
  1337. err = lua_pcall(ws->state, 1, 1, 0);
  1338. if (err != 0) {
  1339. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1340. } else {
  1341. if (lua_isboolean(ws->state, -1)) {
  1342. ok = lua_toboolean(ws->state, -1);
  1343. }
  1344. lua_pop(ws->state, 1);
  1345. }
  1346. (void)pthread_mutex_unlock(&ws->ws_mutex);
  1347. return ok;
  1348. }
  1349. static int lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1350. {
  1351. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1352. int err, ok = 0;
  1353. assert(ws != NULL);
  1354. assert(ws->state != NULL);
  1355. (void)pthread_mutex_lock(&ws->ws_mutex);
  1356. lua_getglobal(ws->state, "ready");
  1357. lua_newtable(ws->state);
  1358. lua_pushstring(ws->state, "client");
  1359. lua_pushlightuserdata(ws->state, (void *)conn);
  1360. lua_rawset(ws->state, -3);
  1361. err = lua_pcall(ws->state, 1, 1, 0);
  1362. if (err != 0) {
  1363. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1364. } else {
  1365. if (lua_isboolean(ws->state, -1)) {
  1366. ok = lua_toboolean(ws->state, -1);
  1367. }
  1368. lua_pop(ws->state, 1);
  1369. }
  1370. (void)pthread_mutex_unlock(&ws->ws_mutex);
  1371. return ok;
  1372. }
  1373. static void lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1374. {
  1375. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1376. struct mg_shared_lua_websocket_list **shared_websock_list =
  1377. &(conn->ctx->shared_lua_websockets);
  1378. int err = 0;
  1379. unsigned i;
  1380. assert(ws != NULL);
  1381. assert(ws->state != NULL);
  1382. (void)pthread_mutex_lock(&ws->ws_mutex);
  1383. lua_getglobal(ws->state, "close");
  1384. lua_newtable(ws->state);
  1385. lua_pushstring(ws->state, "client");
  1386. lua_pushlightuserdata(ws->state, (void *)conn);
  1387. lua_rawset(ws->state, -3);
  1388. err = lua_pcall(ws->state, 1, 0, 0);
  1389. if (err != 0) {
  1390. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1391. }
  1392. for (i = 0; i < ws->references; i++) {
  1393. if (ws->conn[i] == conn) {
  1394. ws->references--;
  1395. ws->conn[i] = ws->conn[ws->references];
  1396. }
  1397. }
  1398. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1399. This must only be done, when all connections are closed, and all
  1400. asynchronous operations and timers are completed/expired. */
  1401. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1402. (void)pthread_mutex_unlock(&ws->ws_mutex);
  1403. }
  1404. #endif