2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
16 module("luci.jsonrpc", package.seeall)
19 function resolve(mod, method)
20 local path = luci.util.split(method, ".")
23 if not type(mod) == "table" then
26 mod = rawget(mod, path[j])
31 mod = type(mod) == "table" and rawget(mod, path[#path]) or nil
32 if type(mod) == "function" then
37 function handle(tbl, rawsource, ...)
38 local decoder = luci.json.Decoder()
39 local stat = luci.ltn12.pump.all(rawsource, decoder:sink())
40 local json = decoder:get()
45 if type(json.method) == "string"
46 and (not json.params or type(json.params) == "table") then
47 local method = resolve(tbl, json.method)
49 response = reply(json.jsonrpc, json.id,
50 proxy(method, unpack(json.params or {})))
52 response = reply(json.jsonrpc, json.id,
53 nil, {code=-32601, message="Method not found."})
56 response = reply(json.jsonrpc, json.id,
57 nil, {code=-32600, message="Invalid request."})
60 response = reply("2.0", nil,
61 nil, {code=-32700, message="Parse error."})
64 return luci.json.Encoder(response, ...):source()
67 function reply(jsonrpc, id, res, err)
69 id = id or luci.json.null
72 if jsonrpc ~= "2.0" then
74 res = res or luci.json.null
75 err = err or luci.json.null
78 return {id=id, result=res, error=err, jsonrpc=jsonrpc}
81 function proxy(method, ...)
82 local res = {luci.util.copcall(method, ...)}
83 local stat = table.remove(res, 1)
86 return nil, {code=-32602, message="Invalid params.", data=table.remove(res, 1)}
89 return res[1] or luci.json.null