aboutsummaryrefslogtreecommitdiffstats
path: root/server/resty/openssl/ctx.lua
blob: eaec39627c6a897c6e42abb2bfeaef7dc8ce888b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
local ffi = require "ffi"
local C = ffi.C
local ffi_gc = ffi.gc

require "resty.openssl.include.ossl_typ"
local format_error = require("resty.openssl.err").format_error
local OPENSSL_3X = require("resty.openssl.version").OPENSSL_3X

ffi.cdef [[
  OSSL_LIB_CTX *OSSL_LIB_CTX_new(void);
  int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file);
  void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx);
]]

local ossl_lib_ctx

local function new(request_context_only, conf_file)
  if not OPENSSL_3X then
    return false, "ctx is only supported from OpenSSL 3.0"
  end

  local ctx = C.OSSL_LIB_CTX_new()
  ffi_gc(ctx, C.OSSL_LIB_CTX_free)

  if conf_file and C.OSSL_LIB_CTX_load_config(ctx, conf_file) ~= 1 then
    return false, format_error("ctx.new")
  end

  if request_context_only then
    ngx.ctx.ossl_lib_ctx = ctx
  else
    ossl_lib_ctx = ctx
  end

  return true
end

local function free(request_context_only)
  if not OPENSSL_3X then
    return false, "ctx is only supported from OpenSSL 3.0"
  end

  if request_context_only then
    ngx.ctx.ossl_lib_ctx = nil
  else
    ossl_lib_ctx = nil
  end

  return true
end

local test_request

do

  local ok, exdata = pcall(require, "thread.exdata")
  if ok and exdata then
    test_request = function()
      local r = exdata()
      if r ~= nil then
          return not not r
      end
    end

  else
    local getfenv = getfenv

    function test_request()
      return not not getfenv(0).__ngx_req
    end
  end
end

return {
  new = new,
  free = free,
  get_libctx = function() return test_request() and ngx.ctx.ossl_lib_ctx or ossl_lib_ctx end,
}