mod_lua.inl 40 KB

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