mod_lua.inl 92 KB

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