1
0

ccache.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
  3. -- Licensed to the public under the Apache License 2.0.
  4. local io = require "io"
  5. local fs = require "nixio.fs"
  6. local util = require "luci.util"
  7. local nixio = require "nixio"
  8. local debug = require "debug"
  9. local string = require "string"
  10. local package = require "package"
  11. local type, loadfile = type, loadfile
  12. module "luci.ccache"
  13. function cache_ondemand(...)
  14. if debug.getinfo(1, 'S').source ~= "=?" then
  15. cache_enable(...)
  16. end
  17. end
  18. function cache_enable(cachepath, mode)
  19. cachepath = cachepath or "/tmp/luci-modulecache"
  20. mode = mode or "r--r--r--"
  21. local loader = package.loaders[2]
  22. local uid = nixio.getuid()
  23. if not fs.stat(cachepath) then
  24. fs.mkdir(cachepath)
  25. end
  26. local function _encode_filename(name)
  27. local encoded = ""
  28. for i=1, #name do
  29. encoded = encoded .. ("%2X" % string.byte(name, i))
  30. end
  31. return encoded
  32. end
  33. local function _load_sane(file)
  34. local stat = fs.stat(file)
  35. if stat and stat.uid == uid and stat.modestr == mode then
  36. return loadfile(file)
  37. end
  38. end
  39. local function _write_sane(file, func)
  40. if nixio.getuid() == uid then
  41. local fp = io.open(file, "w")
  42. if fp then
  43. fp:write(util.get_bytecode(func))
  44. fp:close()
  45. fs.chmod(file, mode)
  46. end
  47. end
  48. end
  49. package.loaders[2] = function(mod)
  50. local encoded = cachepath .. "/" .. _encode_filename(mod)
  51. local modcons = _load_sane(encoded)
  52. if modcons then
  53. return modcons
  54. end
  55. -- No cachefile
  56. modcons = loader(mod)
  57. if type(modcons) == "function" then
  58. _write_sane(encoded, modcons)
  59. end
  60. return modcons
  61. end
  62. end