mod_lua.inl 92 KB

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