mod_lua.inl 40 KB

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