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
31 mod = type(mod) == "table" and mod[path[#path]] or nil
32 if type(mod) == "function" then
37 function handle(tbl, rawdata)
38 local stat, json = luci.util.copcall(luci.json.Decode, rawdata)
43 if type(json.method) == "string"
44 and (not json.params or type(json.params) == "table") then
45 if tbl[json.method] then
46 response = reply(json.jsonrpc, json.id,
47 proxy(resolve(tbl, json.method), unpack(json.params or {})))
49 response = reply(json.jsonrpc, json.id,
50 nil, {code=-32601, message="Method not found."})
53 response = reply(json.jsonrpc, json.id,
54 nil, {code=-32600, message="Invalid request."})
57 response = reply(json.jsonrpc, nil,
58 nil, {code=-32700, message="Parse error."})
61 return luci.json.Encode(response)
64 function reply(jsonrpc, id, res, err)
66 id = id or luci.json.Null
69 if jsonrpc ~= "2.0" then
71 res = res or luci.json.Null
72 err = err or luci.json.Null
75 return {id=id, result=res, error=err, jsonrpc=jsonrpc}
78 function proxy(method, ...)
79 local res = {luci.util.copcall(method, ...)}
80 local stat = table.remove(res, 1)
83 return nil, {code=-32602, message="Invalid params.", data=table.remove(res, 1)}
86 return res[1] or luci.json.Null