mod_lua.inl 75 KB

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