mod_lua.inl 45 KB

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