mod_lua.inl 89 KB

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