mod_lua.inl 58 KB

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