mod_lua.inl 41 KB

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