mod_lua.inl 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977
  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. static int s_lua_traceLevel = 1;
  1392. static FILE *s_lua_traceFile = NULL;
  1393. static pthread_mutex_t s_lua_traceMutex;
  1394. /* mg.trace */
  1395. static int
  1396. lsp_trace(lua_State *L)
  1397. {
  1398. int num_args = lua_gettop(L);
  1399. int arg_type[8];
  1400. int trace_level = 0;
  1401. int firstarg = 1;
  1402. int i;
  1403. for (i=0; i<8; i++) {
  1404. if (num_args >= (i + 1)) {
  1405. arg_type[i] = lua_type(L, (i + 1));
  1406. }
  1407. else {
  1408. arg_type[i] = LUA_TNIL;
  1409. }
  1410. }
  1411. if (arg_type[0] == LUA_TNUMBER) {
  1412. trace_level = lua_tointeger(L, 1);
  1413. if (num_args == 1) {
  1414. /* Set a new trace level, return the current one. */
  1415. lua_pushinteger(L, s_lua_traceLevel);
  1416. s_lua_traceLevel = trace_level;
  1417. if (s_lua_traceFile) {
  1418. pthread_mutex_lock(&s_lua_traceMutex);
  1419. fflush(s_lua_traceFile);
  1420. pthread_mutex_unlock(&s_lua_traceMutex);
  1421. }
  1422. return 1;
  1423. }
  1424. firstarg = 2;
  1425. }
  1426. if (trace_level > s_lua_traceLevel) {
  1427. /* If this trace request has a higher trace level than the global trace level, do not trace. */
  1428. lua_pushboolean(L, 0);
  1429. return 1;
  1430. }
  1431. /* Print to file */
  1432. if (s_lua_traceFile) {
  1433. pthread_mutex_lock(&s_lua_traceMutex);
  1434. for (i = firstarg; i <= num_args; i++) {
  1435. if (arg_type[i - 1] == LUA_TSTRING) {
  1436. const char *arg = lua_tostring(L, i);
  1437. fprintf(s_lua_traceFile, "%s\n", arg);
  1438. }
  1439. }
  1440. pthread_mutex_unlock(&s_lua_traceMutex);
  1441. }
  1442. lua_pushboolean(L, 1);
  1443. return 1;
  1444. }
  1445. /* UUID library and function pointer */
  1446. union {
  1447. void *p;
  1448. void (*f)(unsigned char uuid[16]);
  1449. } pf_uuid_generate;
  1450. /* mg.uuid */
  1451. static int
  1452. lsp_uuid(lua_State *L)
  1453. {
  1454. union {
  1455. unsigned char uuid_array[16];
  1456. struct uuid_struct_type {
  1457. uint32_t data1;
  1458. uint16_t data2;
  1459. uint16_t data3;
  1460. uint8_t data4[8];
  1461. } uuid_struct;
  1462. } uuid;
  1463. char uuid_str[40];
  1464. int num_args = lua_gettop(L);
  1465. memset(&uuid, 0, sizeof(uuid));
  1466. memset(uuid_str, 0, sizeof(uuid_str));
  1467. if (num_args == 0) {
  1468. pf_uuid_generate.f(uuid.uuid_array);
  1469. sprintf(uuid_str,
  1470. "{%08lX-%04X-%04X-%02X%02X-"
  1471. "%02X%02X%02X%02X%02X%02X}",
  1472. (unsigned long)uuid.uuid_struct.data1,
  1473. (unsigned)uuid.uuid_struct.data2,
  1474. (unsigned)uuid.uuid_struct.data3,
  1475. (unsigned)uuid.uuid_struct.data4[0],
  1476. (unsigned)uuid.uuid_struct.data4[1],
  1477. (unsigned)uuid.uuid_struct.data4[2],
  1478. (unsigned)uuid.uuid_struct.data4[3],
  1479. (unsigned)uuid.uuid_struct.data4[4],
  1480. (unsigned)uuid.uuid_struct.data4[5],
  1481. (unsigned)uuid.uuid_struct.data4[6],
  1482. (unsigned)uuid.uuid_struct.data4[7]);
  1483. lua_pushstring(L, uuid_str);
  1484. return 1;
  1485. }
  1486. /* Syntax error */
  1487. return luaL_error(L, "invalid random() call");
  1488. }
  1489. #if defined(USE_WEBSOCKET)
  1490. struct lua_websock_data {
  1491. lua_State *state;
  1492. char *script;
  1493. unsigned references;
  1494. struct mg_connection *conn[MAX_WORKER_THREADS];
  1495. pthread_mutex_t ws_mutex;
  1496. };
  1497. #endif
  1498. /* mg.write for websockets */
  1499. static int
  1500. lwebsock_write(lua_State *L)
  1501. {
  1502. #if defined(USE_WEBSOCKET)
  1503. int num_args = lua_gettop(L);
  1504. struct lua_websock_data *ws;
  1505. const char *str;
  1506. size_t size;
  1507. int opcode = -1;
  1508. unsigned i;
  1509. struct mg_connection *client = NULL;
  1510. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1511. lua_gettable(L, LUA_REGISTRYINDEX);
  1512. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1513. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1514. if (num_args == 1) {
  1515. /* just one text: send it to all client */
  1516. if (lua_isstring(L, 1)) {
  1517. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1518. }
  1519. } else if (num_args == 2) {
  1520. if (lua_isnumber(L, 1)) {
  1521. /* opcode number and message text */
  1522. opcode = (int)lua_tointeger(L, 1);
  1523. } else if (lua_isstring(L, 1)) {
  1524. /* opcode string and message text */
  1525. str = lua_tostring(L, 1);
  1526. if (!mg_strncasecmp(str, "text", 4))
  1527. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1528. else if (!mg_strncasecmp(str, "bin", 3))
  1529. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1530. else if (!mg_strncasecmp(str, "close", 5))
  1531. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1532. else if (!mg_strncasecmp(str, "ping", 4))
  1533. opcode = MG_WEBSOCKET_OPCODE_PING;
  1534. else if (!mg_strncasecmp(str, "pong", 4))
  1535. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1536. else if (!mg_strncasecmp(str, "cont", 4))
  1537. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1538. } else if (lua_isuserdata(L, 1)) {
  1539. /* client id and message text */
  1540. client = (struct mg_connection *)lua_touserdata(L, 1);
  1541. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1542. }
  1543. } else if (num_args == 3) {
  1544. if (lua_isuserdata(L, 1)) {
  1545. client = (struct mg_connection *)lua_touserdata(L, 1);
  1546. if (lua_isnumber(L, 2)) {
  1547. /* client id, opcode number and message text */
  1548. opcode = (int)lua_tointeger(L, 2);
  1549. } else if (lua_isstring(L, 2)) {
  1550. /* client id, opcode string and message text */
  1551. str = lua_tostring(L, 2);
  1552. if (!mg_strncasecmp(str, "text", 4))
  1553. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1554. else if (!mg_strncasecmp(str, "bin", 3))
  1555. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1556. else if (!mg_strncasecmp(str, "close", 5))
  1557. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1558. else if (!mg_strncasecmp(str, "ping", 4))
  1559. opcode = MG_WEBSOCKET_OPCODE_PING;
  1560. else if (!mg_strncasecmp(str, "pong", 4))
  1561. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1562. else if (!mg_strncasecmp(str, "cont", 4))
  1563. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1564. }
  1565. }
  1566. }
  1567. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  1568. str = lua_tolstring(L, num_args, &size);
  1569. if (client) {
  1570. for (i = 0; i < ws->references; i++) {
  1571. if (client == ws->conn[i]) {
  1572. mg_lock_connection(ws->conn[i]);
  1573. mg_websocket_write(ws->conn[i], opcode, str, size);
  1574. mg_unlock_connection(ws->conn[i]);
  1575. }
  1576. }
  1577. } else {
  1578. for (i = 0; i < ws->references; i++) {
  1579. mg_lock_connection(ws->conn[i]);
  1580. mg_websocket_write(ws->conn[i], opcode, str, size);
  1581. mg_unlock_connection(ws->conn[i]);
  1582. }
  1583. }
  1584. } else {
  1585. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1586. return luaL_error(L, "invalid websocket write() call");
  1587. }
  1588. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1589. #else
  1590. (void)(L); /* unused */
  1591. #endif
  1592. return 0;
  1593. }
  1594. struct laction_arg {
  1595. lua_State *state;
  1596. const char *script;
  1597. pthread_mutex_t *pmutex;
  1598. char txt[1];
  1599. };
  1600. static int
  1601. lua_action(struct laction_arg *arg)
  1602. {
  1603. int err, ok;
  1604. struct mg_context *ctx;
  1605. (void)pthread_mutex_lock(arg->pmutex);
  1606. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  1607. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  1608. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  1609. lua_pop(arg->state, 1);
  1610. err = luaL_loadstring(arg->state, arg->txt);
  1611. if (err != 0) {
  1612. struct mg_connection fc;
  1613. lua_cry(
  1614. fake_connection(&fc, ctx), err, arg->state, arg->script, "timer");
  1615. (void)pthread_mutex_unlock(arg->pmutex);
  1616. mg_free(arg);
  1617. return 0;
  1618. }
  1619. err = lua_pcall(arg->state, 0, 1, 0);
  1620. if (err != 0) {
  1621. struct mg_connection fc;
  1622. lua_cry(
  1623. fake_connection(&fc, ctx), err, arg->state, arg->script, "timer");
  1624. (void)pthread_mutex_unlock(arg->pmutex);
  1625. mg_free(arg);
  1626. return 0;
  1627. }
  1628. ok = lua_type(arg->state, -1);
  1629. if (lua_isboolean(arg->state, -1)) {
  1630. ok = lua_toboolean(arg->state, -1);
  1631. } else {
  1632. ok = 0;
  1633. }
  1634. lua_pop(arg->state, 1);
  1635. (void)pthread_mutex_unlock(arg->pmutex);
  1636. if (!ok) {
  1637. mg_free(arg);
  1638. }
  1639. return ok;
  1640. }
  1641. static int
  1642. lua_action_free(struct laction_arg *arg)
  1643. {
  1644. if (lua_action(arg)) {
  1645. mg_free(arg);
  1646. }
  1647. return 0;
  1648. }
  1649. static int
  1650. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1651. {
  1652. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1653. int num_args = lua_gettop(L);
  1654. struct lua_websock_data *ws;
  1655. int type1, type2, ok = 0;
  1656. double timediff;
  1657. struct mg_context *ctx;
  1658. struct laction_arg *arg;
  1659. const char *txt;
  1660. size_t txt_len;
  1661. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1662. lua_gettable(L, LUA_REGISTRYINDEX);
  1663. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1664. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1665. lua_gettable(L, LUA_REGISTRYINDEX);
  1666. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1667. if (num_args < 2) {
  1668. return luaL_error(L,
  1669. "not enough arguments for set_timer/interval() call");
  1670. }
  1671. type1 = lua_type(L, 1);
  1672. type2 = lua_type(L, 2);
  1673. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1674. timediff = (double)lua_tonumber(L, 2);
  1675. txt = lua_tostring(L, 1);
  1676. txt_len = strlen(txt);
  1677. arg = (struct laction_arg *)mg_malloc_ctx(sizeof(struct laction_arg)
  1678. + txt_len + 10,
  1679. ctx);
  1680. if (!arg) {
  1681. return luaL_error(L, "out of memory");
  1682. }
  1683. arg->state = L;
  1684. arg->script = ws->script;
  1685. arg->pmutex = &(ws->ws_mutex);
  1686. memcpy(arg->txt, "return(", 7);
  1687. memcpy(arg->txt + 7, txt, txt_len);
  1688. arg->txt[txt_len + 7] = ')';
  1689. arg->txt[txt_len + 8] = 0;
  1690. ok =
  1691. (0
  1692. == timer_add(ctx,
  1693. timediff,
  1694. is_periodic,
  1695. 1,
  1696. (taction)(is_periodic ? lua_action : lua_action_free),
  1697. (void *)arg));
  1698. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1699. /* TODO (mid): not implemented yet */
  1700. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1701. } else {
  1702. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1703. }
  1704. lua_pushboolean(L, ok);
  1705. return 1;
  1706. #else
  1707. (void)(L); /* unused */
  1708. (void)(is_periodic); /* unused */
  1709. return 0;
  1710. #endif
  1711. }
  1712. /* mg.set_timeout for websockets */
  1713. static int
  1714. lwebsocket_set_timeout(lua_State *L)
  1715. {
  1716. return lwebsocket_set_timer(L, 0);
  1717. }
  1718. /* mg.set_interval for websockets */
  1719. static int
  1720. lwebsocket_set_interval(lua_State *L)
  1721. {
  1722. return lwebsocket_set_timer(L, 1);
  1723. }
  1724. /* Debug hook */
  1725. static void
  1726. lua_debug_hook(lua_State *L, lua_Debug *ar)
  1727. {
  1728. int i;
  1729. int stack_len = lua_gettop(L);
  1730. lua_getinfo(L, "nSlu", ar);
  1731. if (ar->event == LUA_HOOKCALL) {
  1732. printf("call\n");
  1733. } else if (ar->event == LUA_HOOKRET) {
  1734. printf("ret\n");
  1735. #if defined(LUA_HOOKTAILRET)
  1736. } else if (ar->event == LUA_HOOKTAILRET) {
  1737. printf("tail ret\n");
  1738. #endif
  1739. #if defined(LUA_HOOKTAILCALL)
  1740. } else if (ar->event == LUA_HOOKTAILCALL) {
  1741. printf("tail call\n");
  1742. #endif
  1743. } else if (ar->event == LUA_HOOKLINE) {
  1744. printf("line\n");
  1745. } else if (ar->event == LUA_HOOKCOUNT) {
  1746. printf("count\n");
  1747. } else {
  1748. printf("unknown (%i)\n", ar->event);
  1749. }
  1750. if (ar->currentline >= 0) {
  1751. printf("%s:%i\n", ar->source, ar->currentline);
  1752. }
  1753. printf("%s (%s)\n", ar->name, ar->namewhat);
  1754. for (i = 1; i <= stack_len; i++) { /* repeat for each level */
  1755. int val_type = lua_type(L, i);
  1756. const char *s;
  1757. size_t n;
  1758. switch (val_type) {
  1759. case LUA_TNIL:
  1760. /* nil value on the stack */
  1761. printf("nil\n");
  1762. break;
  1763. case LUA_TBOOLEAN:
  1764. /* boolean (true / false) */
  1765. printf("boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
  1766. break;
  1767. case LUA_TNUMBER:
  1768. /* number */
  1769. printf("number: %g\n", lua_tonumber(L, i));
  1770. break;
  1771. case LUA_TSTRING:
  1772. /* string with limited length */
  1773. s = lua_tolstring(L, i, &n);
  1774. printf("string: '%.*s%s\n",
  1775. ((n > 30) ? 28 : (int)n),
  1776. s,
  1777. ((n > 30) ? ".." : "'"));
  1778. break;
  1779. default:
  1780. /* other values */
  1781. printf("%s\n", lua_typename(L, val_type));
  1782. break;
  1783. }
  1784. }
  1785. printf("\n");
  1786. }
  1787. /* Lua Environment */
  1788. enum {
  1789. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1790. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1791. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1792. };
  1793. static void
  1794. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1795. {
  1796. const char *s;
  1797. int i;
  1798. /* Export mg.request_info */
  1799. lua_pushstring(L, "request_info");
  1800. lua_newtable(L);
  1801. reg_string(L, "request_method", conn->request_info.request_method);
  1802. reg_string(L, "request_uri", conn->request_info.request_uri);
  1803. reg_string(L, "uri", conn->request_info.local_uri);
  1804. reg_string(L, "http_version", conn->request_info.http_version);
  1805. reg_string(L, "query_string", conn->request_info.query_string);
  1806. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1807. /* TODO (high): ip version */
  1808. reg_int(L, "remote_port", conn->request_info.remote_port);
  1809. reg_int(L, "num_headers", conn->request_info.num_headers);
  1810. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1811. if (conn->path_info != NULL) {
  1812. reg_string(L, "path_info", conn->path_info);
  1813. }
  1814. if (conn->request_info.content_length >= 0) {
  1815. /* reg_int64: content_length */
  1816. lua_pushstring(L, "content_length");
  1817. lua_pushnumber(
  1818. L,
  1819. (lua_Number)conn->request_info
  1820. .content_length); /* lua_Number may be used as 52 bit integer */
  1821. lua_rawset(L, -3);
  1822. }
  1823. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1824. reg_string(L, "content_type", s);
  1825. }
  1826. if (conn->request_info.remote_user != NULL) {
  1827. reg_string(L, "remote_user", conn->request_info.remote_user);
  1828. reg_string(L, "auth_type", "Digest");
  1829. }
  1830. reg_boolean(L, "https", conn->ssl != NULL);
  1831. if (conn->status_code > 0) {
  1832. /* Lua error handler should show the status code */
  1833. reg_int(L, "status", conn->status_code);
  1834. }
  1835. /* Table "HTTP headers" */
  1836. lua_pushstring(L, "http_headers");
  1837. lua_newtable(L);
  1838. for (i = 0; i < conn->request_info.num_headers; i++) {
  1839. reg_string(L,
  1840. conn->request_info.http_headers[i].name,
  1841. conn->request_info.http_headers[i].value);
  1842. }
  1843. lua_rawset(L, -3);
  1844. /* Table "Client Certificate" */
  1845. if (conn->request_info.client_cert) {
  1846. lua_pushstring(L, "client_cert");
  1847. lua_newtable(L);
  1848. reg_string(L, "subject", conn->request_info.client_cert->subject);
  1849. reg_string(L, "issuer", conn->request_info.client_cert->issuer);
  1850. reg_string(L, "serial", conn->request_info.client_cert->serial);
  1851. reg_string(L, "finger", conn->request_info.client_cert->finger);
  1852. lua_rawset(L, -3);
  1853. }
  1854. /* End of request_info */
  1855. lua_rawset(L, -3);
  1856. }
  1857. static void *
  1858. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1859. {
  1860. (void)osize; /* not used */
  1861. if (nsize == 0) {
  1862. mg_free(ptr);
  1863. return NULL;
  1864. }
  1865. return mg_realloc_ctx(ptr, nsize, (struct mg_context *)ud);
  1866. }
  1867. /* In CivetWeb, Lua-Shared is used as *.inl file */
  1868. #define LUA_SHARED_INTERFACE static
  1869. #include "mod_lua_shared.inl"
  1870. static void
  1871. civetweb_open_lua_libs(lua_State *L)
  1872. {
  1873. {
  1874. extern void luaL_openlibs(lua_State *);
  1875. luaL_openlibs(L);
  1876. }
  1877. #if defined(USE_LUA_SQLITE3)
  1878. {
  1879. extern int luaopen_lsqlite3(lua_State *);
  1880. luaopen_lsqlite3(L);
  1881. }
  1882. #endif
  1883. #if defined(USE_LUA_LUAXML)
  1884. {
  1885. extern int luaopen_LuaXML_lib(lua_State *);
  1886. luaopen_LuaXML_lib(L);
  1887. }
  1888. #endif
  1889. #if defined(USE_LUA_FILE_SYSTEM)
  1890. {
  1891. extern int luaopen_lfs(lua_State *);
  1892. luaopen_lfs(L);
  1893. }
  1894. #endif
  1895. }
  1896. static void
  1897. prepare_lua_environment(struct mg_context *ctx,
  1898. struct mg_connection *conn,
  1899. struct lua_websock_data *ws_conn_list,
  1900. lua_State *L,
  1901. const char *script_name,
  1902. int lua_env_type)
  1903. {
  1904. const char *preload_file_name = NULL;
  1905. const char *debug_params = NULL;
  1906. civetweb_open_lua_libs(L);
  1907. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1908. /* Check if debugging should be enabled */
  1909. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1910. debug_params = conn->dom_ctx->config[LUA_DEBUG_PARAMS];
  1911. }
  1912. #endif
  1913. #if LUA_VERSION_NUM == 502
  1914. /* Keep the "connect" method for compatibility,
  1915. * but do not backport it to Lua 5.1.
  1916. * TODO: Redesign the interface.
  1917. */
  1918. luaL_newmetatable(L, LUASOCKET);
  1919. /* self.__index = self */
  1920. lua_pushvalue(L, -1);
  1921. lua_setfield(L, -2, "__index");
  1922. luaL_setfuncs(L, luasocket_methods, 0);
  1923. lua_pop(L, 1);
  1924. lua_register(L, "connect", lsp_connect);
  1925. #endif
  1926. /* Store context in the registry */
  1927. if (ctx != NULL) {
  1928. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1929. lua_pushlightuserdata(L, (void *)ctx);
  1930. lua_settable(L, LUA_REGISTRYINDEX);
  1931. }
  1932. if (ws_conn_list != NULL) {
  1933. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1934. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1935. lua_settable(L, LUA_REGISTRYINDEX);
  1936. }
  1937. /* Lua server pages store the depth of mg.include, in order
  1938. * to detect recursions and prevent stack overflows. */
  1939. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1940. struct lsp_include_history *h;
  1941. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  1942. h = (struct lsp_include_history *)
  1943. lua_newuserdata(L, sizeof(struct lsp_include_history));
  1944. lua_settable(L, LUA_REGISTRYINDEX);
  1945. memset(h, 0, sizeof(struct lsp_include_history));
  1946. }
  1947. /* Register mg module */
  1948. lua_newtable(L);
  1949. switch (lua_env_type) {
  1950. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1951. reg_string(L, "lua_type", "page");
  1952. break;
  1953. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1954. reg_string(L, "lua_type", "script");
  1955. break;
  1956. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1957. reg_string(L, "lua_type", "websocket");
  1958. break;
  1959. }
  1960. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1961. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1962. reg_conn_function(L, "cry", lsp_cry, conn);
  1963. reg_conn_function(L, "read", lsp_read, conn);
  1964. reg_conn_function(L, "write", lsp_write, conn);
  1965. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1966. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1967. reg_conn_function(L, "send_file_body", lsp_send_file_body, conn);
  1968. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1969. }
  1970. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1971. reg_conn_function(L, "include", lsp_include, conn);
  1972. }
  1973. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1974. reg_function(L, "write", lwebsock_write);
  1975. #if defined(USE_TIMERS)
  1976. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1977. reg_function(L, "set_interval", lwebsocket_set_interval);
  1978. #endif
  1979. }
  1980. reg_conn_function(L, "get_mime_type", lsp_get_mime_type, conn);
  1981. reg_conn_function(L, "get_option", lsp_get_option, conn);
  1982. reg_function(L, "time", lsp_get_time);
  1983. reg_function(L, "get_var", lsp_get_var);
  1984. reg_function(L, "get_cookie", lsp_get_cookie);
  1985. reg_function(L, "md5", lsp_md5);
  1986. reg_function(L, "url_encode", lsp_url_encode);
  1987. reg_function(L, "url_decode", lsp_url_decode);
  1988. reg_function(L, "base64_encode", lsp_base64_encode);
  1989. reg_function(L, "base64_decode", lsp_base64_decode);
  1990. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1991. reg_function(L, "random", lsp_random);
  1992. reg_function(L, "get_info", lsp_get_info);
  1993. reg_function(L, "trace", lsp_trace);
  1994. if (pf_uuid_generate.f) {
  1995. reg_function(L, "uuid", lsp_uuid);
  1996. }
  1997. reg_string(L, "version", CIVETWEB_VERSION);
  1998. reg_string(L, "script_name", script_name);
  1999. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2000. reg_string(L, "document_root", conn->dom_ctx->config[DOCUMENT_ROOT]);
  2001. reg_string(L,
  2002. "auth_domain",
  2003. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  2004. #if defined(USE_WEBSOCKET)
  2005. if (conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  2006. reg_string(L,
  2007. "websocket_root",
  2008. conn->dom_ctx->config[WEBSOCKET_ROOT]);
  2009. } else {
  2010. reg_string(L,
  2011. "websocket_root",
  2012. conn->dom_ctx->config[DOCUMENT_ROOT]);
  2013. }
  2014. #endif
  2015. if ((ctx != NULL) && (ctx->systemName != NULL)) {
  2016. reg_string(L, "system", ctx->systemName);
  2017. }
  2018. }
  2019. /* Export connection specific info */
  2020. if (conn != NULL) {
  2021. prepare_lua_request_info(conn, L);
  2022. }
  2023. /* Store as global table "mg" */
  2024. lua_setglobal(L, "mg");
  2025. /* Register "shared" table */
  2026. lua_shared_register(L);
  2027. /* Register default mg.onerror function */
  2028. IGNORE_UNUSED_RESULT(
  2029. luaL_dostring(L,
  2030. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  2031. "debug.traceback(e, 1)) end"));
  2032. /* Check if a preload file is available */
  2033. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  2034. preload_file_name = conn->dom_ctx->config[LUA_PRELOAD_FILE];
  2035. }
  2036. /* Preload file into new Lua environment */
  2037. if (preload_file_name) {
  2038. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file_name));
  2039. }
  2040. /* Call user init function */
  2041. if (ctx != NULL) {
  2042. if (ctx->callbacks.init_lua != NULL) {
  2043. ctx->callbacks.init_lua(conn, L);
  2044. }
  2045. }
  2046. /* If debugging is enabled, add a hook */
  2047. if (debug_params) {
  2048. int mask = 0;
  2049. if (0 != strchr(debug_params, 'c')) {
  2050. mask |= LUA_MASKCALL;
  2051. }
  2052. if (0 != strchr(debug_params, 'r')) {
  2053. mask |= LUA_MASKRET;
  2054. }
  2055. if (0 != strchr(debug_params, 'l')) {
  2056. mask |= LUA_MASKLINE;
  2057. }
  2058. lua_sethook(L, lua_debug_hook, mask, 0);
  2059. }
  2060. }
  2061. static int
  2062. lua_error_handler(lua_State *L)
  2063. {
  2064. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  2065. lua_getglobal(L, "mg");
  2066. if (!lua_isnil(L, -1)) {
  2067. lua_getfield(L, -1, "write"); /* call mg.write() */
  2068. lua_pushstring(L, error_msg);
  2069. lua_pushliteral(L, "\n");
  2070. lua_call(L, 2, 0);
  2071. IGNORE_UNUSED_RESULT(
  2072. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  2073. } else {
  2074. printf("Lua error: [%s]\n", error_msg);
  2075. IGNORE_UNUSED_RESULT(
  2076. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  2077. }
  2078. /* TODO(lsm, low): leave the stack balanced */
  2079. return 0;
  2080. }
  2081. static void
  2082. mg_exec_lua_script(struct mg_connection *conn,
  2083. const char *path,
  2084. const void **exports)
  2085. {
  2086. int i;
  2087. lua_State *L;
  2088. /* Assume the script does not support keep_alive. The script may change this
  2089. * by calling mg.keep_alive(true). */
  2090. conn->must_close = 1;
  2091. /* Execute a plain Lua script. */
  2092. if (path != NULL
  2093. && (L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx)))
  2094. != NULL) {
  2095. prepare_lua_environment(
  2096. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  2097. lua_pushcclosure(L, &lua_error_handler, 0);
  2098. if (exports != NULL) {
  2099. #if LUA_VERSION_NUM > 501
  2100. lua_pushglobaltable(L);
  2101. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2102. lua_CFunction func;
  2103. lua_pushstring(L, (const char *)(exports[i]));
  2104. *(const void **)(&func) = exports[i + 1];
  2105. lua_pushcclosure(L, func, 0);
  2106. lua_rawset(L, -3);
  2107. }
  2108. #else
  2109. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  2110. lua_CFunction func;
  2111. const char *name = (const char *)(exports[i]);
  2112. *(const void **)(&func) = exports[i + 1];
  2113. lua_register(L, name, func);
  2114. }
  2115. #endif
  2116. }
  2117. if (luaL_loadfile(L, path) != 0) {
  2118. lua_error_handler(L);
  2119. }
  2120. lua_pcall(L, 0, 0, -2);
  2121. lua_close(L);
  2122. }
  2123. }
  2124. static int
  2125. handle_lsp_request(struct mg_connection *conn,
  2126. const char *path,
  2127. struct mg_file *filep,
  2128. struct lua_State *ls)
  2129. {
  2130. void *p = NULL;
  2131. lua_State *L = NULL;
  2132. struct lsp_include_history *include_history;
  2133. int error = 1;
  2134. void *file_in_memory; /* TODO(low): remove when removing "file in memory" */
  2135. int (*run_lsp)(struct mg_connection *,
  2136. const char *,
  2137. const char *,
  2138. int64_t,
  2139. lua_State *,
  2140. int);
  2141. const char *addr;
  2142. /* mg_fopen opens the file and sets the size accordingly */
  2143. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  2144. /* File not found or not accessible */
  2145. if (ls == NULL) {
  2146. mg_send_http_error(conn,
  2147. 500,
  2148. "Error: Cannot open script file %s",
  2149. path);
  2150. } else {
  2151. luaL_error(ls, "Cannot include [%s]: not found", path);
  2152. }
  2153. goto cleanup_handle_lsp_request;
  2154. }
  2155. #if defined(MG_USE_OPEN_FILE)
  2156. /* The "file in memory" feature is going to be removed. For details see
  2157. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI */
  2158. file_in_memory = filep->access.membuf;
  2159. #else
  2160. file_in_memory = NULL;
  2161. #endif
  2162. /* Map file in memory (size is known). */
  2163. if (file_in_memory == NULL
  2164. && (p = mmap(NULL,
  2165. (size_t)filep->stat.size,
  2166. PROT_READ,
  2167. MAP_PRIVATE,
  2168. fileno(filep->access.fp),
  2169. 0))
  2170. == MAP_FAILED) {
  2171. /* File was not already in memory, and mmap failed now.
  2172. * Since wi have no data, show an error. */
  2173. if (ls == NULL) {
  2174. /* No open Lua state - use generic error function */
  2175. mg_send_http_error(
  2176. conn,
  2177. 500,
  2178. "Error: Cannot open script\nFile %s can not be mapped",
  2179. path);
  2180. } else {
  2181. /* Lua state exists - use Lua error function */
  2182. luaL_error(ls,
  2183. "mmap(%s, %zu, %d): %s",
  2184. path,
  2185. (size_t)filep->stat.size,
  2186. fileno(filep->access.fp),
  2187. strerror(errno));
  2188. }
  2189. goto cleanup_handle_lsp_request;
  2190. }
  2191. /* File content is now memory mapped. Get mapping address */
  2192. addr = (file_in_memory == NULL) ? (const char *)p
  2193. : (const char *)file_in_memory;
  2194. /* Get a Lua state */
  2195. if (ls != NULL) {
  2196. /* We got a Lua state as argument. Use it! */
  2197. L = ls;
  2198. } else {
  2199. /* We need to create a Lua state. */
  2200. L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2201. if (L == NULL) {
  2202. /* We neither got a Lua state from the command line,
  2203. * nor did we succeed in creating our own state.
  2204. * Show an error, and stop further processing of this request. */
  2205. mg_send_http_error(
  2206. conn,
  2207. 500,
  2208. "%s",
  2209. "Error: Cannot execute script\nlua_newstate failed");
  2210. goto cleanup_handle_lsp_request;
  2211. }
  2212. /* New Lua state needs CivetWeb functions (e.g., the "mg" library). */
  2213. prepare_lua_environment(
  2214. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  2215. }
  2216. /* Get LSP include history table */
  2217. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  2218. lua_gettable(L, LUA_REGISTRYINDEX);
  2219. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  2220. /* Store script name and increment depth */
  2221. include_history->depth++;
  2222. include_history->script[include_history->depth] = path;
  2223. /* Lua state is ready to use now. */
  2224. /* Currently we have two different syntax options:
  2225. * Either "classic" CivetWeb syntax:
  2226. * <? code ?>
  2227. * <?= expression ?>
  2228. * Or "Kepler Syntax"
  2229. * https://keplerproject.github.io/cgilua/manual.html#templates
  2230. * <?lua chunk ?>
  2231. * <?lua= expression ?>
  2232. * <% chunk %>
  2233. * <%= expression %>
  2234. *
  2235. * Two important differences are:
  2236. * - In the "classic" CivetWeb syntax, the Lua Page had to send the HTTP
  2237. * response headers itself. So the first lines are usually something like
  2238. * HTTP/1.0 200 OK
  2239. * Content-Type: text/html
  2240. * followed by additional headers and an empty line, before the actual
  2241. * Lua page in HTML syntax with <? code ?> tags.
  2242. * The "Kepler"Syntax" does not send any HTTP header from the Lua Server
  2243. * Page, but starts directly with <html> code - so it cannot influence
  2244. * the HTTP response code, e.g., to send a 301 Moved Permanently.
  2245. * Due to this difference, the same *.lp file cannot be used with the
  2246. * same algorithm.
  2247. * - The "Kepler Syntax" used to allow mixtures of Lua and HTML inside an
  2248. * incomplete Lua block, e.g.:
  2249. * <lua? for i=1,10 do ?><li><%= key %></li><lua? end ?>
  2250. * This was not provided in "classic" CivetWeb syntax, but you had to use
  2251. * <? for i=1,10 do mg.write("<li>"..i.."</li>") end ?>
  2252. * instead. The parsing algorithm for "Kepler syntax" is more complex
  2253. * than for "classic" CivetWeb syntax - TODO: check timing/performance.
  2254. *
  2255. * CivetWeb now can use both parsing methods, but needs to know what
  2256. * parsing algorithm should be used.
  2257. * Idea: Files starting with '<' are HTML files in "Kepler Syntax", except
  2258. * "<?" which means "classic CivetWeb Syntax".
  2259. *
  2260. */
  2261. run_lsp = run_lsp_civetweb;
  2262. if ((addr[0] == '<') && (addr[1] != '?')) {
  2263. run_lsp = run_lsp_kepler;
  2264. }
  2265. /* We're not sending HTTP headers here, Lua page must do it. */
  2266. error =
  2267. run_lsp(conn, path, addr, filep->stat.size, L, include_history->depth);
  2268. cleanup_handle_lsp_request:
  2269. if (L != NULL && ls == NULL)
  2270. lua_close(L);
  2271. if (p != NULL)
  2272. munmap(p, filep->stat.size);
  2273. (void)mg_fclose(&filep->access);
  2274. return error;
  2275. }
  2276. #if defined(USE_WEBSOCKET)
  2277. struct mg_shared_lua_websocket_list {
  2278. struct lua_websock_data ws;
  2279. struct mg_shared_lua_websocket_list *next;
  2280. };
  2281. static void *
  2282. lua_websocket_new(const char *script, struct mg_connection *conn)
  2283. {
  2284. struct mg_shared_lua_websocket_list **shared_websock_list =
  2285. &(conn->dom_ctx->shared_lua_websockets);
  2286. struct lua_websock_data *ws;
  2287. int err, ok = 0;
  2288. DEBUG_ASSERT(conn->lua_websocket_state == NULL);
  2289. /* lock list (mg_context global) */
  2290. mg_lock_context(conn->phys_ctx);
  2291. while (*shared_websock_list) {
  2292. /* check if ws already in list */
  2293. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  2294. break;
  2295. }
  2296. shared_websock_list = &((*shared_websock_list)->next);
  2297. }
  2298. if (*shared_websock_list == NULL) {
  2299. /* add ws to list */
  2300. *shared_websock_list =
  2301. (struct mg_shared_lua_websocket_list *)mg_calloc_ctx(
  2302. sizeof(struct mg_shared_lua_websocket_list), 1, conn->phys_ctx);
  2303. if (*shared_websock_list == NULL) {
  2304. conn->must_close = 1;
  2305. mg_unlock_context(conn->phys_ctx);
  2306. mg_cry_internal(conn,
  2307. "%s",
  2308. "Cannot create shared websocket struct, OOM");
  2309. return NULL;
  2310. }
  2311. /* init ws list element */
  2312. ws = &(*shared_websock_list)->ws;
  2313. ws->script = mg_strdup_ctx(script, conn->phys_ctx);
  2314. if (!ws->script) {
  2315. conn->must_close = 1;
  2316. mg_unlock_context(conn->phys_ctx);
  2317. mg_cry_internal(conn,
  2318. "%s",
  2319. "Cannot create shared websocket script, OOM");
  2320. return NULL;
  2321. }
  2322. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  2323. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2324. ws->state = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  2325. ws->conn[0] = conn;
  2326. ws->references = 1;
  2327. prepare_lua_environment(conn->phys_ctx,
  2328. conn,
  2329. ws,
  2330. ws->state,
  2331. script,
  2332. LUA_ENV_TYPE_LUA_WEBSOCKET);
  2333. err = luaL_loadfile(ws->state, script);
  2334. if (err != 0) {
  2335. lua_cry(conn, err, ws->state, script, "load");
  2336. }
  2337. err = lua_pcall(ws->state, 0, 0, 0);
  2338. if (err != 0) {
  2339. lua_cry(conn, err, ws->state, script, "init");
  2340. }
  2341. } else {
  2342. /* inc ref count */
  2343. ws = &(*shared_websock_list)->ws;
  2344. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2345. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  2346. }
  2347. mg_unlock_context(conn->phys_ctx);
  2348. /* call add */
  2349. lua_getglobal(ws->state, "open");
  2350. lua_newtable(ws->state);
  2351. prepare_lua_request_info(conn, ws->state);
  2352. lua_pushstring(ws->state, "client");
  2353. lua_pushlightuserdata(ws->state, (void *)conn);
  2354. lua_rawset(ws->state, -3);
  2355. err = lua_pcall(ws->state, 1, 1, 0);
  2356. if (err != 0) {
  2357. lua_cry(conn, err, ws->state, script, "open handler");
  2358. } else {
  2359. if (lua_isboolean(ws->state, -1)) {
  2360. ok = lua_toboolean(ws->state, -1);
  2361. }
  2362. lua_pop(ws->state, 1);
  2363. }
  2364. if (!ok) {
  2365. /* Remove from ws connection list. */
  2366. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  2367. * (see websocket_close). */
  2368. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  2369. }
  2370. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2371. return ok ? (void *)ws : NULL;
  2372. }
  2373. static int
  2374. lua_websocket_data(struct mg_connection *conn,
  2375. int bits,
  2376. char *data,
  2377. size_t data_len,
  2378. void *ws_arg)
  2379. {
  2380. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2381. int err, ok = 0;
  2382. DEBUG_ASSERT(ws != NULL);
  2383. DEBUG_ASSERT(ws->state != NULL);
  2384. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2385. lua_getglobal(ws->state, "data");
  2386. lua_newtable(ws->state);
  2387. lua_pushstring(ws->state, "client");
  2388. lua_pushlightuserdata(ws->state, (void *)conn);
  2389. lua_rawset(ws->state, -3);
  2390. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  2391. a meaning according to
  2392. http://tools.ietf.org/html/rfc6455,
  2393. section 5.2 */
  2394. lua_pushnumber(ws->state, bits);
  2395. lua_rawset(ws->state, -3);
  2396. lua_pushstring(ws->state, "data");
  2397. lua_pushlstring(ws->state, data, data_len);
  2398. lua_rawset(ws->state, -3);
  2399. err = lua_pcall(ws->state, 1, 1, 0);
  2400. if (err != 0) {
  2401. lua_cry(conn, err, ws->state, ws->script, "data handler");
  2402. } else {
  2403. if (lua_isboolean(ws->state, -1)) {
  2404. ok = lua_toboolean(ws->state, -1);
  2405. }
  2406. lua_pop(ws->state, 1);
  2407. }
  2408. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2409. return ok;
  2410. }
  2411. static int
  2412. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  2413. {
  2414. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2415. int err, ok = 0;
  2416. DEBUG_ASSERT(ws != NULL);
  2417. DEBUG_ASSERT(ws->state != NULL);
  2418. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2419. lua_getglobal(ws->state, "ready");
  2420. lua_newtable(ws->state);
  2421. lua_pushstring(ws->state, "client");
  2422. lua_pushlightuserdata(ws->state, (void *)conn);
  2423. lua_rawset(ws->state, -3);
  2424. err = lua_pcall(ws->state, 1, 1, 0);
  2425. if (err != 0) {
  2426. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  2427. } else {
  2428. if (lua_isboolean(ws->state, -1)) {
  2429. ok = lua_toboolean(ws->state, -1);
  2430. }
  2431. lua_pop(ws->state, 1);
  2432. }
  2433. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2434. return ok;
  2435. }
  2436. static void
  2437. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  2438. {
  2439. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  2440. struct mg_shared_lua_websocket_list **shared_websock_list =
  2441. &(conn->dom_ctx->shared_lua_websockets);
  2442. int err = 0;
  2443. unsigned i;
  2444. DEBUG_ASSERT(ws != NULL);
  2445. DEBUG_ASSERT(ws->state != NULL);
  2446. (void)pthread_mutex_lock(&(ws->ws_mutex));
  2447. lua_getglobal(ws->state, "close");
  2448. lua_newtable(ws->state);
  2449. lua_pushstring(ws->state, "client");
  2450. lua_pushlightuserdata(ws->state, (void *)conn);
  2451. lua_rawset(ws->state, -3);
  2452. err = lua_pcall(ws->state, 1, 0, 0);
  2453. if (err != 0) {
  2454. lua_cry(conn, err, ws->state, ws->script, "close handler");
  2455. }
  2456. for (i = 0; i < ws->references; i++) {
  2457. if (ws->conn[i] == conn) {
  2458. ws->references--;
  2459. ws->conn[i] = ws->conn[ws->references];
  2460. }
  2461. }
  2462. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  2463. This must only be done, when all connections are closed, and all
  2464. asynchronous operations and timers are completed/expired. */
  2465. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  2466. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  2467. }
  2468. #endif
  2469. static lua_State *
  2470. mg_prepare_lua_context_script(const char *file_name,
  2471. struct mg_context *ctx,
  2472. char *ebuf,
  2473. size_t ebuf_len)
  2474. {
  2475. struct lua_State *L;
  2476. int lua_ret;
  2477. const char *lua_err_txt;
  2478. (void)ctx;
  2479. L = luaL_newstate();
  2480. if (L == NULL) {
  2481. mg_snprintf(NULL,
  2482. NULL, /* No truncation check for ebuf */
  2483. ebuf,
  2484. ebuf_len,
  2485. "Error: %s",
  2486. "Cannot create Lua state");
  2487. return 0;
  2488. }
  2489. civetweb_open_lua_libs(L);
  2490. lua_ret = luaL_loadfile(L, file_name);
  2491. if (lua_ret != LUA_OK) {
  2492. /* Error when loading the file (e.g. file not found,
  2493. * out of memory, ...)
  2494. */
  2495. lua_err_txt = lua_tostring(L, -1);
  2496. mg_snprintf(NULL,
  2497. NULL, /* No truncation check for ebuf */
  2498. ebuf,
  2499. ebuf_len,
  2500. "Error loading file %s: %s\n",
  2501. file_name,
  2502. lua_err_txt);
  2503. return 0;
  2504. }
  2505. /* The script file is loaded, now call it */
  2506. lua_ret = lua_pcall(L,
  2507. /* no arguments */ 0,
  2508. /* zero or one return value */ 1,
  2509. /* errors as strint return value */ 0);
  2510. if (lua_ret != LUA_OK) {
  2511. /* Error when executing the script */
  2512. lua_err_txt = lua_tostring(L, -1);
  2513. mg_snprintf(NULL,
  2514. NULL, /* No truncation check for ebuf */
  2515. ebuf,
  2516. ebuf_len,
  2517. "Error running file %s: %s\n",
  2518. file_name,
  2519. lua_err_txt);
  2520. return 0;
  2521. }
  2522. /* lua_close(L); must be done somewhere else */
  2523. return L;
  2524. }
  2525. int
  2526. run_lua(const char *file_name)
  2527. {
  2528. int func_ret = EXIT_FAILURE;
  2529. char ebuf[512] = {0};
  2530. lua_State *L =
  2531. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  2532. if (L) {
  2533. /* Script executed */
  2534. if (lua_type(L, -1) == LUA_TNUMBER) {
  2535. func_ret = (int)lua_tonumber(L, -1);
  2536. } else {
  2537. func_ret = EXIT_SUCCESS;
  2538. }
  2539. lua_close(L);
  2540. } else {
  2541. fprintf(stderr, "%s\n", ebuf);
  2542. }
  2543. return func_ret;
  2544. }
  2545. static void *lib_handle_uuid = NULL;
  2546. static void
  2547. lua_init_optional_libraries(void)
  2548. {
  2549. /* Create logging mutex */
  2550. pthread_mutex_init(&s_lua_traceMutex, &pthread_mutex_attr);
  2551. /* shared Lua state */
  2552. lua_shared_init();
  2553. /* UUID library */
  2554. #if !defined(_WIN32)
  2555. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  2556. pf_uuid_generate.p =
  2557. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  2558. #else
  2559. pf_uuid_generate.p = 0;
  2560. #endif
  2561. }
  2562. static void
  2563. lua_exit_optional_libraries(void)
  2564. {
  2565. /* UUID library */
  2566. #if !defined(_WIN32)
  2567. if (lib_handle_uuid) {
  2568. dlclose(lib_handle_uuid);
  2569. }
  2570. #endif
  2571. pf_uuid_generate.p = 0;
  2572. lib_handle_uuid = NULL;
  2573. /* shared Lua state */
  2574. lua_shared_exit();
  2575. /* Delete logging mutex */
  2576. pthread_mutex_destroy(&s_lua_traceMutex);
  2577. }
  2578. /* End of mod_lua.inl */