mod_lua.inl 55 KB

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