mod_lua.inl 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  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 ((file_name) && (num_args <= 2)) {
  500. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  501. lua_gettable(L, LUA_REGISTRYINDEX);
  502. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  503. if (include_history->depth >= ((int)(LSP_INCLUDE_MAX_DEPTH))) {
  504. mg_cry_internal(
  505. conn,
  506. "lsp max include depth of %i reached while including %s",
  507. (int)(LSP_INCLUDE_MAX_DEPTH),
  508. file_name);
  509. } else {
  510. char file_name_path[512];
  511. char *p;
  512. size_t len;
  513. int truncated = 0;
  514. file_name_path[511] = 0;
  515. if (path_type && (*path_type == 'v')) {
  516. /* "virtual" = relative to document root. */
  517. (void)mg_snprintf(conn,
  518. &truncated,
  519. file_name_path,
  520. sizeof(file_name_path),
  521. "%s/%s",
  522. conn->dom_ctx->config[DOCUMENT_ROOT],
  523. file_name);
  524. } else if ((path_type && (*path_type == 'a'))
  525. || (path_type == NULL)) {
  526. /* "absolute" = file name is relative to the
  527. * webserver working directory
  528. * or it is absolute system path. */
  529. /* path_type==NULL is the legacy use case with 1 argument */
  530. (void)mg_snprintf(conn,
  531. &truncated,
  532. file_name_path,
  533. sizeof(file_name_path),
  534. "%s",
  535. file_name);
  536. } else if (path_type && (*path_type == 'r' || *path_type == 'f')) {
  537. /* "relative" = file name is relative to the
  538. * currect document */
  539. (void)mg_snprintf(
  540. conn,
  541. &truncated,
  542. file_name_path,
  543. sizeof(file_name_path),
  544. "%s",
  545. include_history->script[include_history->depth]);
  546. if (!truncated) {
  547. if ((p = strrchr(file_name_path, '/')) != NULL) {
  548. p[1] = '\0';
  549. }
  550. len = strlen(file_name_path);
  551. (void)mg_snprintf(conn,
  552. &truncated,
  553. file_name_path + len,
  554. sizeof(file_name_path) - len,
  555. "%s",
  556. file_name);
  557. }
  558. } else {
  559. return luaL_error(
  560. L,
  561. "invalid path_type in include(file_name, path_type) call");
  562. }
  563. if (handle_lsp_request(conn, file_name_path, &file, L)) {
  564. /* handle_lsp_request returned an error code, meaning an error
  565. * occurred in the included page and mg.onerror returned
  566. * non-zero.
  567. * Stop processing.
  568. */
  569. lsp_abort(L);
  570. }
  571. }
  572. } else {
  573. /* Syntax error */
  574. return luaL_error(L, "invalid include() call");
  575. }
  576. return 0;
  577. }
  578. /* mg.cry: Log an error. Default value for mg.onerror. */
  579. static int
  580. lsp_cry(lua_State *L)
  581. {
  582. struct mg_connection *conn =
  583. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  584. int num_args = lua_gettop(L);
  585. const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  586. if (text) {
  587. mg_cry_internal(conn, "%s", lua_tostring(L, -1));
  588. } else {
  589. /* Syntax error */
  590. return luaL_error(L, "invalid cry() call");
  591. }
  592. return 0;
  593. }
  594. /* mg.redirect: Redirect the request (internally). */
  595. static int
  596. lsp_redirect(lua_State *L)
  597. {
  598. struct mg_connection *conn =
  599. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  600. int num_args = lua_gettop(L);
  601. const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  602. if (target) {
  603. conn->request_info.local_uri = target;
  604. handle_request(conn);
  605. lsp_abort(L);
  606. } else {
  607. /* Syntax error */
  608. return luaL_error(L, "invalid redirect() call");
  609. }
  610. return 0;
  611. }
  612. /* mg.send_file */
  613. static int
  614. lsp_send_file(lua_State *L)
  615. {
  616. struct mg_connection *conn =
  617. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  618. int num_args = lua_gettop(L);
  619. const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
  620. if (filename) {
  621. mg_send_file(conn, filename);
  622. } else {
  623. /* Syntax error */
  624. return luaL_error(L, "invalid send_file() call");
  625. }
  626. return 0;
  627. }
  628. /* mg.get_time */
  629. static int
  630. lsp_get_time(lua_State *L)
  631. {
  632. int num_args = lua_gettop(L);
  633. int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
  634. struct timespec ts;
  635. double d;
  636. clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
  637. d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
  638. lua_pushnumber(L, d);
  639. return 1;
  640. }
  641. /* mg.get_var */
  642. static int
  643. lsp_get_var(lua_State *L)
  644. {
  645. int num_args = lua_gettop(L);
  646. const char *data, *var_name;
  647. size_t data_len, occurrence;
  648. int ret;
  649. struct mg_context *ctx;
  650. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  651. lua_gettable(L, LUA_REGISTRYINDEX);
  652. ctx = (struct mg_context *)lua_touserdata(L, -1);
  653. if (num_args >= 2 && num_args <= 3) {
  654. char *dst;
  655. data = lua_tolstring(L, 1, &data_len);
  656. var_name = lua_tostring(L, 2);
  657. occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
  658. /* Allocate dynamically, so there is no internal limit for get_var */
  659. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  660. if (!dst) {
  661. return luaL_error(L, "out of memory in get_var() call");
  662. }
  663. ret = mg_get_var2(data, data_len, var_name, dst, data_len, occurrence);
  664. if (ret >= 0) {
  665. /* Variable found: return value to Lua */
  666. lua_pushstring(L, dst);
  667. } else {
  668. /* Variable not found */
  669. lua_pushnil(L);
  670. }
  671. mg_free(dst);
  672. } else {
  673. /* Syntax error */
  674. return luaL_error(L, "invalid get_var() call");
  675. }
  676. return 1;
  677. }
  678. /* mg.get_mime_type */
  679. static int
  680. lsp_get_mime_type(lua_State *L)
  681. {
  682. int num_args = lua_gettop(L);
  683. struct vec mime_type = {0, 0};
  684. const char *text;
  685. struct mg_connection *conn =
  686. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  687. if (num_args == 1) {
  688. text = lua_tostring(L, 1);
  689. if (text) {
  690. if (conn) {
  691. get_mime_type(conn, text, &mime_type);
  692. lua_pushlstring(L, mime_type.ptr, mime_type.len);
  693. } else {
  694. text = mg_get_builtin_mime_type(text);
  695. lua_pushstring(L, text);
  696. }
  697. } else {
  698. /* Syntax error */
  699. return luaL_error(L, "invalid argument for get_mime_type() call");
  700. }
  701. } else {
  702. /* Syntax error */
  703. return luaL_error(L, "invalid get_mime_type() call");
  704. }
  705. return 1;
  706. }
  707. /* mg.get_cookie */
  708. static int
  709. lsp_get_cookie(lua_State *L)
  710. {
  711. int num_args = lua_gettop(L);
  712. const char *cookie;
  713. const char *var_name;
  714. int ret;
  715. struct mg_context *ctx;
  716. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  717. lua_gettable(L, LUA_REGISTRYINDEX);
  718. ctx = (struct mg_context *)lua_touserdata(L, -1);
  719. if (num_args == 2) {
  720. /* Correct number of arguments */
  721. size_t data_len;
  722. char *dst;
  723. cookie = lua_tolstring(L, 1, &data_len);
  724. var_name = lua_tostring(L, 2);
  725. if (cookie == NULL || var_name == NULL) {
  726. /* Syntax error */
  727. return luaL_error(L, "invalid get_cookie() call");
  728. }
  729. dst = (char *)mg_malloc_ctx(data_len + 1, ctx);
  730. if (!dst) {
  731. return luaL_error(L, "out of memory in get_cookie() call");
  732. }
  733. ret = mg_get_cookie(cookie, var_name, dst, data_len);
  734. if (ret >= 0) {
  735. lua_pushlstring(L, dst, ret);
  736. } else {
  737. lua_pushnil(L);
  738. }
  739. mg_free(dst);
  740. } else {
  741. /* Syntax error */
  742. return luaL_error(L, "invalid get_cookie() call");
  743. }
  744. return 1;
  745. }
  746. /* mg.md5 */
  747. static int
  748. lsp_md5(lua_State *L)
  749. {
  750. int num_args = lua_gettop(L);
  751. const char *text;
  752. md5_byte_t hash[16];
  753. md5_state_t ctx;
  754. size_t text_len;
  755. char buf[40];
  756. if (num_args == 1) {
  757. text = lua_tolstring(L, 1, &text_len);
  758. if (text) {
  759. md5_init(&ctx);
  760. md5_append(&ctx, (const md5_byte_t *)text, text_len);
  761. md5_finish(&ctx, hash);
  762. bin2str(buf, hash, sizeof(hash));
  763. lua_pushstring(L, buf);
  764. } else {
  765. lua_pushnil(L);
  766. }
  767. } else {
  768. /* Syntax error */
  769. return luaL_error(L, "invalid md5() call");
  770. }
  771. return 1;
  772. }
  773. /* mg.url_encode */
  774. static int
  775. lsp_url_encode(lua_State *L)
  776. {
  777. int num_args = lua_gettop(L);
  778. const char *text;
  779. size_t text_len;
  780. char *dst;
  781. int dst_len;
  782. struct mg_context *ctx;
  783. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  784. lua_gettable(L, LUA_REGISTRYINDEX);
  785. ctx = (struct mg_context *)lua_touserdata(L, -1);
  786. if (num_args == 1) {
  787. text = lua_tolstring(L, 1, &text_len);
  788. if (text) {
  789. dst_len = 3 * (int)text_len + 1;
  790. dst = ((text_len < 0x2AAAAAAA) ? (char *)mg_malloc_ctx(dst_len, ctx)
  791. : (char *)NULL);
  792. if (dst) {
  793. mg_url_encode(text, dst, dst_len);
  794. lua_pushstring(L, dst);
  795. mg_free(dst);
  796. } else {
  797. return luaL_error(L, "out of memory in url_decode() call");
  798. }
  799. } else {
  800. lua_pushnil(L);
  801. }
  802. } else {
  803. /* Syntax error */
  804. return luaL_error(L, "invalid url_encode() call");
  805. }
  806. return 1;
  807. }
  808. /* mg.url_decode */
  809. static int
  810. lsp_url_decode(lua_State *L)
  811. {
  812. int num_args = lua_gettop(L);
  813. const char *text;
  814. size_t text_len;
  815. int is_form;
  816. char *dst;
  817. int dst_len;
  818. struct mg_context *ctx;
  819. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  820. lua_gettable(L, LUA_REGISTRYINDEX);
  821. ctx = (struct mg_context *)lua_touserdata(L, -1);
  822. if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
  823. text = lua_tolstring(L, 1, &text_len);
  824. is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
  825. if (text) {
  826. dst_len = (int)text_len + 1;
  827. dst = ((text_len < 0x7FFFFFFF) ? (char *)mg_malloc_ctx(dst_len, ctx)
  828. : (char *)NULL);
  829. if (dst) {
  830. mg_url_decode(text, (int)text_len, dst, dst_len, is_form);
  831. lua_pushstring(L, dst);
  832. mg_free(dst);
  833. } else {
  834. return luaL_error(L, "out of memory in url_decode() call");
  835. }
  836. } else {
  837. lua_pushnil(L);
  838. }
  839. } else {
  840. /* Syntax error */
  841. return luaL_error(L, "invalid url_decode() call");
  842. }
  843. return 1;
  844. }
  845. /* mg.base64_encode */
  846. static int
  847. lsp_base64_encode(lua_State *L)
  848. {
  849. int num_args = lua_gettop(L);
  850. const char *text;
  851. size_t text_len;
  852. char *dst;
  853. struct mg_context *ctx;
  854. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  855. lua_gettable(L, LUA_REGISTRYINDEX);
  856. ctx = (struct mg_context *)lua_touserdata(L, -1);
  857. if (num_args == 1) {
  858. text = lua_tolstring(L, 1, &text_len);
  859. if (text) {
  860. dst = (char *)mg_malloc_ctx(text_len * 8 / 6 + 4, ctx);
  861. if (dst) {
  862. base64_encode((const unsigned char *)text, (int)text_len, dst);
  863. lua_pushstring(L, dst);
  864. mg_free(dst);
  865. } else {
  866. return luaL_error(L, "out of memory in base64_encode() call");
  867. }
  868. } else {
  869. lua_pushnil(L);
  870. }
  871. } else {
  872. /* Syntax error */
  873. return luaL_error(L, "invalid base64_encode() call");
  874. }
  875. return 1;
  876. }
  877. /* mg.base64_encode */
  878. static int
  879. lsp_base64_decode(lua_State *L)
  880. {
  881. int num_args = lua_gettop(L);
  882. const char *text;
  883. size_t text_len, dst_len;
  884. int ret;
  885. char *dst;
  886. struct mg_context *ctx;
  887. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  888. lua_gettable(L, LUA_REGISTRYINDEX);
  889. ctx = (struct mg_context *)lua_touserdata(L, -1);
  890. if (num_args == 1) {
  891. text = lua_tolstring(L, 1, &text_len);
  892. if (text) {
  893. dst = (char *)mg_malloc_ctx(text_len, ctx);
  894. if (dst) {
  895. ret = base64_decode((const unsigned char *)text,
  896. (int)text_len,
  897. dst,
  898. &dst_len);
  899. if (ret != -1) {
  900. mg_free(dst);
  901. return luaL_error(
  902. L, "illegal character in lsp_base64_decode() call");
  903. } else {
  904. lua_pushlstring(L, dst, dst_len);
  905. mg_free(dst);
  906. }
  907. } else {
  908. return luaL_error(L,
  909. "out of memory in lsp_base64_decode() call");
  910. }
  911. } else {
  912. lua_pushnil(L);
  913. }
  914. } else {
  915. /* Syntax error */
  916. return luaL_error(L, "invalid lsp_base64_decode() call");
  917. }
  918. return 1;
  919. }
  920. /* mg.get_response_code_text */
  921. static int
  922. lsp_get_response_code_text(lua_State *L)
  923. {
  924. int num_args = lua_gettop(L);
  925. int type1;
  926. double code;
  927. const char *text;
  928. if (num_args == 1) {
  929. type1 = lua_type(L, 1);
  930. if (type1 == LUA_TNUMBER) {
  931. /* If the first argument is a number,
  932. convert it to the corresponding text. */
  933. code = lua_tonumber(L, 1);
  934. text = mg_get_response_code_text(NULL, (int)code);
  935. if (text)
  936. lua_pushstring(L, text);
  937. return text ? 1 : 0;
  938. }
  939. }
  940. /* Syntax error */
  941. return luaL_error(L, "invalid get_response_code_text() call");
  942. }
  943. /* mg.random - might be better than math.random on some systems */
  944. static int
  945. lsp_random(lua_State *L)
  946. {
  947. int num_args = lua_gettop(L);
  948. if (num_args == 0) {
  949. /* The civetweb internal random number generator will generate
  950. * a 64 bit random number. */
  951. uint64_t r = get_random();
  952. /* Lua "number" is a IEEE 754 double precission float:
  953. * https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  954. * Thus, mask with 2^53-1 to get an integer with the maximum
  955. * precission available. */
  956. r &= ((((uint64_t)1) << 53) - 1);
  957. lua_pushnumber(L, (double)r);
  958. return 1;
  959. }
  960. /* Syntax error */
  961. return luaL_error(L, "invalid random() call");
  962. }
  963. /* mg.get_info */
  964. static int
  965. lsp_get_info(lua_State *L)
  966. {
  967. int num_args = lua_gettop(L);
  968. int type1, type2;
  969. const char *arg1;
  970. double arg2;
  971. int len;
  972. char *buf;
  973. if (num_args == 1) {
  974. type1 = lua_type(L, 1);
  975. if (type1 == LUA_TSTRING) {
  976. arg1 = lua_tostring(L, 1);
  977. /* Get info according to argument */
  978. if (!mg_strcasecmp(arg1, "system")) {
  979. /* Get system info */
  980. len = mg_get_system_info(NULL, 0);
  981. if (len > 0) {
  982. buf = (char *)mg_malloc(len + 64);
  983. if (!buf) {
  984. return luaL_error(L, "OOM in get_info() call");
  985. }
  986. len = mg_get_system_info(buf, len + 63);
  987. lua_pushlstring(L, buf, len);
  988. mg_free(buf);
  989. } else {
  990. lua_pushstring(L, "");
  991. }
  992. return 1;
  993. }
  994. if (!mg_strcasecmp(arg1, "context")) {
  995. /* Get context */
  996. struct mg_context *ctx;
  997. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  998. lua_gettable(L, LUA_REGISTRYINDEX);
  999. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1000. /* Get context info for server context */
  1001. len = mg_get_context_info(ctx, NULL, 0);
  1002. if (len > 0) {
  1003. buf = (char *)mg_malloc(len + 64);
  1004. if (!buf) {
  1005. return luaL_error(L, "OOM in get_info() call");
  1006. }
  1007. len = mg_get_context_info(ctx, buf, len + 63);
  1008. lua_pushlstring(L, buf, len);
  1009. mg_free(buf);
  1010. } else {
  1011. lua_pushstring(L, "");
  1012. }
  1013. return 1;
  1014. }
  1015. if (!mg_strcasecmp(arg1, "common")) {
  1016. /* Get context info for NULL context */
  1017. len = mg_get_context_info(NULL, NULL, 0);
  1018. if (len > 0) {
  1019. buf = (char *)mg_malloc(len + 64);
  1020. if (!buf) {
  1021. return luaL_error(L, "OOM in get_info() call");
  1022. }
  1023. len = mg_get_context_info(NULL, buf, len + 63);
  1024. lua_pushlstring(L, buf, len);
  1025. mg_free(buf);
  1026. } else {
  1027. lua_pushstring(L, "");
  1028. }
  1029. return 1;
  1030. }
  1031. return 0;
  1032. }
  1033. }
  1034. if (num_args == 2) {
  1035. type1 = lua_type(L, 1);
  1036. type2 = lua_type(L, 2);
  1037. if ((type1 == LUA_TSTRING) && (type2 == LUA_TNUMBER)) {
  1038. arg1 = lua_tostring(L, 1);
  1039. arg2 = lua_tonumber(L, 2);
  1040. /* Get info according to argument */
  1041. if (!mg_strcasecmp(arg1, "connection")) {
  1042. int idx;
  1043. /* Get context */
  1044. struct mg_context *ctx;
  1045. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1046. lua_gettable(L, LUA_REGISTRYINDEX);
  1047. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1048. /* Get connection info for connection idx */
  1049. idx = (int)(arg2 + 0.5);
  1050. /* Lua uses 1 based index, C uses 0 based index */
  1051. idx--;
  1052. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1053. len = mg_get_connection_info(ctx, idx, NULL, 0);
  1054. if (len > 0) {
  1055. buf = (char *)mg_malloc(len + 64);
  1056. if (!buf) {
  1057. return luaL_error(L, "OOM in get_info() call");
  1058. }
  1059. len = mg_get_connection_info(ctx, idx, buf, len + 63);
  1060. lua_pushlstring(L, buf, len);
  1061. mg_free(buf);
  1062. } else {
  1063. lua_pushstring(L, "");
  1064. }
  1065. #else
  1066. (void)ctx;
  1067. (void)idx;
  1068. lua_pushstring(L, "");
  1069. #endif
  1070. return 1;
  1071. }
  1072. return 0;
  1073. }
  1074. }
  1075. /* Syntax error */
  1076. return luaL_error(L, "invalid get_info() call");
  1077. }
  1078. /* mg.get_option */
  1079. static int
  1080. lsp_get_option(lua_State *L)
  1081. {
  1082. int num_args = lua_gettop(L);
  1083. int type1;
  1084. const char *arg1;
  1085. const char *data;
  1086. int optidx;
  1087. /* Get connection */
  1088. struct mg_connection *conn =
  1089. (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
  1090. if (num_args == 0) {
  1091. const struct mg_option *opts = mg_get_valid_options();
  1092. if (!opts) {
  1093. return 0;
  1094. }
  1095. lua_newtable(L);
  1096. while (opts->name) {
  1097. optidx = get_option_index(opts->name);
  1098. if (optidx >= 0) {
  1099. data = conn->dom_ctx->config[optidx];
  1100. if (data) {
  1101. reg_string(L, opts->name, data);
  1102. }
  1103. }
  1104. opts++;
  1105. }
  1106. return 1;
  1107. }
  1108. if (num_args == 1) {
  1109. type1 = lua_type(L, 1);
  1110. if (type1 == LUA_TSTRING) {
  1111. arg1 = lua_tostring(L, 1);
  1112. /* Get option according to argument */
  1113. optidx = get_option_index(arg1);
  1114. if (optidx >= 0) {
  1115. data = conn->dom_ctx->config[optidx];
  1116. if (data) {
  1117. lua_pushstring(L, data);
  1118. return 1;
  1119. }
  1120. }
  1121. return 0;
  1122. }
  1123. }
  1124. /* Syntax error */
  1125. return luaL_error(L, "invalid get_option() call");
  1126. }
  1127. /* UUID library and function pointer */
  1128. union {
  1129. void *p;
  1130. void (*f)(unsigned char uuid[16]);
  1131. } pf_uuid_generate;
  1132. /* mg.uuid */
  1133. static int
  1134. lsp_uuid(lua_State *L)
  1135. {
  1136. union {
  1137. unsigned char uuid_array[16];
  1138. struct uuid_struct_type {
  1139. uint32_t data1;
  1140. uint16_t data2;
  1141. uint16_t data3;
  1142. uint8_t data4[8];
  1143. } uuid_struct;
  1144. } uuid;
  1145. char uuid_str[40];
  1146. int num_args = lua_gettop(L);
  1147. memset(&uuid, 0, sizeof(uuid));
  1148. memset(uuid_str, 0, sizeof(uuid_str));
  1149. if (num_args == 0) {
  1150. pf_uuid_generate.f(uuid.uuid_array);
  1151. sprintf(uuid_str,
  1152. "{%08lX-%04X-%04X-%02X%02X-"
  1153. "%02X%02X%02X%02X%02X%02X}",
  1154. (unsigned long)uuid.uuid_struct.data1,
  1155. (unsigned)uuid.uuid_struct.data2,
  1156. (unsigned)uuid.uuid_struct.data3,
  1157. (unsigned)uuid.uuid_struct.data4[0],
  1158. (unsigned)uuid.uuid_struct.data4[1],
  1159. (unsigned)uuid.uuid_struct.data4[2],
  1160. (unsigned)uuid.uuid_struct.data4[3],
  1161. (unsigned)uuid.uuid_struct.data4[4],
  1162. (unsigned)uuid.uuid_struct.data4[5],
  1163. (unsigned)uuid.uuid_struct.data4[6],
  1164. (unsigned)uuid.uuid_struct.data4[7]);
  1165. lua_pushstring(L, uuid_str);
  1166. return 1;
  1167. }
  1168. /* Syntax error */
  1169. return luaL_error(L, "invalid random() call");
  1170. }
  1171. #if defined(USE_WEBSOCKET)
  1172. struct lua_websock_data {
  1173. lua_State *state;
  1174. char *script;
  1175. unsigned references;
  1176. struct mg_connection *conn[MAX_WORKER_THREADS];
  1177. pthread_mutex_t ws_mutex;
  1178. };
  1179. #endif
  1180. /* mg.write for websockets */
  1181. static int
  1182. lwebsock_write(lua_State *L)
  1183. {
  1184. #if defined(USE_WEBSOCKET)
  1185. int num_args = lua_gettop(L);
  1186. struct lua_websock_data *ws;
  1187. const char *str;
  1188. size_t size;
  1189. int opcode = -1;
  1190. unsigned i;
  1191. struct mg_connection *client = NULL;
  1192. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1193. lua_gettable(L, LUA_REGISTRYINDEX);
  1194. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1195. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1196. if (num_args == 1) {
  1197. /* just one text: send it to all client */
  1198. if (lua_isstring(L, 1)) {
  1199. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1200. }
  1201. } else if (num_args == 2) {
  1202. if (lua_isnumber(L, 1)) {
  1203. /* opcode number and message text */
  1204. opcode = (int)lua_tointeger(L, 1);
  1205. } else if (lua_isstring(L, 1)) {
  1206. /* opcode string and message text */
  1207. str = lua_tostring(L, 1);
  1208. if (!mg_strncasecmp(str, "text", 4))
  1209. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1210. else if (!mg_strncasecmp(str, "bin", 3))
  1211. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1212. else if (!mg_strncasecmp(str, "close", 5))
  1213. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1214. else if (!mg_strncasecmp(str, "ping", 4))
  1215. opcode = MG_WEBSOCKET_OPCODE_PING;
  1216. else if (!mg_strncasecmp(str, "pong", 4))
  1217. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1218. else if (!mg_strncasecmp(str, "cont", 4))
  1219. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1220. } else if (lua_isuserdata(L, 1)) {
  1221. /* client id and message text */
  1222. client = (struct mg_connection *)lua_touserdata(L, 1);
  1223. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1224. }
  1225. } else if (num_args == 3) {
  1226. if (lua_isuserdata(L, 1)) {
  1227. client = (struct mg_connection *)lua_touserdata(L, 1);
  1228. if (lua_isnumber(L, 2)) {
  1229. /* client id, opcode number and message text */
  1230. opcode = (int)lua_tointeger(L, 2);
  1231. } else if (lua_isstring(L, 2)) {
  1232. /* client id, opcode string and message text */
  1233. str = lua_tostring(L, 2);
  1234. if (!mg_strncasecmp(str, "text", 4))
  1235. opcode = MG_WEBSOCKET_OPCODE_TEXT;
  1236. else if (!mg_strncasecmp(str, "bin", 3))
  1237. opcode = MG_WEBSOCKET_OPCODE_BINARY;
  1238. else if (!mg_strncasecmp(str, "close", 5))
  1239. opcode = MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE;
  1240. else if (!mg_strncasecmp(str, "ping", 4))
  1241. opcode = MG_WEBSOCKET_OPCODE_PING;
  1242. else if (!mg_strncasecmp(str, "pong", 4))
  1243. opcode = MG_WEBSOCKET_OPCODE_PONG;
  1244. else if (!mg_strncasecmp(str, "cont", 4))
  1245. opcode = MG_WEBSOCKET_OPCODE_CONTINUATION;
  1246. }
  1247. }
  1248. }
  1249. if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
  1250. str = lua_tolstring(L, num_args, &size);
  1251. if (client) {
  1252. for (i = 0; i < ws->references; i++) {
  1253. if (client == ws->conn[i]) {
  1254. mg_lock_connection(ws->conn[i]);
  1255. mg_websocket_write(ws->conn[i], opcode, str, size);
  1256. mg_unlock_connection(ws->conn[i]);
  1257. }
  1258. }
  1259. } else {
  1260. for (i = 0; i < ws->references; i++) {
  1261. mg_lock_connection(ws->conn[i]);
  1262. mg_websocket_write(ws->conn[i], opcode, str, size);
  1263. mg_unlock_connection(ws->conn[i]);
  1264. }
  1265. }
  1266. } else {
  1267. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1268. return luaL_error(L, "invalid websocket write() call");
  1269. }
  1270. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1271. #else
  1272. (void)(L); /* unused */
  1273. #endif
  1274. return 0;
  1275. }
  1276. struct laction_arg {
  1277. lua_State *state;
  1278. const char *script;
  1279. pthread_mutex_t *pmutex;
  1280. char txt[1];
  1281. };
  1282. static int
  1283. lua_action(struct laction_arg *arg)
  1284. {
  1285. int err, ok;
  1286. struct mg_context *ctx;
  1287. (void)pthread_mutex_lock(arg->pmutex);
  1288. lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
  1289. lua_gettable(arg->state, LUA_REGISTRYINDEX);
  1290. ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
  1291. err = luaL_loadstring(arg->state, arg->txt);
  1292. if (err != 0) {
  1293. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1294. (void)pthread_mutex_unlock(arg->pmutex);
  1295. mg_free(arg);
  1296. return 0;
  1297. }
  1298. err = lua_pcall(arg->state, 0, 1, 0);
  1299. if (err != 0) {
  1300. lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
  1301. (void)pthread_mutex_unlock(arg->pmutex);
  1302. mg_free(arg);
  1303. return 0;
  1304. }
  1305. ok = lua_type(arg->state, -1);
  1306. if (lua_isboolean(arg->state, -1)) {
  1307. ok = lua_toboolean(arg->state, -1);
  1308. } else {
  1309. ok = 0;
  1310. }
  1311. lua_pop(arg->state, 1);
  1312. (void)pthread_mutex_unlock(arg->pmutex);
  1313. if (!ok) {
  1314. mg_free(arg);
  1315. }
  1316. return ok;
  1317. }
  1318. static int
  1319. lua_action_free(struct laction_arg *arg)
  1320. {
  1321. if (lua_action(arg)) {
  1322. mg_free(arg);
  1323. }
  1324. return 0;
  1325. }
  1326. static int
  1327. lwebsocket_set_timer(lua_State *L, int is_periodic)
  1328. {
  1329. #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
  1330. int num_args = lua_gettop(L);
  1331. struct lua_websock_data *ws;
  1332. int type1, type2, ok = 0;
  1333. double timediff;
  1334. struct mg_context *ctx;
  1335. struct laction_arg *arg;
  1336. const char *txt;
  1337. size_t txt_len;
  1338. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1339. lua_gettable(L, LUA_REGISTRYINDEX);
  1340. ctx = (struct mg_context *)lua_touserdata(L, -1);
  1341. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1342. lua_gettable(L, LUA_REGISTRYINDEX);
  1343. ws = (struct lua_websock_data *)lua_touserdata(L, -1);
  1344. if (num_args < 2) {
  1345. return luaL_error(L,
  1346. "not enough arguments for set_timer/interval() call");
  1347. }
  1348. type1 = lua_type(L, 1);
  1349. type2 = lua_type(L, 2);
  1350. if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
  1351. timediff = (double)lua_tonumber(L, 2);
  1352. txt = lua_tostring(L, 1);
  1353. txt_len = strlen(txt);
  1354. arg = (struct laction_arg *)mg_malloc_ctx(sizeof(struct laction_arg)
  1355. + txt_len + 10,
  1356. ctx);
  1357. arg->state = L;
  1358. arg->script = ws->script;
  1359. arg->pmutex = &(ws->ws_mutex);
  1360. memcpy(arg->txt, "return(", 7);
  1361. memcpy(arg->txt + 7, txt, txt_len);
  1362. arg->txt[txt_len + 7] = ')';
  1363. arg->txt[txt_len + 8] = 0;
  1364. ok =
  1365. (0
  1366. == timer_add(ctx,
  1367. timediff,
  1368. is_periodic,
  1369. 1,
  1370. (taction)(is_periodic ? lua_action : lua_action_free),
  1371. (void *)arg));
  1372. } else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
  1373. /* TODO (mid): not implemented yet */
  1374. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1375. } else {
  1376. return luaL_error(L, "invalid arguments for set_timer/interval() call");
  1377. }
  1378. lua_pushboolean(L, ok);
  1379. return 1;
  1380. #else
  1381. (void)(L); /* unused */
  1382. (void)(is_periodic); /* unused */
  1383. return 0;
  1384. #endif
  1385. }
  1386. /* mg.set_timeout for websockets */
  1387. static int
  1388. lwebsocket_set_timeout(lua_State *L)
  1389. {
  1390. return lwebsocket_set_timer(L, 0);
  1391. }
  1392. /* mg.set_interval for websockets */
  1393. static int
  1394. lwebsocket_set_interval(lua_State *L)
  1395. {
  1396. return lwebsocket_set_timer(L, 1);
  1397. }
  1398. enum {
  1399. LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
  1400. LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
  1401. LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
  1402. };
  1403. static void
  1404. prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
  1405. {
  1406. const char *s;
  1407. int i;
  1408. /* Export mg.request_info */
  1409. lua_pushstring(L, "request_info");
  1410. lua_newtable(L);
  1411. reg_string(L, "request_method", conn->request_info.request_method);
  1412. reg_string(L, "request_uri", conn->request_info.request_uri);
  1413. reg_string(L, "uri", conn->request_info.local_uri);
  1414. reg_string(L, "http_version", conn->request_info.http_version);
  1415. reg_string(L, "query_string", conn->request_info.query_string);
  1416. reg_string(L, "remote_addr", conn->request_info.remote_addr);
  1417. /* TODO (high): ip version */
  1418. reg_int(L, "remote_port", conn->request_info.remote_port);
  1419. reg_int(L, "num_headers", conn->request_info.num_headers);
  1420. reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
  1421. if (conn->path_info != NULL) {
  1422. reg_string(L, "path_info", conn->path_info);
  1423. }
  1424. if (conn->request_info.content_length >= 0) {
  1425. /* reg_int64: content_length */
  1426. lua_pushstring(L, "content_length");
  1427. lua_pushnumber(
  1428. L,
  1429. (lua_Number)conn->request_info
  1430. .content_length); /* lua_Number may be used as 52 bit integer */
  1431. lua_rawset(L, -3);
  1432. }
  1433. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  1434. reg_string(L, "content_type", s);
  1435. }
  1436. if (conn->request_info.remote_user != NULL) {
  1437. reg_string(L, "remote_user", conn->request_info.remote_user);
  1438. reg_string(L, "auth_type", "Digest");
  1439. }
  1440. reg_boolean(L, "https", conn->ssl != NULL);
  1441. if (conn->status_code > 0) {
  1442. /* Lua error handler should show the status code */
  1443. reg_int(L, "status", conn->status_code);
  1444. }
  1445. lua_pushstring(L, "http_headers");
  1446. lua_newtable(L);
  1447. for (i = 0; i < conn->request_info.num_headers; i++) {
  1448. reg_string(L,
  1449. conn->request_info.http_headers[i].name,
  1450. conn->request_info.http_headers[i].value);
  1451. }
  1452. lua_rawset(L, -3);
  1453. lua_rawset(L, -3);
  1454. }
  1455. static void
  1456. civetweb_open_lua_libs(lua_State *L)
  1457. {
  1458. {
  1459. extern void luaL_openlibs(lua_State *);
  1460. luaL_openlibs(L);
  1461. }
  1462. #if defined(USE_LUA_SQLITE3)
  1463. {
  1464. extern int luaopen_lsqlite3(lua_State *);
  1465. luaopen_lsqlite3(L);
  1466. }
  1467. #endif
  1468. #if defined(USE_LUA_LUAXML)
  1469. {
  1470. extern int luaopen_LuaXML_lib(lua_State *);
  1471. luaopen_LuaXML_lib(L);
  1472. }
  1473. #endif
  1474. #if defined(USE_LUA_FILE_SYSTEM)
  1475. {
  1476. extern int luaopen_lfs(lua_State *);
  1477. luaopen_lfs(L);
  1478. }
  1479. #endif
  1480. }
  1481. static void
  1482. prepare_lua_environment(struct mg_context *ctx,
  1483. struct mg_connection *conn,
  1484. struct lua_websock_data *ws_conn_list,
  1485. lua_State *L,
  1486. const char *script_name,
  1487. int lua_env_type)
  1488. {
  1489. const char *preload_file_name = NULL;
  1490. civetweb_open_lua_libs(L);
  1491. #if LUA_VERSION_NUM == 502
  1492. /* Keep the "connect" method for compatibility,
  1493. * but do not backport it to Lua 5.1.
  1494. * TODO: Redesign the interface.
  1495. */
  1496. luaL_newmetatable(L, LUASOCKET);
  1497. lua_pushliteral(L, "__index");
  1498. luaL_newlib(L, luasocket_methods);
  1499. lua_rawset(L, -3);
  1500. lua_pop(L, 1);
  1501. lua_register(L, "connect", lsp_connect);
  1502. #endif
  1503. /* Store context in the registry */
  1504. if (ctx != NULL) {
  1505. lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
  1506. lua_pushlightuserdata(L, (void *)ctx);
  1507. lua_settable(L, LUA_REGISTRYINDEX);
  1508. }
  1509. if (ws_conn_list != NULL) {
  1510. lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
  1511. lua_pushlightuserdata(L, (void *)ws_conn_list);
  1512. lua_settable(L, LUA_REGISTRYINDEX);
  1513. }
  1514. /* Lua server pages store the depth of mg.include, in order
  1515. * to detect recursions and prevent stack overflows. */
  1516. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1517. struct lsp_include_history *h;
  1518. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  1519. h = (struct lsp_include_history *)
  1520. lua_newuserdata(L, sizeof(struct lsp_include_history));
  1521. lua_settable(L, LUA_REGISTRYINDEX);
  1522. memset(h, 0, sizeof(struct lsp_include_history));
  1523. }
  1524. /* Register mg module */
  1525. lua_newtable(L);
  1526. switch (lua_env_type) {
  1527. case LUA_ENV_TYPE_LUA_SERVER_PAGE:
  1528. reg_string(L, "lua_type", "page");
  1529. break;
  1530. case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
  1531. reg_string(L, "lua_type", "script");
  1532. break;
  1533. case LUA_ENV_TYPE_LUA_WEBSOCKET:
  1534. reg_string(L, "lua_type", "websocket");
  1535. break;
  1536. }
  1537. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE
  1538. || lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
  1539. reg_conn_function(L, "cry", lsp_cry, conn);
  1540. reg_conn_function(L, "read", lsp_read, conn);
  1541. reg_conn_function(L, "write", lsp_write, conn);
  1542. reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
  1543. reg_conn_function(L, "send_file", lsp_send_file, conn);
  1544. }
  1545. if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
  1546. reg_conn_function(L, "include", lsp_include, conn);
  1547. reg_conn_function(L, "redirect", lsp_redirect, conn);
  1548. }
  1549. if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
  1550. reg_function(L, "write", lwebsock_write);
  1551. #if defined(USE_TIMERS)
  1552. reg_function(L, "set_timeout", lwebsocket_set_timeout);
  1553. reg_function(L, "set_interval", lwebsocket_set_interval);
  1554. #endif
  1555. /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
  1556. }
  1557. reg_conn_function(L, "get_mime_type", lsp_get_mime_type, conn);
  1558. reg_conn_function(L, "get_option", lsp_get_option, conn);
  1559. reg_function(L, "time", lsp_get_time);
  1560. reg_function(L, "get_var", lsp_get_var);
  1561. reg_function(L, "get_cookie", lsp_get_cookie);
  1562. reg_function(L, "md5", lsp_md5);
  1563. reg_function(L, "url_encode", lsp_url_encode);
  1564. reg_function(L, "url_decode", lsp_url_decode);
  1565. reg_function(L, "base64_encode", lsp_base64_encode);
  1566. reg_function(L, "base64_decode", lsp_base64_decode);
  1567. reg_function(L, "get_response_code_text", lsp_get_response_code_text);
  1568. reg_function(L, "random", lsp_random);
  1569. reg_function(L, "get_info", lsp_get_info);
  1570. if (pf_uuid_generate.f) {
  1571. reg_function(L, "uuid", lsp_uuid);
  1572. }
  1573. reg_string(L, "version", CIVETWEB_VERSION);
  1574. reg_string(L, "script_name", script_name);
  1575. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1576. reg_string(L, "document_root", conn->dom_ctx->config[DOCUMENT_ROOT]);
  1577. reg_string(L,
  1578. "auth_domain",
  1579. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  1580. #if defined(USE_WEBSOCKET)
  1581. if (conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  1582. reg_string(L,
  1583. "websocket_root",
  1584. conn->dom_ctx->config[WEBSOCKET_ROOT]);
  1585. } else {
  1586. reg_string(L,
  1587. "websocket_root",
  1588. conn->dom_ctx->config[DOCUMENT_ROOT]);
  1589. }
  1590. #endif
  1591. if (ctx->systemName != NULL) {
  1592. reg_string(L, "system", ctx->systemName);
  1593. }
  1594. }
  1595. /* Export connection specific info */
  1596. if (conn != NULL) {
  1597. prepare_lua_request_info(conn, L);
  1598. }
  1599. lua_setglobal(L, "mg");
  1600. /* Register default mg.onerror function */
  1601. IGNORE_UNUSED_RESULT(
  1602. luaL_dostring(L,
  1603. "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  1604. "debug.traceback(e, 1)) end"));
  1605. /* Check if a preload file is available */
  1606. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  1607. preload_file_name = conn->dom_ctx->config[LUA_PRELOAD_FILE];
  1608. }
  1609. /* Preload file into new Lua environment */
  1610. if (preload_file_name) {
  1611. IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file_name));
  1612. }
  1613. if (ctx != NULL) {
  1614. if (ctx->callbacks.init_lua != NULL) {
  1615. ctx->callbacks.init_lua(conn, L);
  1616. }
  1617. }
  1618. }
  1619. static int
  1620. lua_error_handler(lua_State *L)
  1621. {
  1622. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  1623. lua_getglobal(L, "mg");
  1624. if (!lua_isnil(L, -1)) {
  1625. lua_getfield(L, -1, "write"); /* call mg.write() */
  1626. lua_pushstring(L, error_msg);
  1627. lua_pushliteral(L, "\n");
  1628. lua_call(L, 2, 0);
  1629. IGNORE_UNUSED_RESULT(
  1630. luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  1631. } else {
  1632. printf("Lua error: [%s]\n", error_msg);
  1633. IGNORE_UNUSED_RESULT(
  1634. luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  1635. }
  1636. /* TODO(lsm, low): leave the stack balanced */
  1637. return 0;
  1638. }
  1639. static void *
  1640. lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
  1641. {
  1642. (void)osize; /* not used */
  1643. if (nsize == 0) {
  1644. mg_free(ptr);
  1645. return NULL;
  1646. }
  1647. return mg_realloc_ctx(ptr, nsize, (struct mg_context *)ud);
  1648. }
  1649. static void
  1650. mg_exec_lua_script(struct mg_connection *conn,
  1651. const char *path,
  1652. const void **exports)
  1653. {
  1654. int i;
  1655. lua_State *L;
  1656. /* Assume the script does not support keep_alive. The script may change this
  1657. * by calling mg.keep_alive(true). */
  1658. conn->must_close = 1;
  1659. /* Execute a plain Lua script. */
  1660. if (path != NULL
  1661. && (L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx)))
  1662. != NULL) {
  1663. prepare_lua_environment(
  1664. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  1665. lua_pushcclosure(L, &lua_error_handler, 0);
  1666. if (exports != NULL) {
  1667. #if LUA_VERSION_NUM > 501
  1668. lua_pushglobaltable(L);
  1669. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1670. lua_CFunction func;
  1671. lua_pushstring(L, (const char *)(exports[i]));
  1672. *(const void **)(&func) = exports[i + 1];
  1673. lua_pushcclosure(L, func, 0);
  1674. lua_rawset(L, -3);
  1675. }
  1676. #else
  1677. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  1678. lua_CFunction func;
  1679. const char *name = (const char *)(exports[i]);
  1680. *(const void **)(&func) = exports[i + 1];
  1681. lua_register(L, name, func);
  1682. }
  1683. #endif
  1684. }
  1685. if (luaL_loadfile(L, path) != 0) {
  1686. lua_error_handler(L);
  1687. }
  1688. lua_pcall(L, 0, 0, -2);
  1689. lua_close(L);
  1690. }
  1691. }
  1692. static int
  1693. handle_lsp_request(struct mg_connection *conn,
  1694. const char *path,
  1695. struct mg_file *filep,
  1696. struct lua_State *ls)
  1697. {
  1698. void *p = NULL;
  1699. lua_State *L = NULL;
  1700. struct lsp_include_history *include_history;
  1701. int error = 1;
  1702. void *file_in_memory; /* TODO(low): remove when removing "file in memory" */
  1703. /* Assume the script does not support keep_alive. The script may change this
  1704. * by calling mg.keep_alive(true). */
  1705. conn->must_close = 1;
  1706. /* mg_fopen opens the file and sets the size accordingly */
  1707. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  1708. /* File not found or not accessible */
  1709. if (ls == NULL) {
  1710. mg_send_http_error(conn,
  1711. 500,
  1712. "Error: Cannot open script file %s",
  1713. path);
  1714. } else {
  1715. luaL_error(ls, "Cannot include [%s]: not found", path);
  1716. }
  1717. goto cleanup_handle_lsp_request;
  1718. }
  1719. #if defined(MG_USE_OPEN_FILE)
  1720. /* The "file in memory" feature is going to be removed. For details see
  1721. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI */
  1722. file_in_memory = filep->access.membuf;
  1723. #else
  1724. file_in_memory = NULL;
  1725. #endif
  1726. /* Map file in memory (size is known). */
  1727. if (file_in_memory == NULL
  1728. && (p = mmap(NULL,
  1729. (size_t)filep->stat.size,
  1730. PROT_READ,
  1731. MAP_PRIVATE,
  1732. fileno(filep->access.fp),
  1733. 0)) == MAP_FAILED) {
  1734. /* mmap failed */
  1735. if (ls == NULL) {
  1736. mg_send_http_error(
  1737. conn,
  1738. 500,
  1739. "Error: Cannot open script\nFile %s can not be mapped",
  1740. path);
  1741. } else {
  1742. luaL_error(ls,
  1743. "mmap(%s, %zu, %d): %s",
  1744. path,
  1745. (size_t)filep->stat.size,
  1746. fileno(filep->access.fp),
  1747. strerror(errno));
  1748. }
  1749. goto cleanup_handle_lsp_request;
  1750. }
  1751. if (ls != NULL) {
  1752. L = ls;
  1753. } else {
  1754. L = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  1755. if (L == NULL) {
  1756. mg_send_http_error(
  1757. conn,
  1758. 500,
  1759. "%s",
  1760. "Error: Cannot execute script\nlua_newstate failed");
  1761. goto cleanup_handle_lsp_request;
  1762. }
  1763. prepare_lua_environment(
  1764. conn->phys_ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
  1765. }
  1766. /* Get LSP include history table */
  1767. lua_pushlightuserdata(L, (void *)&lua_regkey_lsp_include_history);
  1768. lua_gettable(L, LUA_REGISTRYINDEX);
  1769. include_history = (struct lsp_include_history *)lua_touserdata(L, -1);
  1770. /* Store script name and increment depth */
  1771. include_history->depth++;
  1772. include_history->script[include_history->depth] = path;
  1773. /* Lua state is ready to use */
  1774. /* We're not sending HTTP headers here, Lua page must do it. */
  1775. error = run_lsp(conn,
  1776. path,
  1777. (file_in_memory == NULL) ? (const char *)p
  1778. : (const char *)file_in_memory,
  1779. filep->stat.size,
  1780. L);
  1781. cleanup_handle_lsp_request:
  1782. if (L != NULL && ls == NULL)
  1783. lua_close(L);
  1784. if (p != NULL)
  1785. munmap(p, filep->stat.size);
  1786. (void)mg_fclose(&filep->access);
  1787. return error;
  1788. }
  1789. #if defined(USE_WEBSOCKET)
  1790. struct mg_shared_lua_websocket_list {
  1791. struct lua_websock_data ws;
  1792. struct mg_shared_lua_websocket_list *next;
  1793. };
  1794. static void *
  1795. lua_websocket_new(const char *script, struct mg_connection *conn)
  1796. {
  1797. struct mg_shared_lua_websocket_list **shared_websock_list =
  1798. &(conn->dom_ctx->shared_lua_websockets);
  1799. struct lua_websock_data *ws;
  1800. int err, ok = 0;
  1801. DEBUG_ASSERT(conn->lua_websocket_state == NULL);
  1802. /* lock list (mg_context global) */
  1803. mg_lock_context(conn->phys_ctx);
  1804. while (*shared_websock_list) {
  1805. /* check if ws already in list */
  1806. if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
  1807. break;
  1808. }
  1809. shared_websock_list = &((*shared_websock_list)->next);
  1810. }
  1811. if (*shared_websock_list == NULL) {
  1812. /* add ws to list */
  1813. *shared_websock_list =
  1814. (struct mg_shared_lua_websocket_list *)mg_calloc_ctx(
  1815. sizeof(struct mg_shared_lua_websocket_list), 1, conn->phys_ctx);
  1816. if (*shared_websock_list == NULL) {
  1817. conn->must_close = 1;
  1818. mg_unlock_context(conn->phys_ctx);
  1819. mg_cry_internal(conn,
  1820. "%s",
  1821. "Cannot create shared websocket struct, OOM");
  1822. return NULL;
  1823. }
  1824. /* init ws list element */
  1825. ws = &(*shared_websock_list)->ws;
  1826. ws->script = mg_strdup_ctx(script, conn->phys_ctx);
  1827. if (!ws->script) {
  1828. conn->must_close = 1;
  1829. mg_unlock_context(conn->phys_ctx);
  1830. mg_cry_internal(conn,
  1831. "%s",
  1832. "Cannot create shared websocket script, OOM");
  1833. return NULL;
  1834. }
  1835. pthread_mutex_init(&(ws->ws_mutex), &pthread_mutex_attr);
  1836. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1837. ws->state = lua_newstate(lua_allocator, (void *)(conn->phys_ctx));
  1838. ws->conn[0] = conn;
  1839. ws->references = 1;
  1840. prepare_lua_environment(conn->phys_ctx,
  1841. conn,
  1842. ws,
  1843. ws->state,
  1844. script,
  1845. LUA_ENV_TYPE_LUA_WEBSOCKET);
  1846. err = luaL_loadfile(ws->state, script);
  1847. if (err != 0) {
  1848. lua_cry(conn, err, ws->state, script, "load");
  1849. }
  1850. err = lua_pcall(ws->state, 0, 0, 0);
  1851. if (err != 0) {
  1852. lua_cry(conn, err, ws->state, script, "init");
  1853. }
  1854. } else {
  1855. /* inc ref count */
  1856. ws = &(*shared_websock_list)->ws;
  1857. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1858. (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
  1859. }
  1860. mg_unlock_context(conn->phys_ctx);
  1861. /* call add */
  1862. lua_getglobal(ws->state, "open");
  1863. lua_newtable(ws->state);
  1864. prepare_lua_request_info(conn, ws->state);
  1865. lua_pushstring(ws->state, "client");
  1866. lua_pushlightuserdata(ws->state, (void *)conn);
  1867. lua_rawset(ws->state, -3);
  1868. err = lua_pcall(ws->state, 1, 1, 0);
  1869. if (err != 0) {
  1870. lua_cry(conn, err, ws->state, script, "open handler");
  1871. } else {
  1872. if (lua_isboolean(ws->state, -1)) {
  1873. ok = lua_toboolean(ws->state, -1);
  1874. }
  1875. lua_pop(ws->state, 1);
  1876. }
  1877. if (!ok) {
  1878. /* Remove from ws connection list. */
  1879. /* TODO (mid): Check if list entry and Lua state needs to be deleted
  1880. * (see websocket_close). */
  1881. (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
  1882. }
  1883. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1884. return ok ? (void *)ws : NULL;
  1885. }
  1886. static int
  1887. lua_websocket_data(struct mg_connection *conn,
  1888. int bits,
  1889. char *data,
  1890. size_t data_len,
  1891. void *ws_arg)
  1892. {
  1893. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1894. int err, ok = 0;
  1895. DEBUG_ASSERT(ws != NULL);
  1896. DEBUG_ASSERT(ws->state != NULL);
  1897. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1898. lua_getglobal(ws->state, "data");
  1899. lua_newtable(ws->state);
  1900. lua_pushstring(ws->state, "client");
  1901. lua_pushlightuserdata(ws->state, (void *)conn);
  1902. lua_rawset(ws->state, -3);
  1903. lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
  1904. a meaning according to
  1905. http://tools.ietf.org/html/rfc6455,
  1906. section 5.2 */
  1907. lua_pushnumber(ws->state, bits);
  1908. lua_rawset(ws->state, -3);
  1909. lua_pushstring(ws->state, "data");
  1910. lua_pushlstring(ws->state, data, data_len);
  1911. lua_rawset(ws->state, -3);
  1912. err = lua_pcall(ws->state, 1, 1, 0);
  1913. if (err != 0) {
  1914. lua_cry(conn, err, ws->state, ws->script, "data handler");
  1915. } else {
  1916. if (lua_isboolean(ws->state, -1)) {
  1917. ok = lua_toboolean(ws->state, -1);
  1918. }
  1919. lua_pop(ws->state, 1);
  1920. }
  1921. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1922. return ok;
  1923. }
  1924. static int
  1925. lua_websocket_ready(struct mg_connection *conn, void *ws_arg)
  1926. {
  1927. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1928. int err, ok = 0;
  1929. DEBUG_ASSERT(ws != NULL);
  1930. DEBUG_ASSERT(ws->state != NULL);
  1931. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1932. lua_getglobal(ws->state, "ready");
  1933. lua_newtable(ws->state);
  1934. lua_pushstring(ws->state, "client");
  1935. lua_pushlightuserdata(ws->state, (void *)conn);
  1936. lua_rawset(ws->state, -3);
  1937. err = lua_pcall(ws->state, 1, 1, 0);
  1938. if (err != 0) {
  1939. lua_cry(conn, err, ws->state, ws->script, "ready handler");
  1940. } else {
  1941. if (lua_isboolean(ws->state, -1)) {
  1942. ok = lua_toboolean(ws->state, -1);
  1943. }
  1944. lua_pop(ws->state, 1);
  1945. }
  1946. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1947. return ok;
  1948. }
  1949. static void
  1950. lua_websocket_close(struct mg_connection *conn, void *ws_arg)
  1951. {
  1952. struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
  1953. struct mg_shared_lua_websocket_list **shared_websock_list =
  1954. &(conn->dom_ctx->shared_lua_websockets);
  1955. int err = 0;
  1956. unsigned i;
  1957. DEBUG_ASSERT(ws != NULL);
  1958. DEBUG_ASSERT(ws->state != NULL);
  1959. (void)pthread_mutex_lock(&(ws->ws_mutex));
  1960. lua_getglobal(ws->state, "close");
  1961. lua_newtable(ws->state);
  1962. lua_pushstring(ws->state, "client");
  1963. lua_pushlightuserdata(ws->state, (void *)conn);
  1964. lua_rawset(ws->state, -3);
  1965. err = lua_pcall(ws->state, 1, 0, 0);
  1966. if (err != 0) {
  1967. lua_cry(conn, err, ws->state, ws->script, "close handler");
  1968. }
  1969. for (i = 0; i < ws->references; i++) {
  1970. if (ws->conn[i] == conn) {
  1971. ws->references--;
  1972. ws->conn[i] = ws->conn[ws->references];
  1973. }
  1974. }
  1975. /* TODO: Delete lua_websock_data and remove it from the websocket list.
  1976. This must only be done, when all connections are closed, and all
  1977. asynchronous operations and timers are completed/expired. */
  1978. (void)shared_websock_list; /* shared_websock_list unused (see open TODO) */
  1979. (void)pthread_mutex_unlock(&(ws->ws_mutex));
  1980. }
  1981. #endif
  1982. static lua_State *
  1983. mg_prepare_lua_context_script(const char *file_name,
  1984. struct mg_context *ctx,
  1985. char *ebuf,
  1986. size_t ebuf_len)
  1987. {
  1988. struct lua_State *L;
  1989. int lua_ret;
  1990. const char *lua_err_txt;
  1991. (void)ctx;
  1992. L = luaL_newstate();
  1993. if (L == NULL) {
  1994. mg_snprintf(NULL,
  1995. NULL, /* No truncation check for ebuf */
  1996. ebuf,
  1997. ebuf_len,
  1998. "Error: %s",
  1999. "Cannot create Lua state");
  2000. return 0;
  2001. }
  2002. civetweb_open_lua_libs(L);
  2003. lua_ret = luaL_loadfile(L, file_name);
  2004. if (lua_ret != LUA_OK) {
  2005. /* Error when loading the file (e.g. file not found,
  2006. * out of memory, ...)
  2007. */
  2008. lua_err_txt = lua_tostring(L, -1);
  2009. mg_snprintf(NULL,
  2010. NULL, /* No truncation check for ebuf */
  2011. ebuf,
  2012. ebuf_len,
  2013. "Error loading file %s: %s\n",
  2014. file_name,
  2015. lua_err_txt);
  2016. return 0;
  2017. }
  2018. /* The script file is loaded, now call it */
  2019. lua_ret = lua_pcall(L,
  2020. /* no arguments */ 0,
  2021. /* zero or one return value */ 1,
  2022. /* errors as strint return value */ 0);
  2023. if (lua_ret != LUA_OK) {
  2024. /* Error when executing the script */
  2025. lua_err_txt = lua_tostring(L, -1);
  2026. mg_snprintf(NULL,
  2027. NULL, /* No truncation check for ebuf */
  2028. ebuf,
  2029. ebuf_len,
  2030. "Error running file %s: %s\n",
  2031. file_name,
  2032. lua_err_txt);
  2033. return 0;
  2034. }
  2035. /* lua_close(L); must be done somewhere else */
  2036. return L;
  2037. }
  2038. int
  2039. run_lua(const char *file_name)
  2040. {
  2041. int func_ret = EXIT_FAILURE;
  2042. char ebuf[512] = {0};
  2043. lua_State *L =
  2044. mg_prepare_lua_context_script(file_name, NULL, ebuf, sizeof(ebuf));
  2045. if (L) {
  2046. /* Script executed */
  2047. if (lua_type(L, -1) == LUA_TNUMBER) {
  2048. func_ret = (int)lua_tonumber(L, -1);
  2049. } else {
  2050. func_ret = EXIT_SUCCESS;
  2051. }
  2052. lua_close(L);
  2053. } else {
  2054. fprintf(stderr, "%s\n", ebuf);
  2055. }
  2056. return func_ret;
  2057. }
  2058. static void *lib_handle_uuid = NULL;
  2059. static void
  2060. lua_init_optional_libraries(void)
  2061. {
  2062. #if !defined(_WIN32)
  2063. lib_handle_uuid = dlopen("libuuid.so", RTLD_LAZY);
  2064. pf_uuid_generate.p =
  2065. (lib_handle_uuid ? dlsym(lib_handle_uuid, "uuid_generate") : 0);
  2066. #else
  2067. pf_uuid_generate.p = 0;
  2068. #endif
  2069. }
  2070. static void
  2071. lua_exit_optional_libraries(void)
  2072. {
  2073. #if !defined(_WIN32)
  2074. if (lib_handle_uuid) {
  2075. dlclose(lib_handle_uuid);
  2076. }
  2077. #endif
  2078. pf_uuid_generate.p = 0;
  2079. lib_handle_uuid = NULL;
  2080. }
  2081. /* End of mod_lua.inl */