mod_lua.inl 67 KB

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