mod_lua.inl 43 KB

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