mod_lua.inl 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557
  1. /* This file is part of the CivetWeb web server.
  2. * See https://github.com/civetweb/civetweb/
  3. */
  4. #include "civetweb_lua.h"
  5. #include "civetweb_private_lua.h"
  6. #if defined(_WIN32)
  7. static void *
  8. mmap(void *addr, int64_t len, int prot, int flags, int fd, int offset)
  9. {
  10. /* TODO (low): This is an incomplete implementation of mmap for windows.
  11. * Currently it is sufficient, but there are a lot of unused parameters.
  12. * Better use a function "mg_map" which only has the required parameters,
  13. * and implement it using mmap in Linux and CreateFileMapping in Windows.
  14. * No one should expect a full mmap for Windows here.
  15. */
  16. HANDLE fh = (HANDLE)_get_osfhandle(fd);
  17. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  18. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
  19. CloseHandle(mh);
  20. /* unused parameters */
  21. (void)addr;
  22. (void)prot;
  23. (void)flags;
  24. (void)offset;
  25. return p;
  26. }
  27. static void
  28. munmap(void *addr, int64_t length)
  29. {
  30. /* unused parameters */
  31. (void)length;
  32. UnmapViewOfFile(addr);
  33. }
  34. #define MAP_FAILED (NULL)
  35. #define MAP_PRIVATE (0)
  36. #define PROT_READ (0)
  37. #else
  38. #include <sys/mman.h>
  39. #endif
  40. static const char *LUASOCKET = "luasocket";
  41. static const char lua_regkey_ctx = 1;
  42. static const char lua_regkey_connlist = 2;
  43. static const char lua_regkey_lsp_include_history = 3;
  44. static const char *LUABACKGROUNDPARAMS = "mg";
  45. #if !defined(LSP_INCLUDE_MAX_DEPTH)
  46. #define LSP_INCLUDE_MAX_DEPTH (32)
  47. #endif
  48. /* Forward declarations */
  49. static void handle_request(struct mg_connection *);
  50. static int handle_lsp_request(struct mg_connection *,
  51. const char *,
  52. struct mg_file *,
  53. struct lua_State *);
  54. static void
  55. reg_lstring(struct lua_State *L,
  56. const char *name,
  57. const void *buffer,
  58. size_t buflen)
  59. {
  60. if (name != NULL && buffer != NULL) {
  61. lua_pushstring(L, name);
  62. lua_pushlstring(L, (const char *)buffer, buflen);
  63. lua_rawset(L, -3);
  64. }
  65. }
  66. static void
  67. reg_llstring(struct lua_State *L,
  68. const void *buffer1,
  69. size_t buflen1,
  70. const void *buffer2,
  71. size_t buflen2)
  72. {
  73. if (buffer1 != NULL && buffer2 != NULL) {
  74. lua_pushlstring(L, (const char *)buffer1, buflen1);
  75. lua_pushlstring(L, (const char *)buffer2, buflen2);
  76. lua_rawset(L, -3);
  77. }
  78. }
  79. #define reg_string(L, name, val) \
  80. reg_lstring(L, name, val, val ? strlen(val) : 0)
  81. static void
  82. reg_int(struct lua_State *L, const char *name, int val)
  83. {
  84. if (name != NULL) {
  85. lua_pushstring(L, name);
  86. lua_pushinteger(L, val);
  87. lua_rawset(L, -3);
  88. }
  89. }
  90. static void
  91. reg_boolean(struct lua_State *L, const char *name, int val)
  92. {
  93. if (name != NULL) {
  94. lua_pushstring(L, name);
  95. lua_pushboolean(L, val != 0);
  96. lua_rawset(L, -3);
  97. }
  98. }
  99. static void
  100. reg_conn_function(struct lua_State *L,
  101. const char *name,
  102. lua_CFunction func,
  103. struct mg_connection *conn)
  104. {
  105. if (name != NULL && func != NULL && conn != NULL) {
  106. lua_pushstring(L, name);
  107. lua_pushlightuserdata(L, conn);
  108. lua_pushcclosure(L, func, 1);
  109. lua_rawset(L, -3);
  110. }
  111. }
  112. static void
  113. reg_function(struct lua_State *L, const char *name, lua_CFunction func)
  114. {
  115. if (name != NULL && func != NULL) {
  116. lua_pushstring(L, name);
  117. lua_pushcclosure(L, func, 0);
  118. lua_rawset(L, -3);
  119. }
  120. }
  121. static void
  122. lua_cry(struct mg_connection *conn,
  123. int err,
  124. lua_State *L,
  125. const char *lua_title,
  126. const char *lua_operation)
  127. {
  128. switch (err) {
  129. case LUA_OK:
  130. case LUA_YIELD:
  131. break;
  132. case LUA_ERRRUN:
  133. mg_cry_internal(conn,
  134. "%s: %s failed: runtime error: %s",
  135. lua_title,
  136. lua_operation,
  137. lua_tostring(L, -1));
  138. break;
  139. case LUA_ERRSYNTAX:
  140. mg_cry_internal(conn,
  141. "%s: %s failed: syntax error: %s",
  142. lua_title,
  143. lua_operation,
  144. lua_tostring(L, -1));
  145. break;
  146. case LUA_ERRMEM:
  147. mg_cry_internal(conn,
  148. "%s: %s failed: out of memory",
  149. lua_title,
  150. lua_operation);
  151. break;
  152. case LUA_ERRGCMM:
  153. mg_cry_internal(conn,
  154. "%s: %s failed: error during garbage collection",
  155. lua_title,
  156. lua_operation);
  157. break;
  158. case LUA_ERRERR:
  159. mg_cry_internal(conn,
  160. "%s: %s failed: error in error handling: %s",
  161. lua_title,
  162. lua_operation,
  163. lua_tostring(L, -1));
  164. break;
  165. default:
  166. mg_cry_internal(
  167. conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
  168. break;
  169. }
  170. }
  171. static int
  172. lsp_sock_close(lua_State *L)
  173. {
  174. int num_args = lua_gettop(L);
  175. size_t s;
  176. SOCKET *psock;
  177. if ((num_args == 1) && lua_istable(L, -1)) {
  178. lua_getfield(L, -1, "sock");
  179. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  180. if (s != sizeof(SOCKET)) {
  181. return luaL_error(L, "invalid internal state in :close() call");
  182. }
  183. /* Do not closesocket(*psock); here, close it in __gc */
  184. (void)psock;
  185. } else {
  186. return luaL_error(L, "invalid :close() call");
  187. }
  188. return 0;
  189. }
  190. static int
  191. lsp_sock_recv(lua_State *L)
  192. {
  193. int num_args = lua_gettop(L);
  194. char buf[2000];
  195. int n;
  196. size_t s;
  197. SOCKET *psock;
  198. if ((num_args == 1) && lua_istable(L, -1)) {
  199. lua_getfield(L, -1, "sock");
  200. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  201. if (s != sizeof(SOCKET)) {
  202. return luaL_error(L, "invalid internal state in :recv() call");
  203. }
  204. n = recv(*psock, buf, sizeof(buf), 0);
  205. if (n <= 0) {
  206. lua_pushnil(L);
  207. } else {
  208. lua_pushlstring(L, buf, n);
  209. }
  210. } else {
  211. return luaL_error(L, "invalid :recv() call");
  212. }
  213. return 1;
  214. }
  215. static int
  216. lsp_sock_send(lua_State *L)
  217. {
  218. int num_args = lua_gettop(L);
  219. const char *buf;
  220. size_t len, sent = 0;
  221. int n = 0;
  222. size_t s;
  223. SOCKET *psock;
  224. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  225. buf = lua_tolstring(L, -1, &len);
  226. lua_getfield(L, -2, "sock");
  227. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  228. if (s != sizeof(SOCKET)) {
  229. return luaL_error(L, "invalid internal state in :close() call");
  230. }
  231. while (sent < len) {
  232. if ((n = send(*psock, buf + sent, (int)(len - sent), 0)) <= 0) {
  233. break;
  234. }
  235. sent += n;
  236. }
  237. lua_pushnumber(L, n);
  238. } else {
  239. return luaL_error(L, "invalid :close() call");
  240. }
  241. return 1;
  242. }
  243. static int
  244. lsp_sock_gc(lua_State *L)
  245. {
  246. int num_args = lua_gettop(L);
  247. size_t s;
  248. SOCKET *psock;
  249. if ((num_args == 1) && lua_istable(L, -1)) {
  250. lua_getfield(L, -1, "sock");
  251. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  252. if (s != sizeof(SOCKET)) {
  253. return luaL_error(
  254. L,
  255. "invalid internal state in __gc for object created by connect");
  256. }
  257. closesocket(*psock);
  258. } else {
  259. return luaL_error(L, "__gc for object created by connect failed");
  260. }
  261. return 0;
  262. }
  263. /* Methods and meta-methods supported by the object returned by connect.
  264. * For meta-methods, see http://lua-users.org/wiki/MetatableEvents */
  265. static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
  266. {"send", lsp_sock_send},
  267. {"recv", lsp_sock_recv},
  268. {"__gc", lsp_sock_gc},
  269. {NULL, NULL}};
  270. static int
  271. lsp_connect(lua_State *L)
  272. {
  273. int num_args = lua_gettop(L);
  274. char ebuf[100];
  275. SOCKET sock;
  276. union usa sa;
  277. int ok;
  278. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2)
  279. && lua_isnumber(L, -1)) {
  280. ok = connect_socket(NULL,
  281. lua_tostring(L, -3),
  282. (int)lua_tonumber(L, -2),
  283. (int)lua_tonumber(L, -1),
  284. ebuf,
  285. sizeof(ebuf),
  286. &sock,
  287. &sa);
  288. if (!ok) {
  289. return luaL_error(L, ebuf);
  290. } else {
  291. lua_newtable(L);
  292. reg_lstring(L, "sock", (const char *)&sock, sizeof(SOCKET));
  293. reg_string(L, "host", lua_tostring(L, -4));
  294. luaL_getmetatable(L, LUASOCKET);
  295. lua_setmetatable(L, -2);
  296. }
  297. } else {
  298. return luaL_error(
  299. L, "connect(host,port,is_ssl): invalid parameter given.");
  300. }
  301. return 1;
  302. }
  303. static int
  304. lsp_error(lua_State *L)
  305. {
  306. lua_getglobal(L, "mg");
  307. lua_getfield(L, -1, "onerror");
  308. lua_pushvalue(L, -3);
  309. lua_pcall(L, 1, 0, 0);
  310. return 0;
  311. }
  312. /* Silently stop processing chunks. */
  313. static void
  314. lsp_abort(lua_State *L)
  315. {
  316. int top = lua_gettop(L);
  317. lua_getglobal(L, "mg");
  318. lua_pushnil(L);
  319. lua_setfield(L, -2, "onerror");
  320. lua_settop(L, top);
  321. lua_pushstring(L, "aborting");
  322. lua_error(L);
  323. }
  324. struct lsp_var_reader_data {
  325. const char *begin;
  326. unsigned len;
  327. unsigned state;
  328. };
  329. /* Helper function to read the content of variable values */
  330. static const char *
  331. lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  332. {
  333. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  334. const char *ret;
  335. (void)(L); /* unused */
  336. /* This reader is called multiple times, to fetch the full Lua script */
  337. switch (reader->state) {
  338. case 0:
  339. /* First call: what function to call */
  340. ret = "mg.write(";
  341. *sz = strlen(ret);
  342. break;
  343. case 1:
  344. /* Second call: forward variable name */
  345. ret = reader->begin;
  346. *sz = reader->len;
  347. break;
  348. case 2:
  349. /* Third call: close function call */
  350. ret = ")";
  351. *sz = strlen(ret);
  352. break;
  353. default:
  354. /* Forth/Final call: tell Lua we got the entire script */
  355. ret = 0;
  356. *sz = 0;
  357. }
  358. /* Step to the next state for the next call */
  359. reader->state++;
  360. return ret;
  361. }
  362. static int
  363. run_lsp(struct mg_connection *conn,
  364. const char *path,
  365. const char *p,
  366. int64_t len,
  367. lua_State *L)
  368. {
  369. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  370. char chunkname[MG_BUF_LEN];
  371. struct lsp_var_reader_data data;
  372. const char lsp_mark1 = '?'; /* Use <? code ?> */
  373. const char lsp_mark2 = '%'; /* Use <% code %> */
  374. for (i = 0; i < len; i++) {
  375. if (p[i] == '\n') {
  376. lines++;
  377. }
  378. /* Lua pages are normal text, unless there is a "<?" or "<%" tag. */
  379. if (((i + 1) < len) && (p[i] == '<')
  380. && ((p[i + 1] == lsp_mark1) || (p[i + 1] == lsp_mark2))) {
  381. /* Opening tag way "<?" or "<%", closing tag must be the same. */
  382. char lsp_mark_used = p[i + 1];
  383. /* <?= var ?> or <%= var %> means a variable is enclosed and its
  384. * value should be printed */
  385. if (0 == memcmp("lua", p + i + 1, 3)) {
  386. /* Syntax: <?lua code ?> or <?lua= var ?> */
  387. /* This is added for compatibility to other LSP syntax
  388. * definitions. */
  389. /* Skip 3 letters ("lua"). */
  390. i += 3;
  391. }
  392. /* Check for '=' in "<?= ..." or "<%= ..." or "<?lua= ..." */
  393. is_var = (((i + 2) < len) && (p[i + 2] == '='));
  394. if (is_var) {
  395. /* use variable value (print it later) */
  396. j = i + 2;
  397. } else {
  398. /* execute script code */
  399. j = i + 1;
  400. }
  401. while (j < len) {
  402. if (p[j] == '\n') {
  403. /* Add line (for line number offset) */
  404. lualines++;
  405. }
  406. /* Check for closing tag. */
  407. if (((j + 1) < len) && (p[j] == lsp_mark_used)
  408. && (p[j + 1] == '>')) {
  409. /* There was a closing tag. Print everything before
  410. * the opening tag. */
  411. mg_write(conn, p + pos, i - pos);
  412. /* Set a name for debugging purposes */
  413. mg_snprintf(conn,
  414. NULL, /* ignore truncation for debugging */
  415. chunkname,
  416. sizeof(chunkname),
  417. "@%s+%i",
  418. path,
  419. lines);
  420. /* Prepare data for Lua C functions */
  421. lua_pushlightuserdata(L, conn);
  422. lua_pushcclosure(L, lsp_error, 1);
  423. if (is_var) {
  424. /* For variables: Print the value */
  425. data.begin = p + (i + 3);
  426. data.len = j - (i + 3);
  427. data.state = 0;
  428. lua_ok = mg_lua_load(
  429. L, lsp_var_reader, &data, chunkname, NULL);
  430. } else {
  431. /* For scripts: Execute them */
  432. lua_ok = luaL_loadbuffer(L,
  433. p + (i + 2),
  434. j - (i + 2),
  435. chunkname);
  436. }
  437. if (lua_ok) {
  438. /* Syntax error or OOM. Error message is pushed on
  439. * stack. */
  440. lua_pcall(L, 1, 0, 0);
  441. } else {
  442. /* Success loading chunk. Call it. */
  443. lua_pcall(L, 0, 0, 1);
  444. }
  445. pos = j + 2;
  446. i = pos - 1;
  447. break;
  448. }
  449. j++;
  450. }
  451. if (lualines > 0) {
  452. lines += lualines;
  453. lualines = 0;
  454. }
  455. }
  456. }
  457. if (i > pos) {
  458. mg_write(conn, p + pos, i - pos);
  459. }
  460. return 0;
  461. }
  462. /* mg.write: Send data to the client */
  463. static int
  464. lsp_write(lua_State *L)
  465. {
  466. struct mg_connection *conn =
  467. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  468. int num_args = lua_gettop(L);
  469. const char *str;
  470. size_t size;
  471. int i;
  472. int rv = 1;
  473. for (i = 1; i <= num_args; i++) {
  474. if (lua_isstring(L, i)) {
  475. str = lua_tolstring(L, i, &size);
  476. if (mg_write(conn, str, size) != (int)size) {
  477. rv = 0;
  478. }
  479. }
  480. }
  481. lua_pushboolean(L, rv);
  482. return 1;
  483. }
  484. /* mg.read: Read data from the client (e.g., from a POST request) */
  485. static int
  486. lsp_read(lua_State *L)
  487. {
  488. struct mg_connection *conn =
  489. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  490. char buf[1024];
  491. int len = mg_read(conn, buf, sizeof(buf));
  492. if (len <= 0)
  493. return 0;
  494. lua_pushlstring(L, buf, len);
  495. return 1;
  496. }
  497. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  498. static int
  499. lsp_keep_alive(lua_State *L)
  500. {
  501. struct mg_connection *conn =
  502. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  503. int num_args = lua_gettop(L);
  504. /* This function may be called with one parameter (boolean) to set the
  505. keep_alive state.
  506. Or without a parameter to just query the current keep_alive state. */
  507. if ((num_args == 1) && lua_isboolean(L, 1)) {
  508. conn->must_close = !lua_toboolean(L, 1);
  509. } else if (num_args != 0) {
  510. /* Syntax error */
  511. return luaL_error(L, "invalid keep_alive() call");
  512. }
  513. /* Return the current "keep_alive" state. This may be false, even it
  514. * keep_alive(true) has been called. */
  515. lua_pushboolean(L, should_keep_alive(conn));
  516. return 1;
  517. }
  518. /* Stack of includes */
  519. struct lsp_include_history {
  520. int depth;
  521. const char *script[LSP_INCLUDE_MAX_DEPTH + 1];
  522. };
  523. /* mg.include: Include another .lp file */
  524. static int
  525. lsp_include(lua_State *L)
  526. {
  527. struct mg_connection *conn =
  528. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  529. int num_args = lua_gettop(L);
  530. struct mg_file file = STRUCT_FILE_INITIALIZER;
  531. const char *file_name = (num_args >= 1) ? lua_tostring(L, 1) : NULL;
  532. const char *path_type = (num_args >= 2) ? lua_tostring(L, 2) : NULL;
  533. struct lsp_include_history *include_history;
  534. if (path_type == NULL) {
  535. /* default to "absolute" */
  536. path_type = "a";
  537. }
  538. if ((file_name != NULL) && (num_args <= 2)) {
  539. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  540. lua_gettable(L, LUA_REGISTRYINDEX);
  541. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  542. if (include_history->depth >= ((int)(LSP_INCLUDE_MAX_DEPTH))) {
  543. mg_cry_internal(
  544. conn,
  545. "lsp max include depth of %i reached while including %s",
  546. (int)(LSP_INCLUDE_MAX_DEPTH),
  547. file_name);
  548. } else {
  549. char file_name_path[512];
  550. char *p;
  551. size_t len;
  552. int truncated = 0;
  553. file_name_path[511] = 0;
  554. if (*path_type == 'v') {
  555. /* "virtual" = relative to document root. */
  556. (void)mg_snprintf(conn,
  557. &truncated,
  558. file_name_path,
  559. sizeof(file_name_path),
  560. "%s/%s",
  561. conn->dom_ctx->config[DOCUMENT_ROOT],
  562. file_name);
  563. } else if (*path_type == 'a') {
  564. /* "absolute" = file name is relative to the
  565. * webserver working directory
  566. * or it is absolute system path. */
  567. /* path_type==NULL is the legacy use case with 1 argument */
  568. (void)mg_snprintf(conn,
  569. &truncated,
  570. file_name_path,
  571. sizeof(file_name_path),
  572. "%s",
  573. file_name);
  574. } else if ((*path_type == 'r') || (*path_type == 'f')) {
  575. /* "relative" = file name is relative to the
  576. * currect document */
  577. (void)mg_snprintf(
  578. conn,
  579. &truncated,
  580. file_name_path,
  581. sizeof(file_name_path),
  582. "%s",
  583. include_history->script[include_history->depth]);
  584. if (!truncated) {
  585. if ((p = strrchr(file_name_path, '/')) != NULL) {
  586. p[1] = '\0';
  587. }
  588. len = strlen(file_name_path);
  589. (void)mg_snprintf(conn,
  590. &truncated,
  591. file_name_path + len,
  592. sizeof(file_name_path) - len,
  593. "%s",
  594. file_name);
  595. }
  596. } else {
  597. return luaL_error(
  598. L,
  599. "invalid path_type in include(file_name, path_type) call");
  600. }
  601. if (handle_lsp_request(conn, file_name_path, &file, L)) {
  602. /* handle_lsp_request returned an error code, meaning an error
  603. * occurred in the included page and mg.onerror returned
  604. * non-zero.
  605. * Stop processing.
  606. */
  607. lsp_abort(L);
  608. }
  609. }
  610. } else {
  611. /* Syntax error */
  612. return luaL_error(L, "invalid include() call");
  613. }
  614. return 0;
  615. }
  616. /* mg.cry: Log an error. Default value for mg.onerror. */
  617. static int
  618. lsp_cry(lua_State *L)
  619. {
  620. struct mg_connection *conn =
  621. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  622. int num_args = lua_gettop(L);
  623. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  624. if (text) {
  625. mg_cry_internal(conn, "%s", lua_tostring(L, -1));
  626. } else {
  627. /* Syntax error */
  628. return luaL_error(L, "invalid cry() call");
  629. }
  630. return 0;
  631. }
  632. /* mg.redirect: Redirect the request (internally). */
  633. static int
  634. lsp_redirect(lua_State *L)
  635. {
  636. struct mg_connection *conn =
  637. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  638. int num_args = lua_gettop(L);
  639. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  640. if (target) {
  641. conn->request_info.local_uri = target;
  642. handle_request(conn);
  643. lsp_abort(L);
  644. } else {
  645. /* Syntax error */
  646. return luaL_error(L, "invalid redirect() call");
  647. }
  648. return 0;
  649. }
  650. /* mg.send_file */
  651. static int
  652. lsp_send_file(lua_State *L)
  653. {
  654. struct mg_connection *conn =
  655. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  656. int num_args = lua_gettop(L);
  657. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  658. if (filename) {
  659. mg_send_file(conn, filename);
  660. } else {
  661. /* Syntax error */
  662. return luaL_error(L, "invalid send_file() call");
  663. }
  664. return 0;
  665. }
  666. /* mg.get_time */
  667. static int
  668. lsp_get_time(lua_State *L)
  669. {
  670. int num_args = lua_gettop(L);
  671. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  672. struct timespec ts;
  673. double d;
  674. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  675. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  676. lua_pushnumber(L, d);
  677. return 1;
  678. }
  679. /* mg.get_var */
  680. static int
  681. lsp_get_var(lua_State *L)
  682. {
  683. int num_args = lua_gettop(L);
  684. const char *data, *var_name;
  685. size_t data_len, occurrence;
  686. int ret;
  687. struct mg_context *ctx;
  688. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  689. lua_gettable(L, LUA_REGISTRYINDEX);
  690. ctx = (struct mg_context *)lua_touserdata(L, -1);
  691. if (num_args >= 2 && num_args <= 3) {
  692. char *dst;
  693. data = lua_tolstring(L, 1, &data_len);
  694. var_name = lua_tostring(L, 2);
  695. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  696. /* Allocate dynamically, so there is no internal limit for get_var */
  697. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  698. if (!dst) {
  699. return luaL_error(L, "out of memory in get_var() call");
  700. }
  701. ret = mg_get_var2(data, data_len, var_name, dst, data_len, occurrence);
  702. if (ret >= 0) {
  703. /* Variable found: return value to Lua */
  704. lua_pushstring(L, dst);
  705. } else {
  706. /* Variable not found */
  707. lua_pushnil(L);
  708. }
  709. mg_free(dst);
  710. } else {
  711. /* Syntax error */
  712. return luaL_error(L, "invalid get_var() call");
  713. }
  714. return 1;
  715. }
  716. /* mg.get_mime_type */
  717. static int
  718. lsp_get_mime_type(lua_State *L)
  719. {
  720. int num_args = lua_gettop(L);
  721. struct vec mime_type = {0, 0};
  722. const char *text;
  723. struct mg_connection *conn =
  724. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  725. if (num_args == 1) {
  726. text = lua_tostring(L, 1);
  727. if (text) {
  728. if (conn) {
  729. get_mime_type(conn, text, &mime_type);
  730. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  731. } else {
  732. text = mg_get_builtin_mime_type(text);
  733. lua_pushstring(L, text);
  734. }
  735. } else {
  736. /* Syntax error */
  737. return luaL_error(L, "invalid argument for get_mime_type() call");
  738. }
  739. } else {
  740. /* Syntax error */
  741. return luaL_error(L, "invalid get_mime_type() call");
  742. }
  743. return 1;
  744. }
  745. /* mg.get_cookie */
  746. static int
  747. lsp_get_cookie(lua_State *L)
  748. {
  749. int num_args = lua_gettop(L);
  750. const char *cookie;
  751. const char *var_name;
  752. int ret;
  753. struct mg_context *ctx;
  754. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  755. lua_gettable(L, LUA_REGISTRYINDEX);
  756. ctx = (struct mg_context *)lua_touserdata(L, -1);
  757. if (num_args == 2) {
  758. /* Correct number of arguments */
  759. size_t data_len;
  760. char *dst;
  761. cookie = lua_tolstring(L, 1, &data_len);
  762. var_name = lua_tostring(L, 2);
  763. if (cookie == NULL || var_name == NULL) {
  764. /* Syntax error */
  765. return luaL_error(L, "invalid get_cookie() call");
  766. }
  767. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  768. if (!dst) {
  769. return luaL_error(L, "out of memory in get_cookie() call");
  770. }
  771. ret = mg_get_cookie(cookie, var_name, dst, data_len);
  772. if (ret >= 0) {
  773. lua_pushlstring(L, dst, ret);
  774. } else {
  775. lua_pushnil(L);
  776. }
  777. mg_free(dst);
  778. } else {
  779. /* Syntax error */
  780. return luaL_error(L, "invalid get_cookie() call");
  781. }
  782. return 1;
  783. }
  784. /* mg.md5 */
  785. static int
  786. lsp_md5(lua_State *L)
  787. {
  788. int num_args = lua_gettop(L);
  789. const char *text;
  790. md5_byte_t hash[16];
  791. md5_state_t ctx;
  792. size_t text_len;
  793. char buf[40];
  794. if (num_args == 1) {
  795. text = lua_tolstring(L, 1, &text_len);
  796. if (text) {
  797. md5_init(&ctx);
  798. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  799. md5_finish(&ctx, hash);
  800. bin2str(buf, hash, sizeof(hash));
  801. lua_pushstring(L, buf);
  802. } else {
  803. lua_pushnil(L);
  804. }
  805. } else {
  806. /* Syntax error */
  807. return luaL_error(L, "invalid md5() call");
  808. }
  809. return 1;
  810. }
  811. /* mg.url_encode */
  812. static int
  813. lsp_url_encode(lua_State *L)
  814. {
  815. int num_args = lua_gettop(L);
  816. const char *text;
  817. size_t text_len;
  818. char *dst;
  819. int dst_len;
  820. struct mg_context *ctx;
  821. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  822. lua_gettable(L, LUA_REGISTRYINDEX);
  823. ctx = (struct mg_context *)lua_touserdata(L, -1);
  824. if (num_args == 1) {
  825. text = lua_tolstring(L, 1, &text_len);
  826. if (text) {
  827. dst_len = 3 * (int)text_len + 1;
  828. dst = ((text_len < 0x2AAAAAAA) ? (char *)mg_malloc_ctx(dst_len, ctx)
  829. : (char *)NULL);
  830. if (dst) {
  831. mg_url_encode(text, dst, dst_len);
  832. lua_pushstring(L, dst);
  833. mg_free(dst);
  834. } else {
  835. return luaL_error(L, "out of memory in url_decode() call");
  836. }
  837. } else {
  838. lua_pushnil(L);
  839. }
  840. } else {
  841. /* Syntax error */
  842. return luaL_error(L, "invalid url_encode() call");
  843. }
  844. return 1;
  845. }
  846. /* mg.url_decode */
  847. static int
  848. lsp_url_decode(lua_State *L)
  849. {
  850. int num_args = lua_gettop(L);
  851. const char *text;
  852. size_t text_len;
  853. int is_form;
  854. char *dst;
  855. int dst_len;
  856. struct mg_context *ctx;
  857. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  858. lua_gettable(L, LUA_REGISTRYINDEX);
  859. ctx = (struct mg_context *)lua_touserdata(L, -1);
  860. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  861. text = lua_tolstring(L, 1, &text_len);
  862. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  863. if (text) {
  864. dst_len = (int)text_len + 1;
  865. dst = ((text_len < 0x7FFFFFFF) ? (char *)mg_malloc_ctx(dst_len, ctx)
  866. : (char *)NULL);
  867. if (dst) {
  868. mg_url_decode(text, (int)text_len, dst, dst_len, is_form);
  869. lua_pushstring(L, dst);
  870. mg_free(dst);
  871. } else {
  872. return luaL_error(L, "out of memory in url_decode() call");
  873. }
  874. } else {
  875. lua_pushnil(L);
  876. }
  877. } else {
  878. /* Syntax error */
  879. return luaL_error(L, "invalid url_decode() call");
  880. }
  881. return 1;
  882. }
  883. /* mg.base64_encode */
  884. static int
  885. lsp_base64_encode(lua_State *L)
  886. {
  887. int num_args = lua_gettop(L);
  888. const char *text;
  889. size_t text_len;
  890. char *dst;
  891. struct mg_context *ctx;
  892. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  893. lua_gettable(L, LUA_REGISTRYINDEX);
  894. ctx = (struct mg_context *)lua_touserdata(L, -1);
  895. if (num_args == 1) {
  896. text = lua_tolstring(L, 1, &text_len);
  897. if (text) {
  898. dst = (char *)mg_malloc_ctx(text_len * 8 / 6 + 4, ctx);
  899. if (dst) {
  900. base64_encode((const unsigned char *)text, (int)text_len, dst);
  901. lua_pushstring(L, dst);
  902. mg_free(dst);
  903. } else {
  904. return luaL_error(L, "out of memory in base64_encode() call");
  905. }
  906. } else {
  907. lua_pushnil(L);
  908. }
  909. } else {
  910. /* Syntax error */
  911. return luaL_error(L, "invalid base64_encode() call");
  912. }
  913. return 1;
  914. }
  915. /* mg.base64_encode */
  916. static int
  917. lsp_base64_decode(lua_State *L)
  918. {
  919. int num_args = lua_gettop(L);
  920. const char *text;
  921. size_t text_len, dst_len;
  922. int ret;
  923. char *dst;
  924. struct mg_context *ctx;
  925. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  926. lua_gettable(L, LUA_REGISTRYINDEX);
  927. ctx = (struct mg_context *)lua_touserdata(L, -1);
  928. if (num_args == 1) {
  929. text = lua_tolstring(L, 1, &text_len);
  930. if (text) {
  931. dst = (char *)mg_malloc_ctx(text_len, ctx);
  932. if (dst) {
  933. ret = base64_decode((const unsigned char *)text,
  934. (int)text_len,
  935. dst,
  936. &dst_len);
  937. if (ret != -1) {
  938. mg_free(dst);
  939. return luaL_error(
  940. L, "illegal character in lsp_base64_decode() call");
  941. } else {
  942. lua_pushlstring(L, dst, dst_len);
  943. mg_free(dst);
  944. }
  945. } else {
  946. return luaL_error(L,
  947. "out of memory in lsp_base64_decode() call");
  948. }
  949. } else {
  950. lua_pushnil(L);
  951. }
  952. } else {
  953. /* Syntax error */
  954. return luaL_error(L, "invalid lsp_base64_decode() call");
  955. }
  956. return 1;
  957. }
  958. /* mg.get_response_code_text */
  959. static int
  960. lsp_get_response_code_text(lua_State *L)
  961. {
  962. int num_args = lua_gettop(L);
  963. int type1;
  964. double code;
  965. const char *text;
  966. if (num_args == 1) {
  967. type1 = lua_type(L, 1);
  968. if (type1 == LUA_TNUMBER) {
  969. /* If the first argument is a number,
  970. convert it to the corresponding text. */
  971. code = lua_tonumber(L, 1);
  972. text = mg_get_response_code_text(NULL, (int)code);
  973. if (text) { /* <-- should be always true */
  974. lua_pushstring(L, text);
  975. }
  976. return text ? 1 : 0;
  977. }
  978. }
  979. /* Syntax error */
  980. return luaL_error(L, "invalid get_response_code_text() call");
  981. }
  982. /* mg.random - might be better than math.random on some systems */
  983. static int
  984. lsp_random(lua_State *L)
  985. {
  986. int num_args = lua_gettop(L);
  987. if (num_args == 0) {
  988. /* The civetweb internal random number generator will generate
  989. * a 64 bit random number. */
  990. uint64_t r = get_random();
  991. /* Lua "number" is a IEEE 754 double precission float:
  992. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  993. * Thus, mask with 2^53-1 to get an integer with the maximum
  994. * precission available. */
  995. r &= ((((uint64_t)1) << 53) - 1);
  996. lua_pushnumber(L, (double)r);
  997. return 1;
  998. }
  999. /* Syntax error */
  1000. return luaL_error(L, "invalid random() call");
  1001. }
  1002. /* mg.get_info */
  1003. static int
  1004. lsp_get_info(lua_State *L)
  1005. {
  1006. int num_args = lua_gettop(L);
  1007. int type1, type2;
  1008. const char *arg1;
  1009. double arg2;
  1010. int len;
  1011. char *buf;
  1012. if (num_args == 1) {
  1013. type1 = lua_type(L, 1);
  1014. if (type1 == LUA_TSTRING) {
  1015. arg1 = lua_tostring(L, 1);
  1016. /* Get info according to argument */
  1017. if (!mg_strcasecmp(arg1, "system")) {
  1018. /* Get system info */
  1019. len = mg_get_system_info(NULL, 0);
  1020. if (len > 0) {
  1021. buf = (char *)mg_malloc(len + 64);
  1022. if (!buf) {
  1023. return luaL_error(L, "OOM in get_info() call");
  1024. }
  1025. len = mg_get_system_info(buf, len + 63);
  1026. lua_pushlstring(L, buf, len);
  1027. mg_free(buf);
  1028. } else {
  1029. lua_pushstring(L, "");
  1030. }
  1031. return 1;
  1032. }
  1033. if (!mg_strcasecmp(arg1, "context")) {
  1034. /* Get context */
  1035. struct mg_context *ctx;
  1036. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1037. lua_gettable(L, LUA_REGISTRYINDEX);
  1038. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1039. /* Get context info for server context */
  1040. len = mg_get_context_info(ctx, NULL, 0);
  1041. if (len > 0) {
  1042. buf = (char *)mg_malloc(len + 64);
  1043. if (!buf) {
  1044. return luaL_error(L, "OOM in get_info() call");
  1045. }
  1046. len = mg_get_context_info(ctx, buf, len + 63);
  1047. lua_pushlstring(L, buf, len);
  1048. mg_free(buf);
  1049. } else {
  1050. lua_pushstring(L, "");
  1051. }
  1052. return 1;
  1053. }
  1054. if (!mg_strcasecmp(arg1, "common")) {
  1055. /* Get context info for NULL context */
  1056. len = mg_get_context_info(NULL, NULL, 0);
  1057. if (len > 0) {
  1058. buf = (char *)mg_malloc(len + 64);
  1059. if (!buf) {
  1060. return luaL_error(L, "OOM in get_info() call");
  1061. }
  1062. len = mg_get_context_info(NULL, buf, len + 63);
  1063. lua_pushlstring(L, buf, len);
  1064. mg_free(buf);
  1065. } else {
  1066. lua_pushstring(L, "");
  1067. }
  1068. return 1;
  1069. }
  1070. return 0;
  1071. }
  1072. }
  1073. if (num_args == 2) {
  1074. type1 = lua_type(L, 1);
  1075. type2 = lua_type(L, 2);
  1076. if ((type1 == LUA_TSTRING) && (type2 == LUA_TNUMBER)) {
  1077. arg1 = lua_tostring(L, 1);
  1078. arg2 = lua_tonumber(L, 2);
  1079. /* Get info according to argument */
  1080. if (!mg_strcasecmp(arg1, "connection")) {
  1081. int idx;
  1082. /* Get context */
  1083. struct mg_context *ctx;
  1084. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1085. lua_gettable(L, LUA_REGISTRYINDEX);
  1086. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1087. /* Get connection info for connection idx */
  1088. idx = (int)(arg2 + 0.5);
  1089. /* Lua uses 1 based index, C uses 0 based index */
  1090. idx--;
  1091. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1092. len = mg_get_connection_info(ctx, idx, NULL, 0);
  1093. if (len > 0) {
  1094. buf = (char *)mg_malloc(len + 64);
  1095. if (!buf) {
  1096. return luaL_error(L, "OOM in get_info() call");
  1097. }
  1098. len = mg_get_connection_info(ctx, idx, buf, len + 63);
  1099. lua_pushlstring(L, buf, len);
  1100. mg_free(buf);
  1101. } else {
  1102. lua_pushstring(L, "");
  1103. }
  1104. #else
  1105. (void)ctx;
  1106. (void)idx;
  1107. lua_pushstring(L, "");
  1108. #endif
  1109. return 1;
  1110. }
  1111. return 0;
  1112. }
  1113. }
  1114. /* Syntax error */
  1115. return luaL_error(L, "invalid get_info() call");
  1116. }
  1117. /* mg.get_option */
  1118. static int
  1119. lsp_get_option(lua_State *L)
  1120. {
  1121. int num_args = lua_gettop(L);
  1122. int type1;
  1123. const char *arg1;
  1124. const char *data;
  1125. int optidx;
  1126. /* Get connection */
  1127. struct mg_connection *conn =
  1128. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1129. if (num_args == 0) {
  1130. const struct mg_option *opts = mg_get_valid_options();
  1131. if (!opts) { /* <-- should be always false */
  1132. return 0;
  1133. }
  1134. lua_newtable(L);
  1135. while (opts->name) {
  1136. optidx = get_option_index(opts->name);
  1137. if (optidx >= 0) {
  1138. data = conn->dom_ctx->config[optidx];
  1139. if (data) {
  1140. reg_string(L, opts->name, data);
  1141. }
  1142. }
  1143. opts++;
  1144. }
  1145. return 1;
  1146. }
  1147. if (num_args == 1) {
  1148. type1 = lua_type(L, 1);
  1149. if (type1 == LUA_TSTRING) {
  1150. arg1 = lua_tostring(L, 1);
  1151. /* Get option according to argument */
  1152. optidx = get_option_index(arg1);
  1153. if (optidx >= 0) {
  1154. data = conn->dom_ctx->config[optidx];
  1155. if (data) {
  1156. lua_pushstring(L, data);
  1157. return 1;
  1158. }
  1159. }
  1160. return 0;
  1161. }
  1162. }
  1163. /* Syntax error */
  1164. return luaL_error(L, "invalid get_option() call");
  1165. }
  1166. /* UUID library and function pointer */
  1167. union {
  1168. void *p;
  1169. void (*f)(unsigned char uuid[16]);
  1170. } pf_uuid_generate;
  1171. /* mg.uuid */
  1172. static int
  1173. lsp_uuid(lua_State *L)
  1174. {
  1175. union {
  1176. unsigned char uuid_array[16];
  1177. struct uuid_struct_type {
  1178. uint32_t data1;
  1179. uint16_t data2;
  1180. uint16_t data3;
  1181. uint8_t data4[8];
  1182. } uuid_struct;
  1183. } uuid;
  1184. char uuid_str[40];
  1185. int num_args = lua_gettop(L);
  1186. memset(&uuid, 0, sizeof(uuid));
  1187. memset(uuid_str, 0, sizeof(uuid_str));
  1188. if (num_args == 0) {
  1189. pf_uuid_generate.f(uuid.uuid_array);
  1190. sprintf(uuid_str,
  1191. "{%08lX-%04X-%04X-%02X%02X-"
  1192. "%02X%02X%02X%02X%02X%02X}",
  1193. (unsigned long)uuid.uuid_struct.data1,
  1194. (unsigned)uuid.uuid_struct.data2,
  1195. (unsigned)uuid.uuid_struct.data3,
  1196. (unsigned)uuid.uuid_struct.data4[0],
  1197. (unsigned)uuid.uuid_struct.data4[1],
  1198. (unsigned)uuid.uuid_struct.data4[2],
  1199. (unsigned)uuid.uuid_struct.data4[3],
  1200. (unsigned)uuid.uuid_struct.data4[4],
  1201. (unsigned)uuid.uuid_struct.data4[5],
  1202. (unsigned)uuid.uuid_struct.data4[6],
  1203. (unsigned)uuid.uuid_struct.data4[7]);
  1204. lua_pushstring(L, uuid_str);
  1205. return 1;
  1206. }
  1207. /* Syntax error */
  1208. return luaL_error(L, "invalid random() call");
  1209. }
  1210. #if defined(USE_WEBSOCKET)
  1211. struct lua_websock_data {
  1212. lua_State *state;
  1213. char *script;
  1214. unsigned references;
  1215. struct mg_connection *conn[MAX_WORKER_THREADS];
  1216. pthread_mutex_t ws_mutex;
  1217. };
  1218. #endif
  1219. /* mg.write for websockets */
  1220. static int
  1221. lwebsock_write(lua_State *L)
  1222. {
  1223. #if defined(USE_WEBSOCKET)
  1224. int num_args = lua_gettop(L);
  1225. struct lua_websock_data *ws;
  1226. const char *str;
  1227. size_t size;
  1228. int opcode = -1;
  1229. unsigned i;
  1230. struct mg_connection *client = NULL;
  1231. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1232. lua_gettable(L, LUA_REGISTRYINDEX);
  1233. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1234. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1235. if (num_args == 1) {
  1236. /* just one text: send it to all client */
  1237. if (lua_isstring(L, 1)) {
  1238. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1239. }
  1240. } else if (num_args == 2) {
  1241. if (lua_isnumber(L, 1)) {
  1242. /* opcode number and message text */
  1243. opcode = (int)lua_tointeger(L, 1);
  1244. } else if (lua_isstring(L, 1)) {
  1245. /* opcode string and message text */
  1246. str = lua_tostring(L, 1);
  1247. if (!mg_strncasecmp(str, "text", 4))
  1248. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1249. else if (!mg_strncasecmp(str, "bin", 3))
  1250. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1251. else if (!mg_strncasecmp(str, "close", 5))
  1252. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1253. else if (!mg_strncasecmp(str, "ping", 4))
  1254. opcode = MG_WEBSOCKET_OPCODE_PING;
  1255. else if (!mg_strncasecmp(str, "pong", 4))
  1256. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1257. else if (!mg_strncasecmp(str, "cont", 4))
  1258. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1259. } else if (lua_isuserdata(L, 1)) {
  1260. /* client id and message text */
  1261. client = (struct mg_connection *)lua_touserdata(L, 1);
  1262. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1263. }
  1264. } else if (num_args == 3) {
  1265. if (lua_isuserdata(L, 1)) {
  1266. client = (struct mg_connection *)lua_touserdata(L, 1);
  1267. if (lua_isnumber(L, 2)) {
  1268. /* client id, opcode number and message text */
  1269. opcode = (int)lua_tointeger(L, 2);
  1270. } else if (lua_isstring(L, 2)) {
  1271. /* client id, opcode string and message text */
  1272. str = lua_tostring(L, 2);
  1273. if (!mg_strncasecmp(str, "text", 4))
  1274. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1275. else if (!mg_strncasecmp(str, "bin", 3))
  1276. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1277. else if (!mg_strncasecmp(str, "close", 5))
  1278. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1279. else if (!mg_strncasecmp(str, "ping", 4))
  1280. opcode = MG_WEBSOCKET_OPCODE_PING;
  1281. else if (!mg_strncasecmp(str, "pong", 4))
  1282. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1283. else if (!mg_strncasecmp(str, "cont", 4))
  1284. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1285. }
  1286. }
  1287. }
  1288. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  1289. str = lua_tolstring(L, num_args, &size);
  1290. if (client) {
  1291. for (i = 0; i < ws->references; i++) {
  1292. if (client == ws->conn[i]) {
  1293. mg_lock_connection(ws->conn[i]);
  1294. mg_websocket_write(ws->conn[i], opcode, str, size);
  1295. mg_unlock_connection(ws->conn[i]);
  1296. }
  1297. }
  1298. } else {
  1299. for (i = 0; i < ws->references; i++) {
  1300. mg_lock_connection(ws->conn[i]);
  1301. mg_websocket_write(ws->conn[i], opcode, str, size);
  1302. mg_unlock_connection(ws->conn[i]);
  1303. }
  1304. }
  1305. } else {
  1306. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1307. return luaL_error(L, "invalid websocket write() call");
  1308. }
  1309. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1310. #else
  1311. (void)(L); /* unused */
  1312. #endif
  1313. return 0;
  1314. }
  1315. struct laction_arg {
  1316. lua_State *state;
  1317. const char *script;
  1318. pthread_mutex_t *pmutex;
  1319. char txt[1];
  1320. };
  1321. static int
  1322. lua_action(struct laction_arg *arg)
  1323. {
  1324. int err, ok;
  1325. struct mg_context *ctx;
  1326. (void)pthread_mutex_lock(arg->pmutex);
  1327. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  1328. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  1329. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  1330. err = luaL_loadstring(arg->state, arg->txt);
  1331. if (err != 0) {
  1332. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1333. (void)pthread_mutex_unlock(arg->pmutex);
  1334. mg_free(arg);
  1335. return 0;
  1336. }
  1337. err = lua_pcall(arg->state, 0, 1, 0);
  1338. if (err != 0) {
  1339. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1340. (void)pthread_mutex_unlock(arg->pmutex);
  1341. mg_free(arg);
  1342. return 0;
  1343. }
  1344. ok = lua_type(arg->state, -1);
  1345. if (lua_isboolean(arg->state, -1)) {
  1346. ok = lua_toboolean(arg->state, -1);
  1347. } else {
  1348. ok = 0;
  1349. }
  1350. lua_pop(arg->state, 1);
  1351. (void)pthread_mutex_unlock(arg->pmutex);
  1352. if (!ok) {
  1353. mg_free(arg);
  1354. }
  1355. return ok;
  1356. }
  1357. static int
  1358. lua_action_free(struct laction_arg *arg)
  1359. {
  1360. if (lua_action(arg)) {
  1361. mg_free(arg);
  1362. }
  1363. return 0;
  1364. }
  1365. static int
  1366. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1367. {
  1368. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1369. int num_args = lua_gettop(L);
  1370. struct lua_websock_data *ws;
  1371. int type1, type2, ok = 0;
  1372. double timediff;
  1373. struct mg_context *ctx;
  1374. struct laction_arg *arg;
  1375. const char *txt;
  1376. size_t txt_len;
  1377. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1378. lua_gettable(L, LUA_REGISTRYINDEX);
  1379. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1380. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1381. lua_gettable(L, LUA_REGISTRYINDEX);
  1382. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1383. if (num_args < 2) {
  1384. return luaL_error(L,
  1385. "not enough arguments for set_timer/interval() call");
  1386. }
  1387. type1 = lua_type(L, 1);
  1388. type2 = lua_type(L, 2);
  1389. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1390. timediff = (double)lua_tonumber(L, 2);
  1391. txt = lua_tostring(L, 1);
  1392. txt_len = strlen(txt);
  1393. arg = (struct laction_arg *)mg_malloc_ctx(sizeof(struct laction_arg)
  1394. + txt_len + 10,
  1395. ctx);
  1396. if (!arg) {
  1397. return luaL_error(L, "out of memory");
  1398. }
  1399. arg->state = L;
  1400. arg->script = ws->script;
  1401. arg->pmutex = &(ws->ws_mutex);
  1402. memcpy(arg->txt, "return(", 7);
  1403. memcpy(arg->txt + 7, txt, txt_len);
  1404. arg->txt[txt_len + 7] = ')';
  1405. arg->txt[txt_len + 8] = 0;
  1406. ok =
  1407. (0
  1408. == timer_add(ctx,
  1409. timediff,
  1410. is_periodic,
  1411. 1,
  1412. (taction)(is_periodic ? lua_action : lua_action_free),
  1413. (void *)arg));
  1414. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1415. /* TODO (mid): not implemented yet */
  1416. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1417. } else {
  1418. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1419. }
  1420. lua_pushboolean(L, ok);
  1421. return 1;
  1422. #else
  1423. (void)(L); /* unused */
  1424. (void)(is_periodic); /* unused */
  1425. return 0;
  1426. #endif
  1427. }
  1428. /* mg.set_timeout for websockets */
  1429. static int
  1430. lwebsocket_set_timeout(lua_State *L)
  1431. {
  1432. return lwebsocket_set_timer(L, 0);
  1433. }
  1434. /* mg.set_interval for websockets */
  1435. static int
  1436. lwebsocket_set_interval(lua_State *L)
  1437. {
  1438. return lwebsocket_set_timer(L, 1);
  1439. }
  1440. /* Debug hook */
  1441. static void
  1442. lua_debug_hook(lua_State *L, lua_Debug *ar)
  1443. {
  1444. int i;
  1445. int stack_len = lua_gettop(L);
  1446. lua_getinfo(L, "nSlu", ar);
  1447. if (ar->event == LUA_HOOKCALL) {
  1448. printf("call\n");
  1449. } else if (ar->event == LUA_HOOKRET) {
  1450. printf("ret\n");
  1451. #if defined(LUA_HOOKTAILRET)
  1452. } else if (ar->event == LUA_HOOKTAILRET) {
  1453. printf("tail ret\n");
  1454. #endif
  1455. #if defined(LUA_HOOKTAILCALL)
  1456. } else if (ar->event == LUA_HOOKTAILCALL) {
  1457. printf("tail call\n");
  1458. #endif
  1459. } else if (ar->event == LUA_HOOKLINE) {
  1460. printf("line\n");
  1461. } else if (ar->event == LUA_HOOKCOUNT) {
  1462. printf("count\n");
  1463. } else {
  1464. printf("unknown (%i)\n", ar->event);
  1465. }
  1466. if (ar->currentline >= 0) {
  1467. printf("%s:%i\n", ar->source, ar->currentline);
  1468. }
  1469. printf("%s (%s)\n", ar->name, ar->namewhat);
  1470. for (i = 1; i <= stack_len; i++) { /* repeat for each level */
  1471. int val_type = lua_type(L, i);
  1472. const char *s;
  1473. size_t n;
  1474. switch (val_type) {
  1475. case LUA_TNIL:
  1476. /* nil value on the stack */
  1477. printf("nil\n");
  1478. break;
  1479. case LUA_TBOOLEAN:
  1480. /* boolean (true / false) */
  1481. printf("boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
  1482. break;
  1483. case LUA_TNUMBER:
  1484. /* number */
  1485. printf("number: %g\n", lua_tonumber(L, i));
  1486. break;
  1487. case LUA_TSTRING:
  1488. /* string with limited length */
  1489. s = lua_tolstring(L, i, &n);
  1490. printf("string: '%.*s%s\n",
  1491. (n > 30) ? 28 : s,
  1492. (n > 30) ? ".." : "'");
  1493. break;
  1494. default:
  1495. /* other values */
  1496. printf("%s\n", lua_typename(L, val_type));
  1497. break;
  1498. }
  1499. }
  1500. printf("\n");
  1501. }
  1502. /* Lua Environment */
  1503. enum {
  1504. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1505. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1506. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1507. };
  1508. static void
  1509. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1510. {
  1511. const char *s;
  1512. int i;
  1513. /* Export mg.request_info */
  1514. lua_pushstring(L, "request_info");
  1515. lua_newtable(L);
  1516. reg_string(L, "request_method", conn->request_info.request_method);
  1517. reg_string(L, "request_uri", conn->request_info.request_uri);
  1518. reg_string(L, "uri", conn->request_info.local_uri);
  1519. reg_string(L, "http_version", conn->request_info.http_version);
  1520. reg_string(L, "query_string", conn->request_info.query_string);
  1521. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1522. /* TODO (high): ip version */
  1523. reg_int(L, "remote_port", conn->request_info.remote_port);
  1524. reg_int(L, "num_headers", conn->request_info.num_headers);
  1525. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1526. if (conn->path_info != NULL) {
  1527. reg_string(L, "path_info", conn->path_info);
  1528. }
  1529. if (conn->request_info.content_length >= 0) {
  1530. /* reg_int64: content_length */
  1531. lua_pushstring(L, "content_length");
  1532. lua_pushnumber(
  1533. L,
  1534. (lua_Number)conn->request_info
  1535. .content_length); /* lua_Number may be used as 52 bit integer */
  1536. lua_rawset(L, -3);
  1537. }
  1538. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1539. reg_string(L, "content_type", s);
  1540. }
  1541. if (conn->request_info.remote_user != NULL) {
  1542. reg_string(L, "remote_user", conn->request_info.remote_user);
  1543. reg_string(L, "auth_type", "Digest");
  1544. }
  1545. reg_boolean(L, "https", conn->ssl != NULL);
  1546. if (conn->status_code > 0) {
  1547. /* Lua error handler should show the status code */
  1548. reg_int(L, "status", conn->status_code);
  1549. }
  1550. lua_pushstring(L, "http_headers");
  1551. lua_newtable(L);
  1552. for (i = 0; i < conn->request_info.num_headers; i++) {
  1553. reg_string(L,
  1554. conn->request_info.http_headers[i].name,
  1555. conn->request_info.http_headers[i].value);
  1556. }
  1557. lua_rawset(L, -3);
  1558. lua_rawset(L, -3);
  1559. }
  1560. static void
  1561. civetweb_open_lua_libs(lua_State *L)
  1562. {
  1563. {
  1564. extern void luaL_openlibs(lua_State *);
  1565. luaL_openlibs(L);
  1566. }
  1567. #if defined(USE_LUA_SQLITE3)
  1568. {
  1569. extern int luaopen_lsqlite3(lua_State *);
  1570. luaopen_lsqlite3(L);
  1571. }
  1572. #endif
  1573. #if defined(USE_LUA_LUAXML)
  1574. {
  1575. extern int luaopen_LuaXML_lib(lua_State *);
  1576. luaopen_LuaXML_lib(L);
  1577. }
  1578. #endif
  1579. #if defined(USE_LUA_FILE_SYSTEM)
  1580. {
  1581. extern int luaopen_lfs(lua_State *);
  1582. luaopen_lfs(L);
  1583. }
  1584. #endif
  1585. }
  1586. static void
  1587. prepare_lua_environment(struct mg_context *ctx,
  1588. struct mg_connection *conn,
  1589. struct lua_websock_data *ws_conn_list,
  1590. lua_State *L,
  1591. const char *script_name,
  1592. int lua_env_type)
  1593. {
  1594. const char *preload_file_name = NULL;
  1595. const char *debug_params = NULL;
  1596. civetweb_open_lua_libs(L);
  1597. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1598. /* Check if debugging should be enabled */
  1599. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1600. debug_params = conn->dom_ctx->config[LUA_DEBUG_PARAMS];
  1601. }
  1602. #endif
  1603. #if LUA_VERSION_NUM == 502
  1604. /* Keep the "connect" method for compatibility,
  1605. * but do not backport it to Lua 5.1.
  1606. * TODO: Redesign the interface.
  1607. */
  1608. luaL_newmetatable(L, LUASOCKET);
  1609. lua_pushliteral(L, "__index");
  1610. luaL_newlib(L, luasocket_methods);
  1611. lua_rawset(L, -3);
  1612. lua_pop(L, 1);
  1613. lua_register(L, "connect", lsp_connect);
  1614. #endif
  1615. /* Store context in the registry */
  1616. if (ctx != NULL) {
  1617. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1618. lua_pushlightuserdata(L, (void *)ctx);
  1619. lua_settable(L, LUA_REGISTRYINDEX);
  1620. }
  1621. if (ws_conn_list != NULL) {
  1622. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1623. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1624. lua_settable(L, LUA_REGISTRYINDEX);
  1625. }
  1626. /* Lua server pages store the depth of mg.include, in order
  1627. * to detect recursions and prevent stack overflows. */
  1628. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1629. struct lsp_include_history *h;
  1630. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  1631. h = (struct lsp_include_history *)
  1632. lua_newuserdata(L, sizeof(struct lsp_include_history));
  1633. lua_settable(L, LUA_REGISTRYINDEX);
  1634. memset(h, 0, sizeof(struct lsp_include_history));
  1635. }
  1636. /* Register mg module */
  1637. lua_newtable(L);
  1638. switch (lua_env_type) {
  1639. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1640. reg_string(L, "lua_type", "page");
  1641. break;
  1642. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1643. reg_string(L, "lua_type", "script");
  1644. break;
  1645. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1646. reg_string(L, "lua_type", "websocket");
  1647. break;
  1648. }
  1649. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1650. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1651. reg_conn_function(L, "cry", lsp_cry, conn);
  1652. reg_conn_function(L, "read", lsp_read, conn);
  1653. reg_conn_function(L, "write", lsp_write, conn);
  1654. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1655. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1656. }
  1657. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1658. reg_conn_function(L, "include", lsp_include, conn);
  1659. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1660. }
  1661. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1662. reg_function(L, "write", lwebsock_write);
  1663. #if defined(USE_TIMERS)
  1664. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1665. reg_function(L, "set_interval", lwebsocket_set_interval);
  1666. #endif
  1667. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1668. }
  1669. reg_conn_function(L, "get_mime_type", lsp_get_mime_type, conn);
  1670. reg_conn_function(L, "get_option", lsp_get_option, conn);
  1671. reg_function(L, "time", lsp_get_time);
  1672. reg_function(L, "get_var", lsp_get_var);
  1673. reg_function(L, "get_cookie", lsp_get_cookie);
  1674. reg_function(L, "md5", lsp_md5);
  1675. reg_function(L, "url_encode", lsp_url_encode);
  1676. reg_function(L, "url_decode", lsp_url_decode);
  1677. reg_function(L, "base64_encode", lsp_base64_encode);
  1678. reg_function(L, "base64_decode", lsp_base64_decode);
  1679. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1680. reg_function(L, "random", lsp_random);
  1681. reg_function(L, "get_info", lsp_get_info);
  1682. if (pf_uuid_generate.f) {
  1683. reg_function(L, "uuid", lsp_uuid);
  1684. }
  1685. reg_string(L, "version", CIVETWEB_VERSION);
  1686. reg_string(L, "script_name", script_name);
  1687. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1688. reg_string(L, "document_root", conn->dom_ctx->config[DOCUMENT_ROOT]);
  1689. reg_string(L,
  1690. "auth_domain",
  1691. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  1692. #if defined(USE_WEBSOCKET)
  1693. if (conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  1694. reg_string(L,
  1695. "websocket_root",
  1696. conn->dom_ctx->config[WEBSOCKET_ROOT]);
  1697. } else {
  1698. reg_string(L,
  1699. "websocket_root",
  1700. conn->dom_ctx->config[DOCUMENT_ROOT]);
  1701. }
  1702. #endif
  1703. if ((ctx != NULL) && (ctx->systemName != NULL)) {
  1704. reg_string(L, "system", ctx->systemName);
  1705. }
  1706. }
  1707. /* Export connection specific info */
  1708. if (conn != NULL) {
  1709. prepare_lua_request_info(conn, L);
  1710. }
  1711. lua_setglobal(L, "mg");
  1712. /* Register default mg.onerror function */
  1713. IGNORE_UNUSED_RESULT(
  1714. luaL_dostring(L,
  1715. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1716. "debug.traceback(e, 1)) end"));
  1717. /* Check if a preload file is available */
  1718. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1719. preload_file_name = conn->dom_ctx->config[LUA_PRELOAD_FILE];
  1720. }
  1721. /* Preload file into new Lua environment */
  1722. if (preload_file_name) {
  1723. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file_name));
  1724. }
  1725. /* Call user init function */
  1726. if (ctx != NULL) {
  1727. if (ctx->callbacks.init_lua != NULL) {
  1728. ctx->callbacks.init_lua(conn, L);
  1729. }
  1730. }
  1731. /* If debugging is enabled, add a hook */
  1732. if (debug_params) {
  1733. int mask = 0;
  1734. if (0 != strchr(debug_params, "c")) {
  1735. mask |= LUA_MASKCALL;
  1736. }
  1737. if (0 != strchr(debug_params, "r")) {
  1738. mask |= LUA_MASKRET;
  1739. }
  1740. if (0 != strchr(debug_params, "l")) {
  1741. mask |= LUA_MASKLINE;
  1742. }
  1743. lua_sethook(L, lua_debug_hook, mask, 0);
  1744. }
  1745. }
  1746. static int
  1747. lua_error_handler(lua_State *L)
  1748. {
  1749. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1750. lua_getglobal(L, "mg");
  1751. if (!lua_isnil(L, -1)) {
  1752. lua_getfield(L, -1, "write"); /* call mg.write() */
  1753. lua_pushstring(L, error_msg);
  1754. lua_pushliteral(L, "\n");
  1755. lua_call(L, 2, 0);
  1756. IGNORE_UNUSED_RESULT(
  1757. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1758. } else {
  1759. printf("Lua error: [%s]\n", error_msg);
  1760. IGNORE_UNUSED_RESULT(
  1761. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1762. }
  1763. /* TODO(lsm, low): leave the stack balanced */
  1764. return 0;
  1765. }
  1766. static void *
  1767. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1768. {
  1769. (void)osize; /* not used */
  1770. if (nsize == 0) {
  1771. mg_free(ptr);
  1772. return NULL;
  1773. }
  1774. return mg_realloc_ctx(ptr, nsize, (struct mg_context *)ud);
  1775. }
  1776. static void
  1777. mg_exec_lua_script(struct mg_connection *conn,
  1778. const char *path,
  1779. const void **exports)
  1780. {
  1781. int i;
  1782. lua_State *L;
  1783. /* Assume the script does not support keep_alive. The script may change this
  1784. * by calling mg.keep_alive(true). */
  1785. conn->must_close = 1;
  1786. /* Execute a plain Lua script. */
  1787. if (path != NULL
  1788. && (L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx)))
  1789. != NULL) {
  1790. prepare_lua_environment(
  1791. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1792. lua_pushcclosure(L, &lua_error_handler, 0);
  1793. if (exports != NULL) {
  1794. #if LUA_VERSION_NUM > 501
  1795. lua_pushglobaltable(L);
  1796. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1797. lua_CFunction func;
  1798. lua_pushstring(L, (const char *)(exports[i]));
  1799. *(const void **)(&func) = exports[i + 1];
  1800. lua_pushcclosure(L, func, 0);
  1801. lua_rawset(L, -3);
  1802. }
  1803. #else
  1804. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1805. lua_CFunction func;
  1806. const char *name = (const char *)(exports[i]);
  1807. *(const void **)(&func) = exports[i + 1];
  1808. lua_register(L, name, func);
  1809. }
  1810. #endif
  1811. }
  1812. if (luaL_loadfile(L, path) != 0) {
  1813. lua_error_handler(L);
  1814. }
  1815. lua_pcall(L, 0, 0, -2);
  1816. lua_close(L);
  1817. }
  1818. }
  1819. static int
  1820. handle_lsp_request(struct mg_connection *conn,
  1821. const char *path,
  1822. struct mg_file *filep,
  1823. struct lua_State *ls)
  1824. {
  1825. void *p = NULL;
  1826. lua_State *L = NULL;
  1827. struct lsp_include_history *include_history;
  1828. int error = 1;
  1829. void *file_in_memory; /* TODO(low): remove when removing "file in memory" */
  1830. /* Assume the script does not support keep_alive. The script may change this
  1831. * by calling mg.keep_alive(true). */
  1832. conn->must_close = 1;
  1833. /* mg_fopen opens the file and sets the size accordingly */
  1834. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  1835. /* File not found or not accessible */
  1836. if (ls == NULL) {
  1837. mg_send_http_error(conn,
  1838. 500,
  1839. "Error: Cannot open script file %s",
  1840. path);
  1841. } else {
  1842. luaL_error(ls, "Cannot include [%s]: not found", path);
  1843. }
  1844. goto cleanup_handle_lsp_request;
  1845. }
  1846. #if defined(MG_USE_OPEN_FILE)
  1847. /* The "file in memory" feature is going to be removed. For details see
  1848. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI */
  1849. file_in_memory = filep->access.membuf;
  1850. #else
  1851. file_in_memory = NULL;
  1852. #endif
  1853. /* Map file in memory (size is known). */
  1854. if (file_in_memory == NULL
  1855. && (p = mmap(NULL,
  1856. (size_t)filep->stat.size,
  1857. PROT_READ,
  1858. MAP_PRIVATE,
  1859. fileno(filep->access.fp),
  1860. 0)) == MAP_FAILED) {
  1861. /* mmap failed */
  1862. if (ls == NULL) {
  1863. mg_send_http_error(
  1864. conn,
  1865. 500,
  1866. "Error: Cannot open script\nFile %s can not be mapped",
  1867. path);
  1868. } else {
  1869. luaL_error(ls,
  1870. "mmap(%s, %zu, %d): %s",
  1871. path,
  1872. (size_t)filep->stat.size,
  1873. fileno(filep->access.fp),
  1874. strerror(errno));
  1875. }
  1876. goto cleanup_handle_lsp_request;
  1877. }
  1878. if (ls != NULL) {
  1879. L = ls;
  1880. } else {
  1881. L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  1882. if (L == NULL) {
  1883. mg_send_http_error(
  1884. conn,
  1885. 500,
  1886. "%s",
  1887. "Error: Cannot execute script\nlua_newstate failed");
  1888. goto cleanup_handle_lsp_request;
  1889. }
  1890. prepare_lua_environment(
  1891. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1892. }
  1893. /* Get LSP include history table */
  1894. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  1895. lua_gettable(L, LUA_REGISTRYINDEX);
  1896. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  1897. /* Store script name and increment depth */
  1898. include_history->depth++;
  1899. include_history->script[include_history->depth] = path;
  1900. /* Lua state is ready to use */
  1901. /* We're not sending HTTP headers here, Lua page must do it. */
  1902. error = run_lsp(conn,
  1903. path,
  1904. (file_in_memory == NULL) ? (const char *)p
  1905. : (const char *)file_in_memory,
  1906. filep->stat.size,
  1907. L);
  1908. cleanup_handle_lsp_request:
  1909. if (L != NULL && ls == NULL)
  1910. lua_close(L);
  1911. if (p != NULL)
  1912. munmap(p, filep->stat.size);
  1913. (void)mg_fclose(&filep->access);
  1914. return error;
  1915. }
  1916. #if defined(USE_WEBSOCKET)
  1917. struct mg_shared_lua_websocket_list {
  1918. struct lua_websock_data ws;
  1919. struct mg_shared_lua_websocket_list *next;
  1920. };
  1921. static void *
  1922. lua_websocket_new(const char *script, struct mg_connection *conn)
  1923. {
  1924. struct mg_shared_lua_websocket_list **shared_websock_list =
  1925. &(conn->dom_ctx->shared_lua_websockets);
  1926. struct lua_websock_data *ws;
  1927. int err, ok = 0;
  1928. DEBUG_ASSERT(conn->lua_websocket_state == NULL);
  1929. /* lock list (mg_context global) */
  1930. mg_lock_context(conn->phys_ctx);
  1931. while (*shared_websock_list) {
  1932. /* check if ws already in list */
  1933. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1934. break;
  1935. }
  1936. shared_websock_list = &((*shared_websock_list)->next);
  1937. }
  1938. if (*shared_websock_list == NULL) {
  1939. /* add ws to list */
  1940. *shared_websock_list =
  1941. (struct mg_shared_lua_websocket_list *)mg_calloc_ctx(
  1942. sizeof(struct mg_shared_lua_websocket_list), 1, conn->phys_ctx);
  1943. if (*shared_websock_list == NULL) {
  1944. conn->must_close = 1;
  1945. mg_unlock_context(conn->phys_ctx);
  1946. mg_cry_internal(conn,
  1947. "%s",
  1948. "Cannot create shared websocket struct, OOM");
  1949. return NULL;
  1950. }
  1951. /* init ws list element */
  1952. ws = &(*shared_websock_list)->ws;
  1953. ws->script = mg_strdup_ctx(script, conn->phys_ctx);
  1954. if (!ws->script) {
  1955. conn->must_close = 1;
  1956. mg_unlock_context(conn->phys_ctx);
  1957. mg_cry_internal(conn,
  1958. "%s",
  1959. "Cannot create shared websocket script, OOM");
  1960. return NULL;
  1961. }
  1962. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1963. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1964. ws->state = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  1965. ws->conn[0] = conn;
  1966. ws->references = 1;
  1967. prepare_lua_environment(conn->phys_ctx,
  1968. conn,
  1969. ws,
  1970. ws->state,
  1971. script,
  1972. LUA_ENV_TYPE_LUA_WEBSOCKET);
  1973. err = luaL_loadfile(ws->state, script);
  1974. if (err != 0) {
  1975. lua_cry(conn, err, ws->state, script, "load");
  1976. }
  1977. err = lua_pcall(ws->state, 0, 0, 0);
  1978. if (err != 0) {
  1979. lua_cry(conn, err, ws->state, script, "init");
  1980. }
  1981. } else {
  1982. /* inc ref count */
  1983. ws = &(*shared_websock_list)->ws;
  1984. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1985. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1986. }
  1987. mg_unlock_context(conn->phys_ctx);
  1988. /* call add */
  1989. lua_getglobal(ws->state, "open");
  1990. lua_newtable(ws->state);
  1991. prepare_lua_request_info(conn, ws->state);
  1992. lua_pushstring(ws->state, "client");
  1993. lua_pushlightuserdata(ws->state, (void *)conn);
  1994. lua_rawset(ws->state, -3);
  1995. err = lua_pcall(ws->state, 1, 1, 0);
  1996. if (err != 0) {
  1997. lua_cry(conn, err, ws->state, script, "open handler");
  1998. } else {
  1999. if (lua_isboolean(ws->state, -1)) {
  2000. ok = lua_toboolean(ws->state, -1);
  2001. }
  2002. lua_pop(ws->state, 1);
  2003. }
  2004. if (!ok) {
  2005. /* Remove from ws connection list. */
  2006. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  2007. * (see websocket_close). */
  2008. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  2009. }
  2010. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2011. return ok ? (void *)ws : NULL;
  2012. }
  2013. static int
  2014. lua_websocket_data(struct mg_connection *conn,
  2015. int bits,
  2016. char *data,
  2017. size_t data_len,
  2018. void *ws_arg)
  2019. {
  2020. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2021. int err, ok = 0;
  2022. DEBUG_ASSERT(ws != NULL);
  2023. DEBUG_ASSERT(ws->state != NULL);
  2024. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2025. lua_getglobal(ws->state, "data");
  2026. lua_newtable(ws->state);
  2027. lua_pushstring(ws->state, "client");
  2028. lua_pushlightuserdata(ws->state, (void *)conn);
  2029. lua_rawset(ws->state, -3);
  2030. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  2031. a meaning according to
  2032. http://tools.ietf.org/html/rfc6455,
  2033. section 5.2 */
  2034. lua_pushnumber(ws->state, bits);
  2035. lua_rawset(ws->state, -3);
  2036. lua_pushstring(ws->state, "data");
  2037. lua_pushlstring(ws->state, data, data_len);
  2038. lua_rawset(ws->state, -3);
  2039. err = lua_pcall(ws->state, 1, 1, 0);
  2040. if (err != 0) {
  2041. lua_cry(conn, err, ws->state, ws->script, "data handler");
  2042. } else {
  2043. if (lua_isboolean(ws->state, -1)) {
  2044. ok = lua_toboolean(ws->state, -1);
  2045. }
  2046. lua_pop(ws->state, 1);
  2047. }
  2048. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2049. return ok;
  2050. }
  2051. static int
  2052. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  2053. {
  2054. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2055. int err, ok = 0;
  2056. DEBUG_ASSERT(ws != NULL);
  2057. DEBUG_ASSERT(ws->state != NULL);
  2058. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2059. lua_getglobal(ws->state, "ready");
  2060. lua_newtable(ws->state);
  2061. lua_pushstring(ws->state, "client");
  2062. lua_pushlightuserdata(ws->state, (void *)conn);
  2063. lua_rawset(ws->state, -3);
  2064. err = lua_pcall(ws->state, 1, 1, 0);
  2065. if (err != 0) {
  2066. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  2067. } else {
  2068. if (lua_isboolean(ws->state, -1)) {
  2069. ok = lua_toboolean(ws->state, -1);
  2070. }
  2071. lua_pop(ws->state, 1);
  2072. }
  2073. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2074. return ok;
  2075. }
  2076. static void
  2077. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  2078. {
  2079. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2080. struct mg_shared_lua_websocket_list **shared_websock_list =
  2081. &(conn->dom_ctx->shared_lua_websockets);
  2082. int err = 0;
  2083. unsigned i;
  2084. DEBUG_ASSERT(ws != NULL);
  2085. DEBUG_ASSERT(ws->state != NULL);
  2086. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2087. lua_getglobal(ws->state, "close");
  2088. lua_newtable(ws->state);
  2089. lua_pushstring(ws->state, "client");
  2090. lua_pushlightuserdata(ws->state, (void *)conn);
  2091. lua_rawset(ws->state, -3);
  2092. err = lua_pcall(ws->state, 1, 0, 0);
  2093. if (err != 0) {
  2094. lua_cry(conn, err, ws->state, ws->script, "close handler");
  2095. }
  2096. for (i = 0; i < ws->references; i++) {
  2097. if (ws->conn[i] == conn) {
  2098. ws->references--;
  2099. ws->conn[i] = ws->conn[ws->references];
  2100. }
  2101. }
  2102. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  2103. This must only be done, when all connections are closed, and all
  2104. asynchronous operations and timers are completed/expired. */
  2105. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  2106. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2107. }
  2108. #endif
  2109. static lua_State *
  2110. mg_prepare_lua_context_script(const char *file_name,
  2111. struct mg_context *ctx,
  2112. char *ebuf,
  2113. size_t ebuf_len)
  2114. {
  2115. struct lua_State *L;
  2116. int lua_ret;
  2117. const char *lua_err_txt;
  2118. (void)ctx;
  2119. L = luaL_newstate();
  2120. if (L == NULL) {
  2121. mg_snprintf(NULL,
  2122. NULL, /* No truncation check for ebuf */
  2123. ebuf,
  2124. ebuf_len,
  2125. "Error: %s",
  2126. "Cannot create Lua state");
  2127. return 0;
  2128. }
  2129. civetweb_open_lua_libs(L);
  2130. lua_ret = luaL_loadfile(L, file_name);
  2131. if (lua_ret != LUA_OK) {
  2132. /* Error when loading the file (e.g. file not found,
  2133. * out of memory, ...)
  2134. */
  2135. lua_err_txt = lua_tostring(L, -1);
  2136. mg_snprintf(NULL,
  2137. NULL, /* No truncation check for ebuf */
  2138. ebuf,
  2139. ebuf_len,
  2140. "Error loading file %s: %s\n",
  2141. file_name,
  2142. lua_err_txt);
  2143. return 0;
  2144. }
  2145. /* The script file is loaded, now call it */
  2146. lua_ret = lua_pcall(L,
  2147. /* no arguments */ 0,
  2148. /* zero or one return value */ 1,
  2149. /* errors as strint return value */ 0);
  2150. if (lua_ret != LUA_OK) {
  2151. /* Error when executing the script */
  2152. lua_err_txt = lua_tostring(L, -1);
  2153. mg_snprintf(NULL,
  2154. NULL, /* No truncation check for ebuf */
  2155. ebuf,
  2156. ebuf_len,
  2157. "Error running file %s: %s\n",
  2158. file_name,
  2159. lua_err_txt);
  2160. return 0;
  2161. }
  2162. /* lua_close(L); must be done somewhere else */
  2163. return L;
  2164. }
  2165. int
  2166. run_lua(const char *file_name)
  2167. {
  2168. int func_ret = EXIT_FAILURE;
  2169. char ebuf[512] = {0};
  2170. lua_State *L =
  2171. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  2172. if (L) {
  2173. /* Script executed */
  2174. if (lua_type(L, -1) == LUA_TNUMBER) {
  2175. func_ret = (int)lua_tonumber(L, -1);
  2176. } else {
  2177. func_ret = EXIT_SUCCESS;
  2178. }
  2179. lua_close(L);
  2180. } else {
  2181. fprintf(stderr, "%s\n", ebuf);
  2182. }
  2183. return func_ret;
  2184. }
  2185. static void *lib_handle_uuid = NULL;
  2186. static void
  2187. lua_init_optional_libraries(void)
  2188. {
  2189. #if !defined(_WIN32)
  2190. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  2191. pf_uuid_generate.p =
  2192. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  2193. #else
  2194. pf_uuid_generate.p = 0;
  2195. #endif
  2196. }
  2197. static void
  2198. lua_exit_optional_libraries(void)
  2199. {
  2200. #if !defined(_WIN32)
  2201. if (lib_handle_uuid) {
  2202. dlclose(lib_handle_uuid);
  2203. }
  2204. #endif
  2205. pf_uuid_generate.p = 0;
  2206. lib_handle_uuid = NULL;
  2207. }
  2208. /* End of mod_lua.inl */