mime.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. -----------------------------------------------------------------------------
  2. -- MIME support for the Lua language.
  3. -- Author: Diego Nehab
  4. -- Conforming to RFCs 2045-2049
  5. -----------------------------------------------------------------------------
  6. -----------------------------------------------------------------------------
  7. -- Declare module and import dependencies
  8. -----------------------------------------------------------------------------
  9. local base = _G
  10. local ltn12 = require("ltn12")
  11. local mime = require("mime.core")
  12. local io = require("io")
  13. local string = require("string")
  14. local _M = mime
  15. -- encode, decode and wrap algorithm tables
  16. local encodet, decodet, wrapt = {},{},{}
  17. _M.encodet = encodet
  18. _M.decodet = decodet
  19. _M.wrapt = wrapt
  20. -- creates a function that chooses a filter by name from a given table
  21. local function choose(table)
  22. return function(name, opt1, opt2)
  23. if base.type(name) ~= "string" then
  24. name, opt1, opt2 = "default", name, opt1
  25. end
  26. local f = table[name or "nil"]
  27. if not f then
  28. base.error("unknown key (" .. base.tostring(name) .. ")", 3)
  29. else return f(opt1, opt2) end
  30. end
  31. end
  32. -- define the encoding filters
  33. encodet['base64'] = function()
  34. return ltn12.filter.cycle(_M.b64, "")
  35. end
  36. encodet['quoted-printable'] = function(mode)
  37. return ltn12.filter.cycle(_M.qp, "",
  38. (mode == "binary") and "=0D=0A" or "\r\n")
  39. end
  40. -- define the decoding filters
  41. decodet['base64'] = function()
  42. return ltn12.filter.cycle(_M.unb64, "")
  43. end
  44. decodet['quoted-printable'] = function()
  45. return ltn12.filter.cycle(_M.unqp, "")
  46. end
  47. local function format(chunk)
  48. if chunk then
  49. if chunk == "" then return "''"
  50. else return string.len(chunk) end
  51. else return "nil" end
  52. end
  53. -- define the line-wrap filters
  54. wrapt['text'] = function(length)
  55. length = length or 76
  56. return ltn12.filter.cycle(_M.wrp, length, length)
  57. end
  58. wrapt['base64'] = wrapt['text']
  59. wrapt['default'] = wrapt['text']
  60. wrapt['quoted-printable'] = function()
  61. return ltn12.filter.cycle(_M.qpwrp, 76, 76)
  62. end
  63. -- function that choose the encoding, decoding or wrap algorithm
  64. _M.encode = choose(encodet)
  65. _M.decode = choose(decodet)
  66. _M.wrap = choose(wrapt)
  67. -- define the end-of-line normalization filter
  68. function _M.normalize(marker)
  69. return ltn12.filter.cycle(_M.eol, 0, marker)
  70. end
  71. -- high level stuffing filter
  72. function _M.stuff()
  73. return ltn12.filter.cycle(_M.dot, 2)
  74. end
  75. return _M