mod_lua.inl 71 KB

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