mod_lua.inl 92 KB

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