mod_lua.inl 45 KB

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