mod_lua.c 11 KB

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