tlshelper.lua 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. local socket = require "http.sockethelper"
  2. local c = require "ltls.c"
  3. local tlshelper = {}
  4. function tlshelper.init_requestfunc(fd, tls_ctx)
  5. local readfunc = socket.readfunc(fd)
  6. local writefunc = socket.writefunc(fd)
  7. return function ()
  8. local ds1 = tls_ctx:handshake()
  9. writefunc(ds1)
  10. while not tls_ctx:finished() do
  11. local ds2 = readfunc()
  12. local ds3 = tls_ctx:handshake(ds2)
  13. if ds3 then
  14. writefunc(ds3)
  15. end
  16. end
  17. end
  18. end
  19. function tlshelper.init_responsefunc(fd, tls_ctx)
  20. local readfunc = socket.readfunc(fd)
  21. local writefunc = socket.writefunc(fd)
  22. return function ()
  23. while not tls_ctx:finished() do
  24. local ds1 = readfunc()
  25. local ds2 = tls_ctx:handshake(ds1)
  26. if ds2 then
  27. writefunc(ds2)
  28. end
  29. end
  30. local ds3 = tls_ctx:write()
  31. writefunc(ds3)
  32. end
  33. end
  34. function tlshelper.closefunc(tls_ctx)
  35. return function ()
  36. tls_ctx:close()
  37. end
  38. end
  39. function tlshelper.readfunc(fd, tls_ctx)
  40. local function readfunc()
  41. readfunc = socket.readfunc(fd)
  42. return ""
  43. end
  44. local read_buff = ""
  45. return function (sz)
  46. if not sz then
  47. local s = ""
  48. if #read_buff == 0 then
  49. local ds = readfunc()
  50. s = tls_ctx:read(ds)
  51. end
  52. s = read_buff .. s
  53. read_buff = ""
  54. return s
  55. else
  56. while #read_buff < sz do
  57. local ds = readfunc()
  58. local s = tls_ctx:read(ds)
  59. read_buff = read_buff .. s
  60. end
  61. local s = string.sub(read_buff, 1, sz)
  62. read_buff = string.sub(read_buff, sz+1, #read_buff)
  63. return s
  64. end
  65. end
  66. end
  67. function tlshelper.writefunc(fd, tls_ctx)
  68. local writefunc = socket.writefunc(fd)
  69. return function (s)
  70. local ds = tls_ctx:write(s)
  71. return writefunc(ds)
  72. end
  73. end
  74. function tlshelper.readallfunc(fd, tls_ctx)
  75. return function ()
  76. local ds = socket.readall(fd)
  77. local s = tls_ctx:read(ds)
  78. return s
  79. end
  80. end
  81. function tlshelper.newctx()
  82. return c.newctx()
  83. end
  84. function tlshelper.newtls(method, ssl_ctx, hostname)
  85. return c.newtls(method, ssl_ctx, hostname)
  86. end
  87. return tlshelper