mod_lua.inl 70 KB

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