mod_lua.inl 53 KB

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