4 rpcSessionID
= L
.env
.sessionid
|| '00000000000000000000000000000000',
5 rpcBaseURL
= L
.url('admin/ubus'),
6 rpcInterceptorFns
= [];
14 * The `LuCI.rpc` class provides high level ubus JSON-RPC abstractions
15 * and means for listing and invoking remove RPC methods.
17 return L
.Class
.extend(/** @lends LuCI.rpc.prototype */ {
19 call: function(req
, cb
, nobatch
) {
22 if (Array
.isArray(req
)) {
24 return Promise
.resolve([]);
26 for (var i
= 0; i
< req
.length
; i
++)
28 q
+= '%s%s.%s'.format(
34 else if (req
.params
) {
35 q
+= '/%s.%s'.format(req
.params
[1], req
.params
[2]);
38 return L
.Request
.post(rpcBaseURL
+ q
, req
, {
39 timeout
: (L
.env
.rpctimeout
|| 20) * 1000,
45 parseCallReply: function(req
, res
) {
48 if (res
instanceof Error
)
49 return req
.reject(res
);
53 L
.raise('RPCError', 'RPC call to %s/%s failed with HTTP error %d: %s',
54 req
.object
, req
.method
, res
.status
, res
.statusText
|| '?');
63 * The interceptor args are intentionally swapped.
64 * Response is passed as first arg to align with Request class interceptors
66 Promise
.all(rpcInterceptorFns
.map(function(fn
) { return fn(msg
, req
) }))
67 .then(this.handleCallReply
.bind(this, req
, msg
))
71 handleCallReply: function(req
, msg
) {
72 var type
= Object
.prototype.toString
,
76 /* verify message frame */
77 if (!L
.isObject(msg
) || msg
.jsonrpc
!= '2.0')
78 L
.raise('RPCError', 'RPC call to %s/%s returned invalid message frame',
79 req
.object
, req
.method
);
81 /* check error condition */
82 if (L
.isObject(msg
.error
) && msg
.error
.code
&& msg
.error
.message
)
83 L
.raise('RPCError', 'RPC call to %s/%s failed with error %d: %s',
84 req
.object
, req
.method
, msg
.error
.code
, msg
.error
.message
|| '?');
90 if (!req
.object
&& !req
.method
) {
93 else if (Array
.isArray(msg
.result
)) {
94 ret
= (msg
.result
.length
> 1) ? msg
.result
[1] : msg
.result
[0];
98 for (var key
in req
.expect
) {
99 if (ret
!= null && key
!= '')
102 if (ret
== null || type
.call(ret
) != type
.call(req
.expect
[key
]))
103 ret
= req
.expect
[key
];
110 if (typeof(req
.filter
) == 'function') {
112 req
.priv
[1] = req
.params
;
113 ret
= req
.filter
.apply(this, req
.priv
);
120 * Lists available remote ubus objects or the method signatures of
123 * This function has two signatures and is sensitive to the number of
124 * arguments passed to it:
126 * Returns an array containing the names of all remote `ubus` objects
127 * - `list("objname", ...)`
128 * Returns method signatures for each given `ubus` object name.
130 * @param {...string} [objectNames]
131 * If any object names are given, this function will return the method
132 * signatures of each given object.
134 * @returns {Promise<Array<string>|Object<string, Object<string, Object<string, string>>>>}
135 * When invoked without arguments, this function will return a promise
136 * resolving to an array of `ubus` object names. When invoked with one or
137 * more arguments, a promise resolving to an object describing the method
138 * signatures of each requested `ubus` object name will be returned.
145 params
: arguments
.length
? this.varargs(arguments
) : undefined
148 return new Promise(L
.bind(function(resolveFn
, rejectFn
) {
149 /* store request info */
156 this.call(msg
, this.parseCallReply
.bind(this, req
));
161 * @typedef {Object} DeclareOptions
164 * @property {string} object
165 * The name of the remote `ubus` object to invoke.
167 * @property {string} method
168 * The name of the remote `ubus` method to invoke.
170 * @property {string[]} [params]
171 * Lists the named parameters expected by the remote `ubus` RPC method.
172 * The arguments passed to the resulting generated method call function
173 * will be mapped to named parameters in the order they appear in this
176 * Extraneous parameters passed to the generated function will not be
177 * sent to the remote procedure but are passed to the
178 * {@link LuCI.rpc~filterFn filter function} if one is specified.
181 * - `params: [ "foo", "bar" ]` -
182 * When the resulting call function is invoked with `fn(true, false)`,
183 * the corresponding args object sent to the remote procedure will be
184 * `{ foo: true, bar: false }`.
185 * - `params: [ "test" ], filter: function(reply, args, extra) { ... }` -
186 * When the resultung generated function is invoked with
187 * `fn("foo", "bar", "baz")` then `{ "test": "foo" }` will be sent as
188 * argument to the remote procedure and the filter function will be
189 * invoked with `filterFn(reply, [ "foo" ], "bar", "baz")`
191 * @property {Object<string,*>} [expect]
192 * Describes the expected return data structure. The given object is
193 * supposed to contain a single key selecting the value to use from
194 * the returned `ubus` reply object. The value of the sole key within
195 * the `expect` object is used to infer the expected type of the received
198 * If the received data does not contain `expect`'s key, or if the
199 * type of the data differs from the type of the value in the expect
200 * object, the expect object's value is returned as default instead.
202 * The key in the `expect` object may be an empty string (`''`) in which
203 * case the entire reply object is selected instead of one of its subkeys.
205 * If the `expect` option is omitted, the received reply will be returned
206 * as-is, regardless of its format or type.
209 * - `expect: { '': { error: 'Invalid response' } }` -
210 * This requires the entire `ubus` reply to be a plain JavaScript
211 * object. If the reply isn't an object but e.g. an array or a numeric
212 * error code instead, it will get replaced with
213 * `{ error: 'Invalid response' }` instead.
214 * - `expect: { results: [] }` -
215 * This requires the received `ubus` reply to be an object containing
216 * a key `results` with an array as value. If the received reply does
217 * not contain such a key, or if `reply.results` points to a non-array
218 * value, the empty array (`[]`) will be used instead.
219 * - `expect: { success: false }` -
220 * This requires the received `ubus` reply to be an object containing
221 * a key `success` with a boolean value. If the reply does not contain
222 * `success` or if `reply.success` is not a boolean value, `false` will
223 * be returned as default instead.
225 * @property {LuCI.rpc~filterFn} [filter]
226 * Specfies an optional filter function which is invoked to transform the
227 * received reply data before it is returned to the caller.
232 * The filter function is invoked to transform a received `ubus` RPC call
233 * reply before returning it to the caller.
235 * @callback LuCI.rpc~filterFn
238 * The received `ubus` reply data or a subset of it as described in the
239 * `expect` option of the RPC call declaration. In case of remote call
240 * errors, `data` is numeric `ubus` error code instead.
242 * @param {Array<*>} args
243 * The arguments the RPC method has been invoked with.
245 * @param {...*} extraArgs
246 * All extraneous arguments passed to the RPC method exceeding the number
247 * of arguments describes in the RPC call declaration.
250 * The return value of the filter function will be returned to the caller
251 * of the RPC method as-is.
255 * The generated invocation function is returned by
256 * {@link LuCI.rpc#declare rpc.declare()} and encapsulates a single
259 * Calling this function will execute a remote `ubus` HTTP call request
260 * using the arguments passed to it as arguments and return a promise
261 * resolving to the received reply values.
263 * @callback LuCI.rpc~invokeFn
265 * @param {...*} params
266 * The parameters to pass to the remote procedure call. The given
267 * positional arguments will be named to named RPC parameters according
268 * to the names specified in the `params` array of the method declaration.
270 * Any additional parameters exceeding the amount of arguments in the
271 * `params` declaration are passed as private extra arguments to the
272 * declared filter function.
274 * @return {Promise<*>}
275 * Returns a promise resolving to the result data of the remote `ubus`
276 * RPC method invocation, optionally substituted and filtered according
277 * to the `expect` and `filter` declarations.
281 * Describes a remote RPC call procedure and returns a function
284 * @param {LuCI.rpc.DeclareOptions} options
285 * If any object names are given, this function will return the method
286 * signatures of each given object.
288 * @returns {LuCI.rpc~invokeFn}
289 * Returns a new function implementing the method call described in
292 declare: function(options
) {
293 return Function
.prototype.bind
.call(function(rpc
, options
) {
294 var args
= this.varargs(arguments
, 2);
295 return new Promise(function(resolveFn
, rejectFn
) {
296 /* build parameter object */
299 if (Array
.isArray(options
.params
))
300 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
301 params
[options
.params
[p_off
]] = args
[p_off
];
303 /* all remaining arguments are private args */
304 var priv
= [ undefined, undefined ];
305 for (; p_off
< args
.length
; p_off
++)
306 priv
.push(args
[p_off
]);
308 /* store request info */
310 expect
: options
.expect
,
311 filter
: options
.filter
,
316 object
: options
.object
,
317 method
: options
.method
320 /* build message object */
334 rpc
.call(msg
, rpc
.parseCallReply
.bind(rpc
, req
), options
.nobatch
);
336 }, this, this, options
);
340 * Returns the current RPC session id.
343 * Returns the 32 byte session ID string used for authenticating remote
346 getSessionID: function() {
351 * Set the RPC session id to use.
353 * @param {string} sid
354 * Sets the 32 byte session ID string used for authenticating remote
357 setSessionID: function(sid
) {
362 * Returns the current RPC base URL.
365 * Returns the RPC URL endpoint to issue requests against.
367 getBaseURL: function() {
372 * Set the RPC base URL to use.
374 * @param {string} sid
375 * Sets the RPC URL endpoint to issue requests against.
377 setBaseURL: function(url
) {
382 * Translates a numeric `ubus` error code into a human readable
385 * @param {number} statusCode
386 * The numeric status code.
389 * Returns the textual description of the code.
391 getStatusText: function(statusCode
) {
392 switch (statusCode
) {
393 case 0: return _('Command OK');
394 case 1: return _('Invalid command');
395 case 2: return _('Invalid argument');
396 case 3: return _('Method not found');
397 case 4: return _('Resource not found');
398 case 5: return _('No data received');
399 case 6: return _('Permission denied');
400 case 7: return _('Request timeout');
401 case 8: return _('Not supported');
402 case 9: return _('Unspecified error');
403 case 10: return _('Connection lost');
404 default: return _('Unknown error code');
409 * Registered interceptor functions are invoked before the standard reply
410 * parsing and handling logic.
412 * By returning rejected promises, interceptor functions can cause the
413 * invocation function to fail, regardless of the received reply.
415 * Interceptors may also modify their message argument in-place to
416 * rewrite received replies before they're processed by the standard
417 * response handling code.
419 * A common use case for such functions is to detect failing RPC replies
420 * due to expired authentication in order to trigger a new login.
422 * @callback LuCI.rpc~interceptorFn
425 * The unprocessed, JSON decoded remote RPC method call reply.
427 * Since interceptors run before the standard parsing logic, the reply
428 * data is not verified for correctness or filtered according to
429 * `expect` and `filter` specifications in the declarations.
431 * @param {Object} req
432 * The related request object which is an extended variant of the
433 * declaration object, allowing access to internals of the invocation
434 * function such as `filter`, `expect` or `params` values.
436 * @return {Promise<*>|*}
437 * Interceptor functions may return a promise to defer response
438 * processing until some delayed work completed. Any values the returned
439 * promise resolves to are ignored.
441 * When the returned promise rejects with an error, the invocation
442 * function will fail too, forwarding the error to the caller.
446 * Registers a new interceptor function.
448 * @param {LuCI.rpc~interceptorFn} interceptorFn
449 * The inteceptor function to register.
451 * @returns {LuCI.rpc~interceptorFn}
452 * Returns the given function value.
454 addInterceptor: function(interceptorFn
) {
455 if (typeof(interceptorFn
) == 'function')
456 rpcInterceptorFns
.push(interceptorFn
);
457 return interceptorFn
;
461 * Removes a registered interceptor function.
463 * @param {LuCI.rpc~interceptorFn} interceptorFn
464 * The inteceptor function to remove.
467 * Returns `true` if the given function has been removed or `false`
468 * if it has not been found.
470 removeInterceptor: function(interceptorFn
) {
471 var oldlen
= rpcInterceptorFns
.length
, i
= oldlen
;
473 if (rpcInterceptorFns
[i
] === interceptorFn
)
474 rpcInterceptorFns
.splice(i
, 1);
475 return (rpcInterceptorFns
.length
< oldlen
);