mod_lua.inl 91 KB

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