mod_lua.inl 41 KB

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