mod_lua.inl 85 KB

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