19cdb0ad39e8ea71d3f1c6742d5a0ac491535dec
[project/luci.git] / modules / luci-base / root / usr / libexec / rpcd / luci
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 methods = {
12 getInitList = {
13 args = { name = "name" },
14 call = function(args)
15 local sys = require "luci.sys"
16 local _, name, scripts = nil, nil, {}
17 for _, name in ipairs(args.name and { args.name } or sys.init.names()) do
18 local index = sys.init.index(name)
19 if index then
20 scripts[name] = { index = index, enabled = sys.init.enabled(name) }
21 else
22 return { error = "No such init script" }
23 end
24 end
25 return scripts
26 end
27 },
28
29 setInitAction = {
30 args = { name = "name", action = "action" },
31 call = function(args)
32 local sys = require "luci.sys"
33 if type(sys.init[args.action]) ~= "function" then
34 return { error = "Invalid action" }
35 end
36 return { result = sys.init[args.action](args.name) }
37 end
38 },
39
40 getLocaltime = {
41 call = function(args)
42 return { result = os.time() }
43 end
44 },
45
46 setLocaltime = {
47 args = { localtime = 0 },
48 call = function(args)
49 local sys = require "luci.sys"
50 local date = os.date("*t", args.localtime)
51 if date then
52 sys.call("date -s '%04d-%02d-%02d %02d:%02d:%02d' >/dev/null" %{ date.year, date.month, date.day, date.hour, date.min, date.sec })
53 sys.call("/etc/init.d/sysfixtime restart >/dev/null")
54 end
55 return { result = args.localtime }
56 end
57 },
58
59 getTimezones = {
60 call = function(args)
61 local util = require "luci.util"
62 local zones = require "luci.sys.zoneinfo"
63
64 local tz = readfile("/etc/TZ")
65 local res = util.ubus("uci", "get", {
66 config = "system",
67 section = "@system[0]",
68 option = "zonename"
69 })
70
71 local result = {}
72 local _, zone
73 for _, zone in ipairs(zones.TZ) do
74 result[zone[1]] = {
75 tzstring = zone[2],
76 active = (res and res.value == zone[1]) and true or nil
77 }
78 end
79 return result
80 end
81 },
82
83 getLEDs = {
84 call = function()
85 local iter = fs.dir("/sys/class/leds")
86 local result = { }
87
88 if iter then
89 local led
90 for led in iter do
91 local m, s
92
93 result[led] = { triggers = {} }
94
95 s = readfile("/sys/class/leds/"..led.."/trigger")
96 for s in (s or ""):gmatch("%S+") do
97 m = s:match("^%[(.+)%]$")
98 result[led].triggers[#result[led].triggers+1] = m or s
99 result[led].active_trigger = m or result[led].active_trigger
100 end
101
102 s = readfile("/sys/class/leds/"..led.."/brightness")
103 if s then
104 result[led].brightness = tonumber(s)
105 end
106
107 s = readfile("/sys/class/leds/"..led.."/max_brightness")
108 if s then
109 result[led].max_brightness = tonumber(s)
110 end
111 end
112 end
113
114 return result
115 end
116 },
117
118 getUSBDevices = {
119 call = function()
120 local fs = require "nixio.fs"
121 local iter = fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer")
122 local result = { }
123
124 if iter then
125 result.devices = {}
126
127 local p
128 for p in iter do
129 local id = p:match("/([^/]+)/manufacturer$")
130
131 result.devices[#result.devices+1] = {
132 id = id,
133 vid = readfile("/sys/bus/usb/devices/"..id.."/idVendor"),
134 pid = readfile("/sys/bus/usb/devices/"..id.."/idProduct"),
135 vendor = readfile("/sys/bus/usb/devices/"..id.."/manufacturer"),
136 product = readfile("/sys/bus/usb/devices/"..id.."/product"),
137 speed = tonumber((readfile("/sys/bus/usb/devices/"..id.."/product")))
138 }
139 end
140 end
141
142 iter = fs.glob("/sys/bus/usb/devices/*/*-port[0-9]*")
143
144 if iter then
145 result.ports = {}
146
147 local p
148 for p in iter do
149 local port = p:match("([^/]+)$")
150 local link = fs.readlink(p.."/device")
151
152 result.ports[#result.ports+1] = {
153 port = port,
154 device = link and fs.basename(link)
155 }
156 end
157 end
158
159 return result
160 end
161 },
162
163 getConntrackHelpers = {
164 call = function()
165 local ok, fd = pcall(io.open, "/usr/share/fw3/helpers.conf", "r")
166 local rv = {}
167
168 if ok then
169 local entry
170
171 while true do
172 local line = fd:read("*l")
173 if not line then
174 break
175 end
176
177 if line:match("^%s*config%s") then
178 if entry then
179 rv[#rv+1] = entry
180 end
181 entry = {}
182 else
183 local opt, val = line:match("^%s*option%s+(%S+)%s+(%S.*)$")
184 if opt and val then
185 opt = opt:gsub("^'(.+)'$", "%1"):gsub('^"(.+)"$', "%1")
186 val = val:gsub("^'(.+)'$", "%1"):gsub('^"(.+)"$', "%1")
187 entry[opt] = val
188 end
189 end
190 end
191
192 if entry then
193 rv[#rv+1] = entry
194 end
195
196 fd:close()
197 end
198
199 return { result = rv }
200 end
201 },
202
203 getFeatures = {
204 call = function()
205 local fs = require "nixio.fs"
206 local rv = {}
207 local ok, fd
208
209 rv.firewall = fs.access("/sbin/fw3")
210 rv.opkg = fs.access("/bin/opkg")
211 rv.offloading = fs.access("/sys/module/xt_FLOWOFFLOAD/refcnt")
212 rv.br2684ctl = fs.access("/usr/sbin/br2684ctl")
213 rv.swconfig = fs.access("/sbin/swconfig")
214 rv.odhcpd = fs.access("/usr/sbin/odhcpd")
215 rv.zram = fs.access("/sys/class/zram-control")
216 rv.sysntpd = fs.readlink("/usr/sbin/ntpd") and true
217 rv.ipv6 = fs.access("/proc/net/ipv6_route")
218 rv.dropbear = fs.access("/usr/sbin/dropbear")
219 rv.cabundle = fs.access("/etc/ssl/certs/ca-certificates.crt")
220 rv.relayd = fs.access("/usr/sbin/relayd")
221 rv.dsl = fs.access("/sbin/vdsl_cpe_control")
222
223 local wifi_features = { "eap", "11n", "11ac", "11r", "acs", "sae", "owe", "suiteb192", "wep", "wps" }
224
225 if fs.access("/usr/sbin/hostapd") then
226 rv.hostapd = { cli = fs.access("/usr/sbin/hostapd_cli") }
227
228 local _, feature
229 for _, feature in ipairs(wifi_features) do
230 rv.hostapd[feature] =
231 (os.execute(string.format("/usr/sbin/hostapd -v%s >/dev/null 2>/dev/null", feature)) == 0)
232 end
233 end
234
235 if fs.access("/usr/sbin/wpa_supplicant") then
236 rv.wpasupplicant = { cli = fs.access("/usr/sbin/wpa_cli") }
237
238 local _, feature
239 for _, feature in ipairs(wifi_features) do
240 rv.wpasupplicant[feature] =
241 (os.execute(string.format("/usr/sbin/wpa_supplicant -v%s >/dev/null 2>/dev/null", feature)) == 0)
242 end
243 end
244
245 ok, fd = pcall(io.popen, "dnsmasq --version 2>/dev/null")
246 if ok then
247 rv.dnsmasq = {}
248
249 while true do
250 local line = fd:read("*l")
251 if not line then
252 break
253 end
254
255 local opts = line:match("^Compile time options: (.+)$")
256 if opts then
257 local opt
258 for opt in opts:gmatch("%S+") do
259 local no = opt:match("^no%-(%S+)$")
260 rv.dnsmasq[string.lower(no or opt)] = not no
261 end
262 break
263 end
264 end
265
266 fd:close()
267 end
268
269 ok, fd = pcall(io.popen, "ipset --help 2>/dev/null")
270 if ok then
271 rv.ipset = {}
272
273 local sets = false
274
275 while true do
276 local line = fd:read("*l")
277 if not line then
278 break
279 elseif line:match("^Supported set types:") then
280 sets = true
281 elseif sets then
282 local set, ver = line:match("^%s+(%S+)%s+(%d+)")
283 if set and not rv.ipset[set] then
284 rv.ipset[set] = tonumber(ver)
285 end
286 end
287 end
288
289 fd:close()
290 end
291
292 return rv
293 end
294 },
295
296 getSwconfigFeatures = {
297 args = { switch = "switch0" },
298 call = function(args)
299 local util = require "luci.util"
300
301 -- Parse some common switch properties from swconfig help output.
302 local swc, err = io.popen("swconfig dev %s help 2>/dev/null" % util.shellquote(args.switch))
303 if swc then
304 local is_port_attr = false
305 local is_vlan_attr = false
306 local rv = {}
307
308 while true do
309 local line = swc:read("*l")
310 if not line then break end
311
312 if line:match("^%s+%-%-vlan") then
313 is_vlan_attr = true
314
315 elseif line:match("^%s+%-%-port") then
316 is_vlan_attr = false
317 is_port_attr = true
318
319 elseif line:match("cpu @") then
320 rv.switch_title = line:match("^switch%d: %w+%((.-)%)")
321 rv.num_vlans = tonumber(line:match("vlans: (%d+)")) or 16
322 rv.min_vid = 1
323
324 elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
325 if is_vlan_attr then rv.vid_option = line:match(": (%w+)") end
326
327 elseif line:match(": enable_vlan4k") then
328 rv.vlan4k_option = "enable_vlan4k"
329
330 elseif line:match(": enable_vlan") then
331 rv.vlan_option = "enable_vlan"
332
333 elseif line:match(": enable_learning") then
334 rv.learning_option = "enable_learning"
335
336 elseif line:match(": enable_mirror_rx") then
337 rv.mirror_option = "enable_mirror_rx"
338
339 elseif line:match(": max_length") then
340 rv.jumbo_option = "max_length"
341 end
342 end
343
344 swc:close()
345
346 if not next(rv) then
347 return { error = "No such switch" }
348 end
349
350 return rv
351 else
352 return { error = err }
353 end
354 end
355 },
356
357 getSwconfigPortState = {
358 args = { switch = "switch0" },
359 call = function(args)
360 local util = require "luci.util"
361
362 local swc, err = io.popen("swconfig dev %s show 2>/dev/null" % util.shellquote(args.switch))
363 if swc then
364 local ports = { }
365
366 while true do
367 local line = swc:read("*l")
368 if not line or (line:match("^VLAN %d+:") and #ports > 0) then
369 break
370 end
371
372 local pnum = line:match("^Port (%d+):$")
373 if pnum then
374 port = {
375 port = tonumber(pnum),
376 duplex = false,
377 speed = 0,
378 link = false,
379 auto = false,
380 rxflow = false,
381 txflow = false
382 }
383
384 ports[#ports+1] = port
385 end
386
387 if port then
388 local m
389
390 if line:match("full[%- ]duplex") then
391 port.duplex = true
392 end
393
394 m = line:match(" speed:(%d+)")
395 if m then
396 port.speed = tonumber(m)
397 end
398
399 m = line:match("(%d+) Mbps")
400 if m and port.speed == 0 then
401 port.speed = tonumber(m)
402 end
403
404 m = line:match("link: (%d+)")
405 if m and port.speed == 0 then
406 port.speed = tonumber(m)
407 end
408
409 if line:match("link: ?up") or line:match("status: ?up") then
410 port.link = true
411 end
412
413 if line:match("auto%-negotiate") or line:match("link:.-auto") then
414 port.auto = true
415 end
416
417 if line:match("link:.-rxflow") then
418 port.rxflow = true
419 end
420
421 if line:match("link:.-txflow") then
422 port.txflow = true
423 end
424 end
425 end
426
427 swc:close()
428
429 if not next(ports) then
430 return { error = "No such switch" }
431 end
432
433 return { result = ports }
434 else
435 return { error = err }
436 end
437 end
438 },
439
440 setPassword = {
441 args = { username = "root", password = "password" },
442 call = function(args)
443 local util = require "luci.util"
444 return {
445 result = (os.execute("(echo %s; sleep 1; echo %s) | passwd %s >/dev/null 2>&1" %{
446 luci.util.shellquote(args.password),
447 luci.util.shellquote(args.password),
448 luci.util.shellquote(args.username)
449 }) == 0)
450 }
451 end
452 },
453
454 getBlockDevices = {
455 call = function()
456 local fs = require "nixio.fs"
457
458 local block = io.popen("/sbin/block info", "r")
459 if block then
460 local rv = {}
461
462 while true do
463 local ln = block:read("*l")
464 if not ln then
465 break
466 end
467
468 local dev = ln:match("^/dev/(.-):")
469 if dev then
470 local s = tonumber((fs.readfile("/sys/class/block/" .. dev .."/size")))
471 local e = {
472 dev = "/dev/" .. dev,
473 size = s and s * 512
474 }
475
476 local key, val = { }
477 for key, val in ln:gmatch([[(%w+)="(.-)"]]) do
478 e[key:lower()] = val
479 end
480
481 rv[dev] = e
482 end
483 end
484
485 block:close()
486
487 return rv
488 else
489 return { error = "Unable to execute block utility" }
490 end
491 end
492 },
493
494 setBlockDetect = {
495 call = function()
496 return { result = (os.execute("/sbin/block detect > /etc/config/fstab") == 0) }
497 end
498 },
499
500 getMountPoints = {
501 call = function()
502 local fs = require "nixio.fs"
503
504 local fd, err = io.open("/proc/mounts", "r")
505 if fd then
506 local rv = {}
507
508 while true do
509 local ln = fd:read("*l")
510 if not ln then
511 break
512 end
513
514 local device, mount, fstype, options, freq, pass = ln:match("^(%S*) (%S*) (%S*) (%S*) (%d+) (%d+)$")
515 if device and mount then
516 device = device:gsub("\\(%d+)", function(n) return string.char(tonumber(n, 8)) end)
517 mount = mount:gsub("\\(%d+)", function(n) return string.char(tonumber(n, 8)) end)
518
519 local stat = fs.statvfs(mount)
520 if stat and stat.blocks > 0 then
521 rv[#rv+1] = {
522 device = device,
523 mount = mount,
524 size = stat.bsize * stat.blocks,
525 avail = stat.bsize * stat.bavail,
526 free = stat.bsize * stat.bfree
527 }
528 end
529 end
530 end
531
532 fd:close()
533
534 return { result = rv }
535 else
536 return { error = err }
537 end
538 end
539 },
540
541 getRealtimeStats = {
542 args = { mode = "interface", device = "eth0" },
543 call = function(args)
544 local util = require "luci.util"
545
546 local flags
547 if args.mode == "interface" then
548 flags = "-i %s" % util.shellquote(args.device)
549 elseif args.mode == "wireless" then
550 flags = "-r %s" % util.shellquote(args.device)
551 elseif args.mode == "conntrack" then
552 flags = "-c"
553 elseif args.mode == "load" then
554 flags = "-l"
555 else
556 return { error = "Invalid mode" }
557 end
558
559 local fd, err = io.popen("luci-bwc %s" % flags, "r")
560 if fd then
561 local parse = json.new()
562 local done
563
564 parse:parse("[")
565
566 while true do
567 local ln = fd:read("*l")
568 if not ln then
569 break
570 end
571
572 done, err = parse:parse((ln:gsub("%d+", "%1.0")))
573
574 if done then
575 err = "Unexpected JSON data"
576 end
577
578 if err then
579 break
580 end
581 end
582
583 fd:close()
584
585 done, err = parse:parse("]")
586
587 if err then
588 return { error = err }
589 elseif not done then
590 return { error = "Incomplete JSON data" }
591 else
592 return { result = parse:get() }
593 end
594 else
595 return { error = err }
596 end
597 end
598 },
599
600 getConntrackList = {
601 call = function()
602 local sys = require "luci.sys"
603 return { result = sys.net.conntrack() }
604 end
605 },
606
607 getProcessList = {
608 call = function()
609 local sys = require "luci.sys"
610 local res = {}
611 for _, v in pairs(sys.process.list()) do
612 res[#res + 1] = v
613 end
614 return { result = res }
615 end
616 }
617 }
618
619 local function parseInput()
620 local parse = json.new()
621 local done, err
622
623 while true do
624 local chunk = io.read(4096)
625 if not chunk then
626 break
627 elseif not done and not err then
628 done, err = parse:parse(chunk)
629 end
630 end
631
632 if not done then
633 print(json.stringify({ error = err or "Incomplete input" }))
634 os.exit(1)
635 end
636
637 return parse:get()
638 end
639
640 local function validateArgs(func, uargs)
641 local method = methods[func]
642 if not method then
643 print(json.stringify({ error = "Method not found" }))
644 os.exit(1)
645 end
646
647 if type(uargs) ~= "table" then
648 print(json.stringify({ error = "Invalid arguments" }))
649 os.exit(1)
650 end
651
652 uargs.ubus_rpc_session = nil
653
654 local k, v
655 local margs = method.args or {}
656 for k, v in pairs(uargs) do
657 if margs[k] == nil or
658 (v ~= nil and type(v) ~= type(margs[k]))
659 then
660 print(json.stringify({ error = "Invalid arguments" }))
661 os.exit(1)
662 end
663 end
664
665 return method
666 end
667
668 if arg[1] == "list" then
669 local _, method, rv = nil, nil, {}
670 for _, method in pairs(methods) do rv[_] = method.args or {} end
671 print((json.stringify(rv):gsub(":%[%]", ":{}")))
672 elseif arg[1] == "call" then
673 local args = parseInput()
674 local method = validateArgs(arg[2], args)
675 local result, code = method.call(args)
676 print((json.stringify(result):gsub("^%[%]$", "{}")))
677 os.exit(code or 0)
678 end