luci-proto-openconnect: fix certificate file paths
[project/luci.git] / protocols / luci-proto-openconnect / root / usr / libexec / rpcd / luci.openconnect
1 #!/usr/bin/env lua
2
3 local json = require "luci.jsonc"
4 local fs = require "nixio.fs"
5
6 local function readfile(path)
7 local s = fs.readfile(path)
8 return s and (s:gsub("^%s+", ""):gsub("%s+$", ""))
9 end
10
11 local function writefile(path, data)
12 local n = fs.writefile(path, data)
13 return (n == #data)
14 end
15
16 local function parseInput()
17 local parse = json.new()
18 local done, err
19
20 while true do
21 local chunk = io.read(4096)
22 if not chunk then
23 break
24 elseif not done and not err then
25 done, err = parse:parse(chunk)
26 end
27 end
28
29 if not done then
30 print(json.stringify({ error = err or "Incomplete input" }))
31 os.exit(1)
32 end
33
34 return parse:get()
35 end
36
37 if arg[1] == "list" then
38 print(json.stringify({
39 getCertificates = {
40 interface = "interface"
41 },
42 setCertificates = {
43 interface = "interface",
44 user_certificate = "PEM file data",
45 user_privatekey = "PEM file data",
46 ca_certificate = "PEM file data"
47 }
48 }))
49 elseif arg[1] == "call" then
50 local args = parseInput()
51
52 if not args.interface or
53 type(args.interface) ~= "string" or
54 not args.interface:match("^[a-zA-Z0-9_]+$")
55 then
56 print(json.stringify({ error = "Invalid interface name" }))
57 os.exit(1)
58 end
59
60 if arg[2] == "getCertificates" then
61 print(json.stringify({
62 user_certificate = readfile(string.format("/etc/openconnect/user-cert-vpn-%s.pem", args.interface)),
63 user_privatekey = readfile(string.format("/etc/openconnect/user-key-vpn-%s.pem", args.interface)),
64 ca_certificate = readfile(string.format("/etc/openconnect/ca-vpn-%s.pem", args.interface))
65 }))
66 elseif arg[2] == "setCertificates" then
67 if args.user_certificate then
68 writefile(string.format("/etc/openconnect/user-cert-vpn-%s.pem", args.interface), args.user_certificate)
69 end
70 if args.user_privatekey then
71 writefile(string.format("/etc/openconnect/user-key-vpn-%s.pem", args.interface), args.user_privatekey)
72 end
73 if args.ca_certificate then
74 writefile(string.format("/etc/openconnect/ca-vpn-%s.pem", args.interface), args.ca_certificate)
75 end
76 print(json.stringify({ result = true }))
77 end
78 end