mod_lua.inl 70 KB

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