mod_lua.inl 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  1. #include "civetweb_lua.h"
  2. #include "civetweb_private_lua.h"
  3. #ifdef _WIN32
  4. static void *
  5. mmap(void *addr, int64_t len, int prot, int flags, int fd, int offset)
  6. {
  7. /* TODO (low): This is an incomplete implementation of mmap for windows.
  8. * Currently it is sufficient, but there are a lot of unused parameters.
  9. * Better use a function "mg_map" which only has the required parameters,
  10. * and implement it using mmap in Linux and CreateFileMapping in Windows.
  11. * Noone should expect a full mmap for Windows here.
  12. */
  13. HANDLE fh = (HANDLE)_get_osfhandle(fd);
  14. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  15. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
  16. CloseHandle(mh);
  17. /* unused parameters */
  18. (void)addr;
  19. (void)prot;
  20. (void)flags;
  21. (void)offset;
  22. return p;
  23. }
  24. static void
  25. munmap(void *addr, int64_t length)
  26. {
  27. /* unused parameters */
  28. (void)length;
  29. UnmapViewOfFile(addr);
  30. }
  31. #define MAP_FAILED (NULL)
  32. #define MAP_PRIVATE (0)
  33. #define PROT_READ (0)
  34. #else
  35. #include <sys/mman.h>
  36. #endif
  37. static const char *LUASOCKET = "luasocket";
  38. static const char lua_regkey_ctx = 1;
  39. static const char lua_regkey_connlist = 2;
  40. /* Forward declarations */
  41. static void handle_request(struct mg_connection *);
  42. static int handle_lsp_request(struct mg_connection *,
  43. const char *,
  44. struct mg_file *,
  45. struct lua_State *);
  46. static void
  47. reg_lstring(struct lua_State *L,
  48. const char *name,
  49. const void *buffer,
  50. size_t buflen)
  51. {
  52. if (name != NULL && buffer != NULL) {
  53. lua_pushstring(L, name);
  54. lua_pushlstring(L, (const char *)buffer, buflen);
  55. lua_rawset(L, -3);
  56. }
  57. }
  58. #define reg_string(L, name, val) \
  59. reg_lstring(L, name, val, val ? strlen(val) : 0)
  60. static void
  61. reg_int(struct lua_State *L, const char *name, int val)
  62. {
  63. if (name != NULL) {
  64. lua_pushstring(L, name);
  65. lua_pushinteger(L, val);
  66. lua_rawset(L, -3);
  67. }
  68. }
  69. static void
  70. reg_boolean(struct lua_State *L, const char *name, int val)
  71. {
  72. if (name != NULL) {
  73. lua_pushstring(L, name);
  74. lua_pushboolean(L, val != 0);
  75. lua_rawset(L, -3);
  76. }
  77. }
  78. static void
  79. reg_conn_function(struct lua_State *L,
  80. const char *name,
  81. lua_CFunction func,
  82. struct mg_connection *conn)
  83. {
  84. if (name != NULL && func != NULL && conn != NULL) {
  85. lua_pushstring(L, name);
  86. lua_pushlightuserdata(L, conn);
  87. lua_pushcclosure(L, func, 1);
  88. lua_rawset(L, -3);
  89. }
  90. }
  91. static void
  92. reg_function(struct lua_State *L, const char *name, lua_CFunction func)
  93. {
  94. if (name != NULL && func != NULL) {
  95. lua_pushstring(L, name);
  96. lua_pushcclosure(L, func, 0);
  97. lua_rawset(L, -3);
  98. }
  99. }
  100. static void
  101. lua_cry(struct mg_connection *conn,
  102. int err,
  103. lua_State *L,
  104. const char *lua_title,
  105. const char *lua_operation)
  106. {
  107. switch (err) {
  108. case LUA_OK:
  109. case LUA_YIELD:
  110. break;
  111. case LUA_ERRRUN:
  112. mg_cry(conn,
  113. "%s: %s failed: runtime error: %s",
  114. lua_title,
  115. lua_operation,
  116. lua_tostring(L, -1));
  117. break;
  118. case LUA_ERRSYNTAX:
  119. mg_cry(conn,
  120. "%s: %s failed: syntax error: %s",
  121. lua_title,
  122. lua_operation,
  123. lua_tostring(L, -1));
  124. break;
  125. case LUA_ERRMEM:
  126. mg_cry(conn, "%s: %s failed: out of memory", lua_title, lua_operation);
  127. break;
  128. case LUA_ERRGCMM:
  129. mg_cry(conn,
  130. "%s: %s failed: error during garbage collection",
  131. lua_title,
  132. lua_operation);
  133. break;
  134. case LUA_ERRERR:
  135. mg_cry(conn,
  136. "%s: %s failed: error in error handling: %s",
  137. lua_title,
  138. lua_operation,
  139. lua_tostring(L, -1));
  140. break;
  141. default:
  142. mg_cry(conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
  143. break;
  144. }
  145. }
  146. static int
  147. lsp_sock_close(lua_State *L)
  148. {
  149. int num_args = lua_gettop(L);
  150. size_t s;
  151. SOCKET *psock;
  152. if ((num_args == 1) && lua_istable(L, -1)) {
  153. lua_getfield(L, -1, "sock");
  154. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  155. if (s != sizeof(SOCKET)) {
  156. return luaL_error(L, "invalid internal state in :close() call");
  157. }
  158. /* Do not closesocket(*psock); here, close it in __gc */
  159. (void)psock;
  160. } else {
  161. return luaL_error(L, "invalid :close() call");
  162. }
  163. return 0;
  164. }
  165. static int
  166. lsp_sock_recv(lua_State *L)
  167. {
  168. int num_args = lua_gettop(L);
  169. char buf[2000];
  170. int n;
  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 :recv() call");
  178. }
  179. n = recv(*psock, buf, sizeof(buf), 0);
  180. if (n <= 0) {
  181. lua_pushnil(L);
  182. } else {
  183. lua_pushlstring(L, buf, n);
  184. }
  185. } else {
  186. return luaL_error(L, "invalid :recv() call");
  187. }
  188. return 1;
  189. }
  190. static int
  191. lsp_sock_send(lua_State *L)
  192. {
  193. int num_args = lua_gettop(L);
  194. const char *buf;
  195. size_t len, sent = 0;
  196. int n = 0;
  197. size_t s;
  198. SOCKET *psock;
  199. if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
  200. buf = lua_tolstring(L, -1, &len);
  201. lua_getfield(L, -2, "sock");
  202. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  203. if (s != sizeof(SOCKET)) {
  204. return luaL_error(L, "invalid internal state in :close() call");
  205. }
  206. while (sent < len) {
  207. if ((n = send(*psock, buf + sent, (int)(len - sent), 0)) <= 0) {
  208. break;
  209. }
  210. sent += n;
  211. }
  212. lua_pushnumber(L, n);
  213. } else {
  214. return luaL_error(L, "invalid :close() call");
  215. }
  216. return 1;
  217. }
  218. static int
  219. lsp_sock_gc(lua_State *L)
  220. {
  221. int num_args = lua_gettop(L);
  222. size_t s;
  223. SOCKET *psock;
  224. if ((num_args == 1) && lua_istable(L, -1)) {
  225. lua_getfield(L, -1, "sock");
  226. psock = (SOCKET *)lua_tolstring(L, -1, &s);
  227. if (s != sizeof(SOCKET)) {
  228. return luaL_error(
  229. L,
  230. "invalid internal state in __gc for object created by connect");
  231. }
  232. closesocket(*psock);
  233. } else {
  234. return luaL_error(L, "__gc for object created by connect failed");
  235. }
  236. return 0;
  237. }
  238. /* Methods and meta-methods supported by the object returned by connect.
  239. * For meta-methods, see http://lua-users.org/wiki/MetatableEvents */
  240. static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
  241. {"send", lsp_sock_send},
  242. {"recv", lsp_sock_recv},
  243. {"__gc", lsp_sock_gc},
  244. {NULL, NULL}};
  245. static int
  246. lsp_connect(lua_State *L)
  247. {
  248. int num_args = lua_gettop(L);
  249. char ebuf[100];
  250. SOCKET sock;
  251. union usa sa;
  252. int ok;
  253. if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2)
  254. && lua_isnumber(L, -1)) {
  255. ok = connect_socket(NULL,
  256. lua_tostring(L, -3),
  257. (int)lua_tonumber(L, -2),
  258. (int)lua_tonumber(L, -1),
  259. ebuf,
  260. sizeof(ebuf),
  261. &sock,
  262. &sa);
  263. if (!ok) {
  264. return luaL_error(L, ebuf);
  265. } else {
  266. lua_newtable(L);
  267. reg_lstring(L, "sock", (const char *)&sock, sizeof(SOCKET));
  268. reg_string(L, "host", lua_tostring(L, -4));
  269. luaL_getmetatable(L, LUASOCKET);
  270. lua_setmetatable(L, -2);
  271. }
  272. } else {
  273. return luaL_error(
  274. L, "connect(host,port,is_ssl): invalid parameter given.");
  275. }
  276. return 1;
  277. }
  278. static int
  279. lsp_error(lua_State *L)
  280. {
  281. lua_getglobal(L, "mg");
  282. lua_getfield(L, -1, "onerror");
  283. lua_pushvalue(L, -3);
  284. lua_pcall(L, 1, 0, 0);
  285. return 0;
  286. }
  287. /* Silently stop processing chunks. */
  288. static void
  289. lsp_abort(lua_State *L)
  290. {
  291. int top = lua_gettop(L);
  292. lua_getglobal(L, "mg");
  293. lua_pushnil(L);
  294. lua_setfield(L, -2, "onerror");
  295. lua_settop(L, top);
  296. lua_pushstring(L, "aborting");
  297. lua_error(L);
  298. }
  299. struct lsp_var_reader_data {
  300. const char *begin;
  301. unsigned len;
  302. unsigned state;
  303. };
  304. static const char *
  305. lsp_var_reader(lua_State *L, void *ud, size_t *sz)
  306. {
  307. struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
  308. const char *ret;
  309. (void)(L); /* unused */
  310. switch (reader->state) {
  311. case 0:
  312. ret = "mg.write(";
  313. *sz = strlen(ret);
  314. break;
  315. case 1:
  316. ret = reader->begin;
  317. *sz = reader->len;
  318. break;
  319. case 2:
  320. ret = ")";
  321. *sz = strlen(ret);
  322. break;
  323. default:
  324. ret = 0;
  325. *sz = 0;
  326. }
  327. reader->state++;
  328. return ret;
  329. }
  330. static int
  331. lsp(struct mg_connection *conn,
  332. const char *path,
  333. const char *p,
  334. int64_t len,
  335. lua_State *L)
  336. {
  337. int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
  338. char chunkname[MG_BUF_LEN];
  339. struct lsp_var_reader_data data;
  340. for (i = 0; i < len; i++) {
  341. if (p[i] == '\n')
  342. lines++;
  343. if (((i + 1) < len) && (p[i] == '<') && (p[i + 1] == '?')) {
  344. /* <?= ?> means a variable is enclosed and its value should be
  345. * printed */
  346. is_var = (((i + 2) < len) && (p[i + 2] == '='));
  347. if (is_var)
  348. j = i + 2;
  349. else
  350. j = i + 1;
  351. while (j < len) {
  352. if (p[j] == '\n')
  353. lualines++;
  354. if (((j + 1) < len) && (p[j] == '?') && (p[j + 1] == '>')) {
  355. mg_write(conn, p + pos, i - pos);
  356. mg_snprintf(conn,
  357. NULL, /* name only used for debugging */
  358. chunkname,
  359. sizeof(chunkname),
  360. "@%s+%i",
  361. path,
  362. lines);
  363. lua_pushlightuserdata(L, conn);
  364. lua_pushcclosure(L, lsp_error, 1);
  365. if (is_var) {
  366. data.begin = p + (i + 3);
  367. data.len = j - (i + 3);
  368. data.state = 0;
  369. lua_ok = mg_lua_load(
  370. L, lsp_var_reader, &data, chunkname, NULL);
  371. } else {
  372. lua_ok = luaL_loadbuffer(L,
  373. p + (i + 2),
  374. j - (i + 2),
  375. chunkname);
  376. }
  377. if (lua_ok) {
  378. /* Syntax error or OOM. Error message is pushed on
  379. * stack. */
  380. lua_pcall(L, 1, 0, 0);
  381. } else {
  382. /* Success loading chunk. Call it. */
  383. lua_pcall(L, 0, 0, 1);
  384. }
  385. pos = j + 2;
  386. i = pos - 1;
  387. break;
  388. }
  389. j++;
  390. }
  391. if (lualines > 0) {
  392. lines += lualines;
  393. lualines = 0;
  394. }
  395. }
  396. }
  397. if (i > pos) {
  398. mg_write(conn, p + pos, i - pos);
  399. }
  400. return 0;
  401. }
  402. /* mg.write: Send data to the client */
  403. static int
  404. lsp_write(lua_State *L)
  405. {
  406. struct mg_connection *conn =
  407. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  408. int num_args = lua_gettop(L);
  409. const char *str;
  410. size_t size;
  411. int i;
  412. int rv = 1;
  413. for (i = 1; i <= num_args; i++) {
  414. if (lua_isstring(L, i)) {
  415. str = lua_tolstring(L, i, &size);
  416. if (mg_write(conn, str, size) != (int)size) {
  417. rv = 0;
  418. }
  419. }
  420. }
  421. lua_pushboolean(L, rv);
  422. return 1;
  423. }
  424. /* mg.read: Read data from the client (e.g., from a POST request) */
  425. static int
  426. lsp_read(lua_State *L)
  427. {
  428. struct mg_connection *conn =
  429. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  430. char buf[1024];
  431. int len = mg_read(conn, buf, sizeof(buf));
  432. if (len <= 0)
  433. return 0;
  434. lua_pushlstring(L, buf, len);
  435. return 1;
  436. }
  437. /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
  438. static int
  439. lsp_keep_alive(lua_State *L)
  440. {
  441. struct mg_connection *conn =
  442. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  443. int num_args = lua_gettop(L);
  444. /* This function may be called with one parameter (boolean) to set the
  445. keep_alive state.
  446. Or without a parameter to just query the current keep_alive state. */
  447. if ((num_args == 1) && lua_isboolean(L, 1)) {
  448. conn->must_close = !lua_toboolean(L, 1);
  449. } else if (num_args != 0) {
  450. /* Syntax error */
  451. return luaL_error(L, "invalid keep_alive() call");
  452. }
  453. /* Return the current "keep_alive" state. This may be false, even it
  454. * keep_alive(true) has been called. */
  455. lua_pushboolean(L, should_keep_alive(conn));
  456. return 1;
  457. }
  458. /* mg.include: Include another .lp file */
  459. static int
  460. lsp_include(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. struct mg_file file = STRUCT_FILE_INITIALIZER;
  466. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  467. if (filename) {
  468. if (handle_lsp_request(conn, filename, &file, L)) {
  469. /* handle_lsp_request returned an error code, meaning an error
  470. occured in
  471. the included page and mg.onerror returned non-zero. Stop processing.
  472. */
  473. lsp_abort(L);
  474. }
  475. } else {
  476. /* Syntax error */
  477. return luaL_error(L, "invalid include() call");
  478. }
  479. return 0;
  480. }
  481. /* mg.cry: Log an error. Default value for mg.onerror. */
  482. static int
  483. lsp_cry(lua_State *L)
  484. {
  485. struct mg_connection *conn =
  486. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  487. int num_args = lua_gettop(L);
  488. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  489. if (text) {
  490. mg_cry(conn, "%s", lua_tostring(L, -1));
  491. } else {
  492. /* Syntax error */
  493. return luaL_error(L, "invalid cry() call");
  494. }
  495. return 0;
  496. }
  497. /* mg.redirect: Redirect the request (internally). */
  498. static int
  499. lsp_redirect(lua_State *L)
  500. {
  501. struct mg_connection *conn =
  502. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  503. int num_args = lua_gettop(L);
  504. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  505. if (target) {
  506. conn->request_info.local_uri = target;
  507. handle_request(conn);
  508. lsp_abort(L);
  509. } else {
  510. /* Syntax error */
  511. return luaL_error(L, "invalid redirect() call");
  512. }
  513. return 0;
  514. }
  515. /* mg.send_file */
  516. static int
  517. lsp_send_file(lua_State *L)
  518. {
  519. struct mg_connection *conn =
  520. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  521. int num_args = lua_gettop(L);
  522. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  523. if (filename) {
  524. mg_send_file(conn, filename);
  525. } else {
  526. /* Syntax error */
  527. return luaL_error(L, "invalid send_file() call");
  528. }
  529. return 0;
  530. }
  531. /* mg.get_time */
  532. static int
  533. lsp_get_time(lua_State *L)
  534. {
  535. int num_args = lua_gettop(L);
  536. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  537. struct timespec ts;
  538. double d;
  539. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  540. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  541. lua_pushnumber(L, d);
  542. return 1;
  543. }
  544. /* mg.get_var */
  545. static int
  546. lsp_get_var(lua_State *L)
  547. {
  548. int num_args = lua_gettop(L);
  549. const char *data, *var_name;
  550. size_t data_len, occurrence;
  551. int ret;
  552. char dst[512];
  553. if (num_args >= 2 && num_args <= 3) {
  554. data = lua_tolstring(L, 1, &data_len);
  555. var_name = lua_tostring(L, 2);
  556. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  557. ret =
  558. mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
  559. if (ret >= 0) {
  560. /* Variable found: return value to Lua */
  561. lua_pushstring(L, dst);
  562. } else {
  563. /* Variable not found (TODO (mid): may be string too long) */
  564. lua_pushnil(L);
  565. }
  566. } else {
  567. /* Syntax error */
  568. return luaL_error(L, "invalid get_var() call");
  569. }
  570. return 1;
  571. }
  572. /* mg.get_mime_type */
  573. static int
  574. lsp_get_mime_type(lua_State *L)
  575. {
  576. int num_args = lua_gettop(L);
  577. struct vec mime_type = {0, 0};
  578. struct mg_context *ctx;
  579. const char *text;
  580. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  581. lua_gettable(L, LUA_REGISTRYINDEX);
  582. ctx = (struct mg_context *)lua_touserdata(L, -1);
  583. if (num_args == 1) {
  584. text = lua_tostring(L, 1);
  585. if (text) {
  586. if (ctx) {
  587. get_mime_type(ctx, text, &mime_type);
  588. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  589. } else {
  590. text = mg_get_builtin_mime_type(text);
  591. lua_pushstring(L, text);
  592. }
  593. } else {
  594. /* Syntax error */
  595. return luaL_error(L, "invalid argument for get_mime_type() call");
  596. }
  597. } else {
  598. /* Syntax error */
  599. return luaL_error(L, "invalid get_mime_type() call");
  600. }
  601. return 1;
  602. }
  603. /* mg.get_cookie */
  604. static int
  605. lsp_get_cookie(lua_State *L)
  606. {
  607. int num_args = lua_gettop(L);
  608. const char *cookie;
  609. const char *var_name;
  610. int ret;
  611. char dst[512];
  612. if (num_args == 2) {
  613. cookie = lua_tostring(L, 1);
  614. var_name = lua_tostring(L, 2);
  615. if (cookie != NULL && var_name != NULL) {
  616. ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
  617. } else {
  618. ret = -1;
  619. }
  620. if (ret >= 0) {
  621. lua_pushlstring(L, dst, ret);
  622. } else {
  623. lua_pushnil(L);
  624. }
  625. } else {
  626. /* Syntax error */
  627. return luaL_error(L, "invalid get_cookie() call");
  628. }
  629. return 1;
  630. }
  631. /* mg.md5 */
  632. static int
  633. lsp_md5(lua_State *L)
  634. {
  635. int num_args = lua_gettop(L);
  636. const char *text;
  637. md5_byte_t hash[16];
  638. md5_state_t ctx;
  639. size_t text_len;
  640. char buf[40];
  641. if (num_args == 1) {
  642. text = lua_tolstring(L, 1, &text_len);
  643. if (text) {
  644. md5_init(&ctx);
  645. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  646. md5_finish(&ctx, hash);
  647. bin2str(buf, hash, sizeof(hash));
  648. lua_pushstring(L, buf);
  649. } else {
  650. lua_pushnil(L);
  651. }
  652. } else {
  653. /* Syntax error */
  654. return luaL_error(L, "invalid md5() call");
  655. }
  656. return 1;
  657. }
  658. /* mg.url_encode */
  659. static int
  660. lsp_url_encode(lua_State *L)
  661. {
  662. int num_args = lua_gettop(L);
  663. const char *text;
  664. size_t text_len;
  665. char dst[512 * 3];
  666. if (num_args == 1) {
  667. text = lua_tolstring(L, 1, &text_len);
  668. if (text) {
  669. mg_url_encode(text, dst, sizeof(dst));
  670. lua_pushstring(L, dst);
  671. } else {
  672. lua_pushnil(L);
  673. }
  674. } else {
  675. /* Syntax error */
  676. return luaL_error(L, "invalid url_encode() call");
  677. }
  678. return 1;
  679. }
  680. /* mg.url_decode */
  681. static int
  682. lsp_url_decode(lua_State *L)
  683. {
  684. int num_args = lua_gettop(L);
  685. const char *text;
  686. size_t text_len;
  687. int is_form;
  688. char dst[512];
  689. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  690. text = lua_tolstring(L, 1, &text_len);
  691. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  692. if (text) {
  693. mg_url_decode(text, text_len, dst, (int)sizeof(dst), is_form);
  694. lua_pushstring(L, dst);
  695. } else {
  696. lua_pushnil(L);
  697. }
  698. } else {
  699. /* Syntax error */
  700. return luaL_error(L, "invalid url_decode() call");
  701. }
  702. return 1;
  703. }
  704. /* mg.base64_encode */
  705. static int
  706. lsp_base64_encode(lua_State *L)
  707. {
  708. int num_args = lua_gettop(L);
  709. const char *text;
  710. size_t text_len;
  711. char *dst;
  712. if (num_args == 1) {
  713. text = lua_tolstring(L, 1, &text_len);
  714. if (text) {
  715. dst = (char *)mg_malloc(text_len * 8 / 6 + 4);
  716. if (dst) {
  717. base64_encode((const unsigned char *)text, (int)text_len, dst);
  718. lua_pushstring(L, dst);
  719. mg_free(dst);
  720. } else {
  721. return luaL_error(L, "out of memory in base64_encode() call");
  722. }
  723. } else {
  724. lua_pushnil(L);
  725. }
  726. } else {
  727. /* Syntax error */
  728. return luaL_error(L, "invalid base64_encode() call");
  729. }
  730. return 1;
  731. }
  732. /* mg.base64_encode */
  733. static int
  734. lsp_base64_decode(lua_State *L)
  735. {
  736. int num_args = lua_gettop(L);
  737. const char *text;
  738. size_t text_len, dst_len;
  739. int ret;
  740. char *dst;
  741. if (num_args == 1) {
  742. text = lua_tolstring(L, 1, &text_len);
  743. if (text) {
  744. dst = (char *)mg_malloc(text_len);
  745. if (dst) {
  746. ret = base64_decode((const unsigned char *)text,
  747. (int)text_len,
  748. dst,
  749. &dst_len);
  750. if (ret != -1) {
  751. mg_free(dst);
  752. return luaL_error(
  753. L, "illegal character in lsp_base64_decode() call");
  754. } else {
  755. lua_pushlstring(L, dst, dst_len);
  756. mg_free(dst);
  757. }
  758. } else {
  759. return luaL_error(L,
  760. "out of memory in lsp_base64_decode() call");
  761. }
  762. } else {
  763. lua_pushnil(L);
  764. }
  765. } else {
  766. /* Syntax error */
  767. return luaL_error(L, "invalid lsp_base64_decode() call");
  768. }
  769. return 1;
  770. }
  771. /* mg.get_response_code_text */
  772. static int
  773. lsp_get_response_code_text(lua_State *L)
  774. {
  775. int num_args = lua_gettop(L);
  776. int type1;
  777. double code;
  778. const char *text;
  779. if (num_args == 1) {
  780. type1 = lua_type(L, 1);
  781. if (type1 == LUA_TNUMBER) {
  782. /* If the first argument is a number,
  783. convert it to the corresponding text. */
  784. code = lua_tonumber(L, 1);
  785. text = mg_get_response_code_text(NULL, (int)code);
  786. if (text)
  787. lua_pushstring(L, text);
  788. return text ? 1 : 0;
  789. }
  790. }
  791. /* Syntax error */
  792. return luaL_error(L, "invalid get_response_code_text() call");
  793. }
  794. /* mg.random - might be better than math.random on some systems */
  795. static int
  796. lsp_random(lua_State *L)
  797. {
  798. int num_args = lua_gettop(L);
  799. if (num_args == 0) {
  800. /* The civetweb internal random number generator will generate
  801. * a 64 bit random number. */
  802. uint64_t r = get_random();
  803. /* Lua "number" is a IEEE 754 double precission float:
  804. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  805. * Thus, mask with 2^53-1 to get an integer with the maximum
  806. * precission available. */
  807. r &= ((((uint64_t)1) << 53) - 1);
  808. lua_pushnumber(L, (double)r);
  809. return 1;
  810. }
  811. /* Syntax error */
  812. return luaL_error(L, "invalid random() call");
  813. }
  814. union {
  815. void *p;
  816. void (*f)(unsigned char uuid[16]);
  817. } pf_uuid_generate;
  818. /* mg.uuid */
  819. static int
  820. lsp_uuid(lua_State *L)
  821. {
  822. union {
  823. unsigned char uuid_array[16];
  824. struct uuid_struct_type {
  825. uint32_t data1;
  826. uint16_t data2;
  827. uint16_t data3;
  828. uint8_t data4[8];
  829. } uuid_struct;
  830. } uuid;
  831. char uuid_str[40];
  832. int num_args = lua_gettop(L);
  833. memset(&uuid, 0, sizeof(uuid));
  834. memset(uuid_str, 0, sizeof(uuid_str));
  835. if (num_args == 0) {
  836. pf_uuid_generate.f(uuid.uuid_array);
  837. sprintf(uuid_str,
  838. "{%08lX-%04X-%04X-%02X%02X-"
  839. "%02X%02X%02X%02X%02X%02X}",
  840. (unsigned long)uuid.uuid_struct.data1,
  841. (unsigned)uuid.uuid_struct.data2,
  842. (unsigned)uuid.uuid_struct.data3,
  843. (unsigned)uuid.uuid_struct.data4[0],
  844. (unsigned)uuid.uuid_struct.data4[1],
  845. (unsigned)uuid.uuid_struct.data4[2],
  846. (unsigned)uuid.uuid_struct.data4[3],
  847. (unsigned)uuid.uuid_struct.data4[4],
  848. (unsigned)uuid.uuid_struct.data4[5],
  849. (unsigned)uuid.uuid_struct.data4[6],
  850. (unsigned)uuid.uuid_struct.data4[7]);
  851. lua_pushstring(L, uuid_str);
  852. return 1;
  853. }
  854. /* Syntax error */
  855. return luaL_error(L, "invalid random() call");
  856. }
  857. #ifdef USE_WEBSOCKET
  858. struct lua_websock_data {
  859. lua_State *state;
  860. char *script;
  861. unsigned references;
  862. struct mg_connection *conn[MAX_WORKER_THREADS];
  863. pthread_mutex_t ws_mutex;
  864. };
  865. #endif
  866. /* mg.write for websockets */
  867. static int
  868. lwebsock_write(lua_State *L)
  869. {
  870. #ifdef USE_WEBSOCKET
  871. int num_args = lua_gettop(L);
  872. struct lua_websock_data *ws;
  873. const char *str;
  874. size_t size;
  875. int opcode = -1;
  876. unsigned i;
  877. struct mg_connection *client = NULL;
  878. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  879. lua_gettable(L, LUA_REGISTRYINDEX);
  880. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  881. (void)pthread_mutex_lock(&(ws->ws_mutex));
  882. if (num_args == 1) {
  883. /* just one text: send it to all client */
  884. if (lua_isstring(L, 1)) {
  885. opcode = WEBSOCKET_OPCODE_TEXT;
  886. }
  887. } else if (num_args == 2) {
  888. if (lua_isnumber(L, 1)) {
  889. /* opcode number and message text */
  890. opcode = (int)lua_tointeger(L, 1);
  891. } else if (lua_isstring(L, 1)) {
  892. /* opcode string and message text */
  893. str = lua_tostring(L, 1);
  894. if (!mg_strncasecmp(str, "text", 4))
  895. opcode = WEBSOCKET_OPCODE_TEXT;
  896. else if (!mg_strncasecmp(str, "bin", 3))
  897. opcode = WEBSOCKET_OPCODE_BINARY;
  898. else if (!mg_strncasecmp(str, "close", 5))
  899. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  900. else if (!mg_strncasecmp(str, "ping", 4))
  901. opcode = WEBSOCKET_OPCODE_PING;
  902. else if (!mg_strncasecmp(str, "pong", 4))
  903. opcode = WEBSOCKET_OPCODE_PONG;
  904. else if (!mg_strncasecmp(str, "cont", 4))
  905. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  906. } else if (lua_isuserdata(L, 1)) {
  907. /* client id and message text */
  908. client = (struct mg_connection *)lua_touserdata(L, 1);
  909. opcode = WEBSOCKET_OPCODE_TEXT;
  910. }
  911. } else if (num_args == 3) {
  912. if (lua_isuserdata(L, 1)) {
  913. client = (struct mg_connection *)lua_touserdata(L, 1);
  914. if (lua_isnumber(L, 2)) {
  915. /* client id, opcode number and message text */
  916. opcode = (int)lua_tointeger(L, 2);
  917. } else if (lua_isstring(L, 2)) {
  918. /* client id, opcode string and message text */
  919. str = lua_tostring(L, 2);
  920. if (!mg_strncasecmp(str, "text", 4))
  921. opcode = WEBSOCKET_OPCODE_TEXT;
  922. else if (!mg_strncasecmp(str, "bin", 3))
  923. opcode = WEBSOCKET_OPCODE_BINARY;
  924. else if (!mg_strncasecmp(str, "close", 5))
  925. opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  926. else if (!mg_strncasecmp(str, "ping", 4))
  927. opcode = WEBSOCKET_OPCODE_PING;
  928. else if (!mg_strncasecmp(str, "pong", 4))
  929. opcode = WEBSOCKET_OPCODE_PONG;
  930. else if (!mg_strncasecmp(str, "cont", 4))
  931. opcode = WEBSOCKET_OPCODE_CONTINUATION;
  932. }
  933. }
  934. }
  935. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  936. str = lua_tolstring(L, num_args, &size);
  937. if (client) {
  938. for (i = 0; i < ws->references; i++) {
  939. if (client == ws->conn[i]) {
  940. mg_websocket_write(ws->conn[i], opcode, str, size);
  941. }
  942. }
  943. } else {
  944. for (i = 0; i < ws->references; i++) {
  945. mg_websocket_write(ws->conn[i], opcode, str, size);
  946. }
  947. }
  948. } else {
  949. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  950. return luaL_error(L, "invalid websocket write() call");
  951. }
  952. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  953. #else
  954. (void)(L); /* unused */
  955. #endif
  956. return 0;
  957. }
  958. struct laction_arg {
  959. lua_State *state;
  960. const char *script;
  961. pthread_mutex_t *pmutex;
  962. char txt[1];
  963. };
  964. static int
  965. lua_action(struct laction_arg *arg)
  966. {
  967. int err, ok;
  968. struct mg_context *ctx;
  969. (void)pthread_mutex_lock(arg->pmutex);
  970. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  971. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  972. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  973. err = luaL_loadstring(arg->state, arg->txt);
  974. if (err != 0) {
  975. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  976. (void)pthread_mutex_unlock(arg->pmutex);
  977. mg_free(arg);
  978. return 0;
  979. }
  980. err = lua_pcall(arg->state, 0, 1, 0);
  981. if (err != 0) {
  982. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  983. (void)pthread_mutex_unlock(arg->pmutex);
  984. mg_free(arg);
  985. return 0;
  986. }
  987. ok = lua_type(arg->state, -1);
  988. if (lua_isboolean(arg->state, -1)) {
  989. ok = lua_toboolean(arg->state, -1);
  990. } else {
  991. ok = 0;
  992. }
  993. lua_pop(arg->state, 1);
  994. (void)pthread_mutex_unlock(arg->pmutex);
  995. if (!ok) {
  996. mg_free(arg);
  997. }
  998. return ok;
  999. }
  1000. static int
  1001. lua_action_free(struct laction_arg *arg)
  1002. {
  1003. if (lua_action(arg)) {
  1004. mg_free(arg);
  1005. }
  1006. return 0;
  1007. }
  1008. static int
  1009. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1010. {
  1011. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1012. int num_args = lua_gettop(L);
  1013. struct lua_websock_data *ws;
  1014. int type1, type2, ok = 0;
  1015. double timediff;
  1016. struct mg_context *ctx;
  1017. struct laction_arg *arg;
  1018. const char *txt;
  1019. size_t txt_len;
  1020. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1021. lua_gettable(L, LUA_REGISTRYINDEX);
  1022. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1023. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1024. lua_gettable(L, LUA_REGISTRYINDEX);
  1025. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1026. if (num_args < 2) {
  1027. return luaL_error(L,
  1028. "not enough arguments for set_timer/interval() call");
  1029. }
  1030. type1 = lua_type(L, 1);
  1031. type2 = lua_type(L, 2);
  1032. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1033. timediff = (double)lua_tonumber(L, 2);
  1034. txt = lua_tostring(L, 1);
  1035. txt_len = strlen(txt);
  1036. arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg)
  1037. + txt_len + 10);
  1038. arg->state = L;
  1039. arg->script = ws->script;
  1040. arg->pmutex = &(ws->ws_mutex);
  1041. memcpy(arg->txt, "return(", 7);
  1042. memcpy(arg->txt + 7, txt, txt_len);
  1043. arg->txt[txt_len + 7] = ')';
  1044. arg->txt[txt_len + 8] = 0;
  1045. ok =
  1046. (0
  1047. == timer_add(ctx,
  1048. timediff,
  1049. is_periodic,
  1050. 1,
  1051. (taction)(is_periodic ? lua_action : lua_action_free),
  1052. (void *)arg));
  1053. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1054. /* TODO (mid): not implemented yet */
  1055. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1056. } else {
  1057. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1058. }
  1059. lua_pushboolean(L, ok);
  1060. return 1;
  1061. #else
  1062. (void)(L); /* unused */
  1063. (void)(is_periodic); /* unused */
  1064. return 0;
  1065. #endif
  1066. }
  1067. /* mg.set_timeout for websockets */
  1068. static int
  1069. lwebsocket_set_timeout(lua_State *L)
  1070. {
  1071. return lwebsocket_set_timer(L, 0);
  1072. }
  1073. /* mg.set_interval for websockets */
  1074. static int
  1075. lwebsocket_set_interval(lua_State *L)
  1076. {
  1077. return lwebsocket_set_timer(L, 1);
  1078. }
  1079. enum {
  1080. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1081. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1082. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1083. };
  1084. static void
  1085. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1086. {
  1087. const char *s;
  1088. int i;
  1089. /* Export mg.request_info */
  1090. lua_pushstring(L, "request_info");
  1091. lua_newtable(L);
  1092. reg_string(L, "request_method", conn->request_info.request_method);
  1093. reg_string(L, "request_uri", conn->request_info.request_uri);
  1094. reg_string(L, "uri", conn->request_info.local_uri);
  1095. reg_string(L, "http_version", conn->request_info.http_version);
  1096. reg_string(L, "query_string", conn->request_info.query_string);
  1097. #if defined(MG_LEGACY_INTERFACE)
  1098. reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is
  1099. deprecated, use
  1100. remote_addr
  1101. instead */
  1102. #endif
  1103. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1104. /* TODO (high): ip version */
  1105. reg_int(L, "remote_port", conn->request_info.remote_port);
  1106. reg_int(L, "num_headers", conn->request_info.num_headers);
  1107. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1108. if (conn->request_info.content_length >= 0) {
  1109. /* reg_int64: content_length */
  1110. lua_pushstring(L, "content_length");
  1111. lua_pushnumber(
  1112. L,
  1113. (lua_Number)conn->request_info
  1114. .content_length); /* lua_Number may be used as 52 bit integer */
  1115. lua_rawset(L, -3);
  1116. }
  1117. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1118. reg_string(L, "content_type", s);
  1119. }
  1120. if (conn->request_info.remote_user != NULL) {
  1121. reg_string(L, "remote_user", conn->request_info.remote_user);
  1122. reg_string(L, "auth_type", "Digest");
  1123. }
  1124. reg_boolean(L, "https", conn->ssl != NULL);
  1125. if (conn->status_code > 0) {
  1126. /* Lua error handler should show the status code */
  1127. reg_int(L, "status", conn->status_code);
  1128. }
  1129. lua_pushstring(L, "http_headers");
  1130. lua_newtable(L);
  1131. for (i = 0; i < conn->request_info.num_headers; i++) {
  1132. reg_string(L,
  1133. conn->request_info.http_headers[i].name,
  1134. conn->request_info.http_headers[i].value);
  1135. }
  1136. lua_rawset(L, -3);
  1137. lua_rawset(L, -3);
  1138. }
  1139. void
  1140. civetweb_open_lua_libs(lua_State *L)
  1141. {
  1142. {
  1143. extern void luaL_openlibs(lua_State *);
  1144. luaL_openlibs(L);
  1145. }
  1146. #ifdef USE_LUA_SQLITE3
  1147. {
  1148. extern int luaopen_lsqlite3(lua_State *);
  1149. luaopen_lsqlite3(L);
  1150. }
  1151. #endif
  1152. #ifdef USE_LUA_LUAXML
  1153. {
  1154. extern int luaopen_LuaXML_lib(lua_State *);
  1155. luaopen_LuaXML_lib(L);
  1156. }
  1157. #endif
  1158. #ifdef USE_LUA_FILE_SYSTEM
  1159. {
  1160. extern int luaopen_lfs(lua_State *);
  1161. luaopen_lfs(L);
  1162. }
  1163. #endif
  1164. #ifdef USE_LUA_BINARY
  1165. {
  1166. /* TODO (low): Test if this could be used as a replacement for bit32.
  1167. * Check again with Lua 5.3 later. */
  1168. extern int luaopen_binary(lua_State *);
  1169. luaL_requiref(L, "binary", luaopen_binary, 1);
  1170. lua_pop(L, 1);
  1171. }
  1172. #endif
  1173. }
  1174. static void
  1175. prepare_lua_environment(struct mg_context *ctx,
  1176. struct mg_connection *conn,
  1177. struct lua_websock_data *ws_conn_list,
  1178. lua_State *L,
  1179. const char *script_name,
  1180. int lua_env_type)
  1181. {
  1182. civetweb_open_lua_libs(L);
  1183. #if LUA_VERSION_NUM == 502
  1184. /* Keep the "connect" method for compatibility,
  1185. * but do not backport it to Lua 5.1.
  1186. * TODO: Redesign the interface.
  1187. */
  1188. luaL_newmetatable(L, LUASOCKET);
  1189. lua_pushliteral(L, "__index");
  1190. luaL_newlib(L, luasocket_methods);
  1191. lua_rawset(L, -3);
  1192. lua_pop(L, 1);
  1193. lua_register(L, "connect", lsp_connect);
  1194. #endif
  1195. /* Store context in the registry */
  1196. if (ctx != NULL) {
  1197. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1198. lua_pushlightuserdata(L, (void *)ctx);
  1199. lua_settable(L, LUA_REGISTRYINDEX);
  1200. }
  1201. if (ws_conn_list != NULL) {
  1202. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1203. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1204. lua_settable(L, LUA_REGISTRYINDEX);
  1205. }
  1206. /* Register mg module */
  1207. lua_newtable(L);
  1208. switch (lua_env_type) {
  1209. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1210. reg_string(L, "lua_type", "page");
  1211. break;
  1212. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1213. reg_string(L, "lua_type", "script");
  1214. break;
  1215. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1216. reg_string(L, "lua_type", "websocket");
  1217. break;
  1218. }
  1219. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1220. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1221. reg_conn_function(L, "cry", lsp_cry, conn);
  1222. reg_conn_function(L, "read", lsp_read, conn);
  1223. reg_conn_function(L, "write", lsp_write, conn);
  1224. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1225. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1226. }
  1227. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1228. reg_conn_function(L, "include", lsp_include, conn);
  1229. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1230. }
  1231. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1232. reg_function(L, "write", lwebsock_write);
  1233. #ifdef USE_TIMERS
  1234. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1235. reg_function(L, "set_interval", lwebsocket_set_interval);
  1236. #endif
  1237. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1238. }
  1239. reg_function(L, "time", lsp_get_time);
  1240. reg_function(L, "get_var", lsp_get_var);
  1241. reg_function(L, "get_mime_type", lsp_get_mime_type);
  1242. reg_function(L, "get_cookie", lsp_get_cookie);
  1243. reg_function(L, "md5", lsp_md5);
  1244. reg_function(L, "url_encode", lsp_url_encode);
  1245. reg_function(L, "url_decode", lsp_url_decode);
  1246. reg_function(L, "base64_encode", lsp_base64_encode);
  1247. reg_function(L, "base64_decode", lsp_base64_decode);
  1248. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1249. reg_function(L, "random", lsp_random);
  1250. if (pf_uuid_generate.f) {
  1251. reg_function(L, "uuid", lsp_uuid);
  1252. }
  1253. reg_string(L, "version", CIVETWEB_VERSION);
  1254. reg_string(L, "script_name", script_name);
  1255. if (ctx != NULL) {
  1256. reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
  1257. reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
  1258. #if defined(USE_WEBSOCKET)
  1259. if (ctx->config[WEBSOCKET_ROOT]) {
  1260. reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
  1261. } else {
  1262. reg_string(L, "websocket_root", ctx->config[DOCUMENT_ROOT]);
  1263. }
  1264. #endif
  1265. if (ctx->systemName != NULL) {
  1266. reg_string(L, "system", ctx->systemName);
  1267. }
  1268. }
  1269. /* Export connection specific info */
  1270. if (conn != NULL) {
  1271. prepare_lua_request_info(conn, L);
  1272. }
  1273. lua_setglobal(L, "mg");
  1274. /* Register default mg.onerror function */
  1275. IGNORE_UNUSED_RESULT(
  1276. luaL_dostring(L,
  1277. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1278. "debug.traceback(e, 1)) end"));
  1279. if (ctx != NULL) {
  1280. /* Preload */
  1281. if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
  1282. IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
  1283. }
  1284. if (ctx->callbacks.init_lua != NULL) {
  1285. ctx->callbacks.init_lua(conn, L);
  1286. }
  1287. }
  1288. }
  1289. static int
  1290. lua_error_handler(lua_State *L)
  1291. {
  1292. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1293. lua_getglobal(L, "mg");
  1294. if (!lua_isnil(L, -1)) {
  1295. lua_getfield(L, -1, "write"); /* call mg.write() */
  1296. lua_pushstring(L, error_msg);
  1297. lua_pushliteral(L, "\n");
  1298. lua_call(L, 2, 0);
  1299. IGNORE_UNUSED_RESULT(
  1300. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1301. } else {
  1302. printf("Lua error: [%s]\n", error_msg);
  1303. IGNORE_UNUSED_RESULT(
  1304. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1305. }
  1306. /* TODO(lsm, low): leave the stack balanced */
  1307. return 0;
  1308. }
  1309. static void *
  1310. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1311. {
  1312. (void)ud;
  1313. (void)osize; /* not used */
  1314. if (nsize == 0) {
  1315. mg_free(ptr);
  1316. return NULL;
  1317. }
  1318. return mg_realloc(ptr, nsize);
  1319. }
  1320. static void
  1321. mg_exec_lua_script(struct mg_connection *conn,
  1322. const char *path,
  1323. const void **exports)
  1324. {
  1325. int i;
  1326. lua_State *L;
  1327. /* Assume the script does not support keep_alive. The script may change this
  1328. * by calling mg.keep_alive(true). */
  1329. conn->must_close = 1;
  1330. /* Execute a plain Lua script. */
  1331. if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
  1332. prepare_lua_environment(
  1333. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1334. lua_pushcclosure(L, &lua_error_handler, 0);
  1335. if (exports != NULL) {
  1336. #if LUA_VERSION_NUM > 501
  1337. lua_pushglobaltable(L);
  1338. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1339. lua_CFunction func;
  1340. lua_pushstring(L, (const char *)(exports[i]));
  1341. *(const void **)(&func) = exports[i + 1];
  1342. lua_pushcclosure(L, func, 0);
  1343. lua_rawset(L, -3);
  1344. }
  1345. #else
  1346. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1347. lua_CFunction func;
  1348. const char *name = (const char *)(exports[i]);
  1349. *(const void **)(&func) = exports[i + 1];
  1350. lua_register(L, name, func);
  1351. }
  1352. #endif
  1353. }
  1354. if (luaL_loadfile(L, path) != 0) {
  1355. lua_error_handler(L);
  1356. }
  1357. lua_pcall(L, 0, 0, -2);
  1358. lua_close(L);
  1359. }
  1360. }
  1361. static int
  1362. handle_lsp_request(struct mg_connection *conn,
  1363. const char *path,
  1364. struct mg_file *filep,
  1365. struct lua_State *ls)
  1366. {
  1367. void *p = NULL;
  1368. lua_State *L = NULL;
  1369. int error = 1;
  1370. struct mg_file filesize = STRUCT_FILE_INITIALIZER;
  1371. /* Assume the script does not support keep_alive. The script may change this
  1372. * by calling mg.keep_alive(true). */
  1373. conn->must_close = 1;
  1374. /* We need both mg_stat to get file size, and mg_fopen to get fd */
  1375. if (!mg_stat(conn, path, &filesize.stat)) {
  1376. /* File not found */
  1377. if (ls == NULL) {
  1378. send_http_error(conn, 500, "Error: File %s not found", path);
  1379. } else {
  1380. luaL_error(ls, "File [%s] not found", path);
  1381. }
  1382. goto cleanup_handle_lsp_request;
  1383. }
  1384. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  1385. /* File not found or not accessible */
  1386. if (ls == NULL) {
  1387. send_http_error(conn,
  1388. 500,
  1389. "Error: Cannot open script file %s",
  1390. path);
  1391. } else {
  1392. luaL_error(ls, "Cannot [%s] not found", path);
  1393. }
  1394. goto cleanup_handle_lsp_request;
  1395. }
  1396. /* TODO: Operations mg_fopen and mg_stat should do what their names
  1397. * indicate. They should not fill in different members of the same
  1398. * struct mg_file.
  1399. * See Github issue #225 */
  1400. filep->stat.size = filesize.stat.size;
  1401. if (filep->access.membuf == NULL
  1402. && (p = mmap(NULL,
  1403. (size_t)filep->stat.size,
  1404. PROT_READ,
  1405. MAP_PRIVATE,
  1406. fileno(filep->access.fp),
  1407. 0)) == MAP_FAILED) {
  1408. /* mmap failed */
  1409. if (ls == NULL) {
  1410. send_http_error(
  1411. conn,
  1412. 500,
  1413. "Error: Cannot open script\nFile %s can not be mapped",
  1414. path);
  1415. } else {
  1416. luaL_error(ls,
  1417. "mmap(%s, %zu, %d): %s",
  1418. path,
  1419. (size_t)filep->stat.size,
  1420. fileno(filep->access.fp),
  1421. strerror(errno));
  1422. }
  1423. goto cleanup_handle_lsp_request;
  1424. }
  1425. if (ls != NULL) {
  1426. L = ls;
  1427. } else {
  1428. L = lua_newstate(lua_allocator, NULL);
  1429. if (L == NULL) {
  1430. send_http_error(
  1431. conn,
  1432. 500,
  1433. "%s",
  1434. "Error: Cannot execute script\nlua_newstate failed");
  1435. goto cleanup_handle_lsp_request;
  1436. }
  1437. prepare_lua_environment(
  1438. conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1439. }
  1440. /* Lua state is ready to use */
  1441. /* We're not sending HTTP headers here, Lua page must do it. */
  1442. error =
  1443. lsp(conn,
  1444. path,
  1445. (filep->access.membuf == NULL) ? (const char *)p
  1446. : (const char *)filep->access.membuf,
  1447. filep->stat.size,
  1448. L);
  1449. cleanup_handle_lsp_request:
  1450. if (L != NULL && ls == NULL)
  1451. lua_close(L);
  1452. if (p != NULL)
  1453. munmap(p, filep->stat.size);
  1454. (void)mg_fclose(&filep->access);
  1455. return error;
  1456. }
  1457. #ifdef USE_WEBSOCKET
  1458. struct mg_shared_lua_websocket_list {
  1459. struct lua_websock_data ws;
  1460. struct mg_shared_lua_websocket_list *next;
  1461. };
  1462. static void *
  1463. lua_websocket_new(const char *script, struct mg_connection *conn)
  1464. {
  1465. struct mg_shared_lua_websocket_list **shared_websock_list =
  1466. &(conn->ctx->shared_lua_websockets);
  1467. struct lua_websock_data *ws;
  1468. int err, ok = 0;
  1469. assert(conn->lua_websocket_state == NULL);
  1470. /* lock list (mg_context global) */
  1471. mg_lock_context(conn->ctx);
  1472. while (*shared_websock_list) {
  1473. /* check if ws already in list */
  1474. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1475. break;
  1476. }
  1477. shared_websock_list = &((*shared_websock_list)->next);
  1478. }
  1479. if (*shared_websock_list == NULL) {
  1480. /* add ws to list */
  1481. *shared_websock_list = (struct mg_shared_lua_websocket_list *)
  1482. mg_calloc(sizeof(struct mg_shared_lua_websocket_list), 1);
  1483. if (*shared_websock_list == NULL) {
  1484. mg_unlock_context(conn->ctx);
  1485. mg_cry(conn, "Cannot create shared websocket struct, OOM");
  1486. return NULL;
  1487. }
  1488. /* init ws list element */
  1489. ws = &(*shared_websock_list)->ws;
  1490. ws->script = mg_strdup(script); /* TODO (low): handle OOM */
  1491. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1492. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1493. ws->state = lua_newstate(lua_allocator, NULL);
  1494. ws->conn[0] = conn;
  1495. ws->references = 1;
  1496. prepare_lua_environment(
  1497. conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
  1498. err = luaL_loadfile(ws->state, script);
  1499. if (err != 0) {
  1500. lua_cry(conn, err, ws->state, script, "load");
  1501. }
  1502. err = lua_pcall(ws->state, 0, 0, 0);
  1503. if (err != 0) {
  1504. lua_cry(conn, err, ws->state, script, "init");
  1505. }
  1506. } else {
  1507. /* inc ref count */
  1508. ws = &(*shared_websock_list)->ws;
  1509. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1510. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1511. }
  1512. mg_unlock_context(conn->ctx);
  1513. /* call add */
  1514. lua_getglobal(ws->state, "open");
  1515. lua_newtable(ws->state);
  1516. prepare_lua_request_info(conn, ws->state);
  1517. lua_pushstring(ws->state, "client");
  1518. lua_pushlightuserdata(ws->state, (void *)conn);
  1519. lua_rawset(ws->state, -3);
  1520. err = lua_pcall(ws->state, 1, 1, 0);
  1521. if (err != 0) {
  1522. lua_cry(conn, err, ws->state, script, "open handler");
  1523. } else {
  1524. if (lua_isboolean(ws->state, -1)) {
  1525. ok = lua_toboolean(ws->state, -1);
  1526. }
  1527. lua_pop(ws->state, 1);
  1528. }
  1529. if (!ok) {
  1530. /* Remove from ws connection list. */
  1531. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1532. * (see websocket_close). */
  1533. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1534. }
  1535. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1536. return ok ? (void *)ws : NULL;
  1537. }
  1538. static int
  1539. lua_websocket_data(struct mg_connection *conn,
  1540. int bits,
  1541. char *data,
  1542. size_t data_len,
  1543. void *ws_arg)
  1544. {
  1545. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1546. int err, ok = 0;
  1547. assert(ws != NULL);
  1548. assert(ws->state != NULL);
  1549. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1550. lua_getglobal(ws->state, "data");
  1551. lua_newtable(ws->state);
  1552. lua_pushstring(ws->state, "client");
  1553. lua_pushlightuserdata(ws->state, (void *)conn);
  1554. lua_rawset(ws->state, -3);
  1555. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1556. a meaning according to
  1557. http://tools.ietf.org/html/rfc6455,
  1558. section 5.2 */
  1559. lua_pushnumber(ws->state, bits);
  1560. lua_rawset(ws->state, -3);
  1561. lua_pushstring(ws->state, "data");
  1562. lua_pushlstring(ws->state, data, data_len);
  1563. lua_rawset(ws->state, -3);
  1564. err = lua_pcall(ws->state, 1, 1, 0);
  1565. if (err != 0) {
  1566. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1567. } else {
  1568. if (lua_isboolean(ws->state, -1)) {
  1569. ok = lua_toboolean(ws->state, -1);
  1570. }
  1571. lua_pop(ws->state, 1);
  1572. }
  1573. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1574. return ok;
  1575. }
  1576. static int
  1577. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1578. {
  1579. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1580. int err, ok = 0;
  1581. assert(ws != NULL);
  1582. assert(ws->state != NULL);
  1583. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1584. lua_getglobal(ws->state, "ready");
  1585. lua_newtable(ws->state);
  1586. lua_pushstring(ws->state, "client");
  1587. lua_pushlightuserdata(ws->state, (void *)conn);
  1588. lua_rawset(ws->state, -3);
  1589. err = lua_pcall(ws->state, 1, 1, 0);
  1590. if (err != 0) {
  1591. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1592. } else {
  1593. if (lua_isboolean(ws->state, -1)) {
  1594. ok = lua_toboolean(ws->state, -1);
  1595. }
  1596. lua_pop(ws->state, 1);
  1597. }
  1598. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1599. return ok;
  1600. }
  1601. static void
  1602. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1603. {
  1604. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1605. struct mg_shared_lua_websocket_list **shared_websock_list =
  1606. &(conn->ctx->shared_lua_websockets);
  1607. int err = 0;
  1608. unsigned i;
  1609. assert(ws != NULL);
  1610. assert(ws->state != NULL);
  1611. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1612. lua_getglobal(ws->state, "close");
  1613. lua_newtable(ws->state);
  1614. lua_pushstring(ws->state, "client");
  1615. lua_pushlightuserdata(ws->state, (void *)conn);
  1616. lua_rawset(ws->state, -3);
  1617. err = lua_pcall(ws->state, 1, 0, 0);
  1618. if (err != 0) {
  1619. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1620. }
  1621. for (i = 0; i < ws->references; i++) {
  1622. if (ws->conn[i] == conn) {
  1623. ws->references--;
  1624. ws->conn[i] = ws->conn[ws->references];
  1625. }
  1626. }
  1627. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1628. This must only be done, when all connections are closed, and all
  1629. asynchronous operations and timers are completed/expired. */
  1630. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1631. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1632. }
  1633. #endif
  1634. static void *lib_handle_uuid = NULL;
  1635. static void
  1636. lua_init_optional_libraries(void)
  1637. {
  1638. #if !defined(_WIN32)
  1639. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  1640. pf_uuid_generate.p = dlsym(lib_handle_uuid, "uuid_generate");
  1641. #else
  1642. pf_uuid_generate.p = 0;
  1643. #endif
  1644. }
  1645. static void
  1646. lua_exit_optional_libraries(void)
  1647. {
  1648. #if !defined(_WIN32)
  1649. dlclose(lib_handle_uuid);
  1650. #endif
  1651. pf_uuid_generate.p = 0;
  1652. lib_handle_uuid = NULL;
  1653. }