mod_lua.inl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #include <lua.h>
  2. #include <lauxlib.h>
  3. #ifdef _WIN32
  4. static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
  5. int offset)
  6. {
  7. HANDLE fh = (HANDLE) _get_osfhandle(fd);
  8. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  9. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
  10. CloseHandle(mh);
  11. return p;
  12. }
  13. #define munmap(x, y) UnmapViewOfFile(x)
  14. #define MAP_FAILED NULL
  15. #define MAP_PRIVATE 0
  16. #define PROT_READ 0
  17. #else
  18. #include <sys/mman.h>
  19. #endif
  20. static const char *LUASOCKET = "luasocket";
  21. // Forward declarations
  22. static void handle_request(struct mg_connection *);
  23. static int handle_lsp_request(struct mg_connection *, const char *,
  24. struct file *, struct lua_State *);
  25. static void reg_string(struct lua_State *L, const char *name, const char *val)
  26. {
  27. lua_pushstring(L, name);
  28. lua_pushstring(L, val);
  29. lua_rawset(L, -3);
  30. }
  31. static void reg_int(struct lua_State *L, const char *name, int val)
  32. {
  33. lua_pushstring(L, name);
  34. lua_pushinteger(L, val);
  35. lua_rawset(L, -3);
  36. }
  37. static void reg_function(struct lua_State *L, const char *name,
  38. lua_CFunction func, struct mg_connection *conn)
  39. {
  40. lua_pushstring(L, name);
  41. lua_pushlightuserdata(L, conn);
  42. lua_pushcclosure(L, func, 1);
  43. lua_rawset(L, -3);
  44. }
  45. static int lsp_sock_close(lua_State *L)
  46. {
  47. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  48. lua_getfield(L, -1, "sock");
  49. closesocket((SOCKET) lua_tonumber(L, -1));
  50. } else {
  51. return luaL_error(L, "invalid :close() call");
  52. }
  53. return 1;
  54. }
  55. static int lsp_sock_recv(lua_State *L)
  56. {
  57. char buf[2000];
  58. int n;
  59. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  60. lua_getfield(L, -1, "sock");
  61. n = recv((SOCKET) lua_tonumber(L, -1), buf, sizeof(buf), 0);
  62. if (n <= 0) {
  63. lua_pushnil(L);
  64. } else {
  65. lua_pushlstring(L, buf, n);
  66. }
  67. } else {
  68. return luaL_error(L, "invalid :close() call");
  69. }
  70. return 1;
  71. }
  72. static int lsp_sock_send(lua_State *L)
  73. {
  74. const char *buf;
  75. size_t len, sent = 0;
  76. int n = 0, sock;
  77. if (lua_gettop(L) > 1 && lua_istable(L, -2) && lua_isstring(L, -1)) {
  78. buf = lua_tolstring(L, -1, &len);
  79. lua_getfield(L, -2, "sock");
  80. sock = (int) lua_tonumber(L, -1);
  81. while (sent < len) {
  82. if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
  83. break;
  84. }
  85. sent += n;
  86. }
  87. lua_pushnumber(L, n);
  88. } else {
  89. return luaL_error(L, "invalid :close() call");
  90. }
  91. return 1;
  92. }
  93. static const struct luaL_Reg luasocket_methods[] = {
  94. {"close", lsp_sock_close},
  95. {"send", lsp_sock_send},
  96. {"recv", lsp_sock_recv},
  97. {NULL, NULL}
  98. };
  99. static int lsp_connect(lua_State *L)
  100. {
  101. char ebuf[100];
  102. SOCKET sock;
  103. if (lua_isstring(L, -3) && lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
  104. sock = conn2(NULL, lua_tostring(L, -3), (int) lua_tonumber(L, -2),
  105. (int) lua_tonumber(L, -1), ebuf, sizeof(ebuf));
  106. if (sock == INVALID_SOCKET) {
  107. return luaL_error(L, ebuf);
  108. } else {
  109. lua_newtable(L);
  110. reg_int(L, "sock", (int) sock);
  111. reg_string(L, "host", lua_tostring(L, -4));
  112. luaL_getmetatable(L, LUASOCKET);
  113. lua_setmetatable(L, -2);
  114. }
  115. } else {
  116. return luaL_error(L, "connect(host,port,is_ssl): invalid parameter given.");
  117. }
  118. return 1;
  119. }
  120. static int lsp_error(lua_State *L)
  121. {
  122. lua_getglobal(L, "mg");
  123. lua_getfield(L, -1, "onerror");
  124. lua_pushvalue(L, -3);
  125. lua_pcall(L, 1, 0, 0);
  126. return 0;
  127. }
  128. // Silently stop processing chunks.
  129. static void lsp_abort(lua_State *L)
  130. {
  131. int top = lua_gettop(L);
  132. lua_getglobal(L, "mg");
  133. lua_pushnil(L);
  134. lua_setfield(L, -2, "onerror");
  135. lua_settop(L, top);
  136. lua_pushstring(L, "aborting");
  137. lua_error(L);
  138. }
  139. static int lsp(struct mg_connection *conn, const char *path,
  140. const char *p, int64_t len, lua_State *L)
  141. {
  142. int i, j, pos = 0, lines = 1, lualines = 0;
  143. char chunkname[MG_BUF_LEN];
  144. for (i = 0; i < len; i++) {
  145. if (p[i] == '\n') lines++;
  146. if (p[i] == '<' && p[i + 1] == '?') {
  147. for (j = i + 1; j < len ; j++) {
  148. if (p[j] == '\n') lualines++;
  149. if (p[j] == '?' && p[j + 1] == '>') {
  150. mg_write(conn, p + pos, i - pos);
  151. snprintf(chunkname, sizeof(chunkname), "@%s+%i", path, lines);
  152. lua_pushlightuserdata(L, conn);
  153. lua_pushcclosure(L, lsp_error, 1);
  154. if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), chunkname)) {
  155. // Syntax error or OOM. Error message is pushed on stack.
  156. lua_pcall(L, 1, 0, 0);
  157. } else {
  158. // Success loading chunk. Call it.
  159. lua_pcall(L, 0, 0, 1);
  160. }
  161. pos = j + 2;
  162. i = pos - 1;
  163. break;
  164. }
  165. }
  166. if (lualines > 0) {
  167. lines += lualines;
  168. lualines = 0;
  169. }
  170. }
  171. }
  172. if (i > pos) {
  173. mg_write(conn, p + pos, i - pos);
  174. }
  175. return 0;
  176. }
  177. static int lsp_write(lua_State *L)
  178. {
  179. int i, num_args;
  180. const char *str;
  181. size_t size;
  182. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  183. num_args = lua_gettop(L);
  184. for (i = 1; i <= num_args; i++) {
  185. if (lua_isstring(L, i)) {
  186. str = lua_tolstring(L, i, &size);
  187. mg_write(conn, str, size);
  188. }
  189. }
  190. return 0;
  191. }
  192. static int lsp_read(lua_State *L)
  193. {
  194. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  195. char buf[1024];
  196. int len = mg_read(conn, buf, sizeof(buf));
  197. if (len <= 0) return 0;
  198. lua_pushlstring(L, buf, len);
  199. return 1;
  200. }
  201. // mg.include: Include another .lp file
  202. static int lsp_include(lua_State *L)
  203. {
  204. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  205. struct file file = STRUCT_FILE_INITIALIZER;
  206. if (handle_lsp_request(conn, lua_tostring(L, -1), &file, L)) {
  207. // handle_lsp_request returned an error code, meaning an error occured in
  208. // the included page and mg.onerror returned non-zero. Stop processing.
  209. lsp_abort(L);
  210. }
  211. return 0;
  212. }
  213. // mg.cry: Log an error. Default value for mg.onerror.
  214. static int lsp_cry(lua_State *L)
  215. {
  216. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  217. mg_cry(conn, "%s", lua_tostring(L, -1));
  218. return 0;
  219. }
  220. // mg.redirect: Redirect the request (internally).
  221. static int lsp_redirect(lua_State *L)
  222. {
  223. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  224. conn->request_info.uri = lua_tostring(L, -1);
  225. handle_request(conn);
  226. lsp_abort(L);
  227. return 0;
  228. }
  229. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L)
  230. {
  231. const struct mg_request_info *ri = mg_get_request_info(conn);
  232. extern void luaL_openlibs(lua_State *);
  233. int i;
  234. luaL_openlibs(L);
  235. #ifdef USE_LUA_SQLITE3
  236. {
  237. extern int luaopen_lsqlite3(lua_State *);
  238. luaopen_lsqlite3(L);
  239. }
  240. #endif
  241. luaL_newmetatable(L, LUASOCKET);
  242. lua_pushliteral(L, "__index");
  243. luaL_newlib(L, luasocket_methods);
  244. lua_rawset(L, -3);
  245. lua_pop(L, 1);
  246. lua_register(L, "connect", lsp_connect);
  247. if (conn == NULL) return;
  248. // Register mg module
  249. lua_newtable(L);
  250. reg_function(L, "read", lsp_read, conn);
  251. reg_function(L, "write", lsp_write, conn);
  252. reg_function(L, "cry", lsp_cry, conn);
  253. reg_function(L, "include", lsp_include, conn);
  254. reg_function(L, "redirect", lsp_redirect, conn);
  255. reg_string(L, "version", CIVETWEB_VERSION);
  256. // Export request_info
  257. lua_pushstring(L, "request_info");
  258. lua_newtable(L);
  259. reg_string(L, "request_method", ri->request_method);
  260. reg_string(L, "uri", ri->uri);
  261. reg_string(L, "http_version", ri->http_version);
  262. reg_string(L, "query_string", ri->query_string);
  263. reg_int(L, "remote_ip", ri->remote_ip);
  264. reg_int(L, "remote_port", ri->remote_port);
  265. reg_int(L, "num_headers", ri->num_headers);
  266. lua_pushstring(L, "http_headers");
  267. lua_newtable(L);
  268. for (i = 0; i < ri->num_headers; i++) {
  269. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  270. }
  271. lua_rawset(L, -3);
  272. lua_rawset(L, -3);
  273. lua_setglobal(L, "mg");
  274. // Register default mg.onerror function
  275. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
  276. "debug.traceback(e, 1)) end"));
  277. }
  278. static int lua_error_handler(lua_State *L)
  279. {
  280. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  281. lua_getglobal(L, "mg");
  282. if (!lua_isnil(L, -1)) {
  283. lua_getfield(L, -1, "write"); // call mg.write()
  284. lua_pushstring(L, error_msg);
  285. lua_pushliteral(L, "\n");
  286. lua_call(L, 2, 0);
  287. IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
  288. } else {
  289. printf("Lua error: [%s]\n", error_msg);
  290. IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
  291. }
  292. // TODO(lsm): leave the stack balanced
  293. return 0;
  294. }
  295. void mg_exec_lua_script(struct mg_connection *conn, const char *path,
  296. const void **exports)
  297. {
  298. int i;
  299. lua_State *L;
  300. if (path != NULL && (L = luaL_newstate()) != NULL) {
  301. prepare_lua_environment(conn, L);
  302. lua_pushcclosure(L, &lua_error_handler, 0);
  303. lua_pushglobaltable(L);
  304. if (exports != NULL) {
  305. for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
  306. lua_pushstring(L, exports[i]);
  307. lua_pushcclosure(L, (lua_CFunction) exports[i + 1], 0);
  308. lua_rawset(L, -3);
  309. }
  310. }
  311. if (luaL_loadfile(L, path) != 0) {
  312. lua_error_handler(L);
  313. }
  314. lua_pcall(L, 0, 0, -2);
  315. lua_close(L);
  316. }
  317. }
  318. static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
  319. const char *fmt, ...)
  320. {
  321. char buf[MG_BUF_LEN];
  322. va_list ap;
  323. int len;
  324. va_start(ap, fmt);
  325. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  326. va_end(ap);
  327. if (L == NULL) {
  328. send_http_error(conn, 500, http_500_error, "%s", buf);
  329. } else {
  330. lua_pushstring(L, buf);
  331. lua_error(L);
  332. }
  333. }
  334. static int handle_lsp_request(struct mg_connection *conn, const char *path,
  335. struct file *filep, struct lua_State *ls)
  336. {
  337. void *p = NULL;
  338. lua_State *L = NULL;
  339. int error = 1;
  340. // We need both mg_stat to get file size, and mg_fopen to get fd
  341. if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
  342. lsp_send_err(conn, ls, "File [%s] not found", path);
  343. } else if (filep->membuf == NULL &&
  344. (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
  345. fileno(filep->fp), 0)) == MAP_FAILED) {
  346. lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
  347. fileno(filep->fp), strerror(errno));
  348. } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
  349. send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
  350. } else {
  351. // We're not sending HTTP headers here, Lua page must do it.
  352. if (ls == NULL) {
  353. prepare_lua_environment(conn, L);
  354. if (conn->ctx->callbacks.init_lua != NULL) {
  355. conn->ctx->callbacks.init_lua(conn, L);
  356. }
  357. }
  358. error = lsp(conn, path, filep->membuf == NULL ? p : filep->membuf,
  359. filep->size, L);
  360. }
  361. if (L != NULL && ls == NULL) lua_close(L);
  362. if (p != NULL) munmap(p, filep->size);
  363. mg_fclose(filep);
  364. return error;
  365. }