mod_lua.inl 58 KB

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