mod_lua.inl 90 KB

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