mod_lua.inl 77 KB

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