mod_lua.inl 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370
  1. /* This file is part of the CivetWeb web server.
  2. * See https://github.com/civetweb/civetweb/
  3. */
  4. #if !defined(_WIN32)
  5. #include <dlfcn.h>
  6. #include <sys/mman.h>
  7. #endif
  8. #include "civetweb_lua.h"
  9. #include "civetweb_private_lua.h"
  10. #if defined(_WIN32)
  11. static void *
  12. mmap(void *addr, int64_t len, int prot, int flags, int fd, int offset)
  13. {
  14. /* TODO (low): This is an incomplete implementation of mmap for windows.
  15. * Currently it is sufficient, but there are a lot of unused parameters.
  16. * Better use a function "mg_map" which only has the required parameters,
  17. * and implement it using mmap in Linux and CreateFileMapping in Windows.
  18. * No one should expect a full mmap for Windows here.
  19. */
  20. HANDLE fh = (HANDLE)_get_osfhandle(fd);
  21. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  22. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
  23. CloseHandle(mh);
  24. /* unused parameters */
  25. (void)addr;
  26. (void)prot;
  27. (void)flags;
  28. (void)offset;
  29. return p;
  30. }
  31. static void
  32. munmap(void *addr, int64_t length)
  33. {
  34. /* unused parameters */
  35. (void)length;
  36. UnmapViewOfFile(addr);
  37. }
  38. #define MAP_PRIVATE (0)
  39. #define PROT_READ (0)
  40. #endif
  41. static const char *const LUASOCKET = "luasocket";
  42. static const char lua_regkey_ctx = 1;
  43. static const char lua_regkey_connlist = 2;
  44. static const char lua_regkey_lsp_include_history = 3;
  45. static const char lua_regkey_environment_type = 4;
  46. static const char lua_regkey_dtor = 5;
  47. static const char *const LUABACKGROUNDPARAMS = "mg";
  48. /* Limit nesting depth of mg.include.
  49. * This takes a lot of stack (~10 kB per recursion),
  50. * so do not use a too high limit. */
  51. #if !defined(LSP_INCLUDE_MAX_DEPTH)
  52. #define LSP_INCLUDE_MAX_DEPTH (10)
  53. #endif
  54. /* Forward declarations */
  55. static int handle_lsp_request(struct mg_connection *,
  56. const char *,
  57. struct mg_file *,
  58. struct lua_State *);
  59. static void
  60. reg_lstring(struct lua_State *L,
  61. const char *name,
  62. const void *buffer,
  63. size_t buflen)
  64. {
  65. if (name != NULL && buffer != NULL) {
  66. lua_pushstring(L, name);
  67. lua_pushlstring(L, (const char *)buffer, buflen);
  68. lua_rawset(L, -3);
  69. }
  70. }
  71. static void
  72. reg_llstring(struct lua_State *L,
  73. const void *buffer1,
  74. size_t buflen1,
  75. const void *buffer2,
  76. size_t buflen2)
  77. {
  78. if (buffer1 != NULL && buffer2 != NULL) {
  79. lua_pushlstring(L, (const char *)buffer1, buflen1);
  80. lua_pushlstring(L, (const char *)buffer2, buflen2);
  81. lua_rawset(L, -3);
  82. }
  83. }
  84. #define reg_string(L, name, val) \
  85. reg_lstring(L, name, val, val ? strlen(val) : 0)
  86. static void
  87. reg_int(struct lua_State *L, const char *name, int val)
  88. {
  89. if (name != NULL) {
  90. lua_pushstring(L, name);
  91. lua_pushinteger(L, val);
  92. lua_rawset(L, -3);
  93. }
  94. }
  95. static void
  96. reg_boolean(struct lua_State *L, const char *name, int val)
  97. {
  98. if (name != NULL) {
  99. lua_pushstring(L, name);
  100. lua_pushboolean(L, val != 0);
  101. lua_rawset(L, -3);
  102. }
  103. }
  104. static void
  105. reg_conn_function(struct lua_State *L,
  106. const char *name,
  107. lua_CFunction func,
  108. struct mg_connection *conn)
  109. {
  110. if (name != NULL && func != NULL && conn != NULL) {
  111. lua_pushstring(L, name);
  112. lua_pushlightuserdata(L, conn);
  113. lua_pushcclosure(L, func, 1);
  114. lua_rawset(L, -3);
  115. }
  116. }
  117. static void
  118. reg_function(struct lua_State *L, const char *name, lua_CFunction func)
  119. {
  120. if (name != NULL && func != NULL) {
  121. lua_pushstring(L, name);
  122. lua_pushcclosure(L, func, 0);
  123. lua_rawset(L, -3);
  124. }
  125. }
  126. static void
  127. lua_cry(struct mg_connection *conn,
  128. int err,
  129. lua_State *L,
  130. const char *lua_title,
  131. const char *lua_operation)
  132. {
  133. DEBUG_TRACE("lua_cry (err=%i): %s: %s", err, lua_title, lua_operation);
  134. switch (err) {
  135. case LUA_OK:
  136. case LUA_YIELD:
  137. break;
  138. case LUA_ERRRUN:
  139. mg_cry_internal(conn,
  140. "%s: %s failed: runtime error: %s",
  141. lua_title,
  142. lua_operation,
  143. lua_tostring(L, -1));
  144. break;
  145. case LUA_ERRSYNTAX:
  146. mg_cry_internal(conn,
  147. "%s: %s failed: syntax error: %s",
  148. lua_title,
  149. lua_operation,
  150. lua_tostring(L, -1));
  151. break;
  152. case LUA_ERRMEM:
  153. mg_cry_internal(conn,
  154. "%s: %s failed: out of memory",
  155. lua_title,
  156. lua_operation);
  157. break;
  158. #if LUA_VERSION_NUM < 504
  159. /* LUA_ERRGCMM has been removed in Lua 5.4.
  160. * See https://www.lua.org/manual/5.4/manual.html#8.3 */
  161. case LUA_ERRGCMM:
  162. mg_cry_internal(conn,
  163. "%s: %s failed: error during garbage collection",
  164. lua_title,
  165. lua_operation);
  166. break;
  167. #endif
  168. case LUA_ERRERR:
  169. mg_cry_internal(conn,
  170. "%s: %s failed: error in error handling: %s",
  171. lua_title,
  172. lua_operation,
  173. lua_tostring(L, -1));
  174. break;
  175. default:
  176. mg_cry_internal(
  177. conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
  178. break;
  179. }
  180. }
  181. static int
  182. lsp_sock_close(lua_State *L)
  183. {
  184. int num_args = lua_gettop(L);
  185. size_t s;
  186. SOCKET *psock;
  187. if ((num_args == 1) && lua_istable(L, -1)) {
  188. lua_getfield(L, -1, "sock");
  189. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  190. if (s != sizeof(SOCKET)) {
  191. return luaL_error(L, "invalid internal state in :close() call");
  192. }
  193. /* Do not closesocket(*psock); here, close it in __gc */
  194. (void)psock;
  195. } else {
  196. return luaL_error(L, "invalid :close() call");
  197. }
  198. return 0;
  199. }
  200. static int
  201. lsp_sock_recv(lua_State *L)
  202. {
  203. int num_args = lua_gettop(L);
  204. char buf[2000];
  205. int n;
  206. size_t s;
  207. SOCKET *psock;
  208. if ((num_args == 1) && lua_istable(L, -1)) {
  209. lua_getfield(L, -1, "sock");
  210. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  211. if (s != sizeof(SOCKET)) {
  212. return luaL_error(L, "invalid internal state in :recv() call");
  213. }
  214. n = recv(*psock, buf, sizeof(buf), 0);
  215. if (n <= 0) {
  216. lua_pushnil(L);
  217. } else {
  218. lua_pushlstring(L, buf, n);
  219. }
  220. } else {
  221. return luaL_error(L, "invalid :recv() call");
  222. }
  223. return 1;
  224. }
  225. static int
  226. lsp_sock_send(lua_State *L)
  227. {
  228. int num_args = lua_gettop(L);
  229. const char *buf;
  230. size_t len, sent = 0;
  231. int n = 0;
  232. size_t s;
  233. SOCKET *psock;
  234. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  235. buf = lua_tolstring(L, -1, &len);
  236. lua_getfield(L, -2, "sock");
  237. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  238. if (s != sizeof(SOCKET)) {
  239. return luaL_error(L, "invalid internal state in :close() call");
  240. }
  241. while (sent < len) {
  242. if ((n = send(*psock, buf + sent, (int)(len - sent), 0)) <= 0) {
  243. break;
  244. }
  245. sent += n;
  246. }
  247. lua_pushnumber(L, n);
  248. } else {
  249. return luaL_error(L, "invalid :close() call");
  250. }
  251. return 1;
  252. }
  253. static int
  254. lsp_sock_gc(lua_State *L)
  255. {
  256. int num_args = lua_gettop(L);
  257. size_t s;
  258. SOCKET *psock;
  259. if ((num_args == 1) && lua_istable(L, -1)) {
  260. lua_getfield(L, -1, "sock");
  261. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  262. if (s != sizeof(SOCKET)) {
  263. return luaL_error(
  264. L,
  265. "invalid internal state in __gc for object created by connect");
  266. }
  267. closesocket(*psock);
  268. } else {
  269. return luaL_error(L, "__gc for object created by connect failed");
  270. }
  271. return 0;
  272. }
  273. /* Methods and meta-methods supported by the object returned by connect.
  274. * For meta-methods, see http://lua-users.org/wiki/MetatableEvents */
  275. static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
  276. {"send", lsp_sock_send},
  277. {"recv", lsp_sock_recv},
  278. {"__gc", lsp_sock_gc},
  279. {NULL, NULL}};
  280. static int
  281. lsp_connect(lua_State *L)
  282. {
  283. int num_args = lua_gettop(L);
  284. char ebuf[100];
  285. SOCKET sock;
  286. union usa sa;
  287. int ok;
  288. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2)
  289. && lua_isnumber(L, -1)) {
  290. ok = connect_socket(NULL,
  291. lua_tostring(L, -3),
  292. (int)lua_tonumber(L, -2),
  293. (int)lua_tonumber(L, -1),
  294. ebuf,
  295. sizeof(ebuf),
  296. &sock,
  297. &sa);
  298. if (!ok) {
  299. return luaL_error(L, ebuf);
  300. } else {
  301. set_blocking_mode(sock);
  302. lua_newtable(L);
  303. reg_lstring(L, "sock", (const char *)&sock, sizeof(SOCKET));
  304. reg_string(L, "host", lua_tostring(L, -4));
  305. luaL_getmetatable(L, LUASOCKET);
  306. lua_setmetatable(L, -2);
  307. }
  308. } else {
  309. return luaL_error(
  310. L, "connect(host,port,is_ssl): invalid parameter given.");
  311. }
  312. return 1;
  313. }
  314. static int
  315. lsp_error(lua_State *L)
  316. {
  317. DEBUG_TRACE("%s", "lsp_error");
  318. lua_getglobal(L, "mg");
  319. lua_getfield(L, -1, "onerror");
  320. lua_pushvalue(L, -3);
  321. lua_pcall(L, 1, 0, 0);
  322. return 0;
  323. }
  324. /* Silently stop processing chunks. */
  325. static void
  326. lsp_abort(lua_State *L)
  327. {
  328. int top = lua_gettop(L);
  329. DEBUG_TRACE("%s", "lsp_abort");
  330. lua_getglobal(L, "mg");
  331. lua_pushnil(L);
  332. lua_setfield(L, -2, "onerror");
  333. lua_settop(L, top);
  334. lua_pushstring(L, "aborting");
  335. lua_error(L);
  336. }
  337. struct lsp_var_reader_data {
  338. int64_t len;
  339. int64_t consumed;
  340. const char *begin;
  341. unsigned char state;
  342. char tag;
  343. };
  344. /* Helper function to read the content of variable values */
  345. static const char *
  346. lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  347. {
  348. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  349. const char *ret;
  350. (void)(L); /* unused */
  351. /* This reader is called multiple times, to fetch the full Lua script */
  352. switch (reader->state) {
  353. case 0:
  354. /* First call: what function to call */
  355. reader->consumed = 0;
  356. ret = "mg.write(";
  357. *sz = strlen(ret);
  358. break;
  359. case 1:
  360. /* Second call: forward variable name */
  361. ret = reader->begin;
  362. *sz = (size_t)reader->len;
  363. reader->consumed += reader->len;
  364. break;
  365. case 2:
  366. /* Third call: close function call */
  367. ret = ")";
  368. *sz = strlen(ret);
  369. break;
  370. default:
  371. /* Forth/Final call: tell Lua we got the entire script */
  372. ret = 0;
  373. *sz = 0;
  374. }
  375. /* Step to the next state for the next call */
  376. reader->state++;
  377. return ret;
  378. }
  379. static const char *
  380. lsp_kepler_reader(lua_State *L, void *ud, size_t *sz)
  381. {
  382. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  383. const char *ret;
  384. int64_t i;
  385. int64_t left;
  386. (void)(L); /* unused */
  387. /* This reader is called multiple times, to fetch the full Lua script */
  388. if (reader->state == 0) {
  389. /* First call: Send opening tag - what function to call */
  390. ret = "mg.write([=======[";
  391. *sz = strlen(ret);
  392. reader->state = 1;
  393. reader->consumed = 0;
  394. return ret;
  395. }
  396. if (reader->state == 4) {
  397. /* Final call: Tell Lua reader, we reached the end */
  398. *sz = 0;
  399. return 0;
  400. }
  401. left = reader->len - reader->consumed;
  402. if (left == 0) {
  403. /* We reached the end of the file/available data. */
  404. /* Send closing tag. */
  405. ret = "]=======]);\n";
  406. *sz = strlen(ret);
  407. reader->state = 4; /* Next will be the final call */
  408. return ret;
  409. }
  410. if (left > MG_BUF_LEN / 100) {
  411. left = MG_BUF_LEN / 100; /* TODO XXX */
  412. }
  413. i = 0;
  414. if (reader->state == 1) {
  415. /* State 1: plain text - put inside mg.write(...) */
  416. for (;;) {
  417. /* Find next tag */
  418. while ((i < left) && (reader->begin[i + reader->consumed] != '<')) {
  419. i++;
  420. }
  421. if (i > 0) {
  422. /* Forward all data until the next tag */
  423. int64_t j = reader->consumed;
  424. reader->consumed += i;
  425. *sz = (size_t)i; /* cast is ok, i is limited to MG_BUF_LEN */
  426. return reader->begin + j;
  427. }
  428. /* assert (reader->begin[reader->state] == '<') */
  429. /* assert (i == 0) */
  430. if (0 == memcmp(reader->begin + reader->consumed, "<?lua", 5)) {
  431. /* kepler <?lua syntax */
  432. i = 5;
  433. reader->tag = '?';
  434. break;
  435. } else if (0 == memcmp(reader->begin + reader->consumed, "<%", 2)) {
  436. /* kepler <% syntax */
  437. i = 2;
  438. reader->tag = '%';
  439. break;
  440. } else if (0 == memcmp(reader->begin + reader->consumed, "<?", 2)) {
  441. /* civetweb <? syntax */
  442. i = 2;
  443. reader->tag = '?';
  444. break;
  445. } else {
  446. i = 1;
  447. }
  448. }
  449. /* We found an opening or closing tag, or we reached the end of the
  450. * file/data block */
  451. if (reader->begin[reader->consumed + i] == '=') {
  452. /* Lua= tag - Lua expression to print */
  453. ret = "]=======]);\nmg.write(";
  454. reader->state = 3;
  455. i++;
  456. } else {
  457. /* Normal Lua tag - Lua chunk */
  458. ret = "]=======]);\n";
  459. reader->state = 2;
  460. }
  461. *sz = strlen(ret);
  462. reader->consumed += i; /* length of <?lua or <% tag */
  463. return ret;
  464. }
  465. if ((reader->state == 2) || (reader->state == 3)) {
  466. /* State 2: Lua chunkg - keep outside mg.write(...) */
  467. /* State 3: Lua expression - inside mg.write(...) */
  468. for (;;) {
  469. int close_tag_found = 0;
  470. /* Find end tag */
  471. while ((i < left)
  472. && (reader->begin[i + reader->consumed] != reader->tag)) {
  473. i++;
  474. }
  475. if (i > 0) {
  476. /* Forward all data inside the Lua script tag */
  477. int64_t j = reader->consumed;
  478. reader->consumed += i;
  479. *sz = (size_t)i; /* cast is ok, i is limited to MG_BUF_LEN */
  480. return reader->begin + j;
  481. }
  482. /* Is this the closing tag we are looking for? */
  483. close_tag_found =
  484. ((i + 1 < left)
  485. && (reader->begin[i + 1 + reader->consumed] == '>'));
  486. if (close_tag_found) {
  487. /* Drop close tag */
  488. reader->consumed += 2;
  489. if (reader->state == 2) {
  490. /* Send a new opening tag to Lua */
  491. ret = ";\nmg.write([=======[";
  492. } else {
  493. ret = ");\nmg.write([=======[";
  494. }
  495. *sz = strlen(ret);
  496. reader->state = 1;
  497. return ret;
  498. } else {
  499. /* Not a close tag, continue searching */
  500. i++;
  501. }
  502. }
  503. }
  504. /* Must never be reached */
  505. *sz = 0;
  506. return 0;
  507. }
  508. static int
  509. run_lsp_kepler(struct mg_connection *conn,
  510. const char *path,
  511. const char *p,
  512. int64_t len,
  513. lua_State *L,
  514. int depth)
  515. {
  516. int lua_ok;
  517. struct lsp_var_reader_data data;
  518. char date[64];
  519. time_t curtime = time(NULL);
  520. gmt_time_string(date, sizeof(date), &curtime);
  521. if (depth == 1) {
  522. /* Top level page assumes keep_alive is disabled.
  523. * Do not overwrite this setting for included pages. */
  524. conn->must_close = 1;
  525. /* Only send a HTML header, if this is the top level page.
  526. * If this page is included by some mg.include calls, do not add a
  527. * header. */
  528. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  529. send_no_cache_header(conn);
  530. send_additional_header(conn);
  531. mg_printf(conn,
  532. "Date: %s\r\n"
  533. "Connection: close\r\n"
  534. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  535. date);
  536. }
  537. data.begin = p;
  538. data.len = len;
  539. data.state = 0;
  540. data.consumed = 0;
  541. data.tag = 0;
  542. lua_ok = mg_lua_load(L, lsp_kepler_reader, &data, path, NULL);
  543. if (lua_ok) {
  544. /* Syntax error or OOM.
  545. * Error message is pushed on stack. */
  546. lua_pcall(L, 1, 0, 0);
  547. lua_cry(conn, lua_ok, L, "LSP", "execute"); /* XXX TODO: everywhere ! */
  548. } else {
  549. /* Success loading chunk. Call it. */
  550. lua_pcall(L, 0, 0, 1);
  551. }
  552. return 0;
  553. }
  554. static int
  555. run_lsp_civetweb(struct mg_connection *conn,
  556. const char *path,
  557. const char *p,
  558. int64_t len,
  559. lua_State *L,
  560. int depth)
  561. {
  562. int i, j, s, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  563. char chunkname[MG_BUF_LEN];
  564. struct lsp_var_reader_data data;
  565. const char lsp_mark1 = '?'; /* Use <? code ?> */
  566. const char lsp_mark2 = '%'; /* Use <% code %> */
  567. if (depth == 1) {
  568. /* Assume the script does not support keep_alive. The script may change
  569. * this by calling mg.keep_alive(true). */
  570. conn->must_close = 1;
  571. }
  572. for (i = 0; i < len; i++) {
  573. if (p[i] == '\n') {
  574. lines++;
  575. }
  576. /* Lua pages are normal text, unless there is a "<?" or "<%" tag. */
  577. if (((i + 1) < len) && (p[i] == '<')
  578. && ((p[i + 1] == lsp_mark1) || (p[i + 1] == lsp_mark2))) {
  579. /* Opening tag way "<?" or "<%", closing tag must be the same. */
  580. char lsp_mark_used = p[i + 1];
  581. /* <?= var ?> or <%= var %> means a variable is enclosed and its
  582. * value should be printed */
  583. if (0 == memcmp("lua", p + i + 2, 3)) {
  584. /* Syntax: <?lua code ?> or <?lua= var ?> */
  585. /* This is added for compatibility to other LSP syntax
  586. * definitions. */
  587. /* Skip 3 letters ("lua"). */
  588. s = 3;
  589. } else {
  590. /* no additional letters to skip, only "<?" */
  591. s = 0;
  592. }
  593. /* Check for '=' in "<?= ..." or "<%= ..." or "<?lua= ..." */
  594. is_var = (((i + s + 2) < len) && (p[i + s + 2] == '='));
  595. if (is_var) {
  596. /* use variable value (print it later) */
  597. j = i + 2;
  598. } else {
  599. /* execute script code */
  600. j = i + 1;
  601. }
  602. while (j < len) {
  603. if (p[j] == '\n') {
  604. /* Add line (for line number offset) */
  605. lualines++;
  606. }
  607. /* Check for closing tag. */
  608. if (((j + 1) < len) && (p[j] == lsp_mark_used)
  609. && (p[j + 1] == '>')) {
  610. /* We found the closing tag of the Lua tag. */
  611. /* Print everything before the Lua opening tag. */
  612. mg_write(conn, p + pos, i - pos);
  613. /* Set a name for debugging purposes */
  614. mg_snprintf(conn,
  615. NULL, /* ignore truncation for debugging */
  616. chunkname,
  617. sizeof(chunkname),
  618. "@%s+%i",
  619. path,
  620. lines);
  621. /* Prepare data for Lua C functions */
  622. lua_pushlightuserdata(L, conn);
  623. lua_pushcclosure(L, lsp_error, 1);
  624. /* Distinguish between <? script ?> (is_var == 0)
  625. * and <?= expression ?> (is_var != 0). */
  626. if (is_var) {
  627. /* For variables: Print the value */
  628. /* Note: <?= expression ?> is equivalent to
  629. * <? mg.write( expression ) ?> */
  630. data.begin = p + (i + 3 + s);
  631. data.len = j - (i + 3 + s);
  632. data.state = 0;
  633. data.consumed = 0;
  634. data.tag = 0;
  635. lua_ok = mg_lua_load(
  636. L, lsp_var_reader, &data, chunkname, NULL);
  637. } else {
  638. /* For scripts: Execute them */
  639. lua_ok = luaL_loadbuffer(L,
  640. p + (i + 2 + s),
  641. j - (i + 2 + s),
  642. chunkname);
  643. }
  644. if (lua_ok) {
  645. /* Syntax error or OOM.
  646. * Error message is pushed on stack. */
  647. lua_pcall(L, 1, 0, 0);
  648. } else {
  649. /* Success loading chunk. Call it. */
  650. lua_pcall(L, 0, 0, 1);
  651. }
  652. /* Progress until after the Lua closing tag. */
  653. pos = j + 2;
  654. i = pos - 1;
  655. break;
  656. }
  657. j++;
  658. }
  659. /* Line number for debugging/error logging. */
  660. if (lualines > 0) {
  661. lines += lualines;
  662. lualines = 0;
  663. }
  664. }
  665. }
  666. /* Print everything after the last Lua closing tag. */
  667. if (i > pos) {
  668. mg_write(conn, p + pos, i - pos);
  669. }
  670. return 0;
  671. }
  672. /* mg.write: Send data to the client */
  673. static int
  674. lsp_write(lua_State *L)
  675. {
  676. struct mg_connection *conn =
  677. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  678. int num_args = lua_gettop(L);
  679. const char *str;
  680. size_t size;
  681. int i;
  682. int rv = 1;
  683. for (i = 1; i <= num_args; i++) {
  684. if (lua_isstring(L, i)) {
  685. str = lua_tolstring(L, i, &size);
  686. if (mg_write(conn, str, size) != (int)size) {
  687. rv = 0;
  688. }
  689. }
  690. }
  691. lua_pushboolean(L, rv);
  692. return 1;
  693. }
  694. /* mg.read: Read data from the client (e.g., from a POST request) */
  695. static int
  696. lsp_read(lua_State *L)
  697. {
  698. struct mg_connection *conn =
  699. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  700. char buf[1024];
  701. int len = mg_read(conn, buf, sizeof(buf));
  702. if (len <= 0)
  703. return 0;
  704. lua_pushlstring(L, buf, len);
  705. return 1;
  706. }
  707. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  708. static int
  709. lsp_keep_alive(lua_State *L)
  710. {
  711. struct mg_connection *conn =
  712. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  713. int num_args = lua_gettop(L);
  714. /* This function may be called with one parameter (boolean) to set the
  715. keep_alive state.
  716. Or without a parameter to just query the current keep_alive state. */
  717. if ((num_args == 1) && lua_isboolean(L, 1)) {
  718. conn->must_close = !lua_toboolean(L, 1);
  719. } else if (num_args != 0) {
  720. /* Syntax error */
  721. return luaL_error(L, "invalid keep_alive() call");
  722. }
  723. /* Return the current "keep_alive" state. This may be false, even it
  724. * keep_alive(true) has been called. */
  725. lua_pushboolean(L, should_keep_alive(conn));
  726. return 1;
  727. }
  728. /* Stack of includes */
  729. struct lsp_include_history {
  730. int depth;
  731. const char *script[LSP_INCLUDE_MAX_DEPTH + 1];
  732. };
  733. /* mg.include: Include another .lp file */
  734. static int
  735. lsp_include(lua_State *L)
  736. {
  737. struct mg_connection *conn =
  738. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  739. int num_args = lua_gettop(L);
  740. struct mg_file file = STRUCT_FILE_INITIALIZER;
  741. const char *file_name = (num_args >= 1) ? lua_tostring(L, 1) : NULL;
  742. const char *path_type = (num_args >= 2) ? lua_tostring(L, 2) : NULL;
  743. struct lsp_include_history *include_history;
  744. if (path_type == NULL) {
  745. /* default to "absolute" */
  746. path_type = "a";
  747. }
  748. if ((file_name != NULL) && (num_args <= 2)) {
  749. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  750. lua_gettable(L, LUA_REGISTRYINDEX);
  751. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  752. if (include_history->depth >= ((int)(LSP_INCLUDE_MAX_DEPTH))) {
  753. mg_cry_internal(
  754. conn,
  755. "lsp max include depth of %i reached while including %s",
  756. (int)(LSP_INCLUDE_MAX_DEPTH),
  757. file_name);
  758. } else {
  759. char file_name_path[512];
  760. char *p;
  761. size_t len;
  762. int truncated = 0;
  763. file_name_path[511] = 0;
  764. if (*path_type == 'v') {
  765. /* "virtual" = relative to document root. */
  766. (void)mg_snprintf(conn,
  767. &truncated,
  768. file_name_path,
  769. sizeof(file_name_path),
  770. "%s/%s",
  771. conn->dom_ctx->config[DOCUMENT_ROOT],
  772. file_name);
  773. } else if (*path_type == 'a') {
  774. /* "absolute" = file name is relative to the
  775. * webserver working directory
  776. * or it is absolute system path. */
  777. /* path_type==NULL is the legacy use case with 1 argument */
  778. (void)mg_snprintf(conn,
  779. &truncated,
  780. file_name_path,
  781. sizeof(file_name_path),
  782. "%s",
  783. file_name);
  784. } else if ((*path_type == 'r') || (*path_type == 'f')) {
  785. /* "relative" = file name is relative to the
  786. * currect document */
  787. (void)mg_snprintf(
  788. conn,
  789. &truncated,
  790. file_name_path,
  791. sizeof(file_name_path),
  792. "%s",
  793. include_history->script[include_history->depth]);
  794. if (!truncated) {
  795. if ((p = strrchr(file_name_path, '/')) != NULL) {
  796. p[1] = '\0';
  797. }
  798. len = strlen(file_name_path);
  799. (void)mg_snprintf(conn,
  800. &truncated,
  801. file_name_path + len,
  802. sizeof(file_name_path) - len,
  803. "%s",
  804. file_name);
  805. }
  806. } else {
  807. return luaL_error(
  808. L,
  809. "invalid path_type in include(file_name, path_type) call");
  810. }
  811. if (handle_lsp_request(conn, file_name_path, &file, L)) {
  812. /* handle_lsp_request returned an error code, meaning an error
  813. * occurred in the included page and mg.onerror returned
  814. * non-zero.
  815. * Stop processing.
  816. */
  817. lsp_abort(L);
  818. }
  819. }
  820. } else {
  821. /* Syntax error */
  822. return luaL_error(L, "invalid include() call");
  823. }
  824. return 0;
  825. }
  826. /* mg.cry: Log an error. Default value for mg.onerror. */
  827. static int
  828. lsp_cry(lua_State *L)
  829. {
  830. struct mg_connection *conn =
  831. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  832. int num_args = lua_gettop(L);
  833. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  834. if (text) {
  835. mg_cry_internal(conn, "%s", lua_tostring(L, -1));
  836. } else {
  837. /* Syntax error */
  838. return luaL_error(L, "invalid cry() call");
  839. }
  840. return 0;
  841. }
  842. /* mg.redirect: Redirect the request (internally). */
  843. static int
  844. lsp_redirect(lua_State *L)
  845. {
  846. struct mg_connection *conn =
  847. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  848. int num_args = lua_gettop(L);
  849. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  850. if (target) {
  851. conn->request_info.local_uri = target;
  852. handle_request(conn);
  853. lsp_abort(L);
  854. } else {
  855. /* Syntax error */
  856. return luaL_error(L, "invalid redirect() call");
  857. }
  858. return 0;
  859. }
  860. /* mg.send_file */
  861. static int
  862. lsp_send_file(lua_State *L)
  863. {
  864. struct mg_connection *conn =
  865. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  866. int num_args = lua_gettop(L);
  867. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  868. if (filename) {
  869. mg_send_file(conn, filename);
  870. } else {
  871. /* Syntax error */
  872. return luaL_error(L, "invalid send_file() call");
  873. }
  874. return 0;
  875. }
  876. /* mg.mg_send_file_body */
  877. static int
  878. lsp_send_file_body(lua_State *L)
  879. {
  880. struct mg_connection *conn =
  881. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  882. int num_args = lua_gettop(L);
  883. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  884. int ret;
  885. if (filename) {
  886. ret = mg_send_file_body(conn, filename);
  887. } else {
  888. /* Syntax error */
  889. return luaL_error(L, "invalid send_file_body() call");
  890. }
  891. lua_pushboolean(L, ret >= 0);
  892. return 1;
  893. }
  894. /* mg.send_http_error */
  895. static int
  896. lsp_send_http_error(lua_State *L)
  897. {
  898. struct mg_connection *conn =
  899. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  900. int num_args = lua_gettop(L);
  901. int status = (num_args >= 1) ? (int)lua_tonumber(L, 1) : -1;
  902. const char *auxText = (num_args >= 2) ? lua_tostring(L, 2) : NULL;
  903. int ret;
  904. if ((status >= 100) && (status <= 999)) {
  905. ret = mg_send_http_error(conn,
  906. status,
  907. (auxText != NULL) ? "%s" : "",
  908. auxText);
  909. } else {
  910. /* Syntax error */
  911. return luaL_error(L, "invalid send_http_error() call");
  912. }
  913. lua_pushnumber(L, ret);
  914. return 1;
  915. }
  916. /* mg.send_http_error */
  917. static int
  918. lsp_send_http_ok(lua_State *L)
  919. {
  920. struct mg_connection *conn =
  921. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  922. int num_args = lua_gettop(L);
  923. int type1, type2;
  924. const char *content_type = NULL;
  925. const char *content = NULL;
  926. int64_t content_len = 0;
  927. int ret;
  928. if (num_args < 2) {
  929. /* Syntax error */
  930. return luaL_error(L, "invalid send_http_ok() call");
  931. }
  932. type1 = lua_type(L, 1);
  933. type2 = lua_type(L, 2);
  934. if (type1 == LUA_TSTRING) {
  935. content_type = lua_tostring(L, 1);
  936. } else if (type1 != LUA_TNIL) {
  937. /* Syntax error */
  938. return luaL_error(L, "invalid send_http_ok() call");
  939. }
  940. if (type2 == LUA_TSTRING) {
  941. size_t len;
  942. content = lua_tolstring(L, 2, &len);
  943. content_len = (int64_t)len;
  944. } else if (type2 == LUA_TNUMBER) {
  945. content_len = (int64_t)lua_tonumber(L, 2);
  946. } else {
  947. /* Syntax error */
  948. return luaL_error(L, "invalid send_http_ok() call");
  949. }
  950. ret = mg_send_http_ok(conn, content_type, content_len);
  951. if ((ret == 0) && (content != NULL) && (content_len > 0)) {
  952. mg_write(conn, content, (size_t)content_len);
  953. }
  954. lua_pushnumber(L, ret);
  955. return 1;
  956. }
  957. /* mg.get_time */
  958. static int
  959. lsp_get_time(lua_State *L)
  960. {
  961. int num_args = lua_gettop(L);
  962. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  963. struct timespec ts;
  964. double d;
  965. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  966. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  967. lua_pushnumber(L, d);
  968. return 1;
  969. }
  970. /* mg.get_var */
  971. static int
  972. lsp_get_var(lua_State *L)
  973. {
  974. int num_args = lua_gettop(L);
  975. const char *data, *var_name;
  976. size_t data_len, occurrence;
  977. int ret;
  978. struct mg_context *ctx;
  979. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  980. lua_gettable(L, LUA_REGISTRYINDEX);
  981. ctx = (struct mg_context *)lua_touserdata(L, -1);
  982. if ((num_args >= 2) && (num_args <= 3)) {
  983. char *dst;
  984. data = lua_tolstring(L, 1, &data_len);
  985. var_name = lua_tostring(L, 2);
  986. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  987. /* Allocate dynamically, so there is no internal limit for get_var */
  988. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  989. if (!dst) {
  990. return luaL_error(L, "out of memory in get_var() call");
  991. }
  992. ret = mg_get_var2(data, data_len, var_name, dst, data_len, occurrence);
  993. if (ret >= 0) {
  994. /* Variable found: return value to Lua */
  995. lua_pushstring(L, dst);
  996. } else {
  997. /* Variable not found */
  998. lua_pushnil(L);
  999. }
  1000. mg_free(dst);
  1001. } else {
  1002. /* Syntax error */
  1003. return luaL_error(L, "invalid get_var() call");
  1004. }
  1005. return 1;
  1006. }
  1007. #define MG_MAX_FORM_FIELDS (64)
  1008. /* mg.split_form_data */
  1009. static int
  1010. lsp_split_form_urlencoded(lua_State *L)
  1011. {
  1012. int num_args = lua_gettop(L);
  1013. const char *in;
  1014. size_t len;
  1015. char *buf;
  1016. struct mg_context *ctx;
  1017. struct mg_header form_fields[MG_MAX_FORM_FIELDS] = {0};
  1018. int ret, i;
  1019. if (num_args != 1) {
  1020. return luaL_error(L, "invalid split_form_data() call");
  1021. }
  1022. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1023. lua_gettable(L, LUA_REGISTRYINDEX);
  1024. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1025. /* Get input (const string) */
  1026. in = lua_tolstring(L, 1, &len);
  1027. /* Create a modifyable copy */
  1028. buf = mg_malloc_ctx(len + 1, ctx);
  1029. if (buf == NULL) {
  1030. return luaL_error(L, "out of memory in invalid split_form_data() call");
  1031. }
  1032. memcpy(buf, in, len + 1);
  1033. /* mg_split_form_urlencoded does the real work */
  1034. ret = mg_split_form_urlencoded(buf, form_fields, MG_MAX_FORM_FIELDS);
  1035. if (ret < 0) {
  1036. return luaL_error(L, "error in invalid split_form_data() call");
  1037. }
  1038. /* return a table */
  1039. lua_newtable(L);
  1040. for (i = 0; i < ret; i++) {
  1041. lua_newtable(L);
  1042. if (form_fields[i].name) {
  1043. lua_pushstring(L, form_fields[i].name);
  1044. } else {
  1045. lua_pushnil(L);
  1046. }
  1047. lua_setfield(L, -2, "name");
  1048. if (form_fields[i].value) {
  1049. lua_pushstring(L, form_fields[i].value);
  1050. } else {
  1051. lua_pushnil(L);
  1052. }
  1053. lua_setfield(L, -2, "value");
  1054. lua_rawseti(L, -2, i + 1);
  1055. }
  1056. mg_free(buf);
  1057. return 1;
  1058. }
  1059. /* mg.get_mime_type */
  1060. static int
  1061. lsp_get_mime_type(lua_State *L)
  1062. {
  1063. int num_args = lua_gettop(L);
  1064. struct vec mime_type = {0, 0};
  1065. const char *text;
  1066. struct mg_connection *conn =
  1067. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1068. if (num_args == 1) {
  1069. text = lua_tostring(L, 1);
  1070. if (text) {
  1071. if (conn) {
  1072. get_mime_type(conn, text, &mime_type);
  1073. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  1074. } else {
  1075. text = mg_get_builtin_mime_type(text);
  1076. lua_pushstring(L, text);
  1077. }
  1078. } else {
  1079. /* Syntax error */
  1080. return luaL_error(L, "invalid argument for get_mime_type() call");
  1081. }
  1082. } else {
  1083. /* Syntax error */
  1084. return luaL_error(L, "invalid get_mime_type() call");
  1085. }
  1086. return 1;
  1087. }
  1088. /* mg.get_cookie */
  1089. static int
  1090. lsp_get_cookie(lua_State *L)
  1091. {
  1092. int num_args = lua_gettop(L);
  1093. const char *cookie;
  1094. const char *var_name;
  1095. int ret;
  1096. struct mg_context *ctx;
  1097. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1098. lua_gettable(L, LUA_REGISTRYINDEX);
  1099. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1100. if (num_args == 2) {
  1101. /* Correct number of arguments */
  1102. size_t data_len;
  1103. char *dst;
  1104. cookie = lua_tolstring(L, 1, &data_len);
  1105. var_name = lua_tostring(L, 2);
  1106. if (cookie == NULL || var_name == NULL) {
  1107. /* Syntax error */
  1108. return luaL_error(L, "invalid get_cookie() call");
  1109. }
  1110. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  1111. if (!dst) {
  1112. return luaL_error(L, "out of memory in get_cookie() call");
  1113. }
  1114. ret = mg_get_cookie(cookie, var_name, dst, data_len);
  1115. if (ret >= 0) {
  1116. lua_pushlstring(L, dst, ret);
  1117. } else {
  1118. lua_pushnil(L);
  1119. }
  1120. mg_free(dst);
  1121. } else {
  1122. /* Syntax error */
  1123. return luaL_error(L, "invalid get_cookie() call");
  1124. }
  1125. return 1;
  1126. }
  1127. /* mg.md5 */
  1128. static int
  1129. lsp_md5(lua_State *L)
  1130. {
  1131. int num_args = lua_gettop(L);
  1132. const char *text;
  1133. md5_byte_t hash[16];
  1134. md5_state_t ctx;
  1135. size_t text_len;
  1136. char buf[40];
  1137. if (num_args == 1) {
  1138. text = lua_tolstring(L, 1, &text_len);
  1139. if (text) {
  1140. md5_init(&ctx);
  1141. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  1142. md5_finish(&ctx, hash);
  1143. bin2str(buf, hash, sizeof(hash));
  1144. lua_pushstring(L, buf);
  1145. } else {
  1146. lua_pushnil(L);
  1147. }
  1148. } else {
  1149. /* Syntax error */
  1150. return luaL_error(L, "invalid md5() call");
  1151. }
  1152. return 1;
  1153. }
  1154. /* mg.url_encode */
  1155. static int
  1156. lsp_url_encode(lua_State *L)
  1157. {
  1158. int num_args = lua_gettop(L);
  1159. const char *text;
  1160. size_t text_len;
  1161. char *dst;
  1162. int dst_len;
  1163. struct mg_context *ctx;
  1164. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1165. lua_gettable(L, LUA_REGISTRYINDEX);
  1166. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1167. if (num_args == 1) {
  1168. text = lua_tolstring(L, 1, &text_len);
  1169. if (text) {
  1170. dst_len = 3 * (int)text_len + 1;
  1171. dst = ((text_len < 0x2AAAAAAA) ? (char *)mg_malloc_ctx(dst_len, ctx)
  1172. : (char *)NULL);
  1173. if (dst) {
  1174. mg_url_encode(text, dst, dst_len);
  1175. lua_pushstring(L, dst);
  1176. mg_free(dst);
  1177. } else {
  1178. return luaL_error(L, "out of memory in url_decode() call");
  1179. }
  1180. } else {
  1181. lua_pushnil(L);
  1182. }
  1183. } else {
  1184. /* Syntax error */
  1185. return luaL_error(L, "invalid url_encode() call");
  1186. }
  1187. return 1;
  1188. }
  1189. /* mg.url_decode */
  1190. static int
  1191. lsp_url_decode(lua_State *L)
  1192. {
  1193. int num_args = lua_gettop(L);
  1194. const char *text;
  1195. size_t text_len;
  1196. int is_form;
  1197. char *dst;
  1198. int dst_len;
  1199. struct mg_context *ctx;
  1200. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1201. lua_gettable(L, LUA_REGISTRYINDEX);
  1202. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1203. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  1204. text = lua_tolstring(L, 1, &text_len);
  1205. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  1206. if (text) {
  1207. dst_len = (int)text_len + 1;
  1208. dst = ((text_len < 0x7FFFFFFF) ? (char *)mg_malloc_ctx(dst_len, ctx)
  1209. : (char *)NULL);
  1210. if (dst) {
  1211. mg_url_decode(text, (int)text_len, dst, dst_len, is_form);
  1212. lua_pushstring(L, dst);
  1213. mg_free(dst);
  1214. } else {
  1215. return luaL_error(L, "out of memory in url_decode() call");
  1216. }
  1217. } else {
  1218. lua_pushnil(L);
  1219. }
  1220. } else {
  1221. /* Syntax error */
  1222. return luaL_error(L, "invalid url_decode() call");
  1223. }
  1224. return 1;
  1225. }
  1226. /* mg.base64_encode */
  1227. static int
  1228. lsp_base64_encode(lua_State *L)
  1229. {
  1230. int num_args = lua_gettop(L);
  1231. const char *text;
  1232. size_t text_len;
  1233. char *dst;
  1234. struct mg_context *ctx;
  1235. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1236. lua_gettable(L, LUA_REGISTRYINDEX);
  1237. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1238. if (num_args == 1) {
  1239. text = lua_tolstring(L, 1, &text_len);
  1240. if (text) {
  1241. dst = (char *)mg_malloc_ctx(text_len * 8 / 6 + 4, ctx);
  1242. if (dst) {
  1243. base64_encode((const unsigned char *)text, (int)text_len, dst);
  1244. lua_pushstring(L, dst);
  1245. mg_free(dst);
  1246. } else {
  1247. return luaL_error(L, "out of memory in base64_encode() call");
  1248. }
  1249. } else {
  1250. lua_pushnil(L);
  1251. }
  1252. } else {
  1253. /* Syntax error */
  1254. return luaL_error(L, "invalid base64_encode() call");
  1255. }
  1256. return 1;
  1257. }
  1258. /* mg.base64_encode */
  1259. static int
  1260. lsp_base64_decode(lua_State *L)
  1261. {
  1262. int num_args = lua_gettop(L);
  1263. const char *text;
  1264. size_t text_len, dst_len;
  1265. int ret;
  1266. char *dst;
  1267. struct mg_context *ctx;
  1268. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1269. lua_gettable(L, LUA_REGISTRYINDEX);
  1270. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1271. if (num_args == 1) {
  1272. text = lua_tolstring(L, 1, &text_len);
  1273. if (text) {
  1274. dst = (char *)mg_malloc_ctx(text_len, ctx);
  1275. if (dst) {
  1276. ret = base64_decode((const unsigned char *)text,
  1277. (int)text_len,
  1278. dst,
  1279. &dst_len);
  1280. if (ret != -1) {
  1281. mg_free(dst);
  1282. return luaL_error(
  1283. L, "illegal character in lsp_base64_decode() call");
  1284. } else {
  1285. lua_pushlstring(L, dst, dst_len);
  1286. mg_free(dst);
  1287. }
  1288. } else {
  1289. return luaL_error(L,
  1290. "out of memory in lsp_base64_decode() call");
  1291. }
  1292. } else {
  1293. lua_pushnil(L);
  1294. }
  1295. } else {
  1296. /* Syntax error */
  1297. return luaL_error(L, "invalid lsp_base64_decode() call");
  1298. }
  1299. return 1;
  1300. }
  1301. /* mg.get_response_code_text */
  1302. static int
  1303. lsp_get_response_code_text(lua_State *L)
  1304. {
  1305. int num_args = lua_gettop(L);
  1306. int type1;
  1307. double code;
  1308. const char *text;
  1309. if (num_args == 1) {
  1310. type1 = lua_type(L, 1);
  1311. if (type1 == LUA_TNUMBER) {
  1312. /* If the first argument is a number,
  1313. convert it to the corresponding text. */
  1314. code = lua_tonumber(L, 1);
  1315. text = mg_get_response_code_text(NULL, (int)code);
  1316. if (text) { /* <-- should be always true */
  1317. lua_pushstring(L, text);
  1318. }
  1319. return text ? 1 : 0;
  1320. }
  1321. }
  1322. /* Syntax error */
  1323. return luaL_error(L, "invalid get_response_code_text() call");
  1324. }
  1325. /* mg.random - might be better than math.random on some systems */
  1326. static int
  1327. lsp_random(lua_State *L)
  1328. {
  1329. int num_args = lua_gettop(L);
  1330. if (num_args == 0) {
  1331. /* The civetweb internal random number generator will generate
  1332. * a 64 bit random number. */
  1333. uint64_t r = get_random();
  1334. /* Lua "number" is a IEEE 754 double precission float:
  1335. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  1336. * Thus, mask with 2^53-1 to get an integer with the maximum
  1337. * precission available. */
  1338. r &= ((((uint64_t)1) << 53) - 1);
  1339. lua_pushnumber(L, (double)r);
  1340. return 1;
  1341. }
  1342. /* Syntax error */
  1343. return luaL_error(L, "invalid random() call");
  1344. }
  1345. /* mg.get_info */
  1346. static int
  1347. lsp_get_info(lua_State *L)
  1348. {
  1349. int num_args = lua_gettop(L);
  1350. int type1, type2;
  1351. const char *arg1;
  1352. double arg2;
  1353. int len;
  1354. char *buf;
  1355. if (num_args == 1) {
  1356. type1 = lua_type(L, 1);
  1357. if (type1 == LUA_TSTRING) {
  1358. arg1 = lua_tostring(L, 1);
  1359. /* Get info according to argument */
  1360. if (!mg_strcasecmp(arg1, "system")) {
  1361. /* Get system info */
  1362. len = mg_get_system_info(NULL, 0);
  1363. if (len > 0) {
  1364. buf = (char *)mg_malloc(len + 64);
  1365. if (!buf) {
  1366. return luaL_error(L, "OOM in get_info() call");
  1367. }
  1368. len = mg_get_system_info(buf, len + 63);
  1369. lua_pushlstring(L, buf, len);
  1370. mg_free(buf);
  1371. } else {
  1372. lua_pushstring(L, "");
  1373. }
  1374. return 1;
  1375. }
  1376. if (!mg_strcasecmp(arg1, "context")) {
  1377. /* Get context */
  1378. struct mg_context *ctx;
  1379. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1380. lua_gettable(L, LUA_REGISTRYINDEX);
  1381. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1382. /* Get context info for server context */
  1383. len = mg_get_context_info(ctx, NULL, 0);
  1384. if (len > 0) {
  1385. buf = (char *)mg_malloc(len + 64);
  1386. if (!buf) {
  1387. return luaL_error(L, "OOM in get_info() call");
  1388. }
  1389. len = mg_get_context_info(ctx, buf, len + 63);
  1390. lua_pushlstring(L, buf, len);
  1391. mg_free(buf);
  1392. } else {
  1393. lua_pushstring(L, "");
  1394. }
  1395. return 1;
  1396. }
  1397. if (!mg_strcasecmp(arg1, "common")) {
  1398. /* Get context info for NULL context */
  1399. len = mg_get_context_info(NULL, NULL, 0);
  1400. if (len > 0) {
  1401. buf = (char *)mg_malloc(len + 64);
  1402. if (!buf) {
  1403. return luaL_error(L, "OOM in get_info() call");
  1404. }
  1405. len = mg_get_context_info(NULL, buf, len + 63);
  1406. lua_pushlstring(L, buf, len);
  1407. mg_free(buf);
  1408. } else {
  1409. lua_pushstring(L, "");
  1410. }
  1411. return 1;
  1412. }
  1413. return 0;
  1414. }
  1415. }
  1416. if (num_args == 2) {
  1417. type1 = lua_type(L, 1);
  1418. type2 = lua_type(L, 2);
  1419. if ((type1 == LUA_TSTRING) && (type2 == LUA_TNUMBER)) {
  1420. arg1 = lua_tostring(L, 1);
  1421. arg2 = lua_tonumber(L, 2);
  1422. /* Get info according to argument */
  1423. if (!mg_strcasecmp(arg1, "connection")) {
  1424. int idx;
  1425. /* Get context */
  1426. struct mg_context *ctx;
  1427. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1428. lua_gettable(L, LUA_REGISTRYINDEX);
  1429. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1430. /* Get connection info for connection idx */
  1431. idx = (int)(arg2 + 0.5);
  1432. /* Lua uses 1 based index, C uses 0 based index */
  1433. idx--;
  1434. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1435. len = mg_get_connection_info(ctx, idx, NULL, 0);
  1436. if (len > 0) {
  1437. buf = (char *)mg_malloc(len + 64);
  1438. if (!buf) {
  1439. return luaL_error(L, "OOM in get_info() call");
  1440. }
  1441. len = mg_get_connection_info(ctx, idx, buf, len + 63);
  1442. lua_pushlstring(L, buf, len);
  1443. mg_free(buf);
  1444. } else {
  1445. lua_pushstring(L, "");
  1446. }
  1447. #else
  1448. (void)ctx;
  1449. (void)idx;
  1450. lua_pushstring(L, "");
  1451. #endif
  1452. return 1;
  1453. }
  1454. return 0;
  1455. }
  1456. }
  1457. /* Syntax error */
  1458. return luaL_error(L, "invalid get_info() call");
  1459. }
  1460. /* mg.get_option */
  1461. static int
  1462. lsp_get_option(lua_State *L)
  1463. {
  1464. int num_args = lua_gettop(L);
  1465. int type1;
  1466. const char *arg1;
  1467. const char *data;
  1468. int optidx;
  1469. /* Get connection */
  1470. struct mg_connection *conn =
  1471. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1472. if (num_args == 0) {
  1473. const struct mg_option *opts = mg_get_valid_options();
  1474. if (!opts) { /* <-- should be always false */
  1475. return 0;
  1476. }
  1477. lua_newtable(L);
  1478. while (opts->name) {
  1479. optidx = get_option_index(opts->name);
  1480. if (optidx >= 0) {
  1481. data = conn->dom_ctx->config[optidx];
  1482. if (data) {
  1483. reg_string(L, opts->name, data);
  1484. }
  1485. }
  1486. opts++;
  1487. }
  1488. return 1;
  1489. }
  1490. if (num_args == 1) {
  1491. type1 = lua_type(L, 1);
  1492. if (type1 == LUA_TSTRING) {
  1493. arg1 = lua_tostring(L, 1);
  1494. /* Get option according to argument */
  1495. optidx = get_option_index(arg1);
  1496. if (optidx >= 0) {
  1497. data = conn->dom_ctx->config[optidx];
  1498. if (data) {
  1499. lua_pushstring(L, data);
  1500. return 1;
  1501. }
  1502. }
  1503. return 0;
  1504. }
  1505. }
  1506. /* Syntax error */
  1507. return luaL_error(L, "invalid get_option() call");
  1508. }
  1509. static int s_lua_traceLevel = 1;
  1510. static FILE *s_lua_traceFile = NULL;
  1511. static pthread_mutex_t s_lua_traceMutex;
  1512. /* mg.trace */
  1513. static int
  1514. lsp_trace(lua_State *L)
  1515. {
  1516. int num_args = lua_gettop(L);
  1517. int arg_type[8];
  1518. int trace_level = 0;
  1519. int firstarg = 1;
  1520. int i;
  1521. for (i = 0; i < 8; i++) {
  1522. if (num_args >= (i + 1)) {
  1523. arg_type[i] = lua_type(L, (i + 1));
  1524. } else {
  1525. arg_type[i] = LUA_TNIL;
  1526. }
  1527. }
  1528. if (arg_type[0] == LUA_TNUMBER) {
  1529. trace_level = (int)lua_tointeger(L, 1);
  1530. if (num_args == 1) {
  1531. /* Set a new trace level, return the current one. */
  1532. lua_pushinteger(L, s_lua_traceLevel);
  1533. s_lua_traceLevel = trace_level;
  1534. if (s_lua_traceFile) {
  1535. pthread_mutex_lock(&s_lua_traceMutex);
  1536. fflush(s_lua_traceFile);
  1537. pthread_mutex_unlock(&s_lua_traceMutex);
  1538. }
  1539. return 1;
  1540. }
  1541. firstarg = 2;
  1542. }
  1543. if (trace_level > s_lua_traceLevel) {
  1544. /* If this trace request has a higher trace level than the global trace
  1545. * level, do not trace. */
  1546. lua_pushboolean(L, 0);
  1547. return 1;
  1548. }
  1549. /* Print to file */
  1550. if (s_lua_traceFile) {
  1551. pthread_mutex_lock(&s_lua_traceMutex);
  1552. for (i = firstarg; i <= num_args; i++) {
  1553. if (arg_type[i - 1] == LUA_TSTRING) {
  1554. const char *arg = lua_tostring(L, i);
  1555. fprintf(s_lua_traceFile, "%s\n", arg);
  1556. }
  1557. }
  1558. pthread_mutex_unlock(&s_lua_traceMutex);
  1559. }
  1560. lua_pushboolean(L, 1);
  1561. return 1;
  1562. }
  1563. /* UUID library and function pointer */
  1564. union {
  1565. void *p;
  1566. void (*f)(unsigned char uuid[16]);
  1567. } pf_uuid_generate;
  1568. /* mg.uuid */
  1569. static int
  1570. lsp_uuid(lua_State *L)
  1571. {
  1572. union {
  1573. unsigned char uuid_array[16];
  1574. struct uuid_struct_type {
  1575. uint32_t data1;
  1576. uint16_t data2;
  1577. uint16_t data3;
  1578. uint8_t data4[8];
  1579. } uuid_struct;
  1580. } uuid;
  1581. char uuid_str[40];
  1582. int num_args = lua_gettop(L);
  1583. memset(&uuid, 0, sizeof(uuid));
  1584. memset(uuid_str, 0, sizeof(uuid_str));
  1585. if (num_args == 0) {
  1586. pf_uuid_generate.f(uuid.uuid_array);
  1587. sprintf(uuid_str,
  1588. "{%08lX-%04X-%04X-%02X%02X-"
  1589. "%02X%02X%02X%02X%02X%02X}",
  1590. (unsigned long)uuid.uuid_struct.data1,
  1591. (unsigned)uuid.uuid_struct.data2,
  1592. (unsigned)uuid.uuid_struct.data3,
  1593. (unsigned)uuid.uuid_struct.data4[0],
  1594. (unsigned)uuid.uuid_struct.data4[1],
  1595. (unsigned)uuid.uuid_struct.data4[2],
  1596. (unsigned)uuid.uuid_struct.data4[3],
  1597. (unsigned)uuid.uuid_struct.data4[4],
  1598. (unsigned)uuid.uuid_struct.data4[5],
  1599. (unsigned)uuid.uuid_struct.data4[6],
  1600. (unsigned)uuid.uuid_struct.data4[7]);
  1601. lua_pushstring(L, uuid_str);
  1602. return 1;
  1603. }
  1604. /* Syntax error */
  1605. return luaL_error(L, "invalid random() call");
  1606. }
  1607. #if defined(USE_WEBSOCKET)
  1608. struct lua_websock_data {
  1609. lua_State *state;
  1610. char *script;
  1611. unsigned references;
  1612. struct mg_connection *conn[MAX_WORKER_THREADS];
  1613. pthread_mutex_t ws_mutex;
  1614. };
  1615. #endif
  1616. /* mg.write for websockets */
  1617. static int
  1618. lwebsock_write(lua_State *L)
  1619. {
  1620. #if defined(USE_WEBSOCKET)
  1621. int num_args = lua_gettop(L);
  1622. struct lua_websock_data *ws;
  1623. const char *str;
  1624. size_t size;
  1625. int opcode = -1;
  1626. unsigned i;
  1627. struct mg_connection *client = NULL;
  1628. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1629. lua_gettable(L, LUA_REGISTRYINDEX);
  1630. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1631. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1632. if (num_args == 1) {
  1633. /* just one text: send it to all client */
  1634. if (lua_isstring(L, 1)) {
  1635. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1636. }
  1637. } else if (num_args == 2) {
  1638. if (lua_isnumber(L, 1)) {
  1639. /* opcode number and message text */
  1640. opcode = (int)lua_tointeger(L, 1);
  1641. } else if (lua_isstring(L, 1)) {
  1642. /* opcode string and message text */
  1643. str = lua_tostring(L, 1);
  1644. if (!mg_strncasecmp(str, "text", 4))
  1645. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1646. else if (!mg_strncasecmp(str, "bin", 3))
  1647. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1648. else if (!mg_strncasecmp(str, "close", 5))
  1649. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1650. else if (!mg_strncasecmp(str, "ping", 4))
  1651. opcode = MG_WEBSOCKET_OPCODE_PING;
  1652. else if (!mg_strncasecmp(str, "pong", 4))
  1653. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1654. else if (!mg_strncasecmp(str, "cont", 4))
  1655. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1656. } else if (lua_isuserdata(L, 1)) {
  1657. /* client id and message text */
  1658. client = (struct mg_connection *)lua_touserdata(L, 1);
  1659. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1660. }
  1661. } else if (num_args == 3) {
  1662. if (lua_isuserdata(L, 1)) {
  1663. client = (struct mg_connection *)lua_touserdata(L, 1);
  1664. if (lua_isnumber(L, 2)) {
  1665. /* client id, opcode number and message text */
  1666. opcode = (int)lua_tointeger(L, 2);
  1667. } else if (lua_isstring(L, 2)) {
  1668. /* client id, opcode string and message text */
  1669. str = lua_tostring(L, 2);
  1670. if (!mg_strncasecmp(str, "text", 4))
  1671. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1672. else if (!mg_strncasecmp(str, "bin", 3))
  1673. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1674. else if (!mg_strncasecmp(str, "close", 5))
  1675. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1676. else if (!mg_strncasecmp(str, "ping", 4))
  1677. opcode = MG_WEBSOCKET_OPCODE_PING;
  1678. else if (!mg_strncasecmp(str, "pong", 4))
  1679. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1680. else if (!mg_strncasecmp(str, "cont", 4))
  1681. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1682. }
  1683. }
  1684. }
  1685. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  1686. str = lua_tolstring(L, num_args, &size);
  1687. if (client) {
  1688. for (i = 0; i < ws->references; i++) {
  1689. if (client == ws->conn[i]) {
  1690. mg_lock_connection(ws->conn[i]);
  1691. mg_websocket_write(ws->conn[i], opcode, str, size);
  1692. mg_unlock_connection(ws->conn[i]);
  1693. }
  1694. }
  1695. } else {
  1696. for (i = 0; i < ws->references; i++) {
  1697. mg_lock_connection(ws->conn[i]);
  1698. mg_websocket_write(ws->conn[i], opcode, str, size);
  1699. mg_unlock_connection(ws->conn[i]);
  1700. }
  1701. }
  1702. } else {
  1703. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1704. return luaL_error(L, "invalid websocket write() call");
  1705. }
  1706. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1707. #else
  1708. (void)(L); /* unused */
  1709. #endif
  1710. return 0;
  1711. }
  1712. struct laction_string_arg {
  1713. lua_State *L;
  1714. const char *script;
  1715. pthread_mutex_t *pmutex;
  1716. char txt[1];
  1717. };
  1718. struct laction_funcref_arg {
  1719. lua_State *L;
  1720. const char *script;
  1721. pthread_mutex_t *pmutex;
  1722. int funcref;
  1723. };
  1724. static int
  1725. lua_action_string(struct laction_string_arg *arg)
  1726. {
  1727. int err, ok;
  1728. struct mg_context *ctx;
  1729. (void)pthread_mutex_lock(arg->pmutex);
  1730. lua_pushlightuserdata(arg->L, (void *)&lua_regkey_ctx);
  1731. lua_gettable(arg->L, LUA_REGISTRYINDEX);
  1732. ctx = (struct mg_context *)lua_touserdata(arg->L, -1);
  1733. lua_pop(arg->L, 1);
  1734. err = luaL_loadstring(arg->L, arg->txt);
  1735. if (err != 0) {
  1736. struct mg_connection fc;
  1737. lua_cry(fake_connection(&fc, ctx), err, arg->L, arg->script, "timer");
  1738. (void)pthread_mutex_unlock(arg->pmutex);
  1739. return 0;
  1740. }
  1741. err = lua_pcall(arg->L, 0, 1, 0);
  1742. if (err != 0) {
  1743. struct mg_connection fc;
  1744. lua_cry(fake_connection(&fc, ctx), err, arg->L, arg->script, "timer");
  1745. (void)pthread_mutex_unlock(arg->pmutex);
  1746. return 0;
  1747. }
  1748. ok = lua_type(arg->L, -1);
  1749. if (lua_isboolean(arg->L, -1)) {
  1750. ok = lua_toboolean(arg->L, -1);
  1751. } else {
  1752. ok = 0;
  1753. }
  1754. lua_pop(arg->L, 1);
  1755. (void)pthread_mutex_unlock(arg->pmutex);
  1756. return ok;
  1757. }
  1758. static int
  1759. lua_action_funcref(struct laction_funcref_arg *arg)
  1760. {
  1761. int err, ok;
  1762. struct mg_context *ctx;
  1763. (void)pthread_mutex_lock(arg->pmutex);
  1764. lua_pushlightuserdata(arg->L, (void *)&lua_regkey_ctx);
  1765. lua_gettable(arg->L, LUA_REGISTRYINDEX);
  1766. ctx = (struct mg_context *)lua_touserdata(arg->L, -1);
  1767. lua_pop(arg->L, 1);
  1768. lua_rawgeti(arg->L, LUA_REGISTRYINDEX, arg->funcref);
  1769. err = lua_pcall(arg->L, 0, 1, 0);
  1770. if (err != 0) {
  1771. struct mg_connection fc;
  1772. lua_cry(fake_connection(&fc, ctx), err, arg->L, arg->script, "timer");
  1773. (void)pthread_mutex_unlock(arg->pmutex);
  1774. return 0;
  1775. }
  1776. ok = lua_type(arg->L, -1);
  1777. if (lua_isboolean(arg->L, -1)) {
  1778. ok = lua_toboolean(arg->L, -1);
  1779. } else {
  1780. ok = 0;
  1781. }
  1782. lua_pop(arg->L, 1);
  1783. (void)pthread_mutex_unlock(arg->pmutex);
  1784. return ok;
  1785. }
  1786. static void
  1787. lua_action_string_cancel(struct laction_string_arg *arg)
  1788. {
  1789. mg_free(arg);
  1790. }
  1791. static void
  1792. lua_action_funcref_cancel(struct laction_funcref_arg *arg)
  1793. {
  1794. luaL_unref(arg->L, LUA_REGISTRYINDEX, arg->funcref);
  1795. mg_free(arg);
  1796. }
  1797. static int
  1798. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1799. {
  1800. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1801. int num_args = lua_gettop(L);
  1802. struct lua_websock_data *ws;
  1803. int type1, type2, type3, ok = 0;
  1804. double delay, interval;
  1805. struct mg_context *ctx;
  1806. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1807. lua_gettable(L, LUA_REGISTRYINDEX);
  1808. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1809. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1810. lua_gettable(L, LUA_REGISTRYINDEX);
  1811. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1812. if (num_args < 2) {
  1813. return luaL_error(L,
  1814. "not enough arguments for set_timer/interval() call");
  1815. }
  1816. type1 = lua_type(L, 1);
  1817. type2 = lua_type(L, 2);
  1818. type3 = lua_type(L, 3);
  1819. /* Must have at least two arguments, ant the first one has to be some text
  1820. */
  1821. if ((num_args < 2) || (num_args > 3)) {
  1822. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1823. }
  1824. /* Second argument is the delay (and interval) */
  1825. if (type2 != LUA_TNUMBER) {
  1826. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1827. }
  1828. delay = (double)lua_tonumber(L, 2);
  1829. interval = (is_periodic ? delay : 0.0);
  1830. /* Third argument (optional) could be an interval */
  1831. if (num_args > 2) {
  1832. if (is_periodic || (type3 != LUA_TNUMBER)) {
  1833. return luaL_error(
  1834. L, "invalid arguments for set_timer/interval() call");
  1835. }
  1836. interval = (double)lua_tonumber(L, 3);
  1837. }
  1838. /* Check numbers */
  1839. if ((delay < 0.0) || (interval < 0.0)) {
  1840. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1841. }
  1842. /* First value specifies the action */
  1843. if (type1 == LUA_TSTRING) {
  1844. /* Action could be passed as a string value */
  1845. struct laction_string_arg *arg;
  1846. const char *action_txt;
  1847. size_t action_txt_len;
  1848. action_txt = lua_tostring(L, 1);
  1849. if ((action_txt == NULL) || (action_txt[0] == 0)) {
  1850. return luaL_error(
  1851. L, "invalid arguments for set_timer/interval() call");
  1852. }
  1853. action_txt_len = strlen(action_txt);
  1854. /* Create timer data structure and schedule timer */
  1855. arg = (struct laction_string_arg *)mg_malloc_ctx(
  1856. sizeof(struct laction_string_arg) + action_txt_len + 10, ctx);
  1857. if (!arg) {
  1858. return luaL_error(L, "out of memory");
  1859. }
  1860. /* Argument for timer */
  1861. arg->L = L;
  1862. arg->script = ws->script;
  1863. arg->pmutex = &(ws->ws_mutex);
  1864. memcpy(arg->txt, "return(", 7);
  1865. memcpy(arg->txt + 7, action_txt, action_txt_len);
  1866. arg->txt[action_txt_len + 7] = ')';
  1867. arg->txt[action_txt_len + 8] = 0;
  1868. if (0
  1869. == timer_add(ctx,
  1870. delay,
  1871. interval,
  1872. 1,
  1873. (taction)lua_action_string,
  1874. (void *)arg,
  1875. (tcancelaction)lua_action_string_cancel)) {
  1876. /* Timer added successfully */
  1877. ok = 1;
  1878. }
  1879. } else if (type1 == LUA_TFUNCTION) {
  1880. /* Action could be passed as a function */
  1881. int funcref;
  1882. struct laction_funcref_arg *arg;
  1883. lua_pushvalue(L, 1);
  1884. funcref = luaL_ref(L, LUA_REGISTRYINDEX);
  1885. /* Create timer data structure and schedule timer */
  1886. arg = (struct laction_funcref_arg *)
  1887. mg_malloc_ctx(sizeof(struct laction_funcref_arg), ctx);
  1888. if (!arg) {
  1889. return luaL_error(L, "out of memory");
  1890. }
  1891. /* Argument for timer */
  1892. arg->L = L;
  1893. arg->script = ws->script;
  1894. arg->pmutex = &(ws->ws_mutex);
  1895. arg->funcref = funcref;
  1896. if (0
  1897. == timer_add(ctx,
  1898. delay,
  1899. interval,
  1900. 1,
  1901. (taction)lua_action_funcref,
  1902. (void *)arg,
  1903. (tcancelaction)lua_action_funcref_cancel)) {
  1904. /* Timer added successfully */
  1905. ok = 1;
  1906. }
  1907. } else {
  1908. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1909. }
  1910. lua_pushboolean(L, ok);
  1911. return 1;
  1912. #else
  1913. (void)(L); /* unused */
  1914. (void)(is_periodic); /* unused */
  1915. return 0;
  1916. #endif
  1917. }
  1918. /* mg.set_timeout for websockets */
  1919. static int
  1920. lwebsocket_set_timeout(lua_State *L)
  1921. {
  1922. return lwebsocket_set_timer(L, 0);
  1923. }
  1924. /* mg.set_interval for websockets */
  1925. static int
  1926. lwebsocket_set_interval(lua_State *L)
  1927. {
  1928. return lwebsocket_set_timer(L, 1);
  1929. }
  1930. /* Debug hook */
  1931. static void
  1932. lua_debug_hook(lua_State *L, lua_Debug *ar)
  1933. {
  1934. int i;
  1935. int stack_len = lua_gettop(L);
  1936. lua_getinfo(L, "nSlu", ar);
  1937. if (ar->event == LUA_HOOKCALL) {
  1938. printf("call\n");
  1939. } else if (ar->event == LUA_HOOKRET) {
  1940. printf("ret\n");
  1941. #if defined(LUA_HOOKTAILRET)
  1942. } else if (ar->event == LUA_HOOKTAILRET) {
  1943. printf("tail ret\n");
  1944. #endif
  1945. #if defined(LUA_HOOKTAILCALL)
  1946. } else if (ar->event == LUA_HOOKTAILCALL) {
  1947. printf("tail call\n");
  1948. #endif
  1949. } else if (ar->event == LUA_HOOKLINE) {
  1950. printf("line\n");
  1951. } else if (ar->event == LUA_HOOKCOUNT) {
  1952. printf("count\n");
  1953. } else {
  1954. printf("unknown (%i)\n", ar->event);
  1955. }
  1956. if (ar->currentline >= 0) {
  1957. printf("%s:%i\n", ar->source, ar->currentline);
  1958. }
  1959. printf("%s (%s)\n", ar->name, ar->namewhat);
  1960. for (i = 1; i <= stack_len; i++) { /* repeat for each level */
  1961. int val_type = lua_type(L, i);
  1962. const char *s;
  1963. size_t n;
  1964. switch (val_type) {
  1965. case LUA_TNIL:
  1966. /* nil value on the stack */
  1967. printf("nil\n");
  1968. break;
  1969. case LUA_TBOOLEAN:
  1970. /* boolean (true / false) */
  1971. printf("boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
  1972. break;
  1973. case LUA_TNUMBER:
  1974. /* number */
  1975. printf("number: %g\n", lua_tonumber(L, i));
  1976. break;
  1977. case LUA_TSTRING:
  1978. /* string with limited length */
  1979. s = lua_tolstring(L, i, &n);
  1980. printf("string: '%.*s%s\n",
  1981. ((n > 30) ? 28 : (int)n),
  1982. s,
  1983. ((n > 30) ? ".." : "'"));
  1984. break;
  1985. default:
  1986. /* other values */
  1987. printf("%s\n", lua_typename(L, val_type));
  1988. break;
  1989. }
  1990. }
  1991. printf("\n");
  1992. }
  1993. /* Lua Environment */
  1994. enum {
  1995. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1996. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1997. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1998. };
  1999. static void
  2000. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  2001. {
  2002. const char *s;
  2003. int i;
  2004. /* Export mg.request_info */
  2005. lua_pushstring(L, "request_info");
  2006. lua_newtable(L);
  2007. reg_string(L, "request_method", conn->request_info.request_method);
  2008. reg_string(L, "request_uri", conn->request_info.request_uri);
  2009. reg_string(L, "uri", conn->request_info.local_uri);
  2010. reg_string(L, "http_version", conn->request_info.http_version);
  2011. reg_string(L, "query_string", conn->request_info.query_string);
  2012. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  2013. /* TODO (high): ip version */
  2014. reg_int(L, "remote_port", conn->request_info.remote_port);
  2015. reg_int(L, "num_headers", conn->request_info.num_headers);
  2016. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  2017. if (conn->path_info != NULL) {
  2018. reg_string(L, "path_info", conn->path_info);
  2019. }
  2020. if (conn->request_info.content_length >= 0) {
  2021. /* reg_int64: content_length */
  2022. lua_pushstring(L, "content_length");
  2023. lua_pushnumber(
  2024. L,
  2025. (lua_Number)conn->request_info
  2026. .content_length); /* lua_Number may be used as 52 bit integer */
  2027. lua_rawset(L, -3);
  2028. }
  2029. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  2030. reg_string(L, "content_type", s);
  2031. }
  2032. if (conn->request_info.remote_user != NULL) {
  2033. reg_string(L, "remote_user", conn->request_info.remote_user);
  2034. reg_string(L, "auth_type", "Digest");
  2035. }
  2036. reg_boolean(L, "https", conn->ssl != NULL);
  2037. if (conn->status_code > 0) {
  2038. /* Lua error handler should show the status code */
  2039. reg_int(L, "status", conn->status_code);
  2040. }
  2041. /* Table "HTTP headers" */
  2042. lua_pushstring(L, "http_headers");
  2043. lua_newtable(L);
  2044. for (i = 0; i < conn->request_info.num_headers; i++) {
  2045. reg_string(L,
  2046. conn->request_info.http_headers[i].name,
  2047. conn->request_info.http_headers[i].value);
  2048. }
  2049. lua_rawset(L, -3);
  2050. /* Table "Client Certificate" */
  2051. if (conn->request_info.client_cert) {
  2052. lua_pushstring(L, "client_cert");
  2053. lua_newtable(L);
  2054. reg_string(L, "subject", conn->request_info.client_cert->subject);
  2055. reg_string(L, "issuer", conn->request_info.client_cert->issuer);
  2056. reg_string(L, "serial", conn->request_info.client_cert->serial);
  2057. reg_string(L, "finger", conn->request_info.client_cert->finger);
  2058. lua_rawset(L, -3);
  2059. }
  2060. /* End of request_info */
  2061. lua_rawset(L, -3);
  2062. }
  2063. static void *
  2064. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  2065. {
  2066. (void)osize; /* not used */
  2067. if (nsize == 0) {
  2068. mg_free(ptr);
  2069. return NULL;
  2070. }
  2071. return mg_realloc_ctx(ptr, nsize, (struct mg_context *)ud);
  2072. }
  2073. /* In CivetWeb, Lua-Shared is used as *.inl file */
  2074. #define LUA_SHARED_INTERFACE static
  2075. #include "mod_lua_shared.inl"
  2076. static void
  2077. civetweb_open_lua_libs(lua_State *L)
  2078. {
  2079. {
  2080. extern void luaL_openlibs(lua_State *);
  2081. luaL_openlibs(L);
  2082. }
  2083. #if defined(USE_LUA_SQLITE3)
  2084. {
  2085. extern int luaopen_lsqlite3(lua_State *);
  2086. luaopen_lsqlite3(L);
  2087. }
  2088. #endif
  2089. #if defined(USE_LUA_LUAXML)
  2090. {
  2091. extern int luaopen_LuaXML_lib(lua_State *);
  2092. luaopen_LuaXML_lib(L);
  2093. // lua_pushvalue(L, -1); to copy value
  2094. lua_setglobal(L, "xml");
  2095. }
  2096. #endif
  2097. #if defined(USE_LUA_FILE_SYSTEM)
  2098. {
  2099. extern int luaopen_lfs(lua_State *);
  2100. luaopen_lfs(L);
  2101. }
  2102. #endif
  2103. }
  2104. /* garbage collect "mg"
  2105. * this indicates when a Lua state is closed
  2106. */
  2107. static int
  2108. lsp_mg_gc(lua_State *L)
  2109. {
  2110. unsigned context_flags;
  2111. struct mg_context *ctx;
  2112. struct mg_connection *conn =
  2113. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  2114. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  2115. lua_gettable(L, LUA_REGISTRYINDEX);
  2116. ctx = (struct mg_context *)lua_touserdata(L, -1);
  2117. lua_pushlightuserdata(L, (void *)&lua_regkey_environment_type);
  2118. lua_gettable(L, LUA_REGISTRYINDEX);
  2119. context_flags = lua_tounsigned(L, -1);
  2120. if (ctx != NULL) {
  2121. if (ctx->callbacks.exit_lua != NULL) {
  2122. ctx->callbacks.exit_lua(conn, L, context_flags);
  2123. }
  2124. }
  2125. return 0;
  2126. }
  2127. static void
  2128. reg_gc(lua_State *L, void *conn)
  2129. {
  2130. /* Key element */
  2131. lua_pushlightuserdata(L, (void *)&lua_regkey_dtor);
  2132. /* Value element */
  2133. lua_newuserdata(L, 0);
  2134. /* Prepare metatable for value element */
  2135. lua_newtable(L);
  2136. /* Add garbage collector key to metatable */
  2137. lua_pushliteral(L, "__gc");
  2138. /* Add garbage collector function with one upvalue (conn) */
  2139. lua_pushlightuserdata(L, conn);
  2140. lua_pushcclosure(L, lsp_mg_gc, 1);
  2141. /* Set __gc = function lsp_mg_gc in metatable */
  2142. lua_rawset(L, -3);
  2143. /* Set metatable for "value element" */
  2144. lua_setmetatable(L, -2);
  2145. /* Add key (lightuserdata) = value (userdata with metatable) */
  2146. lua_settable(L, LUA_REGISTRYINDEX);
  2147. }
  2148. static void
  2149. prepare_lua_environment(struct mg_context *ctx,
  2150. struct mg_connection *conn,
  2151. struct lua_websock_data *ws_conn_list,
  2152. lua_State *L,
  2153. const char *script_name,
  2154. int lua_env_type)
  2155. {
  2156. const char *preload_file_name = NULL;
  2157. const char *debug_params = NULL;
  2158. unsigned lua_context_flags = (unsigned)lua_env_type;
  2159. civetweb_open_lua_libs(L);
  2160. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2161. /* Check if debugging should be enabled */
  2162. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2163. debug_params = conn->dom_ctx->config[LUA_DEBUG_PARAMS];
  2164. }
  2165. #endif
  2166. #if LUA_VERSION_NUM == 502
  2167. /* Keep the "connect" method for compatibility,
  2168. * but do not backport it to Lua 5.1.
  2169. * TODO: Redesign the interface.
  2170. */
  2171. luaL_newmetatable(L, LUASOCKET);
  2172. /* self.__index = self */
  2173. lua_pushvalue(L, -1);
  2174. lua_setfield(L, -2, "__index");
  2175. luaL_setfuncs(L, luasocket_methods, 0);
  2176. lua_pop(L, 1);
  2177. lua_register(L, "connect", lsp_connect);
  2178. #endif
  2179. /* Store context in the registry */
  2180. if (ctx != NULL) {
  2181. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  2182. lua_pushlightuserdata(L, (void *)ctx);
  2183. lua_settable(L, LUA_REGISTRYINDEX);
  2184. }
  2185. if (ws_conn_list != NULL) {
  2186. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  2187. lua_pushlightuserdata(L, (void *)ws_conn_list);
  2188. lua_settable(L, LUA_REGISTRYINDEX);
  2189. }
  2190. lua_pushlightuserdata(L, (void *)&lua_regkey_environment_type);
  2191. lua_pushunsigned(L, (unsigned)lua_context_flags);
  2192. lua_settable(L, LUA_REGISTRYINDEX);
  2193. /* State close function */
  2194. reg_gc(L, conn);
  2195. /* Lua server pages store the depth of mg.include, in order
  2196. * to detect recursions and prevent stack overflows. */
  2197. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  2198. struct lsp_include_history *h;
  2199. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  2200. h = (struct lsp_include_history *)
  2201. lua_newuserdata(L, sizeof(struct lsp_include_history));
  2202. lua_settable(L, LUA_REGISTRYINDEX);
  2203. memset(h, 0, sizeof(struct lsp_include_history));
  2204. }
  2205. /* Register mg module */
  2206. lua_newtable(L);
  2207. switch (lua_env_type) {
  2208. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  2209. reg_string(L, "lua_type", "page");
  2210. break;
  2211. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  2212. reg_string(L, "lua_type", "script");
  2213. break;
  2214. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  2215. reg_string(L, "lua_type", "websocket");
  2216. break;
  2217. }
  2218. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  2219. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  2220. reg_conn_function(L, "cry", lsp_cry, conn);
  2221. reg_conn_function(L, "read", lsp_read, conn);
  2222. reg_conn_function(L, "write", lsp_write, conn);
  2223. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  2224. reg_conn_function(L, "send_file", lsp_send_file, conn);
  2225. reg_conn_function(L, "send_file_body", lsp_send_file_body, conn);
  2226. reg_conn_function(L, "send_http_error", lsp_send_http_error, conn);
  2227. reg_conn_function(L, "send_http_ok", lsp_send_http_ok, conn);
  2228. reg_conn_function(L, "redirect", lsp_redirect, conn);
  2229. }
  2230. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  2231. reg_conn_function(L, "include", lsp_include, conn);
  2232. }
  2233. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  2234. reg_function(L, "write", lwebsock_write);
  2235. #if defined(USE_TIMERS)
  2236. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  2237. reg_function(L, "set_interval", lwebsocket_set_interval);
  2238. #endif
  2239. }
  2240. reg_conn_function(L, "get_mime_type", lsp_get_mime_type, conn);
  2241. reg_conn_function(L, "get_option", lsp_get_option, conn);
  2242. reg_function(L, "time", lsp_get_time);
  2243. reg_function(L, "get_var", lsp_get_var);
  2244. reg_function(L, "split_form_data", lsp_split_form_urlencoded);
  2245. reg_function(L, "get_cookie", lsp_get_cookie);
  2246. reg_function(L, "md5", lsp_md5);
  2247. reg_function(L, "url_encode", lsp_url_encode);
  2248. reg_function(L, "url_decode", lsp_url_decode);
  2249. reg_function(L, "base64_encode", lsp_base64_encode);
  2250. reg_function(L, "base64_decode", lsp_base64_decode);
  2251. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  2252. reg_function(L, "random", lsp_random);
  2253. reg_function(L, "get_info", lsp_get_info);
  2254. reg_function(L, "trace", lsp_trace);
  2255. if (pf_uuid_generate.f) {
  2256. reg_function(L, "uuid", lsp_uuid);
  2257. }
  2258. reg_string(L, "version", CIVETWEB_VERSION);
  2259. reg_string(L, "script_name", script_name);
  2260. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2261. reg_string(L, "document_root", conn->dom_ctx->config[DOCUMENT_ROOT]);
  2262. reg_string(L,
  2263. "auth_domain",
  2264. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  2265. #if defined(USE_WEBSOCKET)
  2266. if (conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  2267. reg_string(L,
  2268. "websocket_root",
  2269. conn->dom_ctx->config[WEBSOCKET_ROOT]);
  2270. } else {
  2271. reg_string(L,
  2272. "websocket_root",
  2273. conn->dom_ctx->config[DOCUMENT_ROOT]);
  2274. }
  2275. #endif
  2276. if ((ctx != NULL) && (ctx->systemName != NULL)) {
  2277. reg_string(L, "system", ctx->systemName);
  2278. }
  2279. }
  2280. /* Export connection specific info */
  2281. if (conn != NULL) {
  2282. prepare_lua_request_info(conn, L);
  2283. }
  2284. /* Store as global table "mg" */
  2285. lua_setglobal(L, "mg");
  2286. /* Register "shared" table */
  2287. lua_shared_register(L);
  2288. /* Register default mg.onerror function */
  2289. IGNORE_UNUSED_RESULT(
  2290. luaL_dostring(L,
  2291. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  2292. "debug.traceback(e, 1)) end"));
  2293. /* Check if a preload file is available */
  2294. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2295. preload_file_name = conn->dom_ctx->config[LUA_PRELOAD_FILE];
  2296. }
  2297. /* Preload file into new Lua environment */
  2298. if (preload_file_name) {
  2299. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file_name));
  2300. }
  2301. /* Call user init function */
  2302. if (ctx != NULL) {
  2303. if (ctx->callbacks.init_lua != NULL) {
  2304. ctx->callbacks.init_lua(conn, L, lua_context_flags);
  2305. }
  2306. }
  2307. /* If debugging is enabled, add a hook */
  2308. if (debug_params) {
  2309. int mask = 0;
  2310. if (0 != strchr(debug_params, 'c')) {
  2311. mask |= LUA_MASKCALL;
  2312. }
  2313. if (0 != strchr(debug_params, 'r')) {
  2314. mask |= LUA_MASKRET;
  2315. }
  2316. if (0 != strchr(debug_params, 'l')) {
  2317. mask |= LUA_MASKLINE;
  2318. }
  2319. lua_sethook(L, lua_debug_hook, mask, 0);
  2320. }
  2321. }
  2322. static int
  2323. lua_error_handler(lua_State *L)
  2324. {
  2325. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  2326. lua_getglobal(L, "mg");
  2327. if (!lua_isnil(L, -1)) {
  2328. lua_getfield(L, -1, "write"); /* call mg.write() */
  2329. lua_pushstring(L, error_msg);
  2330. lua_pushliteral(L, "\n");
  2331. lua_call(L, 2, 0);
  2332. IGNORE_UNUSED_RESULT(
  2333. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  2334. } else {
  2335. printf("Lua error: [%s]\n", error_msg);
  2336. IGNORE_UNUSED_RESULT(
  2337. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  2338. }
  2339. /* TODO(lsm, low): leave the stack balanced */
  2340. return 0;
  2341. }
  2342. static void
  2343. mg_exec_lua_script(struct mg_connection *conn,
  2344. const char *path,
  2345. const void **exports)
  2346. {
  2347. int i;
  2348. lua_State *L;
  2349. /* Assume the script does not support keep_alive. The script may change this
  2350. * by calling mg.keep_alive(true). */
  2351. conn->must_close = 1;
  2352. /* Execute a plain Lua script. */
  2353. if (path != NULL
  2354. && (L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx)))
  2355. != NULL) {
  2356. prepare_lua_environment(
  2357. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  2358. lua_pushcclosure(L, &lua_error_handler, 0);
  2359. if (exports != NULL) {
  2360. #if LUA_VERSION_NUM > 501
  2361. lua_pushglobaltable(L);
  2362. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2363. lua_CFunction func;
  2364. lua_pushstring(L, (const char *)(exports[i]));
  2365. *(const void **)(&func) = exports[i + 1];
  2366. lua_pushcclosure(L, func, 0);
  2367. lua_rawset(L, -3);
  2368. }
  2369. #else
  2370. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2371. lua_CFunction func;
  2372. const char *name = (const char *)(exports[i]);
  2373. *(const void **)(&func) = exports[i + 1];
  2374. lua_register(L, name, func);
  2375. }
  2376. #endif
  2377. }
  2378. if (luaL_loadfile(L, path) != 0) {
  2379. lua_error_handler(L);
  2380. }
  2381. lua_pcall(L, 0, 0, -2);
  2382. lua_close(L);
  2383. }
  2384. }
  2385. static int
  2386. handle_lsp_request(struct mg_connection *conn,
  2387. const char *path,
  2388. struct mg_file *filep,
  2389. struct lua_State *ls)
  2390. {
  2391. void *p = NULL;
  2392. lua_State *L = NULL;
  2393. struct lsp_include_history *include_history;
  2394. int error = 1;
  2395. int (*run_lsp)(struct mg_connection *,
  2396. const char *,
  2397. const char *,
  2398. int64_t,
  2399. lua_State *,
  2400. int);
  2401. const char *addr;
  2402. /* mg_fopen opens the file and sets the size accordingly */
  2403. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  2404. /* File not found or not accessible */
  2405. if (ls == NULL) {
  2406. mg_send_http_error(conn,
  2407. 500,
  2408. "Error: Cannot open script file %s",
  2409. path);
  2410. } else {
  2411. luaL_error(ls, "Cannot include [%s]: not found", path);
  2412. }
  2413. goto cleanup_handle_lsp_request;
  2414. }
  2415. /* Map file in memory (size is known). */
  2416. if ((p = mmap(NULL,
  2417. (size_t)filep->stat.size,
  2418. PROT_READ,
  2419. MAP_PRIVATE,
  2420. fileno(filep->access.fp),
  2421. 0))
  2422. == NULL) {
  2423. /* File was not already in memory, and mmap failed now.
  2424. * Since wi have no data, show an error. */
  2425. if (ls == NULL) {
  2426. /* No open Lua state - use generic error function */
  2427. mg_send_http_error(
  2428. conn,
  2429. 500,
  2430. "Error: Cannot open script\nFile %s can not be mapped",
  2431. path);
  2432. } else {
  2433. /* Lua state exists - use Lua error function */
  2434. luaL_error(ls,
  2435. "mmap(%s, %zu, %d): %s",
  2436. path,
  2437. (size_t)filep->stat.size,
  2438. fileno(filep->access.fp),
  2439. strerror(errno));
  2440. }
  2441. goto cleanup_handle_lsp_request;
  2442. }
  2443. /* File content is now memory mapped. Get mapping address. */
  2444. addr = (const char *)p;
  2445. /* Get a Lua state */
  2446. if (ls != NULL) {
  2447. /* We got a Lua state as argument. Use it! */
  2448. L = ls;
  2449. } else {
  2450. /* We need to create a Lua state. */
  2451. L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2452. if (L == NULL) {
  2453. /* We neither got a Lua state from the command line,
  2454. * nor did we succeed in creating our own state.
  2455. * Show an error, and stop further processing of this request. */
  2456. mg_send_http_error(
  2457. conn,
  2458. 500,
  2459. "%s",
  2460. "Error: Cannot execute script\nlua_newstate failed");
  2461. goto cleanup_handle_lsp_request;
  2462. }
  2463. /* New Lua state needs CivetWeb functions (e.g., the "mg" library). */
  2464. prepare_lua_environment(
  2465. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  2466. }
  2467. /* Get LSP include history table */
  2468. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  2469. lua_gettable(L, LUA_REGISTRYINDEX);
  2470. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  2471. /* Store script name and increment depth */
  2472. include_history->depth++;
  2473. include_history->script[include_history->depth] = path;
  2474. /* Lua state is ready to use now. */
  2475. /* Currently we have two different syntax options:
  2476. * Either "classic" CivetWeb syntax:
  2477. * <? code ?>
  2478. * <?= expression ?>
  2479. * Or "Kepler Syntax"
  2480. * https://keplerproject.github.io/cgilua/manual.html#templates
  2481. * <?lua chunk ?>
  2482. * <?lua= expression ?>
  2483. * <% chunk %>
  2484. * <%= expression %>
  2485. *
  2486. * Two important differences are:
  2487. * - In the "classic" CivetWeb syntax, the Lua Page had to send the HTTP
  2488. * response headers itself. So the first lines are usually something like
  2489. * HTTP/1.0 200 OK
  2490. * Content-Type: text/html
  2491. * followed by additional headers and an empty line, before the actual
  2492. * Lua page in HTML syntax with <? code ?> tags.
  2493. * The "Kepler"Syntax" does not send any HTTP header from the Lua Server
  2494. * Page, but starts directly with <html> code - so it cannot influence
  2495. * the HTTP response code, e.g., to send a 301 Moved Permanently.
  2496. * Due to this difference, the same *.lp file cannot be used with the
  2497. * same algorithm.
  2498. * - The "Kepler Syntax" used to allow mixtures of Lua and HTML inside an
  2499. * incomplete Lua block, e.g.:
  2500. * <lua? for i=1,10 do ?><li><%= key %></li><lua? end ?>
  2501. * This was not provided in "classic" CivetWeb syntax, but you had to use
  2502. * <? for i=1,10 do mg.write("<li>"..i.."</li>") end ?>
  2503. * instead. The parsing algorithm for "Kepler syntax" is more complex
  2504. * than for "classic" CivetWeb syntax - TODO: check timing/performance.
  2505. *
  2506. * CivetWeb now can use both parsing methods, but needs to know what
  2507. * parsing algorithm should be used.
  2508. * Idea: Files starting with '<' are HTML files in "Kepler Syntax", except
  2509. * "<?" which means "classic CivetWeb Syntax".
  2510. *
  2511. */
  2512. run_lsp = run_lsp_civetweb;
  2513. if ((addr[0] == '<') && (addr[1] != '?')) {
  2514. run_lsp = run_lsp_kepler;
  2515. }
  2516. /* We're not sending HTTP headers here, Lua page must do it. */
  2517. error =
  2518. run_lsp(conn, path, addr, filep->stat.size, L, include_history->depth);
  2519. /* pop from stack */
  2520. include_history->depth--;
  2521. cleanup_handle_lsp_request:
  2522. if (L != NULL && ls == NULL)
  2523. lua_close(L);
  2524. if (p != NULL)
  2525. munmap(p, filep->stat.size);
  2526. (void)mg_fclose(&filep->access);
  2527. return error;
  2528. }
  2529. #if defined(USE_WEBSOCKET)
  2530. struct mg_shared_lua_websocket_list {
  2531. struct lua_websock_data ws;
  2532. struct mg_shared_lua_websocket_list *next;
  2533. };
  2534. static void *
  2535. lua_websocket_new(const char *script, struct mg_connection *conn)
  2536. {
  2537. struct mg_shared_lua_websocket_list **shared_websock_list =
  2538. &(conn->dom_ctx->shared_lua_websockets);
  2539. struct lua_websock_data *ws;
  2540. int err, ok = 0;
  2541. DEBUG_ASSERT(conn->lua_websocket_state == NULL);
  2542. /* lock list (mg_context global) */
  2543. mg_lock_context(conn->phys_ctx);
  2544. while (*shared_websock_list) {
  2545. /* check if ws already in list */
  2546. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  2547. break;
  2548. }
  2549. shared_websock_list = &((*shared_websock_list)->next);
  2550. }
  2551. if (*shared_websock_list == NULL) {
  2552. /* add ws to list */
  2553. *shared_websock_list =
  2554. (struct mg_shared_lua_websocket_list *)mg_calloc_ctx(
  2555. sizeof(struct mg_shared_lua_websocket_list), 1, conn->phys_ctx);
  2556. if (*shared_websock_list == NULL) {
  2557. conn->must_close = 1;
  2558. mg_unlock_context(conn->phys_ctx);
  2559. mg_cry_internal(conn,
  2560. "%s",
  2561. "Cannot create shared websocket struct, OOM");
  2562. return NULL;
  2563. }
  2564. /* init ws list element */
  2565. ws = &(*shared_websock_list)->ws;
  2566. ws->script = mg_strdup_ctx(script, conn->phys_ctx);
  2567. if (!ws->script) {
  2568. conn->must_close = 1;
  2569. mg_unlock_context(conn->phys_ctx);
  2570. mg_cry_internal(conn,
  2571. "%s",
  2572. "Cannot create shared websocket script, OOM");
  2573. return NULL;
  2574. }
  2575. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  2576. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2577. ws->state = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2578. ws->conn[0] = conn;
  2579. ws->references = 1;
  2580. prepare_lua_environment(conn->phys_ctx,
  2581. conn,
  2582. ws,
  2583. ws->state,
  2584. script,
  2585. LUA_ENV_TYPE_LUA_WEBSOCKET);
  2586. err = luaL_loadfile(ws->state, script);
  2587. if (err != 0) {
  2588. lua_cry(conn, err, ws->state, script, "load");
  2589. }
  2590. err = lua_pcall(ws->state, 0, 0, 0);
  2591. if (err != 0) {
  2592. lua_cry(conn, err, ws->state, script, "init");
  2593. }
  2594. } else {
  2595. /* inc ref count */
  2596. ws = &(*shared_websock_list)->ws;
  2597. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2598. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  2599. }
  2600. mg_unlock_context(conn->phys_ctx);
  2601. /* call add */
  2602. lua_getglobal(ws->state, "open");
  2603. lua_newtable(ws->state);
  2604. prepare_lua_request_info(conn, ws->state);
  2605. lua_pushstring(ws->state, "client");
  2606. lua_pushlightuserdata(ws->state, (void *)conn);
  2607. lua_rawset(ws->state, -3);
  2608. err = lua_pcall(ws->state, 1, 1, 0);
  2609. if (err != 0) {
  2610. lua_cry(conn, err, ws->state, script, "open handler");
  2611. } else {
  2612. if (lua_isboolean(ws->state, -1)) {
  2613. ok = lua_toboolean(ws->state, -1);
  2614. }
  2615. lua_pop(ws->state, 1);
  2616. }
  2617. if (!ok) {
  2618. /* Remove from ws connection list. */
  2619. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  2620. * (see websocket_close). */
  2621. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  2622. }
  2623. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2624. return ok ? (void *)ws : NULL;
  2625. }
  2626. static int
  2627. lua_websocket_data(struct mg_connection *conn,
  2628. int bits,
  2629. char *data,
  2630. size_t data_len,
  2631. void *ws_arg)
  2632. {
  2633. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2634. int err, ok = 0;
  2635. DEBUG_ASSERT(ws != NULL);
  2636. DEBUG_ASSERT(ws->state != NULL);
  2637. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2638. lua_getglobal(ws->state, "data");
  2639. lua_newtable(ws->state);
  2640. lua_pushstring(ws->state, "client");
  2641. lua_pushlightuserdata(ws->state, (void *)conn);
  2642. lua_rawset(ws->state, -3);
  2643. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  2644. a meaning according to
  2645. http://tools.ietf.org/html/rfc6455,
  2646. section 5.2 */
  2647. lua_pushnumber(ws->state, bits);
  2648. lua_rawset(ws->state, -3);
  2649. lua_pushstring(ws->state, "data");
  2650. lua_pushlstring(ws->state, data, data_len);
  2651. lua_rawset(ws->state, -3);
  2652. err = lua_pcall(ws->state, 1, 1, 0);
  2653. if (err != 0) {
  2654. lua_cry(conn, err, ws->state, ws->script, "data handler");
  2655. } else {
  2656. if (lua_isboolean(ws->state, -1)) {
  2657. ok = lua_toboolean(ws->state, -1);
  2658. }
  2659. lua_pop(ws->state, 1);
  2660. }
  2661. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2662. return ok;
  2663. }
  2664. static int
  2665. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  2666. {
  2667. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2668. int err, ok = 0;
  2669. DEBUG_ASSERT(ws != NULL);
  2670. DEBUG_ASSERT(ws->state != NULL);
  2671. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2672. lua_getglobal(ws->state, "ready");
  2673. lua_newtable(ws->state);
  2674. lua_pushstring(ws->state, "client");
  2675. lua_pushlightuserdata(ws->state, (void *)conn);
  2676. lua_rawset(ws->state, -3);
  2677. err = lua_pcall(ws->state, 1, 1, 0);
  2678. if (err != 0) {
  2679. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  2680. } else {
  2681. if (lua_isboolean(ws->state, -1)) {
  2682. ok = lua_toboolean(ws->state, -1);
  2683. }
  2684. lua_pop(ws->state, 1);
  2685. }
  2686. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2687. return ok;
  2688. }
  2689. static void
  2690. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  2691. {
  2692. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2693. struct mg_shared_lua_websocket_list **shared_websock_list =
  2694. &(conn->dom_ctx->shared_lua_websockets);
  2695. int err = 0;
  2696. unsigned i;
  2697. int delete_state = 0;
  2698. DEBUG_ASSERT(ws != NULL);
  2699. DEBUG_ASSERT(ws->state != NULL);
  2700. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2701. lua_getglobal(ws->state, "close");
  2702. lua_newtable(ws->state);
  2703. lua_pushstring(ws->state, "client");
  2704. lua_pushlightuserdata(ws->state, (void *)conn);
  2705. lua_rawset(ws->state, -3);
  2706. err = lua_pcall(ws->state, 1, 0, 0);
  2707. if (err != 0) {
  2708. lua_cry(conn, err, ws->state, ws->script, "close handler");
  2709. }
  2710. for (i = 0; i < ws->references; i++) {
  2711. if (ws->conn[i] == conn) {
  2712. ws->references--;
  2713. if (ws->references == 0) {
  2714. delete_state = 1;
  2715. break;
  2716. }
  2717. ws->conn[i] = ws->conn[ws->references];
  2718. }
  2719. }
  2720. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  2721. This must only be done, when all connections are closed, and all
  2722. asynchronous operations and timers are completed/expired. */
  2723. if (delete_state) {
  2724. /* lock list (mg_context global) */
  2725. mg_lock_context(conn->phys_ctx);
  2726. while (*shared_websock_list) {
  2727. /* find ws in list */
  2728. if (0 == strcmp(ws->script, (*shared_websock_list)->ws.script)) {
  2729. break;
  2730. }
  2731. shared_websock_list = &((*shared_websock_list)->next);
  2732. }
  2733. if (*shared_websock_list != NULL) {
  2734. /* TODO: If we close the state here, timers must be stopped first */
  2735. /* lua_close(ws->state); <-- other thread will crash, if there are
  2736. * still active timers */
  2737. }
  2738. mg_unlock_context(conn->phys_ctx);
  2739. }
  2740. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2741. }
  2742. #endif
  2743. static lua_State *
  2744. mg_prepare_lua_context_script(const char *file_name,
  2745. struct mg_context *ctx,
  2746. char *ebuf,
  2747. size_t ebuf_len)
  2748. {
  2749. struct lua_State *L;
  2750. int lua_ret;
  2751. const char *lua_err_txt;
  2752. (void)ctx;
  2753. L = luaL_newstate();
  2754. if (L == NULL) {
  2755. mg_snprintf(NULL,
  2756. NULL, /* No truncation check for ebuf */
  2757. ebuf,
  2758. ebuf_len,
  2759. "Error: %s",
  2760. "Cannot create Lua state");
  2761. return 0;
  2762. }
  2763. civetweb_open_lua_libs(L);
  2764. lua_ret = luaL_loadfile(L, file_name);
  2765. if (lua_ret != LUA_OK) {
  2766. /* Error when loading the file (e.g. file not found,
  2767. * out of memory, ...)
  2768. */
  2769. lua_err_txt = lua_tostring(L, -1);
  2770. mg_snprintf(NULL,
  2771. NULL, /* No truncation check for ebuf */
  2772. ebuf,
  2773. ebuf_len,
  2774. "Error loading file %s: %s\n",
  2775. file_name,
  2776. lua_err_txt);
  2777. return 0;
  2778. }
  2779. /* The script file is loaded, now call it */
  2780. lua_ret = lua_pcall(L,
  2781. /* no arguments */ 0,
  2782. /* zero or one return value */ 1,
  2783. /* errors as strint return value */ 0);
  2784. if (lua_ret != LUA_OK) {
  2785. /* Error when executing the script */
  2786. lua_err_txt = lua_tostring(L, -1);
  2787. mg_snprintf(NULL,
  2788. NULL, /* No truncation check for ebuf */
  2789. ebuf,
  2790. ebuf_len,
  2791. "Error running file %s: %s\n",
  2792. file_name,
  2793. lua_err_txt);
  2794. return 0;
  2795. }
  2796. /* lua_close(L); must be done somewhere else */
  2797. return L;
  2798. }
  2799. static void
  2800. lua_ctx_init(struct mg_context *ctx)
  2801. {
  2802. #if defined(USE_WEBSOCKET)
  2803. ctx->dd.shared_lua_websockets = NULL;
  2804. #endif
  2805. }
  2806. static void
  2807. lua_ctx_exit(struct mg_context *ctx)
  2808. {
  2809. #if defined(USE_WEBSOCKET)
  2810. struct mg_shared_lua_websocket_list **shared_websock_list =
  2811. &(ctx->dd.shared_lua_websockets);
  2812. struct mg_shared_lua_websocket_list *next;
  2813. mg_lock_context(ctx);
  2814. while (*shared_websock_list) {
  2815. lua_close((*shared_websock_list)->ws.state);
  2816. mg_free((*shared_websock_list)->ws.script);
  2817. /* Save "next" pointer before freeing list element */
  2818. next = ((*shared_websock_list)->next);
  2819. mg_free(*shared_websock_list);
  2820. shared_websock_list = &next;
  2821. }
  2822. mg_unlock_context(ctx);
  2823. #endif
  2824. }
  2825. int
  2826. run_lua(const char *file_name)
  2827. {
  2828. int func_ret = EXIT_FAILURE;
  2829. char ebuf[512] = {0};
  2830. lua_State *L =
  2831. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  2832. if (L) {
  2833. /* Script executed */
  2834. if (lua_type(L, -1) == LUA_TNUMBER) {
  2835. func_ret = (int)lua_tonumber(L, -1);
  2836. } else {
  2837. func_ret = EXIT_SUCCESS;
  2838. }
  2839. lua_close(L);
  2840. } else {
  2841. fprintf(stderr, "%s\n", ebuf);
  2842. }
  2843. return func_ret;
  2844. }
  2845. static void *lib_handle_uuid = NULL;
  2846. static void
  2847. lua_init_optional_libraries(void)
  2848. {
  2849. /* Create logging mutex */
  2850. pthread_mutex_init(&s_lua_traceMutex, &pthread_mutex_attr);
  2851. /* shared Lua state */
  2852. lua_shared_init();
  2853. /* UUID library */
  2854. #if !defined(_WIN32)
  2855. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  2856. pf_uuid_generate.p =
  2857. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  2858. #else
  2859. pf_uuid_generate.p = 0;
  2860. #endif
  2861. }
  2862. static void
  2863. lua_exit_optional_libraries(void)
  2864. {
  2865. /* UUID library */
  2866. #if !defined(_WIN32)
  2867. if (lib_handle_uuid) {
  2868. dlclose(lib_handle_uuid);
  2869. }
  2870. #endif
  2871. pf_uuid_generate.p = 0;
  2872. lib_handle_uuid = NULL;
  2873. /* shared Lua state */
  2874. lua_shared_exit();
  2875. /* Delete logging mutex */
  2876. pthread_mutex_destroy(&s_lua_traceMutex);
  2877. }
  2878. /* End of mod_lua.inl */