mod_lua.inl 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123
  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.split_form_data */
  1005. static int
  1006. lsp_split_form_data(lua_State *L)
  1007. {
  1008. int num_args = lua_gettop(L);
  1009. const char *in;
  1010. size_t len;
  1011. char *buf;
  1012. struct mg_context *ctx;
  1013. struct mg_header form_fields[MG_MAX_FORM_FIELDS] = {0};
  1014. int ret, i;
  1015. if (num_args != 1) {
  1016. return luaL_error(L, "invalid split_form_data() call");
  1017. }
  1018. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1019. lua_gettable(L, LUA_REGISTRYINDEX);
  1020. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1021. /* Get input (const string) */
  1022. in = lua_tolstring(L, 1, &len);
  1023. /* Create a modifyable copy */
  1024. buf = mg_malloc_ctx(len + 1, ctx);
  1025. if (buf == NULL) {
  1026. return luaL_error(L, "out of memory in invalid split_form_data() call");
  1027. }
  1028. memcpy(buf, in, len + 1);
  1029. /* mg_split_form_encoded does the real work */
  1030. ret = mg_split_form_encoded(buf, form_fields);
  1031. if (ret < 0) {
  1032. return luaL_error(L, "error in invalid split_form_data() call");
  1033. }
  1034. /* return a table */
  1035. lua_newtable(L);
  1036. for (i = 0; i < ret; i++) {
  1037. lua_newtable(L);
  1038. if (form_fields[i].name) {
  1039. lua_pushstring(L, form_fields[i].name);
  1040. } else {
  1041. lua_pushnil(L);
  1042. }
  1043. lua_setfield(L, -2, "name");
  1044. if (form_fields[i].value) {
  1045. lua_pushstring(L, form_fields[i].value);
  1046. } else {
  1047. lua_pushnil(L);
  1048. }
  1049. lua_setfield(L, -2, "value");
  1050. lua_rawseti(L, -2, i + 1);
  1051. }
  1052. mg_free(buf);
  1053. return 1;
  1054. }
  1055. /* mg.get_mime_type */
  1056. static int
  1057. lsp_get_mime_type(lua_State *L)
  1058. {
  1059. int num_args = lua_gettop(L);
  1060. struct vec mime_type = {0, 0};
  1061. const char *text;
  1062. struct mg_connection *conn =
  1063. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1064. if (num_args == 1) {
  1065. text = lua_tostring(L, 1);
  1066. if (text) {
  1067. if (conn) {
  1068. get_mime_type(conn, text, &mime_type);
  1069. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  1070. } else {
  1071. text = mg_get_builtin_mime_type(text);
  1072. lua_pushstring(L, text);
  1073. }
  1074. } else {
  1075. /* Syntax error */
  1076. return luaL_error(L, "invalid argument for get_mime_type() call");
  1077. }
  1078. } else {
  1079. /* Syntax error */
  1080. return luaL_error(L, "invalid get_mime_type() call");
  1081. }
  1082. return 1;
  1083. }
  1084. /* mg.get_cookie */
  1085. static int
  1086. lsp_get_cookie(lua_State *L)
  1087. {
  1088. int num_args = lua_gettop(L);
  1089. const char *cookie;
  1090. const char *var_name;
  1091. int ret;
  1092. struct mg_context *ctx;
  1093. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1094. lua_gettable(L, LUA_REGISTRYINDEX);
  1095. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1096. if (num_args == 2) {
  1097. /* Correct number of arguments */
  1098. size_t data_len;
  1099. char *dst;
  1100. cookie = lua_tolstring(L, 1, &data_len);
  1101. var_name = lua_tostring(L, 2);
  1102. if (cookie == NULL || var_name == NULL) {
  1103. /* Syntax error */
  1104. return luaL_error(L, "invalid get_cookie() call");
  1105. }
  1106. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  1107. if (!dst) {
  1108. return luaL_error(L, "out of memory in get_cookie() call");
  1109. }
  1110. ret = mg_get_cookie(cookie, var_name, dst, data_len);
  1111. if (ret >= 0) {
  1112. lua_pushlstring(L, dst, ret);
  1113. } else {
  1114. lua_pushnil(L);
  1115. }
  1116. mg_free(dst);
  1117. } else {
  1118. /* Syntax error */
  1119. return luaL_error(L, "invalid get_cookie() call");
  1120. }
  1121. return 1;
  1122. }
  1123. /* mg.md5 */
  1124. static int
  1125. lsp_md5(lua_State *L)
  1126. {
  1127. int num_args = lua_gettop(L);
  1128. const char *text;
  1129. md5_byte_t hash[16];
  1130. md5_state_t ctx;
  1131. size_t text_len;
  1132. char buf[40];
  1133. if (num_args == 1) {
  1134. text = lua_tolstring(L, 1, &text_len);
  1135. if (text) {
  1136. md5_init(&ctx);
  1137. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  1138. md5_finish(&ctx, hash);
  1139. bin2str(buf, hash, sizeof(hash));
  1140. lua_pushstring(L, buf);
  1141. } else {
  1142. lua_pushnil(L);
  1143. }
  1144. } else {
  1145. /* Syntax error */
  1146. return luaL_error(L, "invalid md5() call");
  1147. }
  1148. return 1;
  1149. }
  1150. /* mg.url_encode */
  1151. static int
  1152. lsp_url_encode(lua_State *L)
  1153. {
  1154. int num_args = lua_gettop(L);
  1155. const char *text;
  1156. size_t text_len;
  1157. char *dst;
  1158. int dst_len;
  1159. struct mg_context *ctx;
  1160. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1161. lua_gettable(L, LUA_REGISTRYINDEX);
  1162. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1163. if (num_args == 1) {
  1164. text = lua_tolstring(L, 1, &text_len);
  1165. if (text) {
  1166. dst_len = 3 * (int)text_len + 1;
  1167. dst = ((text_len < 0x2AAAAAAA) ? (char *)mg_malloc_ctx(dst_len, ctx)
  1168. : (char *)NULL);
  1169. if (dst) {
  1170. mg_url_encode(text, dst, dst_len);
  1171. lua_pushstring(L, dst);
  1172. mg_free(dst);
  1173. } else {
  1174. return luaL_error(L, "out of memory in url_decode() call");
  1175. }
  1176. } else {
  1177. lua_pushnil(L);
  1178. }
  1179. } else {
  1180. /* Syntax error */
  1181. return luaL_error(L, "invalid url_encode() call");
  1182. }
  1183. return 1;
  1184. }
  1185. /* mg.url_decode */
  1186. static int
  1187. lsp_url_decode(lua_State *L)
  1188. {
  1189. int num_args = lua_gettop(L);
  1190. const char *text;
  1191. size_t text_len;
  1192. int is_form;
  1193. char *dst;
  1194. int dst_len;
  1195. struct mg_context *ctx;
  1196. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1197. lua_gettable(L, LUA_REGISTRYINDEX);
  1198. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1199. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  1200. text = lua_tolstring(L, 1, &text_len);
  1201. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  1202. if (text) {
  1203. dst_len = (int)text_len + 1;
  1204. dst = ((text_len < 0x7FFFFFFF) ? (char *)mg_malloc_ctx(dst_len, ctx)
  1205. : (char *)NULL);
  1206. if (dst) {
  1207. mg_url_decode(text, (int)text_len, dst, dst_len, is_form);
  1208. lua_pushstring(L, dst);
  1209. mg_free(dst);
  1210. } else {
  1211. return luaL_error(L, "out of memory in url_decode() call");
  1212. }
  1213. } else {
  1214. lua_pushnil(L);
  1215. }
  1216. } else {
  1217. /* Syntax error */
  1218. return luaL_error(L, "invalid url_decode() call");
  1219. }
  1220. return 1;
  1221. }
  1222. /* mg.base64_encode */
  1223. static int
  1224. lsp_base64_encode(lua_State *L)
  1225. {
  1226. int num_args = lua_gettop(L);
  1227. const char *text;
  1228. size_t text_len;
  1229. char *dst;
  1230. struct mg_context *ctx;
  1231. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1232. lua_gettable(L, LUA_REGISTRYINDEX);
  1233. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1234. if (num_args == 1) {
  1235. text = lua_tolstring(L, 1, &text_len);
  1236. if (text) {
  1237. dst = (char *)mg_malloc_ctx(text_len * 8 / 6 + 4, ctx);
  1238. if (dst) {
  1239. base64_encode((const unsigned char *)text, (int)text_len, dst);
  1240. lua_pushstring(L, dst);
  1241. mg_free(dst);
  1242. } else {
  1243. return luaL_error(L, "out of memory in base64_encode() call");
  1244. }
  1245. } else {
  1246. lua_pushnil(L);
  1247. }
  1248. } else {
  1249. /* Syntax error */
  1250. return luaL_error(L, "invalid base64_encode() call");
  1251. }
  1252. return 1;
  1253. }
  1254. /* mg.base64_encode */
  1255. static int
  1256. lsp_base64_decode(lua_State *L)
  1257. {
  1258. int num_args = lua_gettop(L);
  1259. const char *text;
  1260. size_t text_len, dst_len;
  1261. int ret;
  1262. char *dst;
  1263. struct mg_context *ctx;
  1264. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1265. lua_gettable(L, LUA_REGISTRYINDEX);
  1266. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1267. if (num_args == 1) {
  1268. text = lua_tolstring(L, 1, &text_len);
  1269. if (text) {
  1270. dst = (char *)mg_malloc_ctx(text_len, ctx);
  1271. if (dst) {
  1272. ret = base64_decode((const unsigned char *)text,
  1273. (int)text_len,
  1274. dst,
  1275. &dst_len);
  1276. if (ret != -1) {
  1277. mg_free(dst);
  1278. return luaL_error(
  1279. L, "illegal character in lsp_base64_decode() call");
  1280. } else {
  1281. lua_pushlstring(L, dst, dst_len);
  1282. mg_free(dst);
  1283. }
  1284. } else {
  1285. return luaL_error(L,
  1286. "out of memory in lsp_base64_decode() call");
  1287. }
  1288. } else {
  1289. lua_pushnil(L);
  1290. }
  1291. } else {
  1292. /* Syntax error */
  1293. return luaL_error(L, "invalid lsp_base64_decode() call");
  1294. }
  1295. return 1;
  1296. }
  1297. /* mg.get_response_code_text */
  1298. static int
  1299. lsp_get_response_code_text(lua_State *L)
  1300. {
  1301. int num_args = lua_gettop(L);
  1302. int type1;
  1303. double code;
  1304. const char *text;
  1305. if (num_args == 1) {
  1306. type1 = lua_type(L, 1);
  1307. if (type1 == LUA_TNUMBER) {
  1308. /* If the first argument is a number,
  1309. convert it to the corresponding text. */
  1310. code = lua_tonumber(L, 1);
  1311. text = mg_get_response_code_text(NULL, (int)code);
  1312. if (text) { /* <-- should be always true */
  1313. lua_pushstring(L, text);
  1314. }
  1315. return text ? 1 : 0;
  1316. }
  1317. }
  1318. /* Syntax error */
  1319. return luaL_error(L, "invalid get_response_code_text() call");
  1320. }
  1321. /* mg.random - might be better than math.random on some systems */
  1322. static int
  1323. lsp_random(lua_State *L)
  1324. {
  1325. int num_args = lua_gettop(L);
  1326. if (num_args == 0) {
  1327. /* The civetweb internal random number generator will generate
  1328. * a 64 bit random number. */
  1329. uint64_t r = get_random();
  1330. /* Lua "number" is a IEEE 754 double precission float:
  1331. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  1332. * Thus, mask with 2^53-1 to get an integer with the maximum
  1333. * precission available. */
  1334. r &= ((((uint64_t)1) << 53) - 1);
  1335. lua_pushnumber(L, (double)r);
  1336. return 1;
  1337. }
  1338. /* Syntax error */
  1339. return luaL_error(L, "invalid random() call");
  1340. }
  1341. /* mg.get_info */
  1342. static int
  1343. lsp_get_info(lua_State *L)
  1344. {
  1345. int num_args = lua_gettop(L);
  1346. int type1, type2;
  1347. const char *arg1;
  1348. double arg2;
  1349. int len;
  1350. char *buf;
  1351. if (num_args == 1) {
  1352. type1 = lua_type(L, 1);
  1353. if (type1 == LUA_TSTRING) {
  1354. arg1 = lua_tostring(L, 1);
  1355. /* Get info according to argument */
  1356. if (!mg_strcasecmp(arg1, "system")) {
  1357. /* Get system info */
  1358. len = mg_get_system_info(NULL, 0);
  1359. if (len > 0) {
  1360. buf = (char *)mg_malloc(len + 64);
  1361. if (!buf) {
  1362. return luaL_error(L, "OOM in get_info() call");
  1363. }
  1364. len = mg_get_system_info(buf, len + 63);
  1365. lua_pushlstring(L, buf, len);
  1366. mg_free(buf);
  1367. } else {
  1368. lua_pushstring(L, "");
  1369. }
  1370. return 1;
  1371. }
  1372. if (!mg_strcasecmp(arg1, "context")) {
  1373. /* Get context */
  1374. struct mg_context *ctx;
  1375. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1376. lua_gettable(L, LUA_REGISTRYINDEX);
  1377. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1378. /* Get context info for server context */
  1379. len = mg_get_context_info(ctx, NULL, 0);
  1380. if (len > 0) {
  1381. buf = (char *)mg_malloc(len + 64);
  1382. if (!buf) {
  1383. return luaL_error(L, "OOM in get_info() call");
  1384. }
  1385. len = mg_get_context_info(ctx, buf, len + 63);
  1386. lua_pushlstring(L, buf, len);
  1387. mg_free(buf);
  1388. } else {
  1389. lua_pushstring(L, "");
  1390. }
  1391. return 1;
  1392. }
  1393. if (!mg_strcasecmp(arg1, "common")) {
  1394. /* Get context info for NULL context */
  1395. len = mg_get_context_info(NULL, NULL, 0);
  1396. if (len > 0) {
  1397. buf = (char *)mg_malloc(len + 64);
  1398. if (!buf) {
  1399. return luaL_error(L, "OOM in get_info() call");
  1400. }
  1401. len = mg_get_context_info(NULL, buf, len + 63);
  1402. lua_pushlstring(L, buf, len);
  1403. mg_free(buf);
  1404. } else {
  1405. lua_pushstring(L, "");
  1406. }
  1407. return 1;
  1408. }
  1409. return 0;
  1410. }
  1411. }
  1412. if (num_args == 2) {
  1413. type1 = lua_type(L, 1);
  1414. type2 = lua_type(L, 2);
  1415. if ((type1 == LUA_TSTRING) && (type2 == LUA_TNUMBER)) {
  1416. arg1 = lua_tostring(L, 1);
  1417. arg2 = lua_tonumber(L, 2);
  1418. /* Get info according to argument */
  1419. if (!mg_strcasecmp(arg1, "connection")) {
  1420. int idx;
  1421. /* Get context */
  1422. struct mg_context *ctx;
  1423. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1424. lua_gettable(L, LUA_REGISTRYINDEX);
  1425. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1426. /* Get connection info for connection idx */
  1427. idx = (int)(arg2 + 0.5);
  1428. /* Lua uses 1 based index, C uses 0 based index */
  1429. idx--;
  1430. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1431. len = mg_get_connection_info(ctx, idx, NULL, 0);
  1432. if (len > 0) {
  1433. buf = (char *)mg_malloc(len + 64);
  1434. if (!buf) {
  1435. return luaL_error(L, "OOM in get_info() call");
  1436. }
  1437. len = mg_get_connection_info(ctx, idx, buf, len + 63);
  1438. lua_pushlstring(L, buf, len);
  1439. mg_free(buf);
  1440. } else {
  1441. lua_pushstring(L, "");
  1442. }
  1443. #else
  1444. (void)ctx;
  1445. (void)idx;
  1446. lua_pushstring(L, "");
  1447. #endif
  1448. return 1;
  1449. }
  1450. return 0;
  1451. }
  1452. }
  1453. /* Syntax error */
  1454. return luaL_error(L, "invalid get_info() call");
  1455. }
  1456. /* mg.get_option */
  1457. static int
  1458. lsp_get_option(lua_State *L)
  1459. {
  1460. int num_args = lua_gettop(L);
  1461. int type1;
  1462. const char *arg1;
  1463. const char *data;
  1464. int optidx;
  1465. /* Get connection */
  1466. struct mg_connection *conn =
  1467. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1468. if (num_args == 0) {
  1469. const struct mg_option *opts = mg_get_valid_options();
  1470. if (!opts) { /* <-- should be always false */
  1471. return 0;
  1472. }
  1473. lua_newtable(L);
  1474. while (opts->name) {
  1475. optidx = get_option_index(opts->name);
  1476. if (optidx >= 0) {
  1477. data = conn->dom_ctx->config[optidx];
  1478. if (data) {
  1479. reg_string(L, opts->name, data);
  1480. }
  1481. }
  1482. opts++;
  1483. }
  1484. return 1;
  1485. }
  1486. if (num_args == 1) {
  1487. type1 = lua_type(L, 1);
  1488. if (type1 == LUA_TSTRING) {
  1489. arg1 = lua_tostring(L, 1);
  1490. /* Get option according to argument */
  1491. optidx = get_option_index(arg1);
  1492. if (optidx >= 0) {
  1493. data = conn->dom_ctx->config[optidx];
  1494. if (data) {
  1495. lua_pushstring(L, data);
  1496. return 1;
  1497. }
  1498. }
  1499. return 0;
  1500. }
  1501. }
  1502. /* Syntax error */
  1503. return luaL_error(L, "invalid get_option() call");
  1504. }
  1505. static int s_lua_traceLevel = 1;
  1506. static FILE *s_lua_traceFile = NULL;
  1507. static pthread_mutex_t s_lua_traceMutex;
  1508. /* mg.trace */
  1509. static int
  1510. lsp_trace(lua_State *L)
  1511. {
  1512. int num_args = lua_gettop(L);
  1513. int arg_type[8];
  1514. int trace_level = 0;
  1515. int firstarg = 1;
  1516. int i;
  1517. for (i = 0; i < 8; i++) {
  1518. if (num_args >= (i + 1)) {
  1519. arg_type[i] = lua_type(L, (i + 1));
  1520. } else {
  1521. arg_type[i] = LUA_TNIL;
  1522. }
  1523. }
  1524. if (arg_type[0] == LUA_TNUMBER) {
  1525. trace_level = lua_tointeger(L, 1);
  1526. if (num_args == 1) {
  1527. /* Set a new trace level, return the current one. */
  1528. lua_pushinteger(L, s_lua_traceLevel);
  1529. s_lua_traceLevel = trace_level;
  1530. if (s_lua_traceFile) {
  1531. pthread_mutex_lock(&s_lua_traceMutex);
  1532. fflush(s_lua_traceFile);
  1533. pthread_mutex_unlock(&s_lua_traceMutex);
  1534. }
  1535. return 1;
  1536. }
  1537. firstarg = 2;
  1538. }
  1539. if (trace_level > s_lua_traceLevel) {
  1540. /* If this trace request has a higher trace level than the global trace
  1541. * level, do not trace. */
  1542. lua_pushboolean(L, 0);
  1543. return 1;
  1544. }
  1545. /* Print to file */
  1546. if (s_lua_traceFile) {
  1547. pthread_mutex_lock(&s_lua_traceMutex);
  1548. for (i = firstarg; i <= num_args; i++) {
  1549. if (arg_type[i - 1] == LUA_TSTRING) {
  1550. const char *arg = lua_tostring(L, i);
  1551. fprintf(s_lua_traceFile, "%s\n", arg);
  1552. }
  1553. }
  1554. pthread_mutex_unlock(&s_lua_traceMutex);
  1555. }
  1556. lua_pushboolean(L, 1);
  1557. return 1;
  1558. }
  1559. /* UUID library and function pointer */
  1560. union {
  1561. void *p;
  1562. void (*f)(unsigned char uuid[16]);
  1563. } pf_uuid_generate;
  1564. /* mg.uuid */
  1565. static int
  1566. lsp_uuid(lua_State *L)
  1567. {
  1568. union {
  1569. unsigned char uuid_array[16];
  1570. struct uuid_struct_type {
  1571. uint32_t data1;
  1572. uint16_t data2;
  1573. uint16_t data3;
  1574. uint8_t data4[8];
  1575. } uuid_struct;
  1576. } uuid;
  1577. char uuid_str[40];
  1578. int num_args = lua_gettop(L);
  1579. memset(&uuid, 0, sizeof(uuid));
  1580. memset(uuid_str, 0, sizeof(uuid_str));
  1581. if (num_args == 0) {
  1582. pf_uuid_generate.f(uuid.uuid_array);
  1583. sprintf(uuid_str,
  1584. "{%08lX-%04X-%04X-%02X%02X-"
  1585. "%02X%02X%02X%02X%02X%02X}",
  1586. (unsigned long)uuid.uuid_struct.data1,
  1587. (unsigned)uuid.uuid_struct.data2,
  1588. (unsigned)uuid.uuid_struct.data3,
  1589. (unsigned)uuid.uuid_struct.data4[0],
  1590. (unsigned)uuid.uuid_struct.data4[1],
  1591. (unsigned)uuid.uuid_struct.data4[2],
  1592. (unsigned)uuid.uuid_struct.data4[3],
  1593. (unsigned)uuid.uuid_struct.data4[4],
  1594. (unsigned)uuid.uuid_struct.data4[5],
  1595. (unsigned)uuid.uuid_struct.data4[6],
  1596. (unsigned)uuid.uuid_struct.data4[7]);
  1597. lua_pushstring(L, uuid_str);
  1598. return 1;
  1599. }
  1600. /* Syntax error */
  1601. return luaL_error(L, "invalid random() call");
  1602. }
  1603. #if defined(USE_WEBSOCKET)
  1604. struct lua_websock_data {
  1605. lua_State *state;
  1606. char *script;
  1607. unsigned references;
  1608. struct mg_connection *conn[MAX_WORKER_THREADS];
  1609. pthread_mutex_t ws_mutex;
  1610. };
  1611. #endif
  1612. /* mg.write for websockets */
  1613. static int
  1614. lwebsock_write(lua_State *L)
  1615. {
  1616. #if defined(USE_WEBSOCKET)
  1617. int num_args = lua_gettop(L);
  1618. struct lua_websock_data *ws;
  1619. const char *str;
  1620. size_t size;
  1621. int opcode = -1;
  1622. unsigned i;
  1623. struct mg_connection *client = NULL;
  1624. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1625. lua_gettable(L, LUA_REGISTRYINDEX);
  1626. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1627. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1628. if (num_args == 1) {
  1629. /* just one text: send it to all client */
  1630. if (lua_isstring(L, 1)) {
  1631. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1632. }
  1633. } else if (num_args == 2) {
  1634. if (lua_isnumber(L, 1)) {
  1635. /* opcode number and message text */
  1636. opcode = (int)lua_tointeger(L, 1);
  1637. } else if (lua_isstring(L, 1)) {
  1638. /* opcode string and message text */
  1639. str = lua_tostring(L, 1);
  1640. if (!mg_strncasecmp(str, "text", 4))
  1641. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1642. else if (!mg_strncasecmp(str, "bin", 3))
  1643. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1644. else if (!mg_strncasecmp(str, "close", 5))
  1645. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1646. else if (!mg_strncasecmp(str, "ping", 4))
  1647. opcode = MG_WEBSOCKET_OPCODE_PING;
  1648. else if (!mg_strncasecmp(str, "pong", 4))
  1649. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1650. else if (!mg_strncasecmp(str, "cont", 4))
  1651. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1652. } else if (lua_isuserdata(L, 1)) {
  1653. /* client id and message text */
  1654. client = (struct mg_connection *)lua_touserdata(L, 1);
  1655. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1656. }
  1657. } else if (num_args == 3) {
  1658. if (lua_isuserdata(L, 1)) {
  1659. client = (struct mg_connection *)lua_touserdata(L, 1);
  1660. if (lua_isnumber(L, 2)) {
  1661. /* client id, opcode number and message text */
  1662. opcode = (int)lua_tointeger(L, 2);
  1663. } else if (lua_isstring(L, 2)) {
  1664. /* client id, opcode string and message text */
  1665. str = lua_tostring(L, 2);
  1666. if (!mg_strncasecmp(str, "text", 4))
  1667. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1668. else if (!mg_strncasecmp(str, "bin", 3))
  1669. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1670. else if (!mg_strncasecmp(str, "close", 5))
  1671. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1672. else if (!mg_strncasecmp(str, "ping", 4))
  1673. opcode = MG_WEBSOCKET_OPCODE_PING;
  1674. else if (!mg_strncasecmp(str, "pong", 4))
  1675. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1676. else if (!mg_strncasecmp(str, "cont", 4))
  1677. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1678. }
  1679. }
  1680. }
  1681. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  1682. str = lua_tolstring(L, num_args, &size);
  1683. if (client) {
  1684. for (i = 0; i < ws->references; i++) {
  1685. if (client == ws->conn[i]) {
  1686. mg_lock_connection(ws->conn[i]);
  1687. mg_websocket_write(ws->conn[i], opcode, str, size);
  1688. mg_unlock_connection(ws->conn[i]);
  1689. }
  1690. }
  1691. } else {
  1692. for (i = 0; i < ws->references; i++) {
  1693. mg_lock_connection(ws->conn[i]);
  1694. mg_websocket_write(ws->conn[i], opcode, str, size);
  1695. mg_unlock_connection(ws->conn[i]);
  1696. }
  1697. }
  1698. } else {
  1699. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1700. return luaL_error(L, "invalid websocket write() call");
  1701. }
  1702. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1703. #else
  1704. (void)(L); /* unused */
  1705. #endif
  1706. return 0;
  1707. }
  1708. struct laction_arg {
  1709. lua_State *state;
  1710. const char *script;
  1711. pthread_mutex_t *pmutex;
  1712. char txt[1];
  1713. };
  1714. static int
  1715. lua_action(struct laction_arg *arg)
  1716. {
  1717. int err, ok;
  1718. struct mg_context *ctx;
  1719. (void)pthread_mutex_lock(arg->pmutex);
  1720. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  1721. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  1722. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  1723. lua_pop(arg->state, 1);
  1724. err = luaL_loadstring(arg->state, arg->txt);
  1725. if (err != 0) {
  1726. struct mg_connection fc;
  1727. lua_cry(
  1728. fake_connection(&fc, ctx), err, arg->state, arg->script, "timer");
  1729. (void)pthread_mutex_unlock(arg->pmutex);
  1730. mg_free(arg);
  1731. return 0;
  1732. }
  1733. err = lua_pcall(arg->state, 0, 1, 0);
  1734. if (err != 0) {
  1735. struct mg_connection fc;
  1736. lua_cry(
  1737. fake_connection(&fc, ctx), err, arg->state, arg->script, "timer");
  1738. (void)pthread_mutex_unlock(arg->pmutex);
  1739. mg_free(arg);
  1740. return 0;
  1741. }
  1742. ok = lua_type(arg->state, -1);
  1743. if (lua_isboolean(arg->state, -1)) {
  1744. ok = lua_toboolean(arg->state, -1);
  1745. } else {
  1746. ok = 0;
  1747. }
  1748. lua_pop(arg->state, 1);
  1749. (void)pthread_mutex_unlock(arg->pmutex);
  1750. if (!ok) {
  1751. mg_free(arg);
  1752. }
  1753. return ok;
  1754. }
  1755. static int
  1756. lua_action_free(struct laction_arg *arg)
  1757. {
  1758. if (lua_action(arg)) {
  1759. mg_free(arg);
  1760. }
  1761. return 0;
  1762. }
  1763. static int
  1764. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1765. {
  1766. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1767. int num_args = lua_gettop(L);
  1768. struct lua_websock_data *ws;
  1769. int type1, type2, ok = 0;
  1770. double timediff;
  1771. struct mg_context *ctx;
  1772. struct laction_arg *arg;
  1773. const char *txt;
  1774. size_t txt_len;
  1775. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1776. lua_gettable(L, LUA_REGISTRYINDEX);
  1777. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1778. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1779. lua_gettable(L, LUA_REGISTRYINDEX);
  1780. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1781. if (num_args < 2) {
  1782. return luaL_error(L,
  1783. "not enough arguments for set_timer/interval() call");
  1784. }
  1785. type1 = lua_type(L, 1);
  1786. type2 = lua_type(L, 2);
  1787. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1788. timediff = (double)lua_tonumber(L, 2);
  1789. txt = lua_tostring(L, 1);
  1790. txt_len = strlen(txt);
  1791. arg = (struct laction_arg *)mg_malloc_ctx(sizeof(struct laction_arg)
  1792. + txt_len + 10,
  1793. ctx);
  1794. if (!arg) {
  1795. return luaL_error(L, "out of memory");
  1796. }
  1797. arg->state = L;
  1798. arg->script = ws->script;
  1799. arg->pmutex = &(ws->ws_mutex);
  1800. memcpy(arg->txt, "return(", 7);
  1801. memcpy(arg->txt + 7, txt, txt_len);
  1802. arg->txt[txt_len + 7] = ')';
  1803. arg->txt[txt_len + 8] = 0;
  1804. ok =
  1805. (0
  1806. == timer_add(ctx,
  1807. timediff,
  1808. is_periodic,
  1809. 1,
  1810. (taction)(is_periodic ? lua_action : lua_action_free),
  1811. (void *)arg));
  1812. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1813. /* TODO (mid): not implemented yet */
  1814. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1815. } else {
  1816. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1817. }
  1818. lua_pushboolean(L, ok);
  1819. return 1;
  1820. #else
  1821. (void)(L); /* unused */
  1822. (void)(is_periodic); /* unused */
  1823. return 0;
  1824. #endif
  1825. }
  1826. /* mg.set_timeout for websockets */
  1827. static int
  1828. lwebsocket_set_timeout(lua_State *L)
  1829. {
  1830. return lwebsocket_set_timer(L, 0);
  1831. }
  1832. /* mg.set_interval for websockets */
  1833. static int
  1834. lwebsocket_set_interval(lua_State *L)
  1835. {
  1836. return lwebsocket_set_timer(L, 1);
  1837. }
  1838. /* Debug hook */
  1839. static void
  1840. lua_debug_hook(lua_State *L, lua_Debug *ar)
  1841. {
  1842. int i;
  1843. int stack_len = lua_gettop(L);
  1844. lua_getinfo(L, "nSlu", ar);
  1845. if (ar->event == LUA_HOOKCALL) {
  1846. printf("call\n");
  1847. } else if (ar->event == LUA_HOOKRET) {
  1848. printf("ret\n");
  1849. #if defined(LUA_HOOKTAILRET)
  1850. } else if (ar->event == LUA_HOOKTAILRET) {
  1851. printf("tail ret\n");
  1852. #endif
  1853. #if defined(LUA_HOOKTAILCALL)
  1854. } else if (ar->event == LUA_HOOKTAILCALL) {
  1855. printf("tail call\n");
  1856. #endif
  1857. } else if (ar->event == LUA_HOOKLINE) {
  1858. printf("line\n");
  1859. } else if (ar->event == LUA_HOOKCOUNT) {
  1860. printf("count\n");
  1861. } else {
  1862. printf("unknown (%i)\n", ar->event);
  1863. }
  1864. if (ar->currentline >= 0) {
  1865. printf("%s:%i\n", ar->source, ar->currentline);
  1866. }
  1867. printf("%s (%s)\n", ar->name, ar->namewhat);
  1868. for (i = 1; i <= stack_len; i++) { /* repeat for each level */
  1869. int val_type = lua_type(L, i);
  1870. const char *s;
  1871. size_t n;
  1872. switch (val_type) {
  1873. case LUA_TNIL:
  1874. /* nil value on the stack */
  1875. printf("nil\n");
  1876. break;
  1877. case LUA_TBOOLEAN:
  1878. /* boolean (true / false) */
  1879. printf("boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
  1880. break;
  1881. case LUA_TNUMBER:
  1882. /* number */
  1883. printf("number: %g\n", lua_tonumber(L, i));
  1884. break;
  1885. case LUA_TSTRING:
  1886. /* string with limited length */
  1887. s = lua_tolstring(L, i, &n);
  1888. printf("string: '%.*s%s\n",
  1889. ((n > 30) ? 28 : (int)n),
  1890. s,
  1891. ((n > 30) ? ".." : "'"));
  1892. break;
  1893. default:
  1894. /* other values */
  1895. printf("%s\n", lua_typename(L, val_type));
  1896. break;
  1897. }
  1898. }
  1899. printf("\n");
  1900. }
  1901. /* Lua Environment */
  1902. enum {
  1903. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1904. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1905. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1906. };
  1907. static void
  1908. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1909. {
  1910. const char *s;
  1911. int i;
  1912. /* Export mg.request_info */
  1913. lua_pushstring(L, "request_info");
  1914. lua_newtable(L);
  1915. reg_string(L, "request_method", conn->request_info.request_method);
  1916. reg_string(L, "request_uri", conn->request_info.request_uri);
  1917. reg_string(L, "uri", conn->request_info.local_uri);
  1918. reg_string(L, "http_version", conn->request_info.http_version);
  1919. reg_string(L, "query_string", conn->request_info.query_string);
  1920. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1921. /* TODO (high): ip version */
  1922. reg_int(L, "remote_port", conn->request_info.remote_port);
  1923. reg_int(L, "num_headers", conn->request_info.num_headers);
  1924. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1925. if (conn->path_info != NULL) {
  1926. reg_string(L, "path_info", conn->path_info);
  1927. }
  1928. if (conn->request_info.content_length >= 0) {
  1929. /* reg_int64: content_length */
  1930. lua_pushstring(L, "content_length");
  1931. lua_pushnumber(
  1932. L,
  1933. (lua_Number)conn->request_info
  1934. .content_length); /* lua_Number may be used as 52 bit integer */
  1935. lua_rawset(L, -3);
  1936. }
  1937. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1938. reg_string(L, "content_type", s);
  1939. }
  1940. if (conn->request_info.remote_user != NULL) {
  1941. reg_string(L, "remote_user", conn->request_info.remote_user);
  1942. reg_string(L, "auth_type", "Digest");
  1943. }
  1944. reg_boolean(L, "https", conn->ssl != NULL);
  1945. if (conn->status_code > 0) {
  1946. /* Lua error handler should show the status code */
  1947. reg_int(L, "status", conn->status_code);
  1948. }
  1949. /* Table "HTTP headers" */
  1950. lua_pushstring(L, "http_headers");
  1951. lua_newtable(L);
  1952. for (i = 0; i < conn->request_info.num_headers; i++) {
  1953. reg_string(L,
  1954. conn->request_info.http_headers[i].name,
  1955. conn->request_info.http_headers[i].value);
  1956. }
  1957. lua_rawset(L, -3);
  1958. /* Table "Client Certificate" */
  1959. if (conn->request_info.client_cert) {
  1960. lua_pushstring(L, "client_cert");
  1961. lua_newtable(L);
  1962. reg_string(L, "subject", conn->request_info.client_cert->subject);
  1963. reg_string(L, "issuer", conn->request_info.client_cert->issuer);
  1964. reg_string(L, "serial", conn->request_info.client_cert->serial);
  1965. reg_string(L, "finger", conn->request_info.client_cert->finger);
  1966. lua_rawset(L, -3);
  1967. }
  1968. /* End of request_info */
  1969. lua_rawset(L, -3);
  1970. }
  1971. static void *
  1972. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1973. {
  1974. (void)osize; /* not used */
  1975. if (nsize == 0) {
  1976. mg_free(ptr);
  1977. return NULL;
  1978. }
  1979. return mg_realloc_ctx(ptr, nsize, (struct mg_context *)ud);
  1980. }
  1981. /* In CivetWeb, Lua-Shared is used as *.inl file */
  1982. #define LUA_SHARED_INTERFACE static
  1983. #include "mod_lua_shared.inl"
  1984. static void
  1985. civetweb_open_lua_libs(lua_State *L)
  1986. {
  1987. {
  1988. extern void luaL_openlibs(lua_State *);
  1989. luaL_openlibs(L);
  1990. }
  1991. #if defined(USE_LUA_SQLITE3)
  1992. {
  1993. extern int luaopen_lsqlite3(lua_State *);
  1994. luaopen_lsqlite3(L);
  1995. }
  1996. #endif
  1997. #if defined(USE_LUA_LUAXML)
  1998. {
  1999. extern int luaopen_LuaXML_lib(lua_State *);
  2000. luaopen_LuaXML_lib(L);
  2001. // lua_pushvalue(L, -1); to copy value
  2002. lua_setglobal(L, "xml");
  2003. }
  2004. #endif
  2005. #if defined(USE_LUA_FILE_SYSTEM)
  2006. {
  2007. extern int luaopen_lfs(lua_State *);
  2008. luaopen_lfs(L);
  2009. }
  2010. #endif
  2011. }
  2012. static void
  2013. prepare_lua_environment(struct mg_context *ctx,
  2014. struct mg_connection *conn,
  2015. struct lua_websock_data *ws_conn_list,
  2016. lua_State *L,
  2017. const char *script_name,
  2018. int lua_env_type)
  2019. {
  2020. const char *preload_file_name = NULL;
  2021. const char *debug_params = NULL;
  2022. civetweb_open_lua_libs(L);
  2023. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2024. /* Check if debugging should be enabled */
  2025. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2026. debug_params = conn->dom_ctx->config[LUA_DEBUG_PARAMS];
  2027. }
  2028. #endif
  2029. #if LUA_VERSION_NUM == 502
  2030. /* Keep the "connect" method for compatibility,
  2031. * but do not backport it to Lua 5.1.
  2032. * TODO: Redesign the interface.
  2033. */
  2034. luaL_newmetatable(L, LUASOCKET);
  2035. /* self.__index = self */
  2036. lua_pushvalue(L, -1);
  2037. lua_setfield(L, -2, "__index");
  2038. luaL_setfuncs(L, luasocket_methods, 0);
  2039. lua_pop(L, 1);
  2040. lua_register(L, "connect", lsp_connect);
  2041. #endif
  2042. /* Store context in the registry */
  2043. if (ctx != NULL) {
  2044. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  2045. lua_pushlightuserdata(L, (void *)ctx);
  2046. lua_settable(L, LUA_REGISTRYINDEX);
  2047. }
  2048. if (ws_conn_list != NULL) {
  2049. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  2050. lua_pushlightuserdata(L, (void *)ws_conn_list);
  2051. lua_settable(L, LUA_REGISTRYINDEX);
  2052. }
  2053. /* Lua server pages store the depth of mg.include, in order
  2054. * to detect recursions and prevent stack overflows. */
  2055. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  2056. struct lsp_include_history *h;
  2057. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  2058. h = (struct lsp_include_history *)
  2059. lua_newuserdata(L, sizeof(struct lsp_include_history));
  2060. lua_settable(L, LUA_REGISTRYINDEX);
  2061. memset(h, 0, sizeof(struct lsp_include_history));
  2062. }
  2063. /* Register mg module */
  2064. lua_newtable(L);
  2065. switch (lua_env_type) {
  2066. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  2067. reg_string(L, "lua_type", "page");
  2068. break;
  2069. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  2070. reg_string(L, "lua_type", "script");
  2071. break;
  2072. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  2073. reg_string(L, "lua_type", "websocket");
  2074. break;
  2075. }
  2076. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  2077. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  2078. reg_conn_function(L, "cry", lsp_cry, conn);
  2079. reg_conn_function(L, "read", lsp_read, conn);
  2080. reg_conn_function(L, "write", lsp_write, conn);
  2081. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  2082. reg_conn_function(L, "send_file", lsp_send_file, conn);
  2083. reg_conn_function(L, "send_file_body", lsp_send_file_body, conn);
  2084. reg_conn_function(L, "send_http_error", lsp_send_http_error, conn);
  2085. reg_conn_function(L, "send_http_ok", lsp_send_http_ok, conn);
  2086. reg_conn_function(L, "redirect", lsp_redirect, conn);
  2087. }
  2088. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  2089. reg_conn_function(L, "include", lsp_include, conn);
  2090. }
  2091. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  2092. reg_function(L, "write", lwebsock_write);
  2093. #if defined(USE_TIMERS)
  2094. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  2095. reg_function(L, "set_interval", lwebsocket_set_interval);
  2096. #endif
  2097. }
  2098. reg_conn_function(L, "get_mime_type", lsp_get_mime_type, conn);
  2099. reg_conn_function(L, "get_option", lsp_get_option, conn);
  2100. reg_function(L, "time", lsp_get_time);
  2101. reg_function(L, "get_var", lsp_get_var);
  2102. reg_function(L, "split_form_data", lsp_split_form_data);
  2103. reg_function(L, "get_cookie", lsp_get_cookie);
  2104. reg_function(L, "md5", lsp_md5);
  2105. reg_function(L, "url_encode", lsp_url_encode);
  2106. reg_function(L, "url_decode", lsp_url_decode);
  2107. reg_function(L, "base64_encode", lsp_base64_encode);
  2108. reg_function(L, "base64_decode", lsp_base64_decode);
  2109. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  2110. reg_function(L, "random", lsp_random);
  2111. reg_function(L, "get_info", lsp_get_info);
  2112. reg_function(L, "trace", lsp_trace);
  2113. if (pf_uuid_generate.f) {
  2114. reg_function(L, "uuid", lsp_uuid);
  2115. }
  2116. reg_string(L, "version", CIVETWEB_VERSION);
  2117. reg_string(L, "script_name", script_name);
  2118. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2119. reg_string(L, "document_root", conn->dom_ctx->config[DOCUMENT_ROOT]);
  2120. reg_string(L,
  2121. "auth_domain",
  2122. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  2123. #if defined(USE_WEBSOCKET)
  2124. if (conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  2125. reg_string(L,
  2126. "websocket_root",
  2127. conn->dom_ctx->config[WEBSOCKET_ROOT]);
  2128. } else {
  2129. reg_string(L,
  2130. "websocket_root",
  2131. conn->dom_ctx->config[DOCUMENT_ROOT]);
  2132. }
  2133. #endif
  2134. if ((ctx != NULL) && (ctx->systemName != NULL)) {
  2135. reg_string(L, "system", ctx->systemName);
  2136. }
  2137. }
  2138. /* Export connection specific info */
  2139. if (conn != NULL) {
  2140. prepare_lua_request_info(conn, L);
  2141. }
  2142. /* Store as global table "mg" */
  2143. lua_setglobal(L, "mg");
  2144. /* Register "shared" table */
  2145. lua_shared_register(L);
  2146. /* Register default mg.onerror function */
  2147. IGNORE_UNUSED_RESULT(
  2148. luaL_dostring(L,
  2149. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  2150. "debug.traceback(e, 1)) end"));
  2151. /* Check if a preload file is available */
  2152. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2153. preload_file_name = conn->dom_ctx->config[LUA_PRELOAD_FILE];
  2154. }
  2155. /* Preload file into new Lua environment */
  2156. if (preload_file_name) {
  2157. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file_name));
  2158. }
  2159. /* Call user init function */
  2160. if (ctx != NULL) {
  2161. if (ctx->callbacks.init_lua != NULL) {
  2162. ctx->callbacks.init_lua(conn, L);
  2163. }
  2164. }
  2165. /* If debugging is enabled, add a hook */
  2166. if (debug_params) {
  2167. int mask = 0;
  2168. if (0 != strchr(debug_params, 'c')) {
  2169. mask |= LUA_MASKCALL;
  2170. }
  2171. if (0 != strchr(debug_params, 'r')) {
  2172. mask |= LUA_MASKRET;
  2173. }
  2174. if (0 != strchr(debug_params, 'l')) {
  2175. mask |= LUA_MASKLINE;
  2176. }
  2177. lua_sethook(L, lua_debug_hook, mask, 0);
  2178. }
  2179. }
  2180. static int
  2181. lua_error_handler(lua_State *L)
  2182. {
  2183. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  2184. lua_getglobal(L, "mg");
  2185. if (!lua_isnil(L, -1)) {
  2186. lua_getfield(L, -1, "write"); /* call mg.write() */
  2187. lua_pushstring(L, error_msg);
  2188. lua_pushliteral(L, "\n");
  2189. lua_call(L, 2, 0);
  2190. IGNORE_UNUSED_RESULT(
  2191. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  2192. } else {
  2193. printf("Lua error: [%s]\n", error_msg);
  2194. IGNORE_UNUSED_RESULT(
  2195. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  2196. }
  2197. /* TODO(lsm, low): leave the stack balanced */
  2198. return 0;
  2199. }
  2200. static void
  2201. mg_exec_lua_script(struct mg_connection *conn,
  2202. const char *path,
  2203. const void **exports)
  2204. {
  2205. int i;
  2206. lua_State *L;
  2207. /* Assume the script does not support keep_alive. The script may change this
  2208. * by calling mg.keep_alive(true). */
  2209. conn->must_close = 1;
  2210. /* Execute a plain Lua script. */
  2211. if (path != NULL
  2212. && (L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx)))
  2213. != NULL) {
  2214. prepare_lua_environment(
  2215. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  2216. lua_pushcclosure(L, &lua_error_handler, 0);
  2217. if (exports != NULL) {
  2218. #if LUA_VERSION_NUM > 501
  2219. lua_pushglobaltable(L);
  2220. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2221. lua_CFunction func;
  2222. lua_pushstring(L, (const char *)(exports[i]));
  2223. *(const void **)(&func) = exports[i + 1];
  2224. lua_pushcclosure(L, func, 0);
  2225. lua_rawset(L, -3);
  2226. }
  2227. #else
  2228. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2229. lua_CFunction func;
  2230. const char *name = (const char *)(exports[i]);
  2231. *(const void **)(&func) = exports[i + 1];
  2232. lua_register(L, name, func);
  2233. }
  2234. #endif
  2235. }
  2236. if (luaL_loadfile(L, path) != 0) {
  2237. lua_error_handler(L);
  2238. }
  2239. lua_pcall(L, 0, 0, -2);
  2240. lua_close(L);
  2241. }
  2242. }
  2243. static int
  2244. handle_lsp_request(struct mg_connection *conn,
  2245. const char *path,
  2246. struct mg_file *filep,
  2247. struct lua_State *ls)
  2248. {
  2249. void *p = NULL;
  2250. lua_State *L = NULL;
  2251. struct lsp_include_history *include_history;
  2252. int error = 1;
  2253. void *file_in_memory; /* TODO(low): remove when removing "file in memory" */
  2254. int (*run_lsp)(struct mg_connection *,
  2255. const char *,
  2256. const char *,
  2257. int64_t,
  2258. lua_State *,
  2259. int);
  2260. const char *addr;
  2261. /* mg_fopen opens the file and sets the size accordingly */
  2262. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  2263. /* File not found or not accessible */
  2264. if (ls == NULL) {
  2265. mg_send_http_error(conn,
  2266. 500,
  2267. "Error: Cannot open script file %s",
  2268. path);
  2269. } else {
  2270. luaL_error(ls, "Cannot include [%s]: not found", path);
  2271. }
  2272. goto cleanup_handle_lsp_request;
  2273. }
  2274. #if defined(MG_USE_OPEN_FILE)
  2275. /* The "file in memory" feature is going to be removed. For details see
  2276. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI */
  2277. file_in_memory = filep->access.membuf;
  2278. #else
  2279. file_in_memory = NULL;
  2280. #endif
  2281. /* Map file in memory (size is known). */
  2282. if (file_in_memory == NULL
  2283. && (p = mmap(NULL,
  2284. (size_t)filep->stat.size,
  2285. PROT_READ,
  2286. MAP_PRIVATE,
  2287. fileno(filep->access.fp),
  2288. 0))
  2289. == MAP_FAILED) {
  2290. /* File was not already in memory, and mmap failed now.
  2291. * Since wi have no data, show an error. */
  2292. if (ls == NULL) {
  2293. /* No open Lua state - use generic error function */
  2294. mg_send_http_error(
  2295. conn,
  2296. 500,
  2297. "Error: Cannot open script\nFile %s can not be mapped",
  2298. path);
  2299. } else {
  2300. /* Lua state exists - use Lua error function */
  2301. luaL_error(ls,
  2302. "mmap(%s, %zu, %d): %s",
  2303. path,
  2304. (size_t)filep->stat.size,
  2305. fileno(filep->access.fp),
  2306. strerror(errno));
  2307. }
  2308. goto cleanup_handle_lsp_request;
  2309. }
  2310. /* File content is now memory mapped. Get mapping address */
  2311. addr = (file_in_memory == NULL) ? (const char *)p
  2312. : (const char *)file_in_memory;
  2313. /* Get a Lua state */
  2314. if (ls != NULL) {
  2315. /* We got a Lua state as argument. Use it! */
  2316. L = ls;
  2317. } else {
  2318. /* We need to create a Lua state. */
  2319. L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2320. if (L == NULL) {
  2321. /* We neither got a Lua state from the command line,
  2322. * nor did we succeed in creating our own state.
  2323. * Show an error, and stop further processing of this request. */
  2324. mg_send_http_error(
  2325. conn,
  2326. 500,
  2327. "%s",
  2328. "Error: Cannot execute script\nlua_newstate failed");
  2329. goto cleanup_handle_lsp_request;
  2330. }
  2331. /* New Lua state needs CivetWeb functions (e.g., the "mg" library). */
  2332. prepare_lua_environment(
  2333. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  2334. }
  2335. /* Get LSP include history table */
  2336. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  2337. lua_gettable(L, LUA_REGISTRYINDEX);
  2338. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  2339. /* Store script name and increment depth */
  2340. include_history->depth++;
  2341. include_history->script[include_history->depth] = path;
  2342. /* Lua state is ready to use now. */
  2343. /* Currently we have two different syntax options:
  2344. * Either "classic" CivetWeb syntax:
  2345. * <? code ?>
  2346. * <?= expression ?>
  2347. * Or "Kepler Syntax"
  2348. * https://keplerproject.github.io/cgilua/manual.html#templates
  2349. * <?lua chunk ?>
  2350. * <?lua= expression ?>
  2351. * <% chunk %>
  2352. * <%= expression %>
  2353. *
  2354. * Two important differences are:
  2355. * - In the "classic" CivetWeb syntax, the Lua Page had to send the HTTP
  2356. * response headers itself. So the first lines are usually something like
  2357. * HTTP/1.0 200 OK
  2358. * Content-Type: text/html
  2359. * followed by additional headers and an empty line, before the actual
  2360. * Lua page in HTML syntax with <? code ?> tags.
  2361. * The "Kepler"Syntax" does not send any HTTP header from the Lua Server
  2362. * Page, but starts directly with <html> code - so it cannot influence
  2363. * the HTTP response code, e.g., to send a 301 Moved Permanently.
  2364. * Due to this difference, the same *.lp file cannot be used with the
  2365. * same algorithm.
  2366. * - The "Kepler Syntax" used to allow mixtures of Lua and HTML inside an
  2367. * incomplete Lua block, e.g.:
  2368. * <lua? for i=1,10 do ?><li><%= key %></li><lua? end ?>
  2369. * This was not provided in "classic" CivetWeb syntax, but you had to use
  2370. * <? for i=1,10 do mg.write("<li>"..i.."</li>") end ?>
  2371. * instead. The parsing algorithm for "Kepler syntax" is more complex
  2372. * than for "classic" CivetWeb syntax - TODO: check timing/performance.
  2373. *
  2374. * CivetWeb now can use both parsing methods, but needs to know what
  2375. * parsing algorithm should be used.
  2376. * Idea: Files starting with '<' are HTML files in "Kepler Syntax", except
  2377. * "<?" which means "classic CivetWeb Syntax".
  2378. *
  2379. */
  2380. run_lsp = run_lsp_civetweb;
  2381. if ((addr[0] == '<') && (addr[1] != '?')) {
  2382. run_lsp = run_lsp_kepler;
  2383. }
  2384. /* We're not sending HTTP headers here, Lua page must do it. */
  2385. error =
  2386. run_lsp(conn, path, addr, filep->stat.size, L, include_history->depth);
  2387. /* pop from stack */
  2388. include_history->depth--;
  2389. cleanup_handle_lsp_request:
  2390. if (L != NULL && ls == NULL)
  2391. lua_close(L);
  2392. if (p != NULL)
  2393. munmap(p, filep->stat.size);
  2394. (void)mg_fclose(&filep->access);
  2395. return error;
  2396. }
  2397. #if defined(USE_WEBSOCKET)
  2398. struct mg_shared_lua_websocket_list {
  2399. struct lua_websock_data ws;
  2400. struct mg_shared_lua_websocket_list *next;
  2401. };
  2402. static void *
  2403. lua_websocket_new(const char *script, struct mg_connection *conn)
  2404. {
  2405. struct mg_shared_lua_websocket_list **shared_websock_list =
  2406. &(conn->dom_ctx->shared_lua_websockets);
  2407. struct lua_websock_data *ws;
  2408. int err, ok = 0;
  2409. DEBUG_ASSERT(conn->lua_websocket_state == NULL);
  2410. /* lock list (mg_context global) */
  2411. mg_lock_context(conn->phys_ctx);
  2412. while (*shared_websock_list) {
  2413. /* check if ws already in list */
  2414. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  2415. break;
  2416. }
  2417. shared_websock_list = &((*shared_websock_list)->next);
  2418. }
  2419. if (*shared_websock_list == NULL) {
  2420. /* add ws to list */
  2421. *shared_websock_list =
  2422. (struct mg_shared_lua_websocket_list *)mg_calloc_ctx(
  2423. sizeof(struct mg_shared_lua_websocket_list), 1, conn->phys_ctx);
  2424. if (*shared_websock_list == NULL) {
  2425. conn->must_close = 1;
  2426. mg_unlock_context(conn->phys_ctx);
  2427. mg_cry_internal(conn,
  2428. "%s",
  2429. "Cannot create shared websocket struct, OOM");
  2430. return NULL;
  2431. }
  2432. /* init ws list element */
  2433. ws = &(*shared_websock_list)->ws;
  2434. ws->script = mg_strdup_ctx(script, conn->phys_ctx);
  2435. if (!ws->script) {
  2436. conn->must_close = 1;
  2437. mg_unlock_context(conn->phys_ctx);
  2438. mg_cry_internal(conn,
  2439. "%s",
  2440. "Cannot create shared websocket script, OOM");
  2441. return NULL;
  2442. }
  2443. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  2444. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2445. ws->state = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2446. ws->conn[0] = conn;
  2447. ws->references = 1;
  2448. prepare_lua_environment(conn->phys_ctx,
  2449. conn,
  2450. ws,
  2451. ws->state,
  2452. script,
  2453. LUA_ENV_TYPE_LUA_WEBSOCKET);
  2454. err = luaL_loadfile(ws->state, script);
  2455. if (err != 0) {
  2456. lua_cry(conn, err, ws->state, script, "load");
  2457. }
  2458. err = lua_pcall(ws->state, 0, 0, 0);
  2459. if (err != 0) {
  2460. lua_cry(conn, err, ws->state, script, "init");
  2461. }
  2462. } else {
  2463. /* inc ref count */
  2464. ws = &(*shared_websock_list)->ws;
  2465. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2466. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  2467. }
  2468. mg_unlock_context(conn->phys_ctx);
  2469. /* call add */
  2470. lua_getglobal(ws->state, "open");
  2471. lua_newtable(ws->state);
  2472. prepare_lua_request_info(conn, ws->state);
  2473. lua_pushstring(ws->state, "client");
  2474. lua_pushlightuserdata(ws->state, (void *)conn);
  2475. lua_rawset(ws->state, -3);
  2476. err = lua_pcall(ws->state, 1, 1, 0);
  2477. if (err != 0) {
  2478. lua_cry(conn, err, ws->state, script, "open handler");
  2479. } else {
  2480. if (lua_isboolean(ws->state, -1)) {
  2481. ok = lua_toboolean(ws->state, -1);
  2482. }
  2483. lua_pop(ws->state, 1);
  2484. }
  2485. if (!ok) {
  2486. /* Remove from ws connection list. */
  2487. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  2488. * (see websocket_close). */
  2489. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  2490. }
  2491. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2492. return ok ? (void *)ws : NULL;
  2493. }
  2494. static int
  2495. lua_websocket_data(struct mg_connection *conn,
  2496. int bits,
  2497. char *data,
  2498. size_t data_len,
  2499. void *ws_arg)
  2500. {
  2501. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2502. int err, ok = 0;
  2503. DEBUG_ASSERT(ws != NULL);
  2504. DEBUG_ASSERT(ws->state != NULL);
  2505. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2506. lua_getglobal(ws->state, "data");
  2507. lua_newtable(ws->state);
  2508. lua_pushstring(ws->state, "client");
  2509. lua_pushlightuserdata(ws->state, (void *)conn);
  2510. lua_rawset(ws->state, -3);
  2511. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  2512. a meaning according to
  2513. http://tools.ietf.org/html/rfc6455,
  2514. section 5.2 */
  2515. lua_pushnumber(ws->state, bits);
  2516. lua_rawset(ws->state, -3);
  2517. lua_pushstring(ws->state, "data");
  2518. lua_pushlstring(ws->state, data, data_len);
  2519. lua_rawset(ws->state, -3);
  2520. err = lua_pcall(ws->state, 1, 1, 0);
  2521. if (err != 0) {
  2522. lua_cry(conn, err, ws->state, ws->script, "data handler");
  2523. } else {
  2524. if (lua_isboolean(ws->state, -1)) {
  2525. ok = lua_toboolean(ws->state, -1);
  2526. }
  2527. lua_pop(ws->state, 1);
  2528. }
  2529. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2530. return ok;
  2531. }
  2532. static int
  2533. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  2534. {
  2535. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2536. int err, ok = 0;
  2537. DEBUG_ASSERT(ws != NULL);
  2538. DEBUG_ASSERT(ws->state != NULL);
  2539. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2540. lua_getglobal(ws->state, "ready");
  2541. lua_newtable(ws->state);
  2542. lua_pushstring(ws->state, "client");
  2543. lua_pushlightuserdata(ws->state, (void *)conn);
  2544. lua_rawset(ws->state, -3);
  2545. err = lua_pcall(ws->state, 1, 1, 0);
  2546. if (err != 0) {
  2547. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  2548. } else {
  2549. if (lua_isboolean(ws->state, -1)) {
  2550. ok = lua_toboolean(ws->state, -1);
  2551. }
  2552. lua_pop(ws->state, 1);
  2553. }
  2554. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2555. return ok;
  2556. }
  2557. static void
  2558. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  2559. {
  2560. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2561. struct mg_shared_lua_websocket_list **shared_websock_list =
  2562. &(conn->dom_ctx->shared_lua_websockets);
  2563. int err = 0;
  2564. unsigned i;
  2565. DEBUG_ASSERT(ws != NULL);
  2566. DEBUG_ASSERT(ws->state != NULL);
  2567. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2568. lua_getglobal(ws->state, "close");
  2569. lua_newtable(ws->state);
  2570. lua_pushstring(ws->state, "client");
  2571. lua_pushlightuserdata(ws->state, (void *)conn);
  2572. lua_rawset(ws->state, -3);
  2573. err = lua_pcall(ws->state, 1, 0, 0);
  2574. if (err != 0) {
  2575. lua_cry(conn, err, ws->state, ws->script, "close handler");
  2576. }
  2577. for (i = 0; i < ws->references; i++) {
  2578. if (ws->conn[i] == conn) {
  2579. ws->references--;
  2580. ws->conn[i] = ws->conn[ws->references];
  2581. }
  2582. }
  2583. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  2584. This must only be done, when all connections are closed, and all
  2585. asynchronous operations and timers are completed/expired. */
  2586. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  2587. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2588. }
  2589. #endif
  2590. static lua_State *
  2591. mg_prepare_lua_context_script(const char *file_name,
  2592. struct mg_context *ctx,
  2593. char *ebuf,
  2594. size_t ebuf_len)
  2595. {
  2596. struct lua_State *L;
  2597. int lua_ret;
  2598. const char *lua_err_txt;
  2599. (void)ctx;
  2600. L = luaL_newstate();
  2601. if (L == NULL) {
  2602. mg_snprintf(NULL,
  2603. NULL, /* No truncation check for ebuf */
  2604. ebuf,
  2605. ebuf_len,
  2606. "Error: %s",
  2607. "Cannot create Lua state");
  2608. return 0;
  2609. }
  2610. civetweb_open_lua_libs(L);
  2611. lua_ret = luaL_loadfile(L, file_name);
  2612. if (lua_ret != LUA_OK) {
  2613. /* Error when loading the file (e.g. file not found,
  2614. * out of memory, ...)
  2615. */
  2616. lua_err_txt = lua_tostring(L, -1);
  2617. mg_snprintf(NULL,
  2618. NULL, /* No truncation check for ebuf */
  2619. ebuf,
  2620. ebuf_len,
  2621. "Error loading file %s: %s\n",
  2622. file_name,
  2623. lua_err_txt);
  2624. return 0;
  2625. }
  2626. /* The script file is loaded, now call it */
  2627. lua_ret = lua_pcall(L,
  2628. /* no arguments */ 0,
  2629. /* zero or one return value */ 1,
  2630. /* errors as strint return value */ 0);
  2631. if (lua_ret != LUA_OK) {
  2632. /* Error when executing the script */
  2633. lua_err_txt = lua_tostring(L, -1);
  2634. mg_snprintf(NULL,
  2635. NULL, /* No truncation check for ebuf */
  2636. ebuf,
  2637. ebuf_len,
  2638. "Error running file %s: %s\n",
  2639. file_name,
  2640. lua_err_txt);
  2641. return 0;
  2642. }
  2643. /* lua_close(L); must be done somewhere else */
  2644. return L;
  2645. }
  2646. int
  2647. run_lua(const char *file_name)
  2648. {
  2649. int func_ret = EXIT_FAILURE;
  2650. char ebuf[512] = {0};
  2651. lua_State *L =
  2652. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  2653. if (L) {
  2654. /* Script executed */
  2655. if (lua_type(L, -1) == LUA_TNUMBER) {
  2656. func_ret = (int)lua_tonumber(L, -1);
  2657. } else {
  2658. func_ret = EXIT_SUCCESS;
  2659. }
  2660. lua_close(L);
  2661. } else {
  2662. fprintf(stderr, "%s\n", ebuf);
  2663. }
  2664. return func_ret;
  2665. }
  2666. static void *lib_handle_uuid = NULL;
  2667. static void
  2668. lua_init_optional_libraries(void)
  2669. {
  2670. /* Create logging mutex */
  2671. pthread_mutex_init(&s_lua_traceMutex, &pthread_mutex_attr);
  2672. /* shared Lua state */
  2673. lua_shared_init();
  2674. /* UUID library */
  2675. #if !defined(_WIN32)
  2676. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  2677. pf_uuid_generate.p =
  2678. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  2679. #else
  2680. pf_uuid_generate.p = 0;
  2681. #endif
  2682. }
  2683. static void
  2684. lua_exit_optional_libraries(void)
  2685. {
  2686. /* UUID library */
  2687. #if !defined(_WIN32)
  2688. if (lib_handle_uuid) {
  2689. dlclose(lib_handle_uuid);
  2690. }
  2691. #endif
  2692. pf_uuid_generate.p = 0;
  2693. lib_handle_uuid = NULL;
  2694. /* shared Lua state */
  2695. lua_shared_exit();
  2696. /* Delete logging mutex */
  2697. pthread_mutex_destroy(&s_lua_traceMutex);
  2698. }
  2699. /* End of mod_lua.inl */