libs/json: Completed JSON library
[project/luci.git] / modules / rpc / luasrc / jsonrpc.lua
1 --[[
2 LuCI - Lua Configuration Interface
3
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
6
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
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14 ]]--
15
16 module("luci.jsonrpc", package.seeall)
17 require "luci.json"
18
19 function resolve(mod, method)
20 local path = luci.util.split(method, ".")
21
22 for j=1, #path-1 do
23 if not type(mod) == "table" then
24 break
25 end
26 mod = rawget(mod, path[j])
27 if not mod then
28 break
29 end
30 end
31 mod = type(mod) == "table" and rawget(mod, path[#path]) or nil
32 if type(mod) == "function" then
33 return mod
34 end
35 end
36
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()
41 local response
42 local success = false
43
44 if stat then
45 if type(json.method) == "string"
46 and (not json.params or type(json.params) == "table") then
47 if tbl[json.method] then
48 response = reply(json.jsonrpc, json.id,
49 proxy(resolve(tbl, json.method), unpack(json.params or {})))
50 else
51 response = reply(json.jsonrpc, json.id,
52 nil, {code=-32601, message="Method not found."})
53 end
54 else
55 response = reply(json.jsonrpc, json.id,
56 nil, {code=-32600, message="Invalid request."})
57 end
58 else
59 response = reply("2.0", nil,
60 nil, {code=-32700, message="Parse error."})
61 end
62
63 return luci.json.Encoder(response, ...):source()
64 end
65
66 function reply(jsonrpc, id, res, err)
67 require "luci.json"
68 id = id or luci.json.null
69
70 -- 1.0 compatibility
71 if jsonrpc ~= "2.0" then
72 jsonrpc = nil
73 res = res or luci.json.null
74 err = err or luci.json.null
75 end
76
77 return {id=id, result=res, error=err, jsonrpc=jsonrpc}
78 end
79
80 function proxy(method, ...)
81 local res = {luci.util.copcall(method, ...)}
82 local stat = table.remove(res, 1)
83
84 if not stat then
85 return nil, {code=-32602, message="Invalid params.", data=table.remove(res, 1)}
86 else
87 if #res <= 1 then
88 return res[1] or luci.json.null
89 else
90 return res
91 end
92 end
93 end