summaryrefslogtreecommitdiffstats
path: root/server/resty/openssl/objects.lua
blob: bd02a3896362fa376b03334d1ef374f7b7434c6f (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
local ffi = require "ffi"
local C = ffi.C
local ffi_str = ffi.string
local ffi_sizeof = ffi.sizeof

require "resty.openssl.include.objects"
require "resty.openssl.include.err"

local buf = ffi.new('char[?]', 100)

local function obj2table(obj)
  local nid = C.OBJ_obj2nid(obj)

  local len = C.OBJ_obj2txt(buf, ffi_sizeof(buf), obj, 1)
  local oid = ffi_str(buf, len)

  return {
    id = oid,
    nid = nid,
    sn = ffi_str(C.OBJ_nid2sn(nid)),
    ln = ffi_str(C.OBJ_nid2ln(nid)),
  }
end

local function nid2table(nid)
  return obj2table(C.OBJ_nid2obj(nid))
end

local function txt2nid(txt)
  if type(txt) ~= "string" then
    return nil, "objects.txt2nid: expect a string at #1"
  end
  local nid = C.OBJ_txt2nid(txt)
  if nid == 0 then
    -- clean up error occurs during OBJ_txt2nid
    C.ERR_clear_error()
    return nil, "objects.txt2nid: invalid NID text " .. txt
  end
  return nid
end

local function txtnid2nid(txt_nid)
  local nid
  if type(txt_nid) == "string" then
    nid = C.OBJ_txt2nid(txt_nid)
    if nid == 0 then
      -- clean up error occurs during OBJ_txt2nid
      C.ERR_clear_error()
      return nil, "objects.txtnid2nid: invalid NID text " .. txt_nid
    end
  elseif type(txt_nid) == "number" then
    nid = txt_nid
  else
    return nil, "objects.txtnid2nid: expect string or number at #1"
  end
  return nid
end

local function find_sigid_algs(nid)
  local out = ffi.new("int[0]")
  if C.OBJ_find_sigid_algs(nid, out, nil) == 0 then
    return 0, "objects.find_sigid_algs: invalid sigid " .. nid
  end
  return tonumber(out[0])
end

return {
  obj2table = obj2table,
  nid2table = nid2table,
  txt2nid = txt2nid,
  txtnid2nid = txtnid2nid,
  find_sigid_algs = find_sigid_algs,
  create = C.OBJ_create,
}