mod_lua.inl 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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, (int)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, (int)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. (int)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(NULL, (int)code);
  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. /* mg.random - might be better than math.random on some systems */
  747. static int
  748. lsp_random(lua_State *L)
  749. {
  750. int num_args = lua_gettop(L);
  751. if (num_args == 0) {
  752. /* The civetweb internal random number generator will generate
  753. * a 64 bit random number. */
  754. uint64_t r = get_random();
  755. /* Lua "number" is a IEEE 754 double precission float:
  756. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  757. * Thus, mask with 2^53-1 to get an integer with the maximum
  758. * precission available. */
  759. r &= ((((uint64_t)1) << 53) - 1);
  760. lua_pushnumber(L, (double)r);
  761. return 1;
  762. }
  763. /* Syntax error */
  764. return luaL_error(L, "invalid random() call");
  765. }
  766. union {
  767. void *p;
  768. void (*f)(unsigned char uuid[16]);
  769. } pf_uuid_generate;
  770. /* mg.uuid */
  771. static int
  772. lsp_uuid(lua_State *L)
  773. {
  774. union {
  775. unsigned char uuid_array[16];
  776. struct uuid_struct_type {
  777. uint32_t data1;
  778. uint16_t data2;
  779. uint16_t data3;
  780. uint8_t data4[8];
  781. } uuid_struct;
  782. } uuid;
  783. char uuid_str[40];
  784. int num_args = lua_gettop(L);
  785. memset(&uuid, 0, sizeof(uuid));
  786. memset(uuid_str, 0, sizeof(uuid_str));
  787. if (num_args == 0) {
  788. pf_uuid_generate.f(uuid.uuid_array);
  789. sprintf(uuid_str,
  790. "{%08lX-%04X-%04X-%02X%02X-"
  791. "%02X%02X%02X%02X%02X%02X}",
  792. (unsigned long)uuid.uuid_struct.data1,
  793. (unsigned)uuid.uuid_struct.data2,
  794. (unsigned)uuid.uuid_struct.data3,
  795. (unsigned)uuid.uuid_struct.data4[0],
  796. (unsigned)uuid.uuid_struct.data4[1],
  797. (unsigned)uuid.uuid_struct.data4[2],
  798. (unsigned)uuid.uuid_struct.data4[3],
  799. (unsigned)uuid.uuid_struct.data4[4],
  800. (unsigned)uuid.uuid_struct.data4[5],
  801. (unsigned)uuid.uuid_struct.data4[6],
  802. (unsigned)uuid.uuid_struct.data4[7]);
  803. lua_pushstring(L, uuid_str);
  804. return 1;
  805. }
  806. /* Syntax error */
  807. return luaL_error(L, "invalid random() call");
  808. }
  809. #ifdef USE_WEBSOCKET
  810. struct lua_websock_data {
  811. lua_State *state;
  812. char *script;
  813. unsigned references;
  814. struct mg_connection *conn[MAX_WORKER_THREADS];
  815. pthread_mutex_t ws_mutex;
  816. };
  817. #endif
  818. /* mg.write for websockets */
  819. static int
  820. lwebsock_write(lua_State *L)
  821. {
  822. #ifdef USE_WEBSOCKET
  823. int num_args = lua_gettop(L);
  824. struct lua_websock_data *ws;
  825. const char *str;
  826. size_t size;
  827. int opcode = -1;
  828. unsigned i;
  829. struct mg_connection *client = NULL;
  830. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  831. lua_gettable(L, LUA_REGISTRYINDEX);
  832. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  833. (void)pthread_mutex_lock(&(ws->ws_mutex));
  834. if (num_args == 1) {
  835. /* just one text: send it to all client */
  836. if (lua_isstring(L, 1)) {
  837. opcode = WEBSOCKET_OPCODE_TEXT;
  838. }
  839. } else if (num_args == 2) {
  840. if (lua_isnumber(L, 1)) {
  841. /* opcode number and message text */
  842. opcode = (int)lua_tointeger(L, 1);
  843. } else if (lua_isstring(L, 1)) {
  844. /* opcode string and message text */
  845. str = lua_tostring(L, 1);
  846. if (!mg_strncasecmp(str, "text", 4))
  847. opcode = WEBSOCKET_OPCODE_TEXT;
  848. else if (!mg_strncasecmp(str, "bin", 3))
  849. opcode = WEBSOCKET_OPCODE_BINARY;
  850. else if (!mg_strncasecmp(str, "close", 5))
  851. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  852. else if (!mg_strncasecmp(str, "ping", 4))
  853. opcode = WEBSOCKET_OPCODE_PING;
  854. else if (!mg_strncasecmp(str, "pong", 4))
  855. opcode = WEBSOCKET_OPCODE_PONG;
  856. else if (!mg_strncasecmp(str, "cont", 4))
  857. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  858. } else if (lua_isuserdata(L, 1)) {
  859. /* client id and message text */
  860. client = (struct mg_connection *)lua_touserdata(L, 1);
  861. opcode = WEBSOCKET_OPCODE_TEXT;
  862. }
  863. } else if (num_args == 3) {
  864. if (lua_isuserdata(L, 1)) {
  865. client = (struct mg_connection *)lua_touserdata(L, 1);
  866. if (lua_isnumber(L, 2)) {
  867. /* client id, opcode number and message text */
  868. opcode = (int)lua_tointeger(L, 2);
  869. } else if (lua_isstring(L, 2)) {
  870. /* client id, opcode string and message text */
  871. str = lua_tostring(L, 2);
  872. if (!mg_strncasecmp(str, "text", 4))
  873. opcode = WEBSOCKET_OPCODE_TEXT;
  874. else if (!mg_strncasecmp(str, "bin", 3))
  875. opcode = WEBSOCKET_OPCODE_BINARY;
  876. else if (!mg_strncasecmp(str, "close", 5))
  877. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  878. else if (!mg_strncasecmp(str, "ping", 4))
  879. opcode = WEBSOCKET_OPCODE_PING;
  880. else if (!mg_strncasecmp(str, "pong", 4))
  881. opcode = WEBSOCKET_OPCODE_PONG;
  882. else if (!mg_strncasecmp(str, "cont", 4))
  883. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  884. }
  885. }
  886. }
  887. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  888. str = lua_tolstring(L, num_args, &size);
  889. if (client) {
  890. for (i = 0; i < ws->references; i++) {
  891. if (client == ws->conn[i]) {
  892. mg_websocket_write(ws->conn[i], opcode, str, size);
  893. }
  894. }
  895. } else {
  896. for (i = 0; i < ws->references; i++) {
  897. mg_websocket_write(ws->conn[i], opcode, str, size);
  898. }
  899. }
  900. } else {
  901. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  902. return luaL_error(L, "invalid websocket write() call");
  903. }
  904. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  905. #else
  906. (void)(L); /* unused */
  907. #endif
  908. return 0;
  909. }
  910. struct laction_arg {
  911. lua_State *state;
  912. const char *script;
  913. pthread_mutex_t *pmutex;
  914. char txt[1];
  915. };
  916. static int
  917. lua_action(struct laction_arg *arg)
  918. {
  919. int err, ok;
  920. struct mg_context *ctx;
  921. (void)pthread_mutex_lock(arg->pmutex);
  922. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  923. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  924. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  925. err = luaL_loadstring(arg->state, arg->txt);
  926. if (err != 0) {
  927. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  928. (void)pthread_mutex_unlock(arg->pmutex);
  929. mg_free(arg);
  930. return 0;
  931. }
  932. err = lua_pcall(arg->state, 0, 1, 0);
  933. if (err != 0) {
  934. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  935. (void)pthread_mutex_unlock(arg->pmutex);
  936. mg_free(arg);
  937. return 0;
  938. }
  939. ok = lua_type(arg->state, -1);
  940. if (lua_isboolean(arg->state, -1)) {
  941. ok = lua_toboolean(arg->state, -1);
  942. } else {
  943. ok = 0;
  944. }
  945. lua_pop(arg->state, 1);
  946. (void)pthread_mutex_unlock(arg->pmutex);
  947. if (!ok) {
  948. mg_free(arg);
  949. }
  950. return ok;
  951. }
  952. static int
  953. lua_action_free(struct laction_arg *arg)
  954. {
  955. if (lua_action(arg)) {
  956. mg_free(arg);
  957. }
  958. return 0;
  959. }
  960. static int
  961. lwebsocket_set_timer(lua_State *L, int is_periodic)
  962. {
  963. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  964. int num_args = lua_gettop(L);
  965. struct lua_websock_data *ws;
  966. int type1, type2, ok = 0;
  967. double timediff;
  968. struct mg_context *ctx;
  969. struct laction_arg *arg;
  970. const char *txt;
  971. size_t txt_len;
  972. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  973. lua_gettable(L, LUA_REGISTRYINDEX);
  974. ctx = (struct mg_context *)lua_touserdata(L, -1);
  975. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  976. lua_gettable(L, LUA_REGISTRYINDEX);
  977. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  978. if (num_args < 2) {
  979. return luaL_error(L,
  980. "not enough arguments for set_timer/interval() call");
  981. }
  982. type1 = lua_type(L, 1);
  983. type2 = lua_type(L, 2);
  984. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  985. timediff = (double)lua_tonumber(L, 2);
  986. txt = lua_tostring(L, 1);
  987. txt_len = strlen(txt);
  988. arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg)
  989. + txt_len + 10);
  990. arg->state = L;
  991. arg->script = ws->script;
  992. arg->pmutex = &(ws->ws_mutex);
  993. memcpy(arg->txt, "return(", 7);
  994. memcpy(arg->txt + 7, txt, txt_len);
  995. arg->txt[txt_len + 7] = ')';
  996. arg->txt[txt_len + 8] = 0;
  997. ok =
  998. (0
  999. == timer_add(ctx,
  1000. timediff,
  1001. is_periodic,
  1002. 1,
  1003. (taction)(is_periodic ? lua_action : lua_action_free),
  1004. (void *)arg));
  1005. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1006. /* TODO (mid): not implemented yet */
  1007. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1008. } else {
  1009. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1010. }
  1011. lua_pushboolean(L, ok);
  1012. return 1;
  1013. #else
  1014. (void)(L); /* unused */
  1015. (void)(is_periodic); /* unused */
  1016. return 0;
  1017. #endif
  1018. }
  1019. /* mg.set_timeout for websockets */
  1020. static int
  1021. lwebsocket_set_timeout(lua_State *L)
  1022. {
  1023. return lwebsocket_set_timer(L, 0);
  1024. }
  1025. /* mg.set_interval for websockets */
  1026. static int
  1027. lwebsocket_set_interval(lua_State *L)
  1028. {
  1029. return lwebsocket_set_timer(L, 1);
  1030. }
  1031. enum {
  1032. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1033. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1034. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1035. };
  1036. static void
  1037. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1038. {
  1039. const char *s;
  1040. int i;
  1041. /* Export mg.request_info */
  1042. lua_pushstring(L, "request_info");
  1043. lua_newtable(L);
  1044. reg_string(L, "request_method", conn->request_info.request_method);
  1045. reg_string(L, "request_uri", conn->request_info.request_uri);
  1046. reg_string(L, "uri", conn->request_info.local_uri);
  1047. reg_string(L, "http_version", conn->request_info.http_version);
  1048. reg_string(L, "query_string", conn->request_info.query_string);
  1049. #if defined(MG_LEGACY_INTERFACE)
  1050. reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is
  1051. deprecated, use
  1052. remote_addr
  1053. instead */
  1054. #endif
  1055. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1056. /* TODO (high): ip version */
  1057. reg_int(L, "remote_port", conn->request_info.remote_port);
  1058. reg_int(L, "num_headers", conn->request_info.num_headers);
  1059. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1060. if (conn->request_info.content_length >= 0) {
  1061. /* reg_int64: content_length */
  1062. lua_pushstring(L, "content_length");
  1063. lua_pushnumber(
  1064. L,
  1065. (lua_Number)conn->request_info
  1066. .content_length); /* lua_Number may be used as 52 bit integer */
  1067. lua_rawset(L, -3);
  1068. }
  1069. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1070. reg_string(L, "content_type", s);
  1071. }
  1072. if (conn->request_info.remote_user != NULL) {
  1073. reg_string(L, "remote_user", conn->request_info.remote_user);
  1074. reg_string(L, "auth_type", "Digest");
  1075. }
  1076. reg_boolean(L, "https", conn->ssl != NULL);
  1077. if (conn->status_code > 0) {
  1078. /* Lua error handler should show the status code */
  1079. reg_int(L, "status", conn->status_code);
  1080. }
  1081. lua_pushstring(L, "http_headers");
  1082. lua_newtable(L);
  1083. for (i = 0; i < conn->request_info.num_headers; i++) {
  1084. reg_string(L,
  1085. conn->request_info.http_headers[i].name,
  1086. conn->request_info.http_headers[i].value);
  1087. }
  1088. lua_rawset(L, -3);
  1089. lua_rawset(L, -3);
  1090. }
  1091. void
  1092. civetweb_open_lua_libs(lua_State *L)
  1093. {
  1094. {
  1095. extern void luaL_openlibs(lua_State *);
  1096. luaL_openlibs(L);
  1097. }
  1098. #ifdef USE_LUA_SQLITE3
  1099. {
  1100. extern int luaopen_lsqlite3(lua_State *);
  1101. luaopen_lsqlite3(L);
  1102. }
  1103. #endif
  1104. #ifdef USE_LUA_LUAXML
  1105. {
  1106. extern int luaopen_LuaXML_lib(lua_State *);
  1107. luaopen_LuaXML_lib(L);
  1108. }
  1109. #endif
  1110. #ifdef USE_LUA_FILE_SYSTEM
  1111. {
  1112. extern int luaopen_lfs(lua_State *);
  1113. luaopen_lfs(L);
  1114. }
  1115. #endif
  1116. #ifdef USE_LUA_BINARY
  1117. {
  1118. /* TODO (low): Test if this could be used as a replacement for bit32.
  1119. * Check again with Lua 5.3 later. */
  1120. extern int luaopen_binary(lua_State *);
  1121. luaL_requiref(L, "binary", luaopen_binary, 1);
  1122. lua_pop(L, 1);
  1123. }
  1124. #endif
  1125. }
  1126. static void
  1127. prepare_lua_environment(struct mg_context *ctx,
  1128. struct mg_connection *conn,
  1129. struct lua_websock_data *ws_conn_list,
  1130. lua_State *L,
  1131. const char *script_name,
  1132. int lua_env_type)
  1133. {
  1134. civetweb_open_lua_libs(L);
  1135. #if LUA_VERSION_NUM == 502
  1136. /* Keep the "connect" method for compatibility,
  1137. * but do not backport it to Lua 5.1.
  1138. * TODO: Redesign the interface.
  1139. */
  1140. luaL_newmetatable(L, LUASOCKET);
  1141. lua_pushliteral(L, "__index");
  1142. luaL_newlib(L, luasocket_methods);
  1143. lua_rawset(L, -3);
  1144. lua_pop(L, 1);
  1145. lua_register(L, "connect", lsp_connect);
  1146. #endif
  1147. /* Store context in the registry */
  1148. if (ctx != NULL) {
  1149. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1150. lua_pushlightuserdata(L, (void *)ctx);
  1151. lua_settable(L, LUA_REGISTRYINDEX);
  1152. }
  1153. if (ws_conn_list != NULL) {
  1154. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1155. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1156. lua_settable(L, LUA_REGISTRYINDEX);
  1157. }
  1158. /* Register mg module */
  1159. lua_newtable(L);
  1160. switch (lua_env_type) {
  1161. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1162. reg_string(L, "lua_type", "page");
  1163. break;
  1164. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1165. reg_string(L, "lua_type", "script");
  1166. break;
  1167. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1168. reg_string(L, "lua_type", "websocket");
  1169. break;
  1170. }
  1171. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1172. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1173. reg_conn_function(L, "cry", lsp_cry, conn);
  1174. reg_conn_function(L, "read", lsp_read, conn);
  1175. reg_conn_function(L, "write", lsp_write, conn);
  1176. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1177. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1178. }
  1179. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1180. reg_conn_function(L, "include", lsp_include, conn);
  1181. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1182. }
  1183. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1184. reg_function(L, "write", lwebsock_write);
  1185. #ifdef USE_TIMERS
  1186. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1187. reg_function(L, "set_interval", lwebsocket_set_interval);
  1188. #endif
  1189. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1190. }
  1191. reg_function(L, "time", lsp_get_time);
  1192. reg_function(L, "get_var", lsp_get_var);
  1193. reg_function(L, "get_mime_type", lsp_get_mime_type);
  1194. reg_function(L, "get_cookie", lsp_get_cookie);
  1195. reg_function(L, "md5", lsp_md5);
  1196. reg_function(L, "url_encode", lsp_url_encode);
  1197. reg_function(L, "url_decode", lsp_url_decode);
  1198. reg_function(L, "base64_encode", lsp_base64_encode);
  1199. reg_function(L, "base64_decode", lsp_base64_decode);
  1200. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1201. reg_function(L, "random", lsp_random);
  1202. if (pf_uuid_generate.f) {
  1203. reg_function(L, "uuid", lsp_uuid);
  1204. }
  1205. reg_string(L, "version", CIVETWEB_VERSION);
  1206. reg_string(L, "script_name", script_name);
  1207. if (ctx != NULL) {
  1208. reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
  1209. reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
  1210. #if defined(USE_WEBSOCKET)
  1211. reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
  1212. #endif
  1213. if (ctx->systemName != NULL) {
  1214. reg_string(L, "system", ctx->systemName);
  1215. }
  1216. }
  1217. /* Export connection specific info */
  1218. if (conn != NULL) {
  1219. prepare_lua_request_info(conn, L);
  1220. }
  1221. lua_setglobal(L, "mg");
  1222. /* Register default mg.onerror function */
  1223. IGNORE_UNUSED_RESULT(
  1224. luaL_dostring(L,
  1225. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1226. "debug.traceback(e, 1)) end"));
  1227. if (ctx != NULL) {
  1228. /* Preload */
  1229. if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
  1230. IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
  1231. }
  1232. if (ctx->callbacks.init_lua != NULL) {
  1233. ctx->callbacks.init_lua(conn, L);
  1234. }
  1235. }
  1236. }
  1237. static int
  1238. lua_error_handler(lua_State *L)
  1239. {
  1240. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1241. lua_getglobal(L, "mg");
  1242. if (!lua_isnil(L, -1)) {
  1243. lua_getfield(L, -1, "write"); /* call mg.write() */
  1244. lua_pushstring(L, error_msg);
  1245. lua_pushliteral(L, "\n");
  1246. lua_call(L, 2, 0);
  1247. IGNORE_UNUSED_RESULT(
  1248. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1249. } else {
  1250. printf("Lua error: [%s]\n", error_msg);
  1251. IGNORE_UNUSED_RESULT(
  1252. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1253. }
  1254. /* TODO(lsm, low): leave the stack balanced */
  1255. return 0;
  1256. }
  1257. static void *
  1258. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1259. {
  1260. (void)ud;
  1261. (void)osize; /* not used */
  1262. if (nsize == 0) {
  1263. mg_free(ptr);
  1264. return NULL;
  1265. }
  1266. return mg_realloc(ptr, nsize);
  1267. }
  1268. static void
  1269. mg_exec_lua_script(struct mg_connection *conn,
  1270. const char *path,
  1271. const void **exports)
  1272. {
  1273. int i;
  1274. lua_State *L;
  1275. /* Assume the script does not support keep_alive. The script may change this
  1276. * by calling mg.keep_alive(true). */
  1277. conn->must_close = 1;
  1278. /* Execute a plain Lua script. */
  1279. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  1280. prepare_lua_environment(
  1281. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1282. lua_pushcclosure(L, &lua_error_handler, 0);
  1283. if (exports != NULL) {
  1284. #if LUA_VERSION_NUM > 501
  1285. lua_pushglobaltable(L);
  1286. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1287. lua_CFunction func;
  1288. lua_pushstring(L, (const char *)(exports[i]));
  1289. *(const void **)(&func) = exports[i + 1];
  1290. lua_pushcclosure(L, func, 0);
  1291. lua_rawset(L, -3);
  1292. }
  1293. #else
  1294. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1295. lua_CFunction func;
  1296. const char *name = (const char *)(exports[i]);
  1297. *(const void **)(&func) = exports[i + 1];
  1298. lua_register(L, name, func);
  1299. }
  1300. #endif
  1301. }
  1302. if (luaL_loadfile(L, path) != 0) {
  1303. lua_error_handler(L);
  1304. }
  1305. lua_pcall(L, 0, 0, -2);
  1306. lua_close(L);
  1307. }
  1308. }
  1309. static int
  1310. handle_lsp_request(struct mg_connection *conn,
  1311. const char *path,
  1312. struct file *filep,
  1313. struct lua_State *ls)
  1314. {
  1315. void *p = NULL;
  1316. lua_State *L = NULL;
  1317. int error = 1;
  1318. struct file filesize = STRUCT_FILE_INITIALIZER;
  1319. /* Assume the script does not support keep_alive. The script may change this
  1320. * by calling mg.keep_alive(true). */
  1321. conn->must_close = 1;
  1322. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  1323. if (!mg_stat(conn, path, &filesize)) {
  1324. /* File not found */
  1325. if (ls == NULL) {
  1326. send_http_error(conn, 500, "Error: File %s not found", path);
  1327. } else {
  1328. luaL_error(ls, "File [%s] not found", path);
  1329. }
  1330. goto cleanup_handle_lsp_request;
  1331. }
  1332. if (!mg_fopen(conn, path, "r", filep)) {
  1333. /* File not found or not accessible */
  1334. if (ls == NULL) {
  1335. send_http_error(conn,
  1336. 500,
  1337. "Error: Cannot open script file %s",
  1338. path);
  1339. } else {
  1340. luaL_error(ls, "Cannot [%s] not found", path);
  1341. }
  1342. goto cleanup_handle_lsp_request;
  1343. }
  1344. /* TODO: Operations mg_fopen and mg_stat should do what their names
  1345. * indicate. They should not fill in different members of the same
  1346. * struct file.
  1347. * See Github issue #225 */
  1348. filep->size = filesize.size;
  1349. if (filep->membuf == NULL
  1350. && (p = mmap(NULL,
  1351. (size_t)filep->size,
  1352. PROT_READ,
  1353. MAP_PRIVATE,
  1354. fileno(filep->fp),
  1355. 0)) == MAP_FAILED) {
  1356. /* mmap failed */
  1357. if (ls == NULL) {
  1358. send_http_error(
  1359. conn,
  1360. 500,
  1361. "Error: Cannot open script\nFile %s can not be mapped",
  1362. path);
  1363. } else {
  1364. luaL_error(ls,
  1365. "mmap(%s, %zu, %d): %s",
  1366. path,
  1367. (size_t)filep->size,
  1368. fileno(filep->fp),
  1369. strerror(errno));
  1370. }
  1371. goto cleanup_handle_lsp_request;
  1372. }
  1373. if (ls != NULL) {
  1374. L = ls;
  1375. } else {
  1376. L = lua_newstate(lua_allocator, NULL);
  1377. if (L == NULL) {
  1378. send_http_error(
  1379. conn,
  1380. 500,
  1381. "%s",
  1382. "Error: Cannot execute script\nlua_newstate failed");
  1383. goto cleanup_handle_lsp_request;
  1384. }
  1385. prepare_lua_environment(
  1386. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1387. }
  1388. /* Lua state is ready to use */
  1389. /* We're not sending HTTP headers here, Lua page must do it. */
  1390. error = lsp(conn,
  1391. path,
  1392. (filep->membuf == NULL) ? (const char *)p
  1393. : (const char *)filep->membuf,
  1394. filep->size,
  1395. L);
  1396. cleanup_handle_lsp_request:
  1397. if (L != NULL && ls == NULL)
  1398. lua_close(L);
  1399. if (p != NULL)
  1400. munmap(p, filep->size);
  1401. mg_fclose(filep);
  1402. return error;
  1403. }
  1404. #ifdef USE_WEBSOCKET
  1405. struct mg_shared_lua_websocket_list {
  1406. struct lua_websock_data ws;
  1407. struct mg_shared_lua_websocket_list *next;
  1408. };
  1409. static void *
  1410. lua_websocket_new(const char *script, struct mg_connection *conn)
  1411. {
  1412. struct mg_shared_lua_websocket_list **shared_websock_list =
  1413. &(conn->ctx->shared_lua_websockets);
  1414. struct lua_websock_data *ws;
  1415. int err, ok = 0;
  1416. assert(conn->lua_websocket_state == NULL);
  1417. /* lock list (mg_context global) */
  1418. mg_lock_context(conn->ctx);
  1419. while (*shared_websock_list) {
  1420. /* check if ws already in list */
  1421. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1422. break;
  1423. }
  1424. shared_websock_list = &((*shared_websock_list)->next);
  1425. }
  1426. if (*shared_websock_list == NULL) {
  1427. /* add ws to list */
  1428. *shared_websock_list = (struct mg_shared_lua_websocket_list *)
  1429. mg_calloc(sizeof(struct mg_shared_lua_websocket_list), 1);
  1430. if (*shared_websock_list == NULL) {
  1431. mg_unlock_context(conn->ctx);
  1432. mg_cry(conn, "Cannot create shared websocket struct, OOM");
  1433. return NULL;
  1434. }
  1435. /* init ws list element */
  1436. ws = &(*shared_websock_list)->ws;
  1437. ws->script = mg_strdup(script); /* TODO (low): handle OOM */
  1438. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1439. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1440. ws->state = lua_newstate(lua_allocator, NULL);
  1441. ws->conn[0] = conn;
  1442. ws->references = 1;
  1443. prepare_lua_environment(
  1444. conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  1445. err = luaL_loadfile(ws->state, script);
  1446. if (err != 0) {
  1447. lua_cry(conn, err, ws->state, script, "load");
  1448. }
  1449. err = lua_pcall(ws->state, 0, 0, 0);
  1450. if (err != 0) {
  1451. lua_cry(conn, err, ws->state, script, "init");
  1452. }
  1453. } else {
  1454. /* inc ref count */
  1455. ws = &(*shared_websock_list)->ws;
  1456. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1457. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1458. }
  1459. mg_unlock_context(conn->ctx);
  1460. /* call add */
  1461. lua_getglobal(ws->state, "open");
  1462. lua_newtable(ws->state);
  1463. prepare_lua_request_info(conn, ws->state);
  1464. lua_pushstring(ws->state, "client");
  1465. lua_pushlightuserdata(ws->state, (void *)conn);
  1466. lua_rawset(ws->state, -3);
  1467. err = lua_pcall(ws->state, 1, 1, 0);
  1468. if (err != 0) {
  1469. lua_cry(conn, err, ws->state, script, "open handler");
  1470. } else {
  1471. if (lua_isboolean(ws->state, -1)) {
  1472. ok = lua_toboolean(ws->state, -1);
  1473. }
  1474. lua_pop(ws->state, 1);
  1475. }
  1476. if (!ok) {
  1477. /* Remove from ws connection list. */
  1478. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1479. * (see websocket_close). */
  1480. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1481. }
  1482. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1483. return ok ? (void *)ws : NULL;
  1484. }
  1485. static int
  1486. lua_websocket_data(struct mg_connection *conn,
  1487. int bits,
  1488. char *data,
  1489. size_t data_len,
  1490. void *ws_arg)
  1491. {
  1492. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1493. int err, ok = 0;
  1494. assert(ws != NULL);
  1495. assert(ws->state != NULL);
  1496. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1497. lua_getglobal(ws->state, "data");
  1498. lua_newtable(ws->state);
  1499. lua_pushstring(ws->state, "client");
  1500. lua_pushlightuserdata(ws->state, (void *)conn);
  1501. lua_rawset(ws->state, -3);
  1502. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1503. a meaning according to
  1504. http://tools.ietf.org/html/rfc6455,
  1505. section 5.2 */
  1506. lua_pushnumber(ws->state, bits);
  1507. lua_rawset(ws->state, -3);
  1508. lua_pushstring(ws->state, "data");
  1509. lua_pushlstring(ws->state, data, data_len);
  1510. lua_rawset(ws->state, -3);
  1511. err = lua_pcall(ws->state, 1, 1, 0);
  1512. if (err != 0) {
  1513. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1514. } else {
  1515. if (lua_isboolean(ws->state, -1)) {
  1516. ok = lua_toboolean(ws->state, -1);
  1517. }
  1518. lua_pop(ws->state, 1);
  1519. }
  1520. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1521. return ok;
  1522. }
  1523. static int
  1524. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1525. {
  1526. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1527. int err, ok = 0;
  1528. assert(ws != NULL);
  1529. assert(ws->state != NULL);
  1530. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1531. lua_getglobal(ws->state, "ready");
  1532. lua_newtable(ws->state);
  1533. lua_pushstring(ws->state, "client");
  1534. lua_pushlightuserdata(ws->state, (void *)conn);
  1535. lua_rawset(ws->state, -3);
  1536. err = lua_pcall(ws->state, 1, 1, 0);
  1537. if (err != 0) {
  1538. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1539. } else {
  1540. if (lua_isboolean(ws->state, -1)) {
  1541. ok = lua_toboolean(ws->state, -1);
  1542. }
  1543. lua_pop(ws->state, 1);
  1544. }
  1545. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1546. return ok;
  1547. }
  1548. static void
  1549. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1550. {
  1551. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1552. struct mg_shared_lua_websocket_list **shared_websock_list =
  1553. &(conn->ctx->shared_lua_websockets);
  1554. int err = 0;
  1555. unsigned i;
  1556. assert(ws != NULL);
  1557. assert(ws->state != NULL);
  1558. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1559. lua_getglobal(ws->state, "close");
  1560. lua_newtable(ws->state);
  1561. lua_pushstring(ws->state, "client");
  1562. lua_pushlightuserdata(ws->state, (void *)conn);
  1563. lua_rawset(ws->state, -3);
  1564. err = lua_pcall(ws->state, 1, 0, 0);
  1565. if (err != 0) {
  1566. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1567. }
  1568. for (i = 0; i < ws->references; i++) {
  1569. if (ws->conn[i] == conn) {
  1570. ws->references--;
  1571. ws->conn[i] = ws->conn[ws->references];
  1572. }
  1573. }
  1574. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1575. This must only be done, when all connections are closed, and all
  1576. asynchronous operations and timers are completed/expired. */
  1577. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1578. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1579. }
  1580. #endif
  1581. static void
  1582. lua_init_optional_libraries(void)
  1583. {
  1584. #if !defined(_WIN32)
  1585. void *dll_handle = dlopen("libuuid.so", RTLD_LAZY);
  1586. pf_uuid_generate.p = dlsym(dll_handle, "uuid_generate");
  1587. #else
  1588. pf_uuid_generate.p = 0;
  1589. #endif
  1590. }