mod_lua.inl 89 KB

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