1 /* 2 * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io> 3 * 4 * Permission to use, copy, modify, and/or distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 /** 18 * # Ubus IPC 19 * 20 * The `ubus` module provides functions for OpenWrt inter-process 21 * communication, including access to ubus registered modules and their 22 * methods, as well as monitoring and publish/subscribe activity on the 23 * ubus message bus. 24 * 25 * Functions can be individually imported using named import syntax: 26 * 27 * ```js 28 * import { connect } from 'ubus'; 29 * 30 * const ubus = connect(); 31 * const result = ubus.call("session", "get", { key: "value" }); 32 * ``` 33 * 34 * Alternatively, the module namespace can be imported using a wildcard 35 * import: 36 * 37 * ```js 38 * import * as ubus from 'ubus'; 39 * 40 * const ctx = ubus.connect(); 41 * ``` 42 * 43 * The `ubus` module may also be loaded via the `-lubus` interpreter switch. 44 * 45 * ## Architecture 46 * 47 * Ubus uses a broker pattern architecture with three main components: 48 * - **`ubusd`**: The central message router/broker that manages 49 * registrations and forwards messages between objects 50 * - **Server objects**: Interfaces/daemons that register methods for 51 * clients to call 52 * - **Client objects**: Callers that invoke server object methods 53 * 54 * All connections go through `ubusd`, significantly reducing the number 55 * of IPC connections compared to traditional client-server models. 56 * 57 * ## Communication Schemes 58 * 59 * Ubus provides three delivery schemes for IPC: 60 * 61 * 1. **Invoke** (one-to-one): Direct method calls to a specific object 62 * by ID 63 * 2. **Subscribe/Notify** (one-to-many, group by object): Notifications 64 * sent to all subscribers of a particular object 65 * 3. **Event Broadcast** (one-to-many, group by event): Events broadcast 66 * to all listeners registered for a matching event pattern 67 * 68 * ## Roles in Ubus 69 * 70 * - **Object**: Process registered to `ubusd`, including services and 71 * service callers 72 * - **Method**: Procedures provided by objects; servers can provide 73 * multiple methods 74 * - **Data**: Information in JSON format carried by requests or replies 75 * - **Subscriber**: Object subscribed to a target service; notified when 76 * the target sends notifications 77 * - **Event**: Identified by a string event pattern; objects can register 78 * to events and send data with matching patterns 79 * - **Event Registrant**: Object registered to an event pattern; receives 80 * forwarded data when matching messages are received 81 * 82 * ## Data Format 83 * 84 * All data is transferred in JSON format via `blobmsg`. Method calls, 85 * requests, and replies all use JSON for data serialization. 86 * 87 * ## Usage Examples 88 * 89 * ### Basic connection and method call 90 * ```js 91 * const ubus = require("ubus"); 92 * 93 * // Connect to ubus and call a method 94 * const conn = ubus.connect(); 95 * if (conn) { 96 * const result = conn.call("network.interface", "status", {}); 97 * printf("Interface status: %.J\n", result); 98 * conn.disconnect(); 99 * } 100 * ``` 101 * 102 * ### Asynchronous method invocation with callback 103 * ```js 104 * const ubus = require("ubus"); 105 * 106 * // Typical pattern: async call with callback 107 * const conn = ubus.connect(); 108 * 109 * conn.defer("some.object", "some_method", {}, (rc, result) => { 110 * if (rc == 0) { 111 * printf("Result: %.J\n", result); 112 * } 113 * }); 114 * ``` 115 * 116 * ### Persistent connection pattern 117 * ```js 118 * const ubus = require("ubus"); 119 * 120 * // Keep connection alive to prevent GC 121 * const ubus_conn = ubus.connect(); 122 * 123 * function handle_request(request) { 124 * ubus_conn.defer("some.object", "some_method", {}, (rc, data) => { 125 * request.reply({ result: data }); 126 * }); 127 * } 128 * ``` 129 * 130 * ### Publishing an object 131 * ```js 132 * const ubus = require("ubus"); 133 * 134 * const conn = ubus.connect(); 135 * const obj = conn.publish("my.service", { 136 * "hello": (req, msg) => { 137 * req.reply({ message: "Hello from " + msg.name }); 138 * } 139 * }); 140 * ``` 141 * 142 * ### Event broadcasting 143 * ```js 144 * const ubus = require("ubus"); 145 * 146 * const conn = ubus.connect(); 147 * 148 * // Register as event listener 149 * const listener = conn.listener("my.event.*", (pattern, data) => { 150 * printf("Received event: %s %.J\n", pattern, data); 151 * }); 152 * 153 * // Send an event 154 * conn.event("my.event.test", { data: "test payload" }); 155 * ``` 156 * 157 * @module ubus 158 * @see https://openwrt.org/docs/techref/ubus 159 */ 160 161 /** 162 * Represents a connection to the ubus bus. 163 * 164 * A connection is established via 165 * {@link module:ubus#connect|connect()} and serves as the primary 166 * interface for all ubus operations. Through a connection, you can: 167 * 168 * - Discover and invoke methods on remote objects 169 * ({@link module:ubus#list|list()}, 170 * {@link module:ubus#call|call()}) 171 * - Publish your own objects to the bus 172 * ({@link module:ubus#publish|publish()}) 173 * - Subscribe to notifications from other objects 174 * ({@link module:ubus#subscriber|subscriber()}) 175 * - Register event listeners for pattern-based events 176 * ({@link module:ubus#listener|listener()}) 177 * - Send broadcast events to other listeners 178 * ({@link module:ubus#event|event()}) 179 * 180 * The connection uses the broker pattern, routing all communication 181 * through ubusd. It supports both synchronous (call) and asynchronous 182 * (defer) method invocations. 183 * 184 * @class module:ubus.connection 185 * @hideconstructor 186 * 187 * @borrows module:ubus#error as module:ubus#error 188 * 189 * @see {@link module:ubus#connect|connect()} 190 * @see {@link module:ubus#open_channel|open_channel()} 191 * 192 * @example 193 * 194 * const conn = connect(); 195 * 196 * conn.list(); 197 * conn.call(…); 198 * conn.defer(…); 199 * conn.publish(…); 200 * conn.remove(…); 201 * conn.listener(…); 202 * conn.subscriber(…); 203 * conn.event(…); 204 * conn.disconnect(); 205 * 206 * conn.error(); 207 */ 208 209 /** 210 * Represents a channel connection to the ubus bus. 211 * 212 * Channels provide bidirectional communication between two ubus objects 213 * through file descriptors. They are created via 214 * {@link module:ubus#open_channel|open_channel()} or from an incoming 215 * request via 216 * {@link module:ubus.request#new_channel|new_channel()}. 217 * 218 * Channels are useful for: 219 * - Establishing dedicated communication paths between specific objects 220 * - Streaming data or multiple requests over a single connection 221 * - File descriptor passing between processes 222 * 223 * @class module:ubus.channel 224 * @hideconstructor 225 * 226 * @borrows module:ubus#error as module:ubus.channel#error 227 * 228 * @see {@link module:ubus#open_channel|open_channel()} 229 * @see {@link module:ubus.request#new_channel|new_channel()} 230 * 231 * @example 232 * 233 * const chan = open_channel(…); 234 * 235 * chan.request(…); 236 * chan.defer(…); 237 * chan.disconnect(); 238 * 239 * chan.error(); 240 */ 241 242 /** 243 * Represents a deferred ubus request. 244 * 245 * A deferred request is created when invoking a method asynchronously 246 * using {@link module:ubus#defer|defer()} or 247 * {@link module:ubus.channel#defer|defer()}. Instead of 248 * blocking and waiting for the result, the operation returns immediately 249 * with a deferred object that can be used to: 250 * 251 * - Check if the request has completed 252 * ({@link module:ubus.deferred#completed|completed()}) 253 * - Wait synchronously for completion 254 * ({@link module:ubus.deferred#await|await()}) 255 * - Abort the pending request if no longer needed 256 * ({@link module:ubus.deferred#abort|abort()}) 257 * 258 * This pattern is useful for: 259 * - Non-blocking operations in event-driven applications 260 * - Timeout handling and request cancellation 261 * - Concurrent execution of multiple ubus method calls 262 * 263 * @class module:ubus.deferred 264 * @hideconstructor 265 * 266 * @see {@link module:ubus#defer|defer()} 267 * @see {@link module:ubus.channel#defer|defer()} 268 * 269 * @example 270 * 271 * const req = defer(…); 272 * 273 * req.await(); 274 * req.completed(); 275 * req.abort(); 276 * 277 * @example 278 * // Typical async pattern with callback 279 * const req = conn.defer("system", "info", {}, (rc, data) => { 280 * if (rc == 0) 281 * printf("Info: %.J\n", data); 282 * }); 283 */ 284 285 /** 286 * Represents a ubus object published on the bus. 287 * 288 * A published object is a service registered with ubusd that provides 289 * methods for other processes to call. Objects are created via 290 * {@link module:ubus#publish|publish()} and can: 291 * 292 * - Expose multiple methods for remote invocation 293 * - Receive notifications from subscribers 294 * ({@link module:ubus.object#subscribed|subscribed()}, 295 * {@link module:ubus.object#notify|notify()}) 296 * - Be removed from the bus when no longer needed 297 * ({@link module:ubus.object#remove|remove()}) 298 * 299 * Objects are identified by their path (e.g., `system`, 300 * `network.interface`) and can be discovered by other processes using 301 * {@link module:ubus#list|list()}. 302 * 303 * @class module:ubus.object 304 * @hideconstructor 305 * 306 * @see {@link module:ubus#publish|publish()} 307 * @see {@link module:ubus#subscriber|subscriber()} 308 * 309 * @example 310 * 311 * const obj = publish(…, { … }); 312 * 313 * obj.subscribed(); 314 * obj.notify(…); 315 * obj.remove(); 316 */ 317 318 /** 319 * Represents a deferred ubus method call context. 320 * 321 * A request object is created when a published object method is invoked 322 * asynchronously. It provides the server-side interface for handling 323 * incoming method calls and sending responses. 324 * 325 * The request context allows the method handler to: 326 * - Send a successful reply with data 327 * ({@link module:ubus.request#reply|reply()}) 328 * - Report an error condition 329 * ({@link module:ubus.request#error|error()}) 330 * - Defer completion for asynchronous processing 331 * ({@link module:ubus.request#defer|defer()}) 332 * - Exchange file descriptors with the caller 333 * ({@link module:ubus.request#get_fd|get_fd()}, 334 * {@link module:ubus.request#set_fd|set_fd()}) 335 * - Establish channel-based communication 336 * ({@link module:ubus.request#new_channel|new_channel()}) 337 * 338 * This is used internally by the ubus module when a published object's 339 * method is called by a client. 340 * 341 * @class module:ubus.request 342 * @hideconstructor 343 * 344 * @see {@link module:ubus#publish|publish()} 345 * 346 * @example 347 * 348 * // Method handler receives request as second argument 349 * const obj = publish("my.service", { 350 * hello: (req, msg) => { 351 * req.reply({ message: "Hello" }); 352 * } 353 * }); 354 */ 355 356 /** 357 * Represents an asynchronous notification request. 358 * 359 * A notify object is created when sending a notification to subscribers 360 * via {@link module:ubus.object#notify|notify()}. It allows 361 * tracking the delivery status of the notification and provides the 362 * ability to abort if needed. 363 * 364 * Notifications are delivered to all subscribers of an object in the 365 * subscribe/notify communication scheme. The notify object provides 366 * non-blocking status checking and cancellation capabilities. 367 * 368 * @class module:ubus.notify 369 * @hideconstructor 370 * 371 * @see {@link module:ubus.object#notify|notify()} 372 * @see {@link module:ubus#subscriber|subscriber()} 373 * 374 * @example 375 * 376 * const n = notify(…); 377 * 378 * n.completed(); 379 * n.abort(); 380 */ 381 382 /** 383 * Represents an event listener for pattern-based events. 384 * 385 * A listener is registered via 386 * {@link module:ubus#listener|listener()} to receive events 387 * matching a specific pattern. Listeners are part of the event broadcast 388 * communication scheme, where events are sent to all registered listeners 389 * with matching event patterns. 390 * 391 * Event patterns support wildcards (e.g., `` `system.*` ``, 392 * `` `network.interface.*` ``) allowing flexible event routing and 393 * subscription. 394 * 395 * @class module:ubus.listener 396 * @hideconstructor 397 * 398 * @see {@link module:ubus#listener|listener()} 399 * @see {@link module:ubus#event|event()} 400 * 401 * @example 402 * 403 * const listener = listener("event.*", (pattern, data) => { … }); 404 * 405 * listener.remove(); 406 */ 407 408 /** 409 * Represents a subscriber to an object's notifications. 410 * 411 * A subscriber is registered via 412 * {@link module:ubus#subscriber|subscriber()} to receive 413 * notifications from a specific object. Subscribers are part of the 414 * subscribe/notify communication scheme, where the target object can send 415 * notifications that are delivered to all registered subscribers. 416 * 417 * When a subscriber is registered, the target object receives a 418 * notification about the new subscription. Similarly, when a subscriber 419 * is removed, the target object is notified of the unsubscription. 420 * 421 * @class module:ubus.subscriber 422 * @hideconstructor 423 * 424 * @see {@link module:ubus#subscriber|subscriber()} 425 * @see {@link module:ubus.object#notify|notify()} 426 * @see {@link module:ubus.object#subscribed|subscribed()} 427 * 428 * @example 429 * 430 * const sub = subscriber(objid, (method, data) => { … }); 431 * 432 * sub.subscribe(); 433 * sub.unsubscribe(); 434 * sub.remove(); 435 */ 436 437 #include <limits.h> 438 #include <fnmatch.h> 439 #include <libubus.h> 440 441 #include "ucode/module.h" 442 443 #define ok_return(expr) do { set_error(0, NULL); return (expr); } while(0) 444 #define err_return(err, ...) do { set_error(err, __VA_ARGS__); return NULL; } while(0) 445 #define errval_return(err, ...) do { set_error(err, __VA_ARGS__); return err; } while(0) 446 447 #define REQUIRED 0 448 #define OPTIONAL 1 449 #define NAMED 2 450 451 static struct { 452 enum ubus_msg_status code; 453 char *msg; 454 } last_error; 455 456 __attribute__((format(printf, 2, 3))) static void 457 set_error(int errcode, const char *fmt, ...) 458 { 459 va_list ap; 460 461 free(last_error.msg); 462 463 last_error.code = errcode; 464 last_error.msg = NULL; 465 466 if (fmt) { 467 va_start(ap, fmt); 468 xvasprintf(&last_error.msg, fmt, ap); 469 va_end(ap); 470 } 471 } 472 473 static char * 474 _arg_type(uc_type_t type) 475 { 476 switch (type) { 477 case UC_INTEGER: return "an integer value"; 478 case UC_BOOLEAN: return "a boolean value"; 479 case UC_STRING: return "a string value"; 480 case UC_DOUBLE: return "a double value"; 481 case UC_ARRAY: return "an array"; 482 case UC_OBJECT: return "an object"; 483 case UC_REGEXP: return "a regular expression"; 484 case UC_CLOSURE: return "a function"; 485 default: return "the expected type"; 486 } 487 } 488 489 static bool 490 _args_get(uc_vm_t *vm, bool named, size_t nargs, ...) 491 { 492 uc_value_t **ptr, *arg, *obj = NULL; 493 uc_type_t type, t; 494 const char *name; 495 size_t index = 0; 496 va_list ap; 497 int opt; 498 499 if (named) { 500 obj = uc_fn_arg(0); 501 502 if (nargs != 1 || ucv_type(obj) != UC_OBJECT) 503 named = false; 504 } 505 506 va_start(ap, nargs); 507 508 while (true) { 509 name = va_arg(ap, const char *); 510 511 if (!name) 512 break; 513 514 type = va_arg(ap, uc_type_t); 515 opt = va_arg(ap, int); 516 ptr = va_arg(ap, uc_value_t **); 517 518 if (named) 519 arg = ucv_object_get(obj, name, NULL); 520 else if (opt != NAMED) 521 arg = uc_fn_arg(index++); 522 else 523 arg = NULL; 524 525 if (opt == REQUIRED && !arg) 526 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Argument %s is required", name); 527 528 t = ucv_type(arg); 529 530 if (t == UC_CFUNCTION) 531 t = UC_CLOSURE; 532 533 if (arg && type && t != type) 534 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Argument %s is not %s", name, _arg_type(type)); 535 536 *ptr = arg; 537 } 538 539 va_end(ap); 540 541 ok_return(true); 542 } 543 544 #define args_get_named(vm, nargs, ...) do { if (!_args_get(vm, true, nargs, __VA_ARGS__, NULL)) return NULL; } while(0) 545 #define args_get(vm, nargs, ...) do { if (!_args_get(vm, false, nargs, __VA_ARGS__, NULL)) return NULL; } while(0) 546 547 static struct blob_buf buf; 548 549 typedef struct { 550 struct ubus_context ctx; 551 struct blob_buf buf; 552 int timeout; 553 bool fd_handle; 554 bool disconnected; 555 556 uc_vm_t *vm; 557 uc_value_t *res; 558 } uc_ubus_connection_t; 559 560 typedef struct { 561 struct ubus_request request; 562 struct uloop_timeout timeout; 563 struct ubus_context *ctx; 564 bool complete; 565 uc_vm_t *vm; 566 uc_value_t *res; 567 uc_value_t *fd_callback; 568 uc_value_t *response; 569 } uc_ubus_deferred_t; 570 571 typedef struct { 572 struct ubus_object obj; 573 struct ubus_object_type type; 574 struct ubus_context *ctx; 575 uc_vm_t *vm; 576 uc_value_t *res; 577 struct ubus_method methods[]; 578 } uc_ubus_object_t; 579 580 typedef struct { 581 struct ubus_request_data req; 582 struct uloop_timeout timeout; 583 struct ubus_context *ctx; 584 uc_value_t *res; 585 uc_vm_t *vm; 586 bool deferred; 587 bool replied; 588 } uc_ubus_request_t; 589 590 typedef struct { 591 struct ubus_notify_request req; 592 struct ubus_context *ctx; 593 uc_vm_t *vm; 594 uc_value_t *res; 595 bool complete; 596 } uc_ubus_notify_t; 597 598 typedef struct { 599 struct ubus_event_handler ev; 600 struct ubus_context *ctx; 601 uc_vm_t *vm; 602 uc_value_t *res; 603 } uc_ubus_listener_t; 604 605 typedef struct { 606 struct ubus_subscriber sub; 607 struct ubus_context *ctx; 608 uc_vm_t *vm; 609 uc_value_t *res; 610 } uc_ubus_subscriber_t; 611 612 typedef struct { 613 bool mret; 614 uc_value_t *res; 615 } uc_ubus_call_res_t; 616 617 /** 618 * Query ubus error information. 619 * 620 * Returns a string containing a description of the last ubus error when 621 * the *numeric* argument is absent or false. 622 * 623 * Returns a ubus status code number when the *numeric* argument is `true`. 624 * 625 * Returns `null` if there is no error information. 626 * 627 * @function module:ubus#error 628 * 629 * @param {boolean} [numeric] 630 * Whether to return a numeric status code (`true`) or a human readable 631 * error message (false). 632 * 633 * @returns {?string|?number} 634 */ 635 static uc_value_t * 636 uc_ubus_error(uc_vm_t *vm, size_t nargs) 637 { 638 uc_value_t *numeric = uc_fn_arg(0), *rv; 639 uc_stringbuf_t *buf; 640 const char *s; 641 642 if (last_error.code == 0) 643 return NULL; 644 645 if (ucv_is_truish(numeric)) { 646 rv = ucv_int64_new(last_error.code); 647 } 648 else { 649 buf = ucv_stringbuf_new(); 650 651 if (last_error.code == UBUS_STATUS_UNKNOWN_ERROR && last_error.msg) { 652 ucv_stringbuf_addstr(buf, last_error.msg, strlen(last_error.msg)); 653 } 654 else { 655 s = ubus_strerror(last_error.code); 656 657 ucv_stringbuf_addstr(buf, s, strlen(s)); 658 659 if (last_error.msg) 660 ucv_stringbuf_printf(buf, ": %s", last_error.msg); 661 } 662 663 rv = ucv_stringbuf_finish(buf); 664 } 665 666 set_error(0, NULL); 667 668 return rv; 669 } 670 671 enum { 672 CONN_RES_FD, 673 CONN_RES_CB, 674 CONN_RES_DISCONNECT_CB, 675 __CONN_RES_MAX 676 }; 677 678 enum { 679 DEFER_RES_CONN, 680 DEFER_RES_CB, 681 DEFER_RES_DATA_CB, 682 DEFER_RES_FD_CB, 683 DEFER_RES_FD, 684 DEFER_RES_RESPONSE, 685 __DEFER_RES_MAX 686 }; 687 688 enum { 689 OBJ_RES_CONN, 690 OBJ_RES_METHODS, 691 OBJ_RES_SUB_CB, 692 __OBJ_RES_MAX 693 }; 694 695 enum { 696 NOTIFY_RES_CONN, 697 NOTIFY_RES_CB, 698 NOTIFY_RES_DATA_CB, 699 NOTIFY_RES_STATUS_CB, 700 __NOTIFY_RES_MAX, 701 }; 702 703 enum { 704 LISTEN_RES_CONN, 705 LISTEN_RES_CB, 706 __LISTEN_RES_MAX, 707 }; 708 709 enum { 710 SUB_RES_CONN, 711 SUB_RES_NOTIFY_CB, 712 SUB_RES_REMOVE_CB, 713 SUB_RES_PATTERNS, 714 __SUB_RES_MAX, 715 }; 716 717 /* Largest value slot count across all ubus resource types. Keep in sync 718 * with the largest __*_RES_MAX above; used to sweep a resource's value 719 * slots without needing to know its specific type. */ 720 enum { 721 UBUS_RES_MAX = __DEFER_RES_MAX 722 }; 723 724 static void 725 uc_ubus_put_res(uc_value_t **rp) 726 { 727 uc_value_t *res = *rp; 728 size_t i; 729 730 *rp = NULL; 731 732 if (!res) 733 return; 734 735 /* drop the stored references (including a per-instance prototype, if 736 * present) to break resource <-> closure reference cycles 737 * deterministically, without waiting for a gc pass. The setter 738 * ignores indexes beyond the resource's own value count, so it is 739 * safe to sweep up to the largest ubus resource slot count. */ 740 for (i = 0; i < UBUS_RES_MAX; i++) 741 ucv_resource_value_set(res, i, NULL); 742 743 ucv_resource_proto_set(res, NULL); 744 745 ucv_resource_persistent_set(res, false); 746 ucv_put(res); 747 } 748 749 #define UBUS_MAX_BLOB_DEPTH 256 750 751 static uc_value_t * 752 blob_to_ucv(uc_vm_t *vm, struct blob_attr *attr, bool table, const char **name, 753 size_t depth); 754 755 static uc_value_t * 756 blob_array_to_ucv_depth(uc_vm_t *vm, struct blob_attr *attr, size_t len, 757 bool table, size_t depth) 758 { 759 uc_value_t *o = table ? ucv_object_new(vm) : ucv_array_new(vm); 760 uc_value_t *v; 761 struct blob_attr *pos; 762 size_t rem = len; 763 const char *name; 764 765 if (!o) 766 return NULL; 767 768 __blob_for_each_attr(pos, attr, rem) { 769 name = NULL; 770 v = blob_to_ucv(vm, pos, table, &name, depth); 771 772 if (table && name) 773 ucv_object_add(o, name, v); 774 else if (!table) 775 ucv_array_push(o, v); 776 else 777 ucv_put(v); 778 } 779 780 return o; 781 } 782 783 static uc_value_t * 784 blob_array_to_ucv(uc_vm_t *vm, struct blob_attr *attr, size_t len, bool table) 785 { 786 return blob_array_to_ucv_depth(vm, attr, len, table, 0); 787 } 788 789 static uc_value_t * 790 blob_to_ucv(uc_vm_t *vm, struct blob_attr *attr, bool table, const char **name, 791 size_t depth) 792 { 793 void *data; 794 int len; 795 796 if (!blobmsg_check_attr(attr, false)) 797 return NULL; 798 799 if (table && blobmsg_name(attr)[0]) 800 *name = blobmsg_name(attr); 801 802 data = blobmsg_data(attr); 803 len = blobmsg_data_len(attr); 804 805 switch (blob_id(attr)) { 806 case BLOBMSG_TYPE_BOOL: 807 return ucv_boolean_new(*(uint8_t *)data); 808 809 case BLOBMSG_TYPE_INT16: 810 return ucv_int64_new((int16_t)be16_to_cpu(*(uint16_t *)data)); 811 812 case BLOBMSG_TYPE_INT32: 813 return ucv_int64_new((int32_t)be32_to_cpu(*(uint32_t *)data)); 814 815 case BLOBMSG_TYPE_INT64: 816 return ucv_int64_new((int64_t)be64_to_cpu(*(uint64_t *)data)); 817 818 case BLOBMSG_TYPE_DOUBLE: 819 ; 820 union { 821 double d; 822 uint64_t u64; 823 } v; 824 825 v.u64 = be64_to_cpu(*(uint64_t *)data); 826 827 return ucv_double_new(v.d); 828 829 case BLOBMSG_TYPE_STRING: 830 return ucv_string_new_length(data, len - 1); 831 832 case BLOBMSG_TYPE_ARRAY: 833 if (depth >= UBUS_MAX_BLOB_DEPTH) 834 return NULL; 835 836 return blob_array_to_ucv_depth(vm, data, len, false, depth + 1); 837 838 case BLOBMSG_TYPE_TABLE: 839 if (depth >= UBUS_MAX_BLOB_DEPTH) 840 return NULL; 841 842 return blob_array_to_ucv_depth(vm, data, len, true, depth + 1); 843 844 default: 845 return NULL; 846 } 847 } 848 849 static void 850 ucv_array_to_blob(uc_value_t *val, struct blob_buf *blob); 851 852 static void 853 ucv_object_to_blob(uc_value_t *val, struct blob_buf *blob); 854 855 static void 856 ucv_to_blob(const char *name, uc_value_t *val, struct blob_buf *blob) 857 { 858 int64_t n; 859 void *c; 860 861 switch (ucv_type(val)) { 862 case UC_NULL: 863 blobmsg_add_field(blob, BLOBMSG_TYPE_UNSPEC, name, NULL, 0); 864 break; 865 866 case UC_BOOLEAN: 867 blobmsg_add_u8(blob, name, ucv_boolean_get(val)); 868 break; 869 870 case UC_INTEGER: 871 n = ucv_int64_get(val); 872 873 if (errno == ERANGE) 874 blobmsg_add_u64(blob, name, ucv_uint64_get(val)); 875 else if (n >= INT32_MIN && n <= INT32_MAX) 876 blobmsg_add_u32(blob, name, n); 877 else 878 blobmsg_add_u64(blob, name, n); 879 880 break; 881 882 case UC_DOUBLE: 883 blobmsg_add_double(blob, name, ucv_double_get(val)); 884 break; 885 886 case UC_STRING: 887 blobmsg_add_field(blob, BLOBMSG_TYPE_STRING, name, 888 ucv_string_get(val), ucv_string_length(val) + 1); 889 break; 890 891 case UC_ARRAY: 892 if (ucv_is_marked(val)) { 893 blobmsg_add_field(blob, BLOBMSG_TYPE_UNSPEC, name, NULL, 0); 894 break; 895 } 896 897 ucv_set_mark(val); 898 c = blobmsg_open_array(blob, name); 899 ucv_array_to_blob(val, blob); 900 blobmsg_close_array(blob, c); 901 ucv_clear_mark(val); 902 break; 903 904 case UC_OBJECT: 905 if (ucv_is_marked(val)) { 906 blobmsg_add_field(blob, BLOBMSG_TYPE_UNSPEC, name, NULL, 0); 907 break; 908 } 909 910 ucv_set_mark(val); 911 c = blobmsg_open_table(blob, name); 912 ucv_object_to_blob(val, blob); 913 blobmsg_close_table(blob, c); 914 ucv_clear_mark(val); 915 break; 916 917 default: 918 break; 919 } 920 } 921 922 static void 923 ucv_array_to_blob(uc_value_t *val, struct blob_buf *blob) 924 { 925 size_t i; 926 927 for (i = 0; i < ucv_array_length(val); i++) 928 ucv_to_blob(NULL, ucv_array_get(val, i), blob); 929 } 930 931 static void 932 ucv_object_to_blob(uc_value_t *val, struct blob_buf *blob) 933 { 934 ucv_object_foreach(val, k, v) 935 ucv_to_blob(k, v, blob); 936 } 937 938 939 static uc_ubus_connection_t * 940 uc_ubus_conn_alloc(uc_vm_t *vm, uc_value_t *timeout, const char *type) 941 { 942 uc_ubus_connection_t *c = NULL; 943 uc_value_t *res; 944 945 res = ucv_resource_create_ex(vm, type, (void **)&c, __CONN_RES_MAX, sizeof(*c)); 946 if (!c) 947 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Out of memory"); 948 949 c->vm = vm; 950 c->res = res; 951 c->timeout = timeout ? ucv_int64_get(timeout) : 30; 952 if (c->timeout < 0) 953 c->timeout = 30; 954 955 return c; 956 } 957 958 /** 959 * Establish a connection to the ubus bus. 960 * 961 * Connects to the specified ubus socket path or the default socket if none 962 * is provided. 963 * 964 * Returns a connection resource on success. 965 * 966 * Returns `null` if the connection could not be established. 967 * 968 * @function module:ubus#connect 969 * 970 * @param {string} [socket] 971 * The path to the ubus socket to connect to. If omitted, the default socket 972 * path is used. 973 * 974 * @param {number} [timeout=30] 975 * The timeout in seconds to use for subsequent ubus operations. 976 * 977 * @returns {?module:ubus.connection} 978 */ 979 static uc_value_t * 980 uc_ubus_connect(uc_vm_t *vm, size_t nargs) 981 { 982 uc_value_t *socket, *timeout; 983 uc_ubus_connection_t *c; 984 985 args_get(vm, nargs, 986 "socket", UC_STRING, true, &socket, 987 "timeout", UC_INTEGER, true, &timeout); 988 989 c = uc_ubus_conn_alloc(vm, timeout, "ubus.connection"); 990 991 if (!c) 992 return NULL; 993 994 if (ubus_connect_ctx(&c->ctx, socket ? ucv_string_get(socket) : NULL)) { 995 ucv_put(c->res); 996 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Unable to connect to ubus socket"); 997 } 998 999 if (c->timeout < 0) 1000 c->timeout = 30; 1001 1002 ubus_add_uloop(&c->ctx); 1003 1004 /* Keep the connection (and its embedded values) reachable across GC 1005 * passes while it is held purely by refcount (e.g. after the script 1006 * dropped its reference but derived resources keep it alive). */ 1007 ucv_resource_persistent_set(c->res, true); 1008 1009 ok_return(ucv_get(c->res)); 1010 } 1011 1012 static void 1013 uc_ubus_signatures_cb(struct ubus_context *c, struct ubus_object_data *o, void *p) 1014 { 1015 uc_value_t *arr = p; 1016 uc_value_t *sig; 1017 1018 if (!o->signature) 1019 return; 1020 1021 sig = blob_array_to_ucv(NULL, blob_data(o->signature), blob_len(o->signature), true); 1022 1023 if (sig) 1024 ucv_array_push(arr, sig); 1025 } 1026 1027 static void 1028 uc_ubus_objects_cb(struct ubus_context *c, struct ubus_object_data *o, void *p) 1029 { 1030 uc_value_t *arr = p; 1031 1032 ucv_array_push(arr, ucv_string_new(o->path)); 1033 } 1034 1035 static bool 1036 _conn_get(uc_vm_t *vm, uc_ubus_connection_t **conn) 1037 { 1038 uc_ubus_connection_t *c; 1039 uc_value_t *res; 1040 1041 if (ucv_type(_uc_fn_this_res(vm)) == UC_OBJECT) { 1042 res = uc_vm_registry_get(vm, "ubus.connection"); 1043 c = ucv_resource_data(res, "ubus.connection"); 1044 1045 if (c && c->ctx.sock.fd >= 0) 1046 goto out; 1047 1048 c = uc_ubus_conn_alloc(vm, NULL, "ubus.connection"); 1049 if (!c) 1050 return NULL; 1051 1052 if (ubus_connect_ctx(&c->ctx, NULL)) { 1053 ucv_put(c->res); 1054 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Unable to connect to ubus socket"); 1055 } 1056 1057 ubus_add_uloop(&c->ctx); 1058 1059 ucv_resource_persistent_set(c->res, true); 1060 uc_vm_registry_set(vm, "ubus.connection", ucv_get(c->res)); 1061 } 1062 else { 1063 c = uc_fn_thisval("ubus.connection"); 1064 if (!c) 1065 c = uc_fn_thisval("ubus.channel"); 1066 1067 if (!c) 1068 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid connection context"); 1069 1070 if (c->ctx.sock.fd < 0) 1071 err_return(UBUS_STATUS_CONNECTION_FAILED, "Connection is closed"); 1072 } 1073 1074 out: 1075 *conn = c; 1076 1077 ok_return(true); 1078 } 1079 1080 #define conn_get(vm, ptr) do { if (!_conn_get(vm, ptr)) return NULL; } while(0) 1081 1082 /** 1083 * List available ubus objects. 1084 * 1085 * Queries the ubus bus for registered objects. If an object name pattern 1086 * is provided, returns signatures for matching objects. Otherwise, returns 1087 * a list of all registered object paths. 1088 * 1089 * Returns an array of object paths or object signatures. 1090 * 1091 * Returns `null` if the list operation failed. 1092 * 1093 * @function module:ubus.connection#list 1094 * 1095 * @param {string} [object_name] 1096 * Optional object name pattern to filter results. When provided, returns 1097 * signatures for matching objects; otherwise returns all object paths. 1098 * 1099 * @returns {?string[]} 1100 */ 1101 static uc_value_t * 1102 uc_ubus_list(uc_vm_t *vm, size_t nargs) 1103 { 1104 uc_ubus_connection_t *c; 1105 uc_value_t *objname, *res = NULL; 1106 enum ubus_msg_status rv; 1107 1108 conn_get(vm, &c); 1109 1110 args_get(vm, nargs, 1111 "object name", UC_STRING, true, &objname); 1112 1113 res = ucv_array_new(vm); 1114 1115 rv = ubus_lookup(&c->ctx, 1116 objname ? ucv_string_get(objname) : NULL, 1117 objname ? uc_ubus_signatures_cb : uc_ubus_objects_cb, 1118 res); 1119 1120 if (rv != UBUS_STATUS_OK) { 1121 ucv_put(res); 1122 err_return(rv, NULL); 1123 } 1124 1125 ok_return(res); 1126 } 1127 1128 static void 1129 uc_ubus_call_cb(struct ubus_request *req, int type, struct blob_attr *msg) 1130 { 1131 uc_ubus_call_res_t *res = req->priv; 1132 uc_value_t *val; 1133 1134 val = msg ? blob_array_to_ucv(NULL, blob_data(msg), blob_len(msg), true) : NULL; 1135 1136 if (res->mret) { 1137 if (!res->res) 1138 res->res = ucv_array_new(NULL); 1139 1140 ucv_array_push(res->res, val); 1141 } 1142 else if (!res->res) { 1143 res->res = val; 1144 } 1145 else { 1146 /* single-return mode keeps the first reply only */ 1147 ucv_put(val); 1148 } 1149 } 1150 1151 static void 1152 uc_ubus_vm_handle_exception(uc_vm_t *vm) 1153 { 1154 uc_value_t *exh, *val; 1155 1156 if (vm->exception.type == EXCEPTION_EXIT) 1157 goto error; 1158 1159 exh = uc_vm_registry_get(vm, "ubus.ex_handler"); 1160 if (!ucv_is_callable(exh)) 1161 goto error; 1162 1163 val = uc_vm_exception_object(vm); 1164 uc_vm_stack_push(vm, ucv_get(exh)); 1165 uc_vm_stack_push(vm, val); 1166 1167 if (uc_vm_call(vm, false, 1) != EXCEPTION_NONE) 1168 goto error; 1169 1170 ucv_put(uc_vm_stack_pop(vm)); 1171 return; 1172 1173 error: 1174 uloop_end(); 1175 } 1176 1177 static bool 1178 uc_ubus_vm_call(uc_vm_t *vm, bool mcall, size_t nargs) 1179 { 1180 if (uc_vm_call(vm, mcall, nargs) == EXCEPTION_NONE) 1181 return true; 1182 1183 uc_ubus_vm_handle_exception(vm); 1184 1185 return false; 1186 } 1187 1188 static void 1189 uc_ubus_call_user_cb(uc_ubus_deferred_t *defer, int ret, uc_value_t *reply) 1190 { 1191 uc_value_t *this = ucv_get(defer->res); 1192 uc_vm_t *vm = defer->vm; 1193 uc_value_t *func; 1194 1195 func = ucv_resource_value_get(this, DEFER_RES_CB); 1196 1197 if (ucv_is_callable(func)) { 1198 uc_vm_stack_push(vm, ucv_get(this)); 1199 uc_vm_stack_push(vm, ucv_get(func)); 1200 uc_vm_stack_push(vm, ucv_int64_new(ret)); 1201 uc_vm_stack_push(vm, ucv_get(reply)); 1202 1203 if (uc_ubus_vm_call(vm, true, 2)) 1204 ucv_put(uc_vm_stack_pop(vm)); 1205 } 1206 1207 uc_ubus_put_res(&defer->res); 1208 ucv_put(this); 1209 } 1210 1211 static void 1212 uc_ubus_call_data_cb(struct ubus_request *req, int type, struct blob_attr *msg) 1213 { 1214 uc_ubus_deferred_t *defer = container_of(req, uc_ubus_deferred_t, request); 1215 1216 if (defer->response != NULL) 1217 return; 1218 1219 defer->response = blob_array_to_ucv(defer->vm, blob_data(msg), blob_len(msg), true); 1220 ucv_resource_value_set(defer->res, DEFER_RES_RESPONSE, defer->response); 1221 } 1222 1223 static void 1224 uc_ubus_call_data_user_cb(struct ubus_request *req, int type, struct blob_attr *msg) 1225 { 1226 uc_ubus_deferred_t *defer = container_of(req, uc_ubus_deferred_t, request); 1227 uc_vm_t *vm = defer->vm; 1228 uc_value_t *func, *reply; 1229 1230 func = ucv_resource_value_get(defer->res, DEFER_RES_DATA_CB); 1231 1232 if (ucv_is_callable(func)) { 1233 reply = blob_array_to_ucv(vm, blob_data(msg), blob_len(msg), true); 1234 1235 uc_vm_stack_push(vm, ucv_get(defer->res)); 1236 uc_vm_stack_push(vm, ucv_get(func)); 1237 uc_vm_stack_push(vm, reply); 1238 1239 if (uc_ubus_vm_call(vm, true, 1)) 1240 ucv_put(uc_vm_stack_pop(vm)); 1241 } 1242 } 1243 1244 static void 1245 uc_ubus_call_fd_cb(struct ubus_request *req, int fd) 1246 { 1247 uc_ubus_deferred_t *defer = container_of(req, uc_ubus_deferred_t, request); 1248 uc_value_t *func = defer->fd_callback; 1249 uc_vm_t *vm = defer->vm; 1250 1251 if (defer->complete) 1252 return; 1253 1254 if (ucv_is_callable(func)) { 1255 uc_vm_stack_push(vm, ucv_get(defer->res)); 1256 uc_vm_stack_push(vm, ucv_get(func)); 1257 uc_vm_stack_push(vm, ucv_int64_new(fd)); 1258 1259 if (uc_ubus_vm_call(vm, true, 1)) 1260 ucv_put(uc_vm_stack_pop(vm)); 1261 } 1262 } 1263 1264 static void 1265 uc_ubus_call_done_cb(struct ubus_request *req, int ret) 1266 { 1267 uc_ubus_deferred_t *defer = container_of(req, uc_ubus_deferred_t, request); 1268 1269 if (defer->complete) 1270 return; 1271 1272 defer->complete = true; 1273 uloop_timeout_cancel(&defer->timeout); 1274 1275 uc_ubus_call_user_cb(defer, ret, defer->response); 1276 } 1277 1278 static void 1279 uc_ubus_call_timeout_cb(struct uloop_timeout *timeout) 1280 { 1281 uc_ubus_deferred_t *defer = container_of(timeout, uc_ubus_deferred_t, timeout); 1282 1283 if (defer->complete) 1284 return; 1285 1286 defer->complete = true; 1287 ubus_abort_request(defer->ctx, &defer->request); 1288 1289 uc_ubus_call_user_cb(defer, UBUS_STATUS_TIMEOUT, NULL); 1290 } 1291 1292 static int 1293 get_fd(uc_vm_t *vm, uc_value_t *val, bool *handle) 1294 { 1295 uc_value_t *fn; 1296 int64_t n; 1297 1298 fn = ucv_property_get(val, "fileno"); 1299 1300 if (ucv_is_callable(fn)) { 1301 if (handle) 1302 *handle = true; 1303 1304 uc_vm_stack_push(vm, ucv_get(val)); 1305 uc_vm_stack_push(vm, ucv_get(fn)); 1306 1307 if (uc_vm_call(vm, true, 0) != EXCEPTION_NONE) 1308 return -1; 1309 1310 val = uc_vm_stack_pop(vm); 1311 n = ucv_int64_get(val); 1312 ucv_put(val); 1313 } 1314 else { 1315 n = ucv_int64_get(val); 1316 } 1317 1318 if (errno || n < 0 || n > (int64_t)INT_MAX) 1319 return -1; 1320 1321 return (int)n; 1322 } 1323 1324 static int 1325 uc_ubus_call_common(uc_vm_t *vm, uc_ubus_connection_t *c, uc_ubus_call_res_t *res, 1326 uint32_t id, uc_value_t *funname, uc_value_t *funargs, 1327 uc_value_t *fd, uc_value_t *fdcb, uc_value_t *mret) 1328 { 1329 uc_ubus_deferred_t defer = {}; 1330 enum ubus_msg_status rv; 1331 int fd_val = -1; 1332 1333 enum { 1334 RET_MODE_SINGLE, 1335 RET_MODE_MULTIPLE, 1336 RET_MODE_IGNORE, 1337 } ret_mode = RET_MODE_SINGLE; 1338 1339 const char * const ret_modes[] = { 1340 [RET_MODE_SINGLE] = "single", 1341 [RET_MODE_MULTIPLE] = "multiple", 1342 [RET_MODE_IGNORE] = "ignore", 1343 }; 1344 1345 if (ucv_type(mret) == UC_STRING) { 1346 const char *str = ucv_string_get(mret); 1347 size_t i; 1348 1349 for (i = 0; i < ARRAY_SIZE(ret_modes); i++) 1350 if (!strcmp(str, ret_modes[i])) 1351 break; 1352 1353 if (i == ARRAY_SIZE(ret_modes)) 1354 errval_return(UBUS_STATUS_INVALID_ARGUMENT, 1355 "Invalid return mode argument"); 1356 1357 ret_mode = i; 1358 } 1359 else if (ucv_type(mret) == UC_BOOLEAN) { 1360 ret_mode = ucv_boolean_get(mret); 1361 } 1362 else if (ret_mode) { 1363 errval_return(UBUS_STATUS_INVALID_ARGUMENT, 1364 "Invalid return mode argument"); 1365 } 1366 1367 blob_buf_init(&c->buf, 0); 1368 1369 if (funargs) 1370 ucv_object_to_blob(funargs, &c->buf); 1371 1372 if (fd) { 1373 bool fd_handle = false; 1374 1375 fd_val = get_fd(vm, fd, &fd_handle); 1376 1377 if (fd_val < 0) 1378 errval_return(UBUS_STATUS_INVALID_ARGUMENT, 1379 "Invalid file descriptor argument"); 1380 1381 if (fd_handle) { 1382 fd_val = dup(fd_val); 1383 1384 if (fd_val < 0) 1385 errval_return(UBUS_STATUS_UNKNOWN_ERROR, 1386 "Unable to duplicate file descriptor"); 1387 } 1388 } 1389 1390 res->mret = (ret_mode == RET_MODE_MULTIPLE); 1391 1392 rv = ubus_invoke_async_fd(&c->ctx, id, ucv_string_get(funname), 1393 c->buf.head, &defer.request, fd_val); 1394 1395 defer.vm = vm; 1396 defer.ctx = &c->ctx; 1397 defer.request.data_cb = uc_ubus_call_cb; 1398 defer.request.priv = res; 1399 1400 if (ucv_is_callable(fdcb)) { 1401 defer.request.fd_cb = uc_ubus_call_fd_cb; 1402 defer.fd_callback = fdcb; 1403 } 1404 1405 if (rv == UBUS_STATUS_OK) { 1406 if (ret_mode == RET_MODE_IGNORE) 1407 ubus_abort_request(&c->ctx, &defer.request); 1408 else 1409 rv = ubus_complete_request(&c->ctx, &defer.request, c->timeout * 1000); 1410 } 1411 1412 /* replies already converted by uc_ubus_call_cb() are ours to release when 1413 * the request ends non-OK; the callers only hand res->res to the script on 1414 * success */ 1415 if (rv != UBUS_STATUS_OK) { 1416 ucv_put(res->res); 1417 res->res = NULL; 1418 } 1419 1420 return rv; 1421 } 1422 1423 /** 1424 * Invoke a ubus method synchronously. 1425 * 1426 * Calls the specified method on a ubus object and waits for the response. 1427 * 1428 * Returns the method response data, or an array of responses if multiple 1429 * replies were received. 1430 * 1431 * Returns `null` if the call failed. 1432 * 1433 * @function module:ubus.connection#call 1434 * 1435 * @param {string|number} object 1436 * The object name (string) or object ID (number) to call the method on. 1437 * 1438 * @param {string} method 1439 * The name of the method to invoke. 1440 * 1441 * @param {Object} [data] 1442 * Optional method arguments as an object with field names and values. 1443 * 1444 * @param {string|boolean} [return="single"] 1445 * Controls how multiple responses are handled: `"single"` returns only 1446 * the first response, `"multiple"` returns an array of all responses, 1447 * `"ignore"` discards the response. 1448 * 1449 * @param {number} [fd] 1450 * Optional file descriptor to send along with the call. 1451 * 1452 * @param {function} [fd_cb] 1453 * Optional callback function invoked when a file descriptor is received. 1454 * 1455 * @returns {?*} 1456 */ 1457 static uc_value_t * 1458 uc_ubus_call(uc_vm_t *vm, size_t nargs) 1459 { 1460 uc_value_t *obj, *funname, *funargs, *fd, *fdcb, *mret = NULL; 1461 uc_ubus_call_res_t res = { 0 }; 1462 uc_ubus_connection_t *c; 1463 enum ubus_msg_status rv; 1464 uint32_t id; 1465 1466 args_get_named(vm, nargs, 1467 "object", 0, REQUIRED, &obj, 1468 "method", UC_STRING, REQUIRED, &funname, 1469 "data", UC_OBJECT, OPTIONAL, &funargs, 1470 "return", 0, OPTIONAL, &mret, 1471 "fd", 0, NAMED, &fd, 1472 "fd_cb", UC_CLOSURE, NAMED, &fdcb); 1473 1474 conn_get(vm, &c); 1475 1476 if (ucv_type(obj) == UC_INTEGER) { 1477 id = ucv_int64_get(obj); 1478 } 1479 else if (ucv_type(obj) == UC_STRING) { 1480 rv = ubus_lookup_id(&c->ctx, ucv_string_get(obj), &id); 1481 1482 if (rv != UBUS_STATUS_OK) 1483 err_return(rv, "Failed to resolve object name '%s'", 1484 ucv_string_get(obj)); 1485 } 1486 else { 1487 err_return(UBUS_STATUS_INVALID_ARGUMENT, 1488 "Argument object is not string or integer"); 1489 } 1490 1491 rv = uc_ubus_call_common(vm, c, &res, id, funname, funargs, fd, fdcb, mret); 1492 1493 if (rv != UBUS_STATUS_OK) { 1494 if (ucv_type(obj) == UC_STRING) 1495 err_return(rv, "Failed to invoke function '%s' on object '%s'", 1496 ucv_string_get(funname), ucv_string_get(obj)); 1497 else 1498 err_return(rv, "Failed to invoke function '%s' on system object %d", 1499 ucv_string_get(funname), (int)ucv_int64_get(obj)); 1500 } 1501 1502 ok_return(res.res); 1503 } 1504 1505 /** 1506 * Send a request on a channel connection. 1507 * 1508 * Similar to call() but uses object ID 0 for channel-based communication. 1509 * 1510 * Returns the method response data. 1511 * 1512 * Returns `null` if the request failed. 1513 * 1514 * @function module:ubus.channel#request 1515 * 1516 * @param {string} method 1517 * The name of the method to invoke. 1518 * 1519 * @param {Object} [data] 1520 * Optional method arguments as an object with field names and values. 1521 * 1522 * @param {string|boolean} [return="single"] 1523 * Controls how multiple responses are handled. 1524 * 1525 * @param {number} [fd] 1526 * Optional file descriptor to send along with the request. 1527 * 1528 * @param {function} [fd_cb] 1529 * Optional callback function invoked when a file descriptor is received. 1530 * 1531 * @returns {?*} 1532 * 1533 * @example 1534 * const chan = open_channel(…); 1535 * const result = chan.request("method_name", { arg: "value" }); 1536 */ 1537 static uc_value_t * 1538 uc_ubus_chan_request(uc_vm_t *vm, size_t nargs) 1539 { 1540 uc_value_t *funname, *funargs, *fd, *fdcb, *mret = NULL; 1541 uc_ubus_call_res_t res = { 0 }; 1542 uc_ubus_connection_t *c; 1543 enum ubus_msg_status rv; 1544 1545 args_get_named(vm, nargs, 1546 "method", UC_STRING, REQUIRED, &funname, 1547 "data", UC_OBJECT, OPTIONAL, &funargs, 1548 "return", 0, OPTIONAL, &mret, 1549 "fd", 0, NAMED, &fd, 1550 "fd_cb", UC_CLOSURE, NAMED, &fdcb); 1551 1552 conn_get(vm, &c); 1553 1554 rv = uc_ubus_call_common(vm, c, &res, 0, funname, funargs, fd, fdcb, mret); 1555 1556 if (rv != UBUS_STATUS_OK) 1557 err_return(rv, "Failed to send request '%s' on channel", 1558 ucv_string_get(funname)); 1559 1560 ok_return(res.res); 1561 } 1562 1563 static int 1564 uc_ubus_defer_common(uc_vm_t *vm, uc_ubus_connection_t *c, uc_ubus_call_res_t *res, 1565 uint32_t id, uc_value_t *funname, uc_value_t *funargs, 1566 uc_value_t *fd, uc_value_t *fdcb, uc_value_t *replycb, 1567 uc_value_t *datacb) 1568 { 1569 uc_ubus_deferred_t *defer = NULL; 1570 enum ubus_msg_status rv; 1571 int fd_val = -1; 1572 1573 blob_buf_init(&c->buf, 0); 1574 1575 if (funargs) 1576 ucv_object_to_blob(funargs, &c->buf); 1577 1578 if (fd) { 1579 bool fd_handle = false; 1580 1581 fd_val = get_fd(vm, fd, &fd_handle); 1582 1583 if (fd_val < 0) 1584 errval_return(UBUS_STATUS_INVALID_ARGUMENT, 1585 "Invalid file descriptor argument"); 1586 1587 if (fd_handle) { 1588 fd_val = dup(fd_val); 1589 1590 if (fd_val < 0) 1591 errval_return(UBUS_STATUS_UNKNOWN_ERROR, 1592 "Unable to duplicate file descriptor"); 1593 } 1594 } 1595 1596 res->res = ucv_resource_create_ex(vm, "ubus.deferred", (void **)&defer, __DEFER_RES_MAX, sizeof(*defer)); 1597 1598 if (!defer) 1599 errval_return(UBUS_STATUS_UNKNOWN_ERROR, "Out of memory"); 1600 1601 rv = ubus_invoke_async_fd(&c->ctx, id, ucv_string_get(funname), 1602 c->buf.head, &defer->request, fd_val); 1603 1604 if (rv == UBUS_STATUS_OK) { 1605 defer->vm = vm; 1606 defer->ctx = &c->ctx; 1607 defer->res = ucv_get(res->res); 1608 ucv_resource_persistent_set(defer->res, true); 1609 ucv_resource_value_set(defer->res, DEFER_RES_CONN, ucv_get(c->res)); 1610 ucv_resource_value_set(defer->res, DEFER_RES_CB, ucv_get(replycb)); 1611 ucv_resource_value_set(defer->res, DEFER_RES_FD, ucv_get(fd)); 1612 ucv_resource_value_set(defer->res, DEFER_RES_DATA_CB, ucv_get(datacb)); 1613 1614 if (ucv_is_callable(datacb)) 1615 defer->request.data_cb = uc_ubus_call_data_user_cb; 1616 else 1617 defer->request.data_cb = uc_ubus_call_data_cb; 1618 1619 if (ucv_is_callable(fdcb)) { 1620 defer->request.fd_cb = uc_ubus_call_fd_cb; 1621 defer->fd_callback = fdcb; 1622 ucv_resource_value_set(defer->res, DEFER_RES_FD_CB, ucv_get(fdcb)); 1623 } 1624 1625 defer->request.complete_cb = uc_ubus_call_done_cb; 1626 1627 ubus_complete_request_async(&c->ctx, &defer->request); 1628 1629 defer->timeout.cb = uc_ubus_call_timeout_cb; 1630 uloop_timeout_set(&defer->timeout, c->timeout * 1000); 1631 } 1632 else { 1633 uc_vm_stack_push(vm, ucv_get(replycb)); 1634 uc_vm_stack_push(vm, ucv_int64_new(rv)); 1635 1636 if (uc_ubus_vm_call(vm, false, 1)) 1637 ucv_put(uc_vm_stack_pop(vm)); 1638 1639 ucv_put(res->res); 1640 } 1641 1642 return rv; 1643 } 1644 1645 /** 1646 * Invoke a ubus method asynchronously. 1647 * 1648 * Initiates a non-blocking call to the specified method on a ubus object. 1649 * The provided callback will be invoked when the response is received or on 1650 * timeout. 1651 * 1652 * Returns a deferred request resource representing the pending operation. 1653 * 1654 * Returns `null` if the deferred call could not be initiated. 1655 * 1656 * @function module:ubus.connection#defer 1657 * 1658 * @param {string} object 1659 * The object name to call the method on. 1660 * 1661 * @param {string} method 1662 * The name of the method to invoke. 1663 * 1664 * @param {Object} [data] 1665 * Optional method arguments as an object with field names and values. 1666 * 1667 * @param {function} [cb] 1668 * Callback function invoked when the operation completes. Receives status 1669 * code and response data as arguments. 1670 * 1671 * @param {function} [data_cb] 1672 * Optional callback invoked for intermediate data notifications. 1673 * 1674 * @param {number} [fd] 1675 * Optional file descriptor to send along with the call. 1676 * 1677 * @param {function} [fd_cb] 1678 * Optional callback function invoked when a file descriptor is received. 1679 * 1680 * @returns {?module:ubus.deferred} 1681 * 1682 * @example 1683 * // Asynchronous call with callback - typical pattern for RPC handlers 1684 * const conn = connect(); 1685 * 1686 * const req = conn.defer("some.object", "some_method", {}, (rc, data) => { 1687 * if (rc == 0) 1688 * printf("Result: %.J\n", data); 1689 * }); 1690 * 1691 * @example 1692 * // Persistent connection pattern - avoid GC by keeping reference 1693 * const ubus = connect(); 1694 * 1695 * function get_status(req) { 1696 * // Use persistent ubus connection for async calls 1697 * return ubus.defer("some.object", "some_method", {}, (rc, data) => { 1698 * req.reply({ result: data }); 1699 * }); 1700 * } 1701 */ 1702 static uc_value_t * 1703 uc_ubus_defer(uc_vm_t *vm, size_t nargs) 1704 { 1705 uc_value_t *objname, *funname, *funargs, *replycb, *datacb, *fd, *fdcb = NULL; 1706 uc_ubus_call_res_t res = { 0 }; 1707 uc_ubus_connection_t *c; 1708 uint32_t id; 1709 int rv; 1710 1711 conn_get(vm, &c); 1712 1713 args_get_named(vm, nargs, 1714 "object", UC_STRING, REQUIRED, &objname, 1715 "method", UC_STRING, REQUIRED, &funname, 1716 "data", UC_OBJECT, OPTIONAL, &funargs, 1717 "cb", UC_CLOSURE, OPTIONAL, &replycb, 1718 "data_cb", UC_CLOSURE, OPTIONAL, &datacb, 1719 "fd", 0, NAMED, &fd, 1720 "fd_cb", UC_CLOSURE, NAMED, &fdcb); 1721 1722 rv = ubus_lookup_id(&c->ctx, ucv_string_get(objname), &id); 1723 1724 if (rv != UBUS_STATUS_OK) 1725 err_return(rv, "Failed to resolve object name '%s'", 1726 ucv_string_get(objname)); 1727 1728 rv = uc_ubus_defer_common(vm, c, &res, id, funname, funargs, fd, fdcb, replycb, datacb); 1729 1730 if (rv != UBUS_STATUS_OK) 1731 err_return(rv, "Failed to invoke function '%s' on object '%s'", 1732 ucv_string_get(funname), ucv_string_get(objname)); 1733 1734 ok_return(res.res); 1735 } 1736 1737 /** 1738 * Send an asynchronous request on a channel connection. 1739 * 1740 * Similar to defer() but uses object ID 0 for channel-based communication. 1741 * 1742 * Returns a deferred request resource representing the pending operation. 1743 * 1744 * Returns `null` if the deferred call could not be initiated. 1745 * 1746 * @function module:ubus.channel#defer 1747 * 1748 * @param {string} method 1749 * The name of the method to invoke. 1750 * 1751 * @param {Object} [data] 1752 * Optional method arguments as an object with field names and values. 1753 * 1754 * @param {function} [cb] 1755 * Callback function invoked when the operation completes. 1756 * 1757 * @param {function} [data_cb] 1758 * Optional callback invoked for intermediate data notifications. 1759 * 1760 * @param {number} [fd] 1761 * Optional file descriptor to send along with the request. 1762 * 1763 * @param {function} [fd_cb] 1764 * Optional callback function invoked when a file descriptor is received. 1765 * 1766 * @returns {?module:ubus.deferred} 1767 * 1768 * @example 1769 * const chan = open_channel(…); 1770 * const req = chan.defer("method_name", { arg: "value" }, 1771 * (status, data) => { 1772 * printf("Status: %d\n", status); 1773 * }); 1774 */ 1775 static uc_value_t * 1776 uc_ubus_chan_defer(uc_vm_t *vm, size_t nargs) 1777 { 1778 uc_value_t *funname, *funargs, *replycb, *datacb, *fd, *fdcb = NULL; 1779 uc_ubus_call_res_t res = { 0 }; 1780 uc_ubus_connection_t *c; 1781 int rv; 1782 1783 conn_get(vm, &c); 1784 1785 args_get_named(vm, nargs, 1786 "method", UC_STRING, REQUIRED, &funname, 1787 "data", UC_OBJECT, OPTIONAL, &funargs, 1788 "cb", UC_CLOSURE, OPTIONAL, &replycb, 1789 "data_cb", UC_CLOSURE, OPTIONAL, &datacb, 1790 "fd", 0, NAMED, &fd, 1791 "fd_cb", UC_CLOSURE, NAMED, &fdcb); 1792 1793 rv = uc_ubus_defer_common(vm, c, &res, 0, funname, funargs, fd, fdcb, replycb, datacb); 1794 1795 if (rv != UBUS_STATUS_OK) 1796 err_return(rv, "Failed to invoke function '%s' on channel", 1797 ucv_string_get(funname)); 1798 1799 ok_return(res.res); 1800 } 1801 1802 1803 /* 1804 * ubus object request context functions 1805 * -------------------------------------------------------------------------- 1806 */ 1807 1808 static void 1809 uc_ubus_request_finish_common(uc_ubus_request_t *callctx, int code) 1810 { 1811 int fd; 1812 1813 fd = ubus_request_get_caller_fd(&callctx->req); 1814 1815 if (fd >= 0) 1816 close(fd); 1817 1818 callctx->replied = true; 1819 uloop_timeout_cancel(&callctx->timeout); 1820 ubus_complete_deferred_request(callctx->ctx, &callctx->req, code); 1821 } 1822 1823 static void 1824 uc_ubus_request_send_reply(uc_ubus_request_t *callctx, uc_value_t *reply) 1825 { 1826 if (!reply) 1827 return; 1828 1829 blob_buf_init(&buf, 0); 1830 ucv_object_to_blob(reply, &buf); 1831 ubus_send_reply(callctx->ctx, &callctx->req, buf.head); 1832 } 1833 1834 static void 1835 uc_ubus_request_finish(uc_ubus_request_t *callctx, int code) 1836 { 1837 if (callctx->replied) 1838 return; 1839 1840 uc_ubus_request_finish_common(callctx, code); 1841 uc_ubus_put_res(&callctx->res); 1842 } 1843 1844 static void 1845 uc_ubus_request_timeout(struct uloop_timeout *timeout) 1846 { 1847 uc_ubus_request_t *callctx = container_of(timeout, uc_ubus_request_t, timeout); 1848 1849 uc_ubus_request_finish(callctx, UBUS_STATUS_TIMEOUT); 1850 } 1851 1852 /** 1853 * Send a reply to a deferred ubus method call. 1854 * 1855 * Sends the specified reply data to the caller of a deferred method 1856 * request. After sending the reply, the request context is finished unless 1857 * `more` is set to `true`. 1858 * 1859 * Returns `true` on success. 1860 * 1861 * Returns `null` if an error occurred or the reply was already sent. 1862 * 1863 * @function module:ubus.request#reply 1864 * 1865 * @param {Object} [reply] 1866 * The reply data to send as an object with field names and values. 1867 * 1868 * @param {number} [rcode=0] 1869 * Optional status code to return. Use negative values to indicate more 1870 * replies will follow. 1871 * 1872 * @returns {?boolean} 1873 * 1874 * @example 1875 * // In a published object method handler 1876 * publish("my.service", { 1877 * "hello": (req, msg) => { 1878 * req.reply({ message: "Hello, " + msg.name }); 1879 * } 1880 * }); 1881 */ 1882 static uc_value_t * 1883 uc_ubus_request_reply(uc_vm_t *vm, size_t nargs) 1884 { 1885 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 1886 int64_t code = UBUS_STATUS_OK; 1887 uc_value_t *reply, *rcode; 1888 bool more = false; 1889 1890 if (!callctx) 1891 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid call context"); 1892 1893 args_get(vm, nargs, 1894 "reply", UC_OBJECT, true, &reply, 1895 "rcode", UC_INTEGER, true, &rcode); 1896 1897 if (callctx->replied) 1898 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Reply has already been sent"); 1899 1900 if (rcode) { 1901 code = ucv_int64_get(rcode); 1902 1903 if (errno == ERANGE || code < -1 || code > __UBUS_STATUS_LAST) 1904 code = UBUS_STATUS_UNKNOWN_ERROR; 1905 1906 if (code < 0) 1907 more = true; 1908 } 1909 1910 uc_ubus_request_send_reply(callctx, reply); 1911 1912 if (!more) 1913 uc_ubus_request_finish(callctx, code); 1914 1915 ok_return(ucv_boolean_new(true)); 1916 } 1917 1918 /** 1919 * Defer completion of a ubus method call. 1920 * 1921 * Marks the current request as deferred, allowing the handler to complete 1922 * the request asynchronously at a later time by calling reply(). 1923 * 1924 * Returns `true` on success. 1925 * 1926 * Returns `null` if an error occurred. 1927 * 1928 * @function module:ubus.request#defer 1929 * 1930 * @returns {?boolean} 1931 * 1932 * @example 1933 * // In a published object method handler 1934 * publish("my.service", { 1935 * "async_method": (req, msg) => { 1936 * req.defer(); 1937 * // Do async work... 1938 * req.reply({ result: "done" }); 1939 * } 1940 * }); 1941 */ 1942 static uc_value_t * 1943 uc_ubus_request_defer(uc_vm_t *vm, size_t nargs) 1944 { 1945 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 1946 1947 if (!callctx) 1948 return NULL; 1949 1950 callctx->deferred = true; 1951 return ucv_boolean_new(true); 1952 } 1953 1954 /** 1955 * Get the caller's file descriptor from a ubus method call. 1956 * 1957 * Returns the UNIX file descriptor number that was passed by the caller, 1958 * or -1 if no file descriptor was sent. 1959 * 1960 * @function module:ubus.request#get_fd 1961 * 1962 * @returns {number} 1963 * The file descriptor number, or -1 if none was provided. 1964 */ 1965 static uc_value_t * 1966 uc_ubus_request_get_fd(uc_vm_t *vm, size_t nargs) 1967 { 1968 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 1969 1970 if (!callctx) 1971 return NULL; 1972 1973 return ucv_int64_new(ubus_request_get_caller_fd(&callctx->req)); 1974 } 1975 1976 /** 1977 * Set a file descriptor to send with a ubus method reply. 1978 * 1979 * Associates a file descriptor with the current request to be sent back to 1980 * the caller along with the reply. 1981 * 1982 * Returns `true` on success. 1983 * 1984 * Returns `null` if an error occurred. 1985 * 1986 * @function module:ubus.request#set_fd 1987 * 1988 * @param {number} fd 1989 * The file descriptor number to send. 1990 * 1991 * @returns {?boolean} 1992 * 1993 * @example 1994 * // In a published object method handler 1995 * publish("my.service", { 1996 * "get_fd": (req, msg) => { 1997 * let fd = some_file_descriptor; 1998 * req.set_fd(fd); 1999 * req.reply({ info: "fd sent" }); 2000 * } 2001 * }); 2002 */ 2003 static uc_value_t * 2004 uc_ubus_request_set_fd(uc_vm_t *vm, size_t nargs) 2005 { 2006 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 2007 bool handle = false; 2008 int fd; 2009 2010 if (!callctx) 2011 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid call context"); 2012 2013 fd = get_fd(vm, uc_fn_arg(0), &handle); 2014 2015 if (fd < 0) 2016 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid file descriptor"); 2017 2018 if (handle) { 2019 fd = dup(fd); 2020 2021 if (fd < 0) 2022 err_return(UBUS_STATUS_UNKNOWN_ERROR, 2023 "Unable to duplicate file descriptor"); 2024 } 2025 2026 ubus_request_set_fd(callctx->ctx, &callctx->req, fd); 2027 2028 return ucv_boolean_new(true); 2029 } 2030 2031 /** 2032 * Finish a ubus method call with an error status. 2033 * 2034 * Completes the current deferred request with the specified error status 2035 * code without sending any reply data. 2036 * 2037 * Returns `true` on success. 2038 * 2039 * Returns `null` if an error occurred or the reply was already sent. 2040 * 2041 * @function module:ubus.request#error 2042 * 2043 * @param {number} [rcode=UBUS_STATUS_UNKNOWN_ERROR] 2044 * The error status code to return. 2045 * 2046 * @returns {?boolean} 2047 * 2048 * @example 2049 * // In a published object method handler 2050 * publish("my.service", { 2051 * "process": (req, msg) => { 2052 * if (!msg.input) { 2053 * req.error(UBUS_STATUS_INVALID_ARGUMENT); 2054 * return; 2055 * } 2056 * req.reply({ result: "ok" }); 2057 * } 2058 * }); 2059 */ 2060 static uc_value_t * 2061 uc_ubus_request_error(uc_vm_t *vm, size_t nargs) 2062 { 2063 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 2064 uc_value_t *rcode = uc_fn_arg(0); 2065 int64_t code; 2066 2067 if (!callctx) 2068 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid call context"); 2069 2070 args_get(vm, nargs, 2071 "rcode", UC_INTEGER, false, &rcode); 2072 2073 if (callctx->replied) 2074 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Reply has already been sent"); 2075 2076 code = ucv_int64_get(rcode); 2077 2078 if (errno == ERANGE || code < 0 || code > __UBUS_STATUS_LAST) 2079 code = UBUS_STATUS_UNKNOWN_ERROR; 2080 2081 uc_ubus_request_finish(callctx, code); 2082 2083 ok_return(ucv_boolean_new(true)); 2084 } 2085 2086 2087 /* 2088 * ubus object notify 2089 * -------------------------------------------------------------------------- 2090 */ 2091 2092 /** 2093 * Check if a notification request has completed. 2094 * 2095 * Returns `true` if the notification request has finished. 2096 * 2097 * Returns `false` if the request is still pending. 2098 * 2099 * @function module:ubus.notify#completed 2100 * 2101 * @returns {boolean} 2102 * 2103 * @example 2104 * const n = obj.notify("method", { data: "value" }); 2105 * if (n.completed()) { 2106 * printf("Notification sent\n"); 2107 * } 2108 */ 2109 static uc_value_t * 2110 uc_ubus_notify_completed(uc_vm_t *vm, size_t nargs) 2111 { 2112 uc_ubus_notify_t *notifyctx = uc_fn_thisval("ubus.notify"); 2113 2114 ok_return(ucv_boolean_new(notifyctx->complete)); 2115 } 2116 2117 /** 2118 * Abort a pending notification request. 2119 * 2120 * Cancels an asynchronous notification request that has not yet completed. 2121 * 2122 * Returns `true` if the request was aborted. 2123 * 2124 * Returns `false` if the request was already completed. 2125 * 2126 * @function module:ubus.notify#abort 2127 * 2128 * @returns {boolean} 2129 * 2130 * @example 2131 * const n = obj.notify("method", { data: "value" }); 2132 * if (!n.completed()) { 2133 * n.abort(); 2134 * } 2135 */ 2136 static uc_value_t * 2137 uc_ubus_notify_abort(uc_vm_t *vm, size_t nargs) 2138 { 2139 uc_ubus_notify_t *notifyctx = uc_fn_thisval("ubus.notify"); 2140 2141 if (notifyctx->complete) 2142 ok_return(ucv_boolean_new(false)); 2143 2144 ubus_abort_request(notifyctx->ctx, ¬ifyctx->req.req); 2145 notifyctx->complete = true; 2146 uc_ubus_put_res(¬ifyctx->res); 2147 2148 ok_return(ucv_boolean_new(true)); 2149 } 2150 2151 static void 2152 uc_ubus_object_notify_data_cb(struct ubus_notify_request *req, int type, struct blob_attr *msg) 2153 { 2154 uc_ubus_notify_t *notifyctx = (uc_ubus_notify_t *)req; 2155 uc_vm_t *vm = notifyctx->vm; 2156 uc_value_t *this, *func; 2157 2158 this = notifyctx->res; 2159 func = ucv_resource_value_get(this, NOTIFY_RES_DATA_CB); 2160 2161 if (ucv_is_callable(func)) { 2162 uc_vm_stack_push(vm, ucv_get(this)); 2163 uc_vm_stack_push(vm, ucv_get(func)); 2164 uc_vm_stack_push(vm, ucv_int64_new(type)); 2165 uc_vm_stack_push(vm, blob_array_to_ucv(vm, blob_data(msg), blob_len(msg), true)); 2166 2167 if (uc_ubus_vm_call(vm, true, 2)) 2168 ucv_put(uc_vm_stack_pop(vm)); 2169 } 2170 } 2171 2172 static void 2173 uc_ubus_object_notify_status_cb(struct ubus_notify_request *req, int idx, int ret) 2174 { 2175 uc_ubus_notify_t *notifyctx = (uc_ubus_notify_t *)req; 2176 uc_vm_t *vm = notifyctx->vm; 2177 uc_value_t *this, *func; 2178 2179 this = notifyctx->res; 2180 func = ucv_resource_value_get(this, NOTIFY_RES_STATUS_CB); 2181 2182 if (ucv_is_callable(func)) { 2183 uc_vm_stack_push(vm, ucv_get(this)); 2184 uc_vm_stack_push(vm, ucv_get(func)); 2185 uc_vm_stack_push(vm, ucv_int64_new(idx)); 2186 uc_vm_stack_push(vm, ucv_int64_new(ret)); 2187 2188 if (uc_ubus_vm_call(vm, true, 2)) 2189 ucv_put(uc_vm_stack_pop(vm)); 2190 } 2191 } 2192 2193 static void 2194 uc_ubus_object_notify_complete_cb(struct ubus_notify_request *req, int idx, int ret) 2195 { 2196 uc_ubus_notify_t *notifyctx = (uc_ubus_notify_t *)req; 2197 uc_vm_t *vm = notifyctx->vm; 2198 uc_value_t *this, *func; 2199 2200 this = ucv_get(notifyctx->res); 2201 func = ucv_resource_value_get(this, NOTIFY_RES_CB); 2202 2203 if (ucv_is_callable(func)) { 2204 uc_vm_stack_push(vm, ucv_get(this)); 2205 uc_vm_stack_push(vm, ucv_get(func)); 2206 uc_vm_stack_push(vm, ucv_int64_new(idx)); 2207 uc_vm_stack_push(vm, ucv_int64_new(ret)); 2208 2209 if (uc_ubus_vm_call(vm, true, 2)) 2210 ucv_put(uc_vm_stack_pop(vm)); 2211 } 2212 2213 notifyctx->complete = true; 2214 uc_ubus_put_res(¬ifyctx->res); 2215 ucv_put(this); 2216 } 2217 2218 /** 2219 * Send a notification from a ubus object. 2220 * 2221 * Sends an asynchronous notification of the specified type to all 2222 * subscribers of the object. Optional callbacks can be provided to handle 2223 * data, status, and completion events. 2224 * 2225 * Returns a notification request resource for asynchronous operations. 2226 * 2227 * Returns a status code number when a synchronous timeout is specified. 2228 * 2229 * Returns `null` if the notification could not be sent. 2230 * 2231 * @function module:ubus.object#notify 2232 * 2233 * @param {string} type 2234 * The notification type string. 2235 * 2236 * @param {Object} [data] 2237 * Optional notification data as an object with field names and values. 2238 * 2239 * @param {function} [data_cb] 2240 * Optional callback invoked for each data notification received. 2241 * 2242 * @param {function} [status_cb] 2243 * Optional callback invoked for status updates. 2244 * 2245 * @param {function} [cb] 2246 * Optional callback invoked when the notification operation completes. 2247 * 2248 * @param {number} [timeout] 2249 * Optional timeout in milliseconds. If specified, the operation waits 2250 * synchronously for completion. 2251 * 2252 * @returns {?module:ubus.notify|?number} 2253 * 2254 * @example 2255 * const obj = publish("my.service", { 2256 * "trigger": (req, msg) => { 2257 * obj.notify("update", { key: "value" }, (idx, ret) => { 2258 * printf("Notification %d: status %d\n", idx, ret); 2259 * }); 2260 * req.reply({ sent: true }); 2261 * } 2262 * }); 2263 */ 2264 static uc_value_t * 2265 uc_ubus_object_notify(uc_vm_t *vm, size_t nargs) 2266 { 2267 uc_value_t *typename, *message, *data_cb, *status_cb, *complete_cb, *timeout; 2268 uc_ubus_object_t *uuobj = uc_fn_thisval("ubus.object"); 2269 uc_ubus_notify_t *notifyctx = NULL; 2270 uc_value_t *res; 2271 int64_t t; 2272 int rv = UBUS_STATUS_UNKNOWN_ERROR; 2273 2274 if (!uuobj) 2275 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid object context"); 2276 2277 args_get_named(vm, nargs, 2278 "type", UC_STRING, REQUIRED, &typename, 2279 "data", UC_OBJECT, OPTIONAL, &message, 2280 "data_cb", UC_CLOSURE, OPTIONAL, &data_cb, 2281 "status_cb", UC_CLOSURE, OPTIONAL, &status_cb, 2282 "cb", UC_CLOSURE, OPTIONAL, &complete_cb, 2283 "timeout", UC_INTEGER, OPTIONAL, &timeout); 2284 2285 t = timeout ? ucv_int64_get(timeout) : -1; 2286 2287 if (errno) 2288 err_return(UBUS_STATUS_INVALID_ARGUMENT, 2289 "Invalid timeout value: %s", strerror(errno)); 2290 2291 res = ucv_resource_create_ex(vm, "ubus.notify", (void **)¬ifyctx, __NOTIFY_RES_MAX, sizeof(*notifyctx)); 2292 2293 if (!notifyctx) 2294 err_return(rv, "Out of memory"); 2295 2296 notifyctx->vm = vm; 2297 notifyctx->ctx = uuobj->ctx; 2298 2299 blob_buf_init(&buf, 0); 2300 2301 if (message) 2302 ucv_object_to_blob(message, &buf); 2303 2304 rv = ubus_notify_async(uuobj->ctx, &uuobj->obj, 2305 ucv_string_get(typename), buf.head, 2306 ¬ifyctx->req); 2307 2308 if (rv != UBUS_STATUS_OK) { 2309 ucv_put(res); 2310 err_return(rv, "Failed to send notification"); 2311 } 2312 2313 notifyctx->res = ucv_get(res); 2314 notifyctx->req.data_cb = uc_ubus_object_notify_data_cb; 2315 notifyctx->req.status_cb = uc_ubus_object_notify_status_cb; 2316 notifyctx->req.complete_cb = uc_ubus_object_notify_complete_cb; 2317 2318 ucv_resource_value_set(res, NOTIFY_RES_CONN, ucv_get(uuobj->res)); 2319 ucv_resource_value_set(res, NOTIFY_RES_CB, ucv_get(complete_cb)); 2320 ucv_resource_value_set(res, NOTIFY_RES_DATA_CB, ucv_get(data_cb)); 2321 ucv_resource_value_set(res, NOTIFY_RES_STATUS_CB, ucv_get(status_cb)); 2322 2323 if (t >= 0) { 2324 rv = ubus_complete_request(uuobj->ctx, ¬ifyctx->req.req, t); 2325 2326 ucv_put(res); 2327 2328 ok_return(ucv_int64_new(rv)); 2329 } 2330 2331 ucv_resource_persistent_set(res, true); 2332 ubus_complete_request_async(uuobj->ctx, ¬ifyctx->req.req); 2333 2334 ok_return(res); 2335 } 2336 2337 2338 /* 2339 * ubus object remove 2340 * -------------------------------------------------------------------------- 2341 */ 2342 2343 static int 2344 uc_ubus_object_remove_common(uc_ubus_object_t *uuobj) 2345 { 2346 int rv = ubus_remove_object(uuobj->ctx, &uuobj->obj); 2347 2348 if (rv != UBUS_STATUS_OK) 2349 return rv; 2350 2351 uc_ubus_put_res(&uuobj->res); 2352 2353 return rv; 2354 } 2355 2356 /** 2357 * Remove a ubus object from the bus. 2358 * 2359 * Unregisters the object from the ubus bus, making it no longer accessible 2360 * to other clients. 2361 * 2362 * Returns `true` on success. 2363 * 2364 * Returns `null` if the object could not be removed. 2365 * 2366 * @function module:ubus.object#remove 2367 * 2368 * @returns {?boolean} 2369 * 2370 * @example 2371 * const obj = publish("my.service", { … }); 2372 * // … do work … 2373 * obj.remove(); 2374 */ 2375 static uc_value_t * 2376 uc_ubus_object_remove(uc_vm_t *vm, size_t nargs) 2377 { 2378 uc_ubus_object_t *uuobj = uc_fn_thisval("ubus.object"); 2379 int rv; 2380 2381 if (!uuobj) 2382 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid object context"); 2383 2384 rv = uc_ubus_object_remove_common(uuobj); 2385 2386 if (rv != UBUS_STATUS_OK) 2387 err_return(rv, "Failed to remove object"); 2388 2389 ok_return(ucv_boolean_new(true)); 2390 } 2391 2392 2393 /* 2394 * ubus object subscription status 2395 */ 2396 2397 /** 2398 * Check if a ubus object has subscribers. 2399 * 2400 * Returns `true` if there are active subscribers to the object. 2401 * 2402 * Returns `false` if no subscribers are currently connected. 2403 * 2404 * @function module:ubus.object#subscribed 2405 * 2406 * @returns {boolean} 2407 * 2408 * @example 2409 * const obj = publish("my.service", { 2410 * "trigger": (req, msg) => { 2411 * if (obj.subscribed()) { 2412 * obj.notify("update", { data: "value" }); 2413 * } 2414 * req.reply({ notified: obj.subscribed() }); 2415 * } 2416 * }); 2417 */ 2418 static uc_value_t * 2419 uc_ubus_object_subscribed(uc_vm_t *vm, size_t nargs) 2420 { 2421 uc_ubus_object_t *uuobj = uc_fn_thisval("ubus.object"); 2422 2423 if (!uuobj) 2424 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid object context"); 2425 2426 ok_return(ucv_boolean_new(uuobj->obj.has_subscribers)); 2427 } 2428 2429 2430 /* 2431 * ubus object method call handling 2432 * -------------------------------------------------------------------------- 2433 */ 2434 2435 static int 2436 uc_ubus_object_call_args(struct ubus_object *obj, const char *ubus_method_name, 2437 struct blob_attr *msg, uc_value_t **res) 2438 { 2439 uc_ubus_object_t *uuobj = (uc_ubus_object_t *)obj; 2440 const struct ubus_method *method = NULL; 2441 const struct blobmsg_hdr *hdr; 2442 struct blob_attr *attr; 2443 size_t len; 2444 bool found; 2445 int i; 2446 2447 for (i = 0; i < obj->n_methods; i++) { 2448 if (!strcmp(obj->methods[i].name, ubus_method_name)) { 2449 method = &obj->methods[i]; 2450 break; 2451 } 2452 } 2453 2454 if (!method) 2455 return UBUS_STATUS_METHOD_NOT_FOUND; 2456 2457 len = blob_len(msg); 2458 2459 __blob_for_each_attr(attr, blob_data(msg), len) { 2460 if (!blobmsg_check_attr_len(attr, false, len)) 2461 return UBUS_STATUS_INVALID_ARGUMENT; 2462 2463 if (!blob_is_extended(attr)) 2464 return UBUS_STATUS_INVALID_ARGUMENT; 2465 2466 hdr = blob_data(attr); 2467 found = false; 2468 2469 for (i = 0; i < method->n_policy; i++) { 2470 if (blobmsg_namelen(hdr) != strlen(method->policy[i].name)) 2471 continue; 2472 2473 if (strcmp(method->policy[i].name, (char *)hdr->name)) 2474 continue; 2475 2476 /* named argument found but wrong type */ 2477 if (blob_id(attr) != method->policy[i].type) 2478 goto inval; 2479 2480 found = true; 2481 break; 2482 } 2483 2484 /* named argument not found in policy */ 2485 if (!found) 2486 goto inval; 2487 } 2488 2489 *res = blob_array_to_ucv(uuobj->vm, blob_data(msg), blob_len(msg), true); 2490 2491 return UBUS_STATUS_OK; 2492 2493 inval: 2494 *res = NULL; 2495 2496 return UBUS_STATUS_INVALID_ARGUMENT; 2497 } 2498 2499 static uc_value_t * 2500 uc_ubus_object_call_info(uc_vm_t *vm, 2501 struct ubus_context *ctx, struct ubus_request_data *req, 2502 struct ubus_object *obj, const char *ubus_method_name) 2503 { 2504 uc_value_t *info, *o; 2505 2506 info = ucv_object_new(vm); 2507 2508 o = ucv_object_new(vm); 2509 2510 ucv_object_add(o, "user", ucv_string_new(req->acl.user)); 2511 ucv_object_add(o, "group", ucv_string_new(req->acl.group)); 2512 2513 if (req->acl.object) 2514 ucv_object_add(o, "object", ucv_string_new(req->acl.object)); 2515 2516 ucv_object_add(info, "acl", o); 2517 2518 o = ucv_object_new(vm); 2519 2520 ucv_object_add(o, "id", ucv_int64_new(obj->id)); 2521 2522 if (obj->name) 2523 ucv_object_add(o, "name", ucv_string_new(obj->name)); 2524 2525 if (obj->path) 2526 ucv_object_add(o, "path", ucv_string_new(obj->path)); 2527 2528 ucv_object_add(info, "object", o); 2529 2530 if (ubus_method_name) 2531 ucv_object_add(info, "method", ucv_string_new(ubus_method_name)); 2532 2533 return info; 2534 } 2535 2536 static int 2537 uc_ubus_handle_reply_common(struct ubus_context *ctx, 2538 struct ubus_request_data *req, 2539 uc_vm_t *vm, uc_value_t *this, uc_value_t *func, 2540 uc_value_t *reqproto) 2541 { 2542 uc_ubus_connection_t *conn = container_of(ctx, uc_ubus_connection_t, ctx); 2543 uc_ubus_request_t *callctx = NULL; 2544 uc_value_t *reqobj, *res; 2545 int rv; 2546 2547 /* allocate deferred method call context. 2548 * 2549 * reqproto is a per-call object, so it must be stored in the request 2550 * resource's instance-specific prototype slot rather than being attached 2551 * to the shared "ubus.request" type prototype. The latter would leak the 2552 * per-call object (and everything it references) into the type prototype 2553 * for the lifetime of the VM, and cause a use-after-free at teardown: 2554 * uc_vm_free() releases the restype prototypes before the final GC, so 2555 * the shared type prototype is freed while still pointing at the 2556 * per-call object, which is then freed again as an unreachable value. 2557 * 2558 * ucv_resource_create_with_proto() takes ownership of reqproto and 2559 * chains it to the type prototype, so property lookup on reqobj still 2560 * falls through to the shared request methods. 2561 */ 2562 reqobj = ucv_resource_create_with_proto(vm, "ubus.request", 2563 (void **)&callctx, 1, sizeof(*callctx), reqproto); 2564 2565 if (!callctx) 2566 return UBUS_STATUS_UNKNOWN_ERROR; 2567 2568 callctx->ctx = ctx; 2569 callctx->vm = vm; 2570 ucv_resource_value_set(reqobj, 0, ucv_get(conn->res)); 2571 2572 ubus_defer_request(ctx, req, &callctx->req); 2573 2574 /* fd is copied to deferred request. ensure it does not get closed early */ 2575 ubus_request_get_caller_fd(req); 2576 2577 /* push object context, handler and request object onto stack */ 2578 uc_vm_stack_push(vm, ucv_get(this)); 2579 uc_vm_stack_push(vm, ucv_get(func)); 2580 uc_vm_stack_push(vm, ucv_get(reqobj)); 2581 2582 /* execute request handler function */ 2583 switch (uc_vm_call(vm, true, 1)) { 2584 case EXCEPTION_NONE: 2585 res = uc_vm_stack_pop(vm); 2586 2587 /* The handler function invoked a nested aync ubus request and returned it */ 2588 if (ucv_resource_data(res, "ubus.deferred")) { 2589 /* Install guard timer in case the reply callback is never called */ 2590 callctx->timeout.cb = uc_ubus_request_timeout; 2591 uloop_timeout_set(&callctx->timeout, 10000 /* FIXME */); 2592 callctx->res = ucv_get(reqobj); 2593 ucv_resource_persistent_set(callctx->res, true); 2594 } 2595 2596 /* Otherwise, when the function returned an object, treat it as 2597 * reply data and conclude deferred request immediately */ 2598 else if (ucv_type(res) == UC_OBJECT) { 2599 blob_buf_init(&buf, 0); 2600 ucv_object_to_blob(res, &buf); 2601 ubus_send_reply(ctx, &callctx->req, buf.head); 2602 2603 uc_ubus_request_finish_common(callctx, UBUS_STATUS_OK); 2604 } 2605 2606 /* If neither a deferred ubus request, nor a plain object were 2607 * returned and if reqobj.reply() hasn't been called, immediately 2608 * finish deferred request with UBUS_STATUS_NO_DATA. */ 2609 else if (!callctx->replied && !callctx->deferred) { 2610 rv = UBUS_STATUS_NO_DATA; 2611 2612 if (ucv_type(res) == UC_INTEGER) { 2613 rv = (int)ucv_int64_get(res); 2614 2615 if (rv < 0 || rv > __UBUS_STATUS_LAST) 2616 rv = UBUS_STATUS_UNKNOWN_ERROR; 2617 } 2618 2619 uc_ubus_request_finish_common(callctx, rv); 2620 } 2621 2622 ucv_put(res); 2623 break; 2624 2625 /* if the handler function invoked exit(), forward exit status as ubus 2626 * return code, map out of range values to UBUS_STATUS_UNKNOWN_ERROR. */ 2627 case EXCEPTION_EXIT: 2628 rv = vm->arg.s32; 2629 2630 if (rv < UBUS_STATUS_OK || rv >= __UBUS_STATUS_LAST) 2631 rv = UBUS_STATUS_UNKNOWN_ERROR; 2632 2633 uc_ubus_request_finish_common(callctx, rv); 2634 break; 2635 2636 /* treat other exceptions as fatal and halt uloop */ 2637 default: 2638 uc_ubus_request_finish_common(callctx, UBUS_STATUS_UNKNOWN_ERROR); 2639 uc_ubus_vm_handle_exception(vm); 2640 break; 2641 } 2642 2643 /* release request object */ 2644 ucv_put(reqobj); 2645 2646 return UBUS_STATUS_OK; 2647 } 2648 2649 static int 2650 uc_ubus_object_call_cb(struct ubus_context *ctx, struct ubus_object *obj, 2651 struct ubus_request_data *req, const char *ubus_method_name, 2652 struct blob_attr *msg) 2653 { 2654 uc_value_t *func, *args = NULL, *reqproto, *methods; 2655 uc_ubus_object_t *uuobj = (uc_ubus_object_t *)obj; 2656 int rv; 2657 2658 methods = ucv_resource_value_get(uuobj->res, OBJ_RES_METHODS); 2659 func = ucv_object_get(ucv_object_get(methods, ubus_method_name, NULL), "call", NULL); 2660 2661 if (!ucv_is_callable(func)) 2662 return UBUS_STATUS_METHOD_NOT_FOUND; 2663 2664 rv = uc_ubus_object_call_args(obj, ubus_method_name, msg, &args); 2665 2666 if (rv != UBUS_STATUS_OK) 2667 return rv; 2668 2669 reqproto = ucv_object_new(uuobj->vm); 2670 2671 ucv_object_add(reqproto, "args", args); 2672 ucv_object_add(reqproto, "info", 2673 uc_ubus_object_call_info(uuobj->vm, ctx, req, obj, ubus_method_name)); 2674 2675 return uc_ubus_handle_reply_common(ctx, req, uuobj->vm, uuobj->res, func, reqproto); 2676 } 2677 2678 2679 /* 2680 * ubus object registration 2681 * -------------------------------------------------------------------------- 2682 */ 2683 2684 static void 2685 uc_ubus_object_subscribe_cb(struct ubus_context *ctx, struct ubus_object *obj) 2686 { 2687 uc_ubus_object_t *uuobj = (uc_ubus_object_t *)obj; 2688 uc_value_t *func; 2689 2690 func = ucv_resource_value_get(uuobj->res, OBJ_RES_SUB_CB); 2691 2692 uc_vm_stack_push(uuobj->vm, ucv_get(uuobj->res)); 2693 uc_vm_stack_push(uuobj->vm, ucv_get(func)); 2694 2695 if (uc_ubus_vm_call(uuobj->vm, true, 0)) 2696 ucv_put(uc_vm_stack_pop(uuobj->vm)); 2697 } 2698 2699 static bool 2700 uc_ubus_object_methods_validate(uc_value_t *methods) 2701 { 2702 uc_value_t *func, *args; 2703 2704 ucv_object_foreach(methods, ubus_method_name, ubus_method_definition) { 2705 (void)ubus_method_name; 2706 2707 func = ucv_object_get(ubus_method_definition, "call", NULL); 2708 args = ucv_object_get(ubus_method_definition, "args", NULL); 2709 2710 if (!ucv_is_callable(func)) 2711 err_return(UBUS_STATUS_INVALID_ARGUMENT, 2712 "Method '%s' field 'call' is not a function value", 2713 ubus_method_name); 2714 2715 if (args) { 2716 if (ucv_type(args) != UC_OBJECT) 2717 err_return(UBUS_STATUS_INVALID_ARGUMENT, 2718 "Method '%s' field 'args' is not an object value", 2719 ubus_method_name); 2720 2721 ucv_object_foreach(args, ubus_argument_name, ubus_argument_typehint) { 2722 (void)ubus_argument_name; 2723 2724 switch (ucv_type(ubus_argument_typehint)) { 2725 case UC_BOOLEAN: 2726 case UC_INTEGER: 2727 case UC_DOUBLE: 2728 case UC_STRING: 2729 case UC_ARRAY: 2730 case UC_OBJECT: 2731 continue; 2732 2733 default: 2734 err_return(UBUS_STATUS_INVALID_ARGUMENT, 2735 "Method '%s' field 'args' argument '%s' hint has unsupported type %s", 2736 ubus_method_name, ubus_argument_name, 2737 ucv_typename(ubus_argument_typehint)); 2738 } 2739 } 2740 } 2741 } 2742 2743 ok_return(true); 2744 } 2745 2746 static bool 2747 uc_ubus_object_method_register(struct ubus_method *method, const char *ubus_method_name, 2748 uc_value_t *ubus_method_arguments) 2749 { 2750 struct blobmsg_policy *policy; 2751 enum blobmsg_type type; 2752 2753 method->name = strdup(ubus_method_name); 2754 method->policy = calloc(ucv_object_length(ubus_method_arguments), sizeof(*method->policy)); 2755 method->handler = uc_ubus_object_call_cb; 2756 2757 if (!method->name || !method->policy) 2758 return false; 2759 2760 ucv_object_foreach(ubus_method_arguments, ubus_argument_name, ubus_argument_typehint) { 2761 switch (ucv_type(ubus_argument_typehint)) { 2762 case UC_BOOLEAN: 2763 type = BLOBMSG_TYPE_INT8; 2764 break; 2765 2766 case UC_INTEGER: 2767 switch (ucv_int64_get(ubus_argument_typehint)) { 2768 case 8: 2769 type = BLOBMSG_TYPE_INT8; 2770 break; 2771 2772 case 16: 2773 type = BLOBMSG_TYPE_INT16; 2774 break; 2775 2776 case 64: 2777 type = BLOBMSG_TYPE_INT64; 2778 break; 2779 2780 default: 2781 type = BLOBMSG_TYPE_INT32; 2782 break; 2783 } 2784 2785 break; 2786 2787 case UC_DOUBLE: 2788 type = BLOBMSG_TYPE_DOUBLE; 2789 break; 2790 2791 case UC_ARRAY: 2792 type = BLOBMSG_TYPE_ARRAY; 2793 break; 2794 2795 case UC_OBJECT: 2796 type = BLOBMSG_TYPE_TABLE; 2797 break; 2798 2799 default: 2800 type = BLOBMSG_TYPE_STRING; 2801 break; 2802 } 2803 2804 policy = (struct blobmsg_policy *)&method->policy[method->n_policy++]; 2805 policy->type = type; 2806 policy->name = strdup(ubus_argument_name); 2807 2808 if (!policy->name) 2809 return false; 2810 } 2811 2812 return true; 2813 } 2814 2815 static uc_ubus_object_t * 2816 uc_ubus_object_register(uc_vm_t *vm, uc_ubus_connection_t *c, const char *ubus_object_name, 2817 uc_value_t *ubus_object_methods) 2818 { 2819 struct ubus_context *ctx = &c->ctx; 2820 const struct blobmsg_policy *policy; 2821 uc_ubus_object_t *uuobj = NULL; 2822 int rv = UBUS_STATUS_UNKNOWN_ERROR; 2823 char *tnptr, *onptr; 2824 struct ubus_method *method; 2825 struct ubus_object *obj; 2826 size_t len, typelen, namelen, methodlen; 2827 uc_value_t *args, *res; 2828 2829 namelen = strlen(ubus_object_name); 2830 typelen = strlen("ucode-ubus-") + namelen; 2831 methodlen = ucv_object_length(ubus_object_methods) * sizeof(struct ubus_method); 2832 len = sizeof(*uuobj) + methodlen + namelen + 1 + typelen + 1; 2833 2834 res = ucv_resource_create_ex(vm, "ubus.object", (void **)&uuobj, __OBJ_RES_MAX, len); 2835 2836 if (!uuobj) 2837 err_return(rv, "Out of memory"); 2838 2839 method = uuobj->methods; 2840 2841 obj = &uuobj->obj; 2842 obj->methods = method; 2843 2844 if (ubus_object_methods) { 2845 ucv_object_foreach(ubus_object_methods, ubus_method_name, ubus_method_definition) { 2846 args = ucv_object_get(ubus_method_definition, "args", NULL); 2847 2848 if (!uc_ubus_object_method_register(&method[obj->n_methods++], ubus_method_name, args)) 2849 goto out; 2850 } 2851 } 2852 2853 onptr = (char *)&uuobj->methods[obj->n_methods]; 2854 tnptr = onptr + namelen + 1; 2855 2856 snprintf(tnptr, typelen, "ucode-ubus-%s", ubus_object_name); 2857 obj->name = memcpy(onptr, ubus_object_name, namelen); 2858 2859 obj->type = (struct ubus_object_type *)&uuobj->type; 2860 obj->type->name = tnptr; 2861 obj->type->methods = obj->methods; 2862 obj->type->n_methods = obj->n_methods; 2863 2864 rv = ubus_add_object(ctx, obj); 2865 2866 if (rv != UBUS_STATUS_OK) 2867 goto out; 2868 2869 uuobj->vm = vm; 2870 uuobj->ctx = ctx; 2871 uuobj->res = ucv_get(res); 2872 ucv_resource_persistent_set(res, true); 2873 ucv_resource_value_set(res, OBJ_RES_CONN, ucv_get(c->res)); 2874 ucv_resource_value_set(res, OBJ_RES_METHODS, ucv_get(ubus_object_methods)); 2875 2876 return uuobj; 2877 2878 out: 2879 for (; obj->n_methods > 0; method++, obj->n_methods--) { 2880 for (policy = method->policy; method->n_policy > 0; policy++, method->n_policy--) 2881 free((char *)policy->name); 2882 2883 free((char *)method->name); 2884 free((char *)method->policy); 2885 } 2886 2887 ucv_put(res); 2888 2889 err_return(rv, "Unable to add ubus object"); 2890 } 2891 2892 /** 2893 * Publish a ubus object on the bus. 2894 * 2895 * Registers a new object with the specified name and methods on the ubus 2896 * bus. The object can define method handlers and an optional subscribe 2897 * callback. 2898 * 2899 * Returns an object resource representing the published object. 2900 * 2901 * Returns `null` if the object could not be registered. 2902 * 2903 * @function module:ubus.connection#publish 2904 * 2905 * @param {string} object_name 2906 * The name to register the object under. 2907 * 2908 * @param {Object} [methods] 2909 * Optional object defining methods with `call` functions and optional 2910 * `args` type specifications. 2911 * 2912 * @param {function} [subscribe_callback] 2913 * Optional callback invoked when a subscriber connects to the object. 2914 * 2915 * @returns {?module:ubus.object} 2916 * 2917 * @example 2918 * const conn = connect(); 2919 * const obj = conn.publish("my.service", { 2920 * "hello": { 2921 * call: (req, msg) => { 2922 * req.reply({ message: "Hello, " + msg.name }); 2923 * }, 2924 * args: { name: "string" } 2925 * } 2926 * }); 2927 */ 2928 static uc_value_t * 2929 uc_ubus_publish(uc_vm_t *vm, size_t nargs) 2930 { 2931 uc_value_t *objname, *methods, *subscribecb; 2932 uc_ubus_connection_t *c; 2933 uc_ubus_object_t *uuobj; 2934 2935 conn_get(vm, &c); 2936 2937 args_get(vm, nargs, 2938 "object name", UC_STRING, false, &objname, 2939 "object methods", UC_OBJECT, true, &methods, 2940 "subscribe callback", UC_CLOSURE, true, &subscribecb); 2941 2942 if (!methods && !subscribecb) 2943 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Either methods or subscribe callback required"); 2944 2945 if (methods && !uc_ubus_object_methods_validate(methods)) 2946 return NULL; 2947 2948 uuobj = uc_ubus_object_register(vm, c, ucv_string_get(objname), methods); 2949 2950 if (!uuobj) 2951 return NULL; 2952 2953 if (subscribecb) { 2954 uuobj->obj.subscribe_cb = uc_ubus_object_subscribe_cb; 2955 ucv_resource_value_set(uuobj->res, OBJ_RES_SUB_CB, ucv_get(subscribecb)); 2956 } 2957 2958 ok_return(uuobj->res); 2959 } 2960 2961 2962 /* 2963 * ubus events 2964 * -------------------------------------------------------------------------- 2965 */ 2966 2967 static int 2968 uc_ubus_listener_remove_common(uc_ubus_listener_t *uul) 2969 { 2970 int rv = ubus_unregister_event_handler(uul->ctx, &uul->ev); 2971 2972 if (rv == UBUS_STATUS_OK) 2973 uc_ubus_put_res(&uul->res); 2974 2975 return rv; 2976 } 2977 2978 /** 2979 * Remove an event listener from the bus. 2980 * 2981 * Unregisters the event handler, stopping it from receiving further events. 2982 * 2983 * Returns `true` on success. 2984 * 2985 * Returns `null` if the listener could not be removed. 2986 * 2987 * @function module:ubus.listener#remove 2988 * 2989 * @returns {?boolean} 2990 * 2991 * @example 2992 * const listener = conn.listener("my.event.*", (type, data) => { 2993 * printf("Event: %s, Data: %.J\n", type, data); 2994 * }); 2995 * // … later … 2996 * listener.remove(); 2997 */ 2998 static uc_value_t * 2999 uc_ubus_listener_remove(uc_vm_t *vm, size_t nargs) 3000 { 3001 uc_ubus_listener_t *uul = uc_fn_thisval("ubus.listener"); 3002 int rv; 3003 3004 rv = uc_ubus_listener_remove_common(uul); 3005 3006 if (rv != UBUS_STATUS_OK) 3007 err_return(rv, "Failed to remove listener object"); 3008 3009 ok_return(ucv_boolean_new(true)); 3010 } 3011 3012 static void 3013 uc_ubus_listener_cb(struct ubus_context *ctx, struct ubus_event_handler *ev, 3014 const char *type, struct blob_attr *msg) 3015 { 3016 uc_ubus_listener_t *uul = (uc_ubus_listener_t *)ev; 3017 uc_value_t *this, *func; 3018 uc_vm_t *vm = uul->vm; 3019 3020 this = uul->res; 3021 func = ucv_resource_value_get(this, LISTEN_RES_CB); 3022 3023 uc_vm_stack_push(vm, ucv_get(this)); 3024 uc_vm_stack_push(vm, ucv_get(func)); 3025 uc_vm_stack_push(vm, ucv_string_new(type)); 3026 uc_vm_stack_push(vm, blob_array_to_ucv(vm, blob_data(msg), blob_len(msg), true)); 3027 3028 if (uc_ubus_vm_call(vm, true, 2)) 3029 ucv_put(uc_vm_stack_pop(vm)); 3030 } 3031 3032 3033 3034 /** 3035 * Register an event listener. 3036 * 3037 * Registers a callback to be invoked when events matching the specified 3038 * pattern are received. The listener receives the event type and data. 3039 * 3040 * Returns a listener resource that can be removed via 3041 * {@link module:ubus.listener#remove|remove()}. 3042 * 3043 * Returns `null` if the listener could not be registered. 3044 * 3045 * @function module:ubus.connection#listener 3046 * 3047 * @param {string} pattern 3048 * The event type pattern to match, supporting wildcards (e.g., 3049 * `` `system.*` ``, `` `my.event.?` ``). 3050 * 3051 * @param {function} cb 3052 * Callback invoked when a matching event is received. Receives the event 3053 * type string and event data object as arguments. 3054 * 3055 * @returns {?module:ubus.listener} 3056 * 3057 * @example 3058 * const conn = connect(); 3059 * const listener = conn.listener("system.*", (type, data) => { 3060 * printf("Event %s: %.J\n", type, data); 3061 * }); 3062 */ 3063 static uc_value_t * 3064 uc_ubus_listener(uc_vm_t *vm, size_t nargs) 3065 { 3066 uc_value_t *cb, *pattern; 3067 uc_ubus_connection_t *c; 3068 uc_ubus_listener_t *uul = NULL; 3069 uc_value_t *res; 3070 int rv; 3071 3072 conn_get(vm, &c); 3073 3074 args_get(vm, nargs, 3075 "event type pattern", UC_STRING, false, &pattern, 3076 "event callback", UC_CLOSURE, false, &cb); 3077 3078 res = ucv_resource_create_ex(vm, "ubus.listener", (void **)&uul, __LISTEN_RES_MAX, sizeof(*uul)); 3079 3080 if (!uul) 3081 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Out of memory"); 3082 3083 uul->vm = vm; 3084 uul->ctx = &c->ctx; 3085 uul->res = res; 3086 uul->ev.cb = uc_ubus_listener_cb; 3087 3088 rv = ubus_register_event_handler(&c->ctx, &uul->ev, 3089 ucv_string_get(pattern)); 3090 3091 if (rv != UBUS_STATUS_OK) { 3092 ucv_put(res); 3093 err_return(rv, "Failed to register listener object"); 3094 } 3095 3096 ucv_resource_persistent_set(res, true); 3097 ucv_resource_value_set(res, LISTEN_RES_CONN, ucv_get(c->res)); 3098 ucv_resource_value_set(res, LISTEN_RES_CB, ucv_get(cb)); 3099 3100 ok_return(ucv_get(res)); 3101 } 3102 3103 /** 3104 * Send a ubus event. 3105 * 3106 * Broadcasts an event of the specified type with optional data to all 3107 * registered event listeners. 3108 * 3109 * Returns `true` on success. 3110 * 3111 * Returns `null` if the event could not be sent. 3112 * 3113 * @function module:ubus.connection#event 3114 * 3115 * @param {string} event_type 3116 * The type string identifying the event. 3117 * 3118 * @param {Object} [event_data] 3119 * Optional event data as an object with field names and values. 3120 * 3121 * @returns {?boolean} 3122 * 3123 * @example 3124 * const conn = connect(); 3125 * conn.event("system.boot", { host: "router1", uptime: 3600 }); 3126 */ 3127 static uc_value_t * 3128 uc_ubus_event(uc_vm_t *vm, size_t nargs) 3129 { 3130 uc_value_t *eventtype, *eventdata; 3131 uc_ubus_connection_t *c; 3132 int rv; 3133 3134 conn_get(vm, &c); 3135 3136 args_get(vm, nargs, 3137 "event id", UC_STRING, false, &eventtype, 3138 "event data", UC_OBJECT, true, &eventdata); 3139 3140 blob_buf_init(&buf, 0); 3141 3142 if (eventdata) 3143 ucv_object_to_blob(eventdata, &buf); 3144 3145 rv = ubus_send_event(&c->ctx, ucv_string_get(eventtype), buf.head); 3146 3147 if (rv != UBUS_STATUS_OK) 3148 err_return(rv, "Unable to send event"); 3149 3150 ok_return(ucv_boolean_new(true)); 3151 } 3152 3153 3154 /* 3155 * ubus subscriptions 3156 * -------------------------------------------------------------------------- 3157 */ 3158 3159 static int 3160 uc_ubus_subscriber_notify_cb(struct ubus_context *ctx, struct ubus_object *obj, 3161 struct ubus_request_data *req, const char *method, 3162 struct blob_attr *msg) 3163 { 3164 struct ubus_subscriber *sub = container_of(obj, struct ubus_subscriber, obj); 3165 uc_ubus_subscriber_t *uusub = container_of(sub, uc_ubus_subscriber_t, sub); 3166 uc_value_t *this, *func, *reqproto; 3167 3168 this = uusub->res; 3169 func = ucv_resource_value_get(this, SUB_RES_NOTIFY_CB); 3170 3171 if (!ucv_is_callable(func)) 3172 return UBUS_STATUS_METHOD_NOT_FOUND; 3173 3174 reqproto = ucv_object_new(uusub->vm); 3175 3176 ucv_object_add(reqproto, "type", ucv_string_new(method)); 3177 3178 ucv_object_add(reqproto, "data", 3179 blob_array_to_ucv(uusub->vm, blob_data(msg), blob_len(msg), true)); 3180 3181 ucv_object_add(reqproto, "info", 3182 uc_ubus_object_call_info(uusub->vm, ctx, req, obj, NULL)); 3183 3184 return uc_ubus_handle_reply_common(ctx, req, uusub->vm, this, func, reqproto); 3185 } 3186 3187 static void 3188 uc_ubus_subscriber_remove_cb(struct ubus_context *ctx, 3189 struct ubus_subscriber *sub, uint32_t id) 3190 { 3191 uc_ubus_subscriber_t *uusub = container_of(sub, uc_ubus_subscriber_t, sub); 3192 uc_value_t *this, *func; 3193 uc_vm_t *vm = uusub->vm; 3194 3195 this = uusub->res; 3196 func = ucv_resource_value_get(this, SUB_RES_REMOVE_CB); 3197 3198 if (!ucv_is_callable(func)) 3199 return; 3200 3201 uc_vm_stack_push(vm, ucv_get(this)); 3202 uc_vm_stack_push(vm, ucv_get(func)); 3203 uc_vm_stack_push(vm, ucv_uint64_new(id)); 3204 3205 if (uc_ubus_vm_call(vm, true, 1)) 3206 ucv_put(uc_vm_stack_pop(vm)); 3207 } 3208 3209 static uc_value_t * 3210 uc_ubus_subscriber_subunsub_common(uc_vm_t *vm, size_t nargs, bool subscribe) 3211 { 3212 uc_ubus_subscriber_t *uusub = uc_fn_thisval("ubus.subscriber"); 3213 uc_value_t *objname; 3214 uint32_t id; 3215 int rv; 3216 3217 if (!uusub) 3218 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid subscriber context"); 3219 3220 args_get(vm, nargs, 3221 "object name", UC_STRING, false, &objname); 3222 3223 rv = ubus_lookup_id(uusub->ctx, ucv_string_get(objname), &id); 3224 3225 if (rv != UBUS_STATUS_OK) 3226 err_return(rv, "Failed to resolve object name '%s'", 3227 ucv_string_get(objname)); 3228 3229 if (subscribe) 3230 rv = ubus_subscribe(uusub->ctx, &uusub->sub, id); 3231 else 3232 rv = ubus_unsubscribe(uusub->ctx, &uusub->sub, id); 3233 3234 if (rv != UBUS_STATUS_OK) 3235 err_return(rv, "Failed to %s object '%s'", 3236 subscribe ? "subscribe" : "unsubscribe", 3237 ucv_string_get(objname)); 3238 3239 ok_return(ucv_boolean_new(true)); 3240 } 3241 3242 /** 3243 * Subscribe to a ubus object. 3244 * 3245 * Registers interest in notifications from the specified object. 3246 * 3247 * Returns `true` on success. 3248 * 3249 * Returns `null` if the subscription failed. 3250 * 3251 * @function module:ubus.subscriber#subscribe 3252 * 3253 * @param {string} object_name 3254 * The name of the object to subscribe to. 3255 * 3256 * @returns {?boolean} 3257 * 3258 * @example 3259 * const conn = connect(); 3260 * const sub = conn.subscriber("my.object", (event) => { 3261 * printf("Notification: type=%s, data=%.J\n", event.type, event.data); 3262 * }); 3263 * // … later, to re-subscribe … 3264 * sub.subscribe("my.object"); 3265 */ 3266 static uc_value_t * 3267 uc_ubus_subscriber_subscribe(uc_vm_t *vm, size_t nargs) 3268 { 3269 return uc_ubus_subscriber_subunsub_common(vm, nargs, true); 3270 } 3271 3272 /** 3273 * Unsubscribe from a ubus object. 3274 * 3275 * Stops receiving notifications from the specified object. 3276 * 3277 * Returns `true` on success. 3278 * 3279 * Returns `null` if the unsubscription failed. 3280 * 3281 * @function module:ubus.subscriber#unsubscribe 3282 * 3283 * @param {string} object_name 3284 * The name of the object to unsubscribe from. 3285 * 3286 * @returns {?boolean} 3287 * 3288 * @example 3289 * const sub = conn.subscriber("my.object", (event) => { … }); 3290 * // … later, to unsubscribe temporarily … 3291 * sub.unsubscribe("my.object"); 3292 */ 3293 static uc_value_t * 3294 uc_ubus_subscriber_unsubscribe(uc_vm_t *vm, size_t nargs) 3295 { 3296 return uc_ubus_subscriber_subunsub_common(vm, nargs, false); 3297 } 3298 3299 static int 3300 uc_ubus_subscriber_remove_common(uc_ubus_subscriber_t *uusub) 3301 { 3302 int rv = ubus_unregister_subscriber(uusub->ctx, &uusub->sub); 3303 3304 if (rv == UBUS_STATUS_OK) 3305 uc_ubus_put_res(&uusub->res); 3306 3307 return rv; 3308 } 3309 3310 #ifdef HAVE_UBUS_NEW_OBJ_CB 3311 static bool 3312 uc_ubus_subscriber_new_object_cb(struct ubus_context *ctx, struct ubus_subscriber *sub, const char *path) 3313 { 3314 uc_ubus_subscriber_t *uusub = container_of(sub, uc_ubus_subscriber_t, sub); 3315 uc_value_t *patterns = ucv_resource_value_get(uusub->res, SUB_RES_PATTERNS); 3316 size_t len = ucv_array_length(patterns); 3317 3318 for (size_t i = 0; i < len; i++) { 3319 uc_value_t *val = ucv_array_get(patterns, i); 3320 const char *pattern; 3321 3322 if (ucv_type(val) != UC_STRING) 3323 continue; 3324 3325 pattern = ucv_string_get(val); 3326 3327 if (fnmatch(pattern, path, 0) == 0) 3328 return true; 3329 } 3330 3331 return false; 3332 } 3333 #endif 3334 3335 /** 3336 * Remove a subscriber from the bus. 3337 * 3338 * Unregisters the subscriber, stopping it from receiving further 3339 * notifications. 3340 * 3341 * Returns `true` on success. 3342 * 3343 * Returns `null` if the subscriber could not be removed. 3344 * 3345 * @function module:ubus.subscriber#remove 3346 * 3347 * @returns {?boolean} 3348 * 3349 * @example 3350 * const sub = conn.subscriber("my.object", (event) => { … }); 3351 * // … when done … 3352 * sub.remove(); 3353 */ 3354 static uc_value_t * 3355 uc_ubus_subscriber_remove(uc_vm_t *vm, size_t nargs) 3356 { 3357 uc_ubus_subscriber_t *uusub = uc_fn_thisval("ubus.subscriber"); 3358 int rv; 3359 3360 if (!uusub) 3361 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid subscriber context"); 3362 3363 rv = uc_ubus_subscriber_remove_common(uusub); 3364 3365 if (rv != UBUS_STATUS_OK) 3366 err_return(rv, "Failed to remove subscriber object"); 3367 3368 ok_return(ucv_boolean_new(true)); 3369 } 3370 3371 /** 3372 * Register a ubus subscriber. 3373 * 3374 * Creates a subscriber that can receive notifications from ubus objects. 3375 * The subscriber can define notify and remove callbacks, and optional 3376 * subscription patterns for automatic object discovery. 3377 * 3378 * Returns a subscriber resource representing the registered subscriber. 3379 * 3380 * Returns `null` if the subscriber could not be registered. 3381 * 3382 * @function module:ubus.connection#subscriber 3383 * 3384 * @param {function} notify_callback 3385 * Callback invoked when a notification is received from a subscribed 3386 * object. 3387 * 3388 * @param {function} remove_callback 3389 * Callback invoked when a subscribed object is removed from the bus. 3390 * 3391 * @param {string[]} [subscription_patterns] 3392 * Optional array of glob patterns for automatic object subscription. 3393 * 3394 * @returns {?module:ubus.subscriber} 3395 * 3396 * @example 3397 * const conn = connect(); 3398 * const sub = conn.subscriber( 3399 * (event) => { 3400 * printf("Received: type=%s, data=%.J\n", 3401 * event.type, event.data); 3402 * }, 3403 * (objid) => { 3404 * printf("Object removed: %d\n", objid); 3405 * }, 3406 * ["network.interface.*"] // Auto-subscribe to matching objects 3407 * ); 3408 * // Subscribe to a specific object 3409 * sub.subscribe("some.object"); 3410 */ 3411 static uc_value_t * 3412 uc_ubus_subscriber(uc_vm_t *vm, size_t nargs) 3413 { 3414 uc_value_t *notify_cb, *remove_cb, *subscriptions; 3415 uc_ubus_subscriber_t *uusub = NULL; 3416 uc_ubus_connection_t *c; 3417 uc_value_t *res; 3418 int rv; 3419 3420 conn_get(vm, &c); 3421 3422 args_get(vm, nargs, 3423 "notify callback", UC_CLOSURE, true, ¬ify_cb, 3424 "remove callback", UC_CLOSURE, true, &remove_cb, 3425 "subscription patterns", UC_ARRAY, true, &subscriptions); 3426 3427 if (!notify_cb && !remove_cb) 3428 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Either notify or remove callback required"); 3429 3430 res = ucv_resource_create_ex(vm, "ubus.subscriber", (void **)&uusub, __SUB_RES_MAX, sizeof(*uusub)); 3431 3432 if (!uusub) 3433 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Out of memory"); 3434 3435 uusub->vm = vm; 3436 uusub->ctx = &c->ctx; 3437 uusub->res = ucv_get(res); 3438 3439 ucv_resource_value_set(res, SUB_RES_CONN, ucv_get(c->res)); 3440 ucv_resource_value_set(res, SUB_RES_NOTIFY_CB, ucv_get(notify_cb)); 3441 ucv_resource_value_set(res, SUB_RES_REMOVE_CB, ucv_get(remove_cb)); 3442 ucv_resource_value_set(res, SUB_RES_PATTERNS, ucv_get(subscriptions)); 3443 3444 #ifdef HAVE_UBUS_NEW_OBJ_CB 3445 if (subscriptions) 3446 uusub->sub.new_obj_cb = uc_ubus_subscriber_new_object_cb; 3447 #endif 3448 3449 rv = ubus_register_subscriber(&c->ctx, &uusub->sub); 3450 3451 if (rv != UBUS_STATUS_OK) { 3452 ucv_put(uusub->res); 3453 ucv_put(res); 3454 err_return(rv, "Failed to register subscriber object"); 3455 } 3456 3457 if (notify_cb) 3458 uusub->sub.cb = uc_ubus_subscriber_notify_cb; 3459 3460 if (remove_cb) 3461 uusub->sub.remove_cb = uc_ubus_subscriber_remove_cb; 3462 3463 ucv_resource_persistent_set(res, true); 3464 3465 ok_return(res); 3466 } 3467 3468 3469 /* 3470 * connection methods 3471 * -------------------------------------------------------------------------- 3472 */ 3473 3474 /** 3475 * Send a reply to an asynchronous method call. 3476 * 3477 * Sends the specified data as a reply to the incoming method call. This 3478 * function should be called within a published object's method handler. 3479 * 3480 * Returns `true` on success. 3481 * 3482 * Returns `null` if the reply could not be sent. 3483 * 3484 * @function module:ubus.request#reply 3485 * 3486 * @param {*} data 3487 * The data to send as reply. Can be any JSON-serializable value. 3488 * 3489 * @returns {boolean} 3490 * 3491 * @example 3492 * // Synchronous reply 3493 * const obj = publish("my.service", { 3494 * hello: (req, msg) => { 3495 * req.reply({ message: "Hello " + msg.name }); 3496 * } 3497 * }); 3498 * 3499 * @example 3500 * // Asynchronous reply after defer completes 3501 * const obj = publish("my.service", { 3502 * some_method: (req) => { 3503 * ubus_conn.defer("other.object", "other_method", {}, 3504 * (rc, data) => { 3505 * req.reply({ result: data }); 3506 * }); 3507 * } 3508 * }); 3509 */ 3510 static uc_value_t * 3511 uc_ubus_remove(uc_vm_t *vm, size_t nargs) 3512 { 3513 uc_ubus_subscriber_t **uusub; 3514 uc_ubus_connection_t *c; 3515 uc_ubus_object_t *uuobj; 3516 uc_ubus_listener_t **uul; 3517 int rv; 3518 3519 conn_get(vm, &c); 3520 3521 uusub = (uc_ubus_subscriber_t **)ucv_resource_dataptr(uc_fn_arg(0), "ubus.subscriber"); 3522 uuobj = (uc_ubus_object_t *)ucv_resource_data(uc_fn_arg(0), "ubus.object"); 3523 uul = (uc_ubus_listener_t **)ucv_resource_dataptr(uc_fn_arg(0), "ubus.listener"); 3524 3525 if (uusub && *uusub) { 3526 if ((*uusub)->ctx != &c->ctx) 3527 err_return(UBUS_STATUS_INVALID_ARGUMENT, 3528 "Subscriber belongs to different connection"); 3529 3530 rv = uc_ubus_subscriber_remove_common(*uusub); 3531 3532 if (rv != UBUS_STATUS_OK) 3533 err_return(rv, "Unable to remove subscriber"); 3534 } 3535 else if (uuobj) { 3536 if (uuobj->ctx != &c->ctx) 3537 err_return(UBUS_STATUS_INVALID_ARGUMENT, 3538 "Object belongs to different connection"); 3539 3540 rv = uc_ubus_object_remove_common(uuobj); 3541 3542 if (rv != UBUS_STATUS_OK) 3543 err_return(rv, "Unable to remove object"); 3544 } 3545 else if (uul && *uul) { 3546 if ((*uul)->ctx != &c->ctx) 3547 err_return(UBUS_STATUS_INVALID_ARGUMENT, 3548 "Listener belongs to different connection"); 3549 3550 rv = uc_ubus_listener_remove_common(*uul); 3551 3552 if (rv != UBUS_STATUS_OK) 3553 err_return(rv, "Unable to remove listener"); 3554 } 3555 else { 3556 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Unhandled resource type"); 3557 } 3558 3559 ok_return(ucv_boolean_new(true)); 3560 } 3561 3562 3563 static void 3564 uc_ubus_conn_teardown(uc_ubus_connection_t *c) 3565 { 3566 /* Idempotently close the transport. Safe to call from within 3567 * ubus_handle_data / a re-entrant disconnect() because it only touches 3568 * the fd, timer and msgbuf -- it never frees the uc_ubus_connection_t 3569 * struct itself, which is owned by the resource refcount and freed in 3570 * free_connection() once that reaches zero. */ 3571 if (c->disconnected) 3572 return; 3573 3574 c->disconnected = true; 3575 3576 if (c->fd_handle && c->ctx.sock.fd >= 0) { 3577 uloop_fd_delete(&c->ctx.sock); 3578 c->ctx.sock.fd = -1; 3579 } 3580 3581 ubus_shutdown(&c->ctx); 3582 c->ctx.sock.fd = -1; 3583 c->ctx.msgbuf.data = NULL; 3584 } 3585 3586 /** 3587 * Disconnect from the ubus bus. 3588 * 3589 * Closes the connection to the ubus bus and releases associated resources. 3590 * All pending requests are aborted. 3591 * 3592 * Returns `true` on success. 3593 * 3594 * @function module:ubus.connection#disconnect 3595 * 3596 * @returns {boolean} 3597 * 3598 * @example 3599 * const conn = connect(); 3600 * // … do work … 3601 * conn.disconnect(); 3602 */ 3603 static uc_value_t * 3604 uc_ubus_disconnect(uc_vm_t *vm, size_t nargs) 3605 { 3606 uc_ubus_connection_t *c; 3607 uc_value_t *reg; 3608 3609 conn_get(vm, &c); 3610 3611 #ifdef HAVE_UBUS_FLUSH_REQUESTS 3612 ubus_flush_requests(&c->ctx); 3613 #endif 3614 3615 /* Close the transport (idempotent, guarded). Safe to run here even if a 3616 * re-entrant path already closed it. */ 3617 uc_ubus_conn_teardown(c); 3618 3619 /* If this connection is the one stored in the module-level registry 3620 * (auto-connect path), clear that entry so it can be reclaimed. The 3621 * registry holds the owned reference; setting the key to NULL releases 3622 * it via ucv_object_add(). (The value returned by uc_vm_registry_get() 3623 * above is a borrowed pointer, so no put is needed here.) */ 3624 reg = uc_vm_registry_get(vm, "ubus.connection"); 3625 3626 if (ucv_resource_data(reg, "ubus.connection") == c) 3627 uc_vm_registry_set(vm, "ubus.connection", NULL); 3628 3629 /* Drop the script's reference to the connection. The struct is not 3630 * freed here if derived resources (objects, defers, listeners, 3631 * subscribers) still hold references; in that case it is reclaimed in 3632 * free_connection() once the last of those is dropped -- which is 3633 * never while ubus_handle_data() is on the stack. */ 3634 uc_ubus_put_res(&c->res); 3635 3636 ok_return(ucv_boolean_new(true)); 3637 } 3638 3639 /** 3640 * Check if a deferred request has completed. 3641 * 3642 * Returns `true` if the deferred request has finished. 3643 * 3644 * Returns `false` if the request is still pending. 3645 * 3646 * @function module:ubus.deferred#completed 3647 * 3648 * @returns {boolean} 3649 */ 3650 static uc_value_t * 3651 uc_ubus_defer_completed(uc_vm_t *vm, size_t nargs) 3652 { 3653 uc_ubus_deferred_t *d = uc_fn_thisval("ubus.deferred"); 3654 3655 if (!d) 3656 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid deferred context"); 3657 3658 ok_return(ucv_boolean_new(d->complete)); 3659 } 3660 3661 /** 3662 * Wait synchronously for a deferred request to complete. 3663 * 3664 * Blocks until the deferred request completes or times out. 3665 * 3666 * Returns `true` if the request completed. 3667 * 3668 * Returns `false` if the request was already completed. 3669 * 3670 * @function module:ubus.deferred#await 3671 * 3672 * @returns {boolean} 3673 */ 3674 static uc_value_t * 3675 uc_ubus_defer_await(uc_vm_t *vm, size_t nargs) 3676 { 3677 uc_ubus_deferred_t *d = uc_fn_thisval("ubus.deferred"); 3678 int64_t remaining; 3679 3680 if (!d) 3681 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid deferred context"); 3682 3683 if (d->complete) 3684 ok_return(ucv_boolean_new(false)); 3685 3686 #ifdef HAVE_ULOOP_TIMEOUT_REMAINING64 3687 remaining = uloop_timeout_remaining64(&d->timeout); 3688 #else 3689 remaining = uloop_timeout_remaining(&d->timeout); 3690 #endif 3691 3692 ubus_complete_request(d->ctx, &d->request, remaining); 3693 3694 ok_return(ucv_boolean_new(true)); 3695 } 3696 3697 /** 3698 * Abort a pending deferred request. 3699 * 3700 * Cancels an asynchronous request that has not yet completed. 3701 * 3702 * Returns `true` if the request was aborted. 3703 * 3704 * Returns `false` if the request was already completed. 3705 * 3706 * @function module:ubus.deferred#abort 3707 * 3708 * @returns {boolean} 3709 */ 3710 static uc_value_t * 3711 uc_ubus_defer_abort(uc_vm_t *vm, size_t nargs) 3712 { 3713 uc_ubus_deferred_t *d = uc_fn_thisval("ubus.deferred"); 3714 3715 if (!d) 3716 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid deferred context"); 3717 3718 if (d->complete) 3719 ok_return(ucv_boolean_new(false)); 3720 3721 ubus_abort_request(d->ctx, &d->request); 3722 uloop_timeout_cancel(&d->timeout); 3723 3724 uc_ubus_put_res(&d->res); 3725 d->complete = true; 3726 3727 ok_return(ucv_boolean_new(true)); 3728 } 3729 3730 /* 3731 * channel related methods 3732 * -------------------------------------------------------------------------- 3733 */ 3734 3735 #ifdef HAVE_UBUS_CHANNEL_SUPPORT 3736 static int 3737 uc_ubus_channel_req_cb(struct ubus_context *ctx, struct ubus_object *obj, 3738 struct ubus_request_data *req, const char *method, 3739 struct blob_attr *msg) 3740 { 3741 uc_ubus_connection_t *c = container_of(ctx, uc_ubus_connection_t, ctx); 3742 uc_value_t *func, *args, *reqproto; 3743 3744 /* A message that was still buffered when the channel was lost reaches 3745 * this callback after the disconnect callback released the resource. */ 3746 if (!c->res) 3747 return UBUS_STATUS_CONNECTION_FAILED; 3748 3749 func = ucv_resource_value_get(c->res, CONN_RES_CB); 3750 3751 if (!ucv_is_callable(func)) 3752 return UBUS_STATUS_METHOD_NOT_FOUND; 3753 3754 args = blob_array_to_ucv(c->vm, blob_data(msg), blob_len(msg), true); 3755 reqproto = ucv_object_new(c->vm); 3756 ucv_object_add(reqproto, "args", args); 3757 3758 if (method) 3759 ucv_object_add(reqproto, "type", ucv_string_new(method)); 3760 3761 return uc_ubus_handle_reply_common(ctx, req, c->vm, c->res, func, reqproto); 3762 } 3763 3764 static void 3765 uc_ubus_channel_disconnect_cb(struct ubus_context *ctx) 3766 { 3767 uc_ubus_connection_t *c = container_of(ctx, uc_ubus_connection_t, ctx); 3768 uc_value_t *res, *func; 3769 3770 /* pin ref across user callback to guard against re-entrant disconnect() */ 3771 res = ucv_get(c->res); 3772 3773 func = ucv_resource_value_get(res, CONN_RES_DISCONNECT_CB); 3774 3775 if (ucv_is_callable(func)) { 3776 uc_vm_stack_push(c->vm, ucv_get(res)); 3777 uc_vm_stack_push(c->vm, ucv_get(func)); 3778 3779 if (uc_ubus_vm_call(c->vm, true, 0)) 3780 ucv_put(uc_vm_stack_pop(c->vm)); 3781 } 3782 3783 blob_buf_free(&c->buf); 3784 3785 /* Idempotent transport close. If the user's disconnect_cb called 3786 * c.disconnect() re-entrantly, uc_ubus_conn_teardown already ran and 3787 * this is a no-op. The struct itself is kept alive by the `res` pin 3788 * above until after both puts below. */ 3789 uc_ubus_conn_teardown(c); 3790 3791 uc_ubus_put_res(&c->res); 3792 ucv_put(res); 3793 } 3794 3795 static uc_value_t * 3796 uc_ubus_channel_add(uc_ubus_connection_t *c, uc_value_t *cb, 3797 uc_value_t *disconnect_cb, uc_value_t *fd) 3798 { 3799 ucv_resource_persistent_set(c->res, true); 3800 ucv_resource_value_set(c->res, CONN_RES_FD, ucv_get(fd)); 3801 ucv_resource_value_set(c->res, CONN_RES_CB, ucv_get(cb)); 3802 ucv_resource_value_set(c->res, CONN_RES_DISCONNECT_CB, ucv_get(disconnect_cb)); 3803 c->ctx.connection_lost = uc_ubus_channel_disconnect_cb; 3804 ubus_add_uloop(&c->ctx); 3805 3806 ok_return(ucv_get(c->res)); 3807 } 3808 3809 #endif 3810 3811 /** 3812 * Create a new ubus channel from a method call context. 3813 * 3814 * Creates a bidirectional channel communication path in response to an 3815 * incoming method call. The callback will be invoked for incoming messages 3816 * on the channel. 3817 * 3818 * Returns a channel connection resource. 3819 * 3820 * Returns `null` if the channel could not be created. 3821 * 3822 * @function module:ubus.request#new_channel 3823 * 3824 * @param {function} cb 3825 * Callback invoked for incoming messages on the channel. 3826 * 3827 * @param {function} [disconnect_cb] 3828 * Optional callback invoked when the channel is disconnected. 3829 * 3830 * @param {number} [timeout=30] 3831 * The timeout in seconds for subsequent operations. 3832 * 3833 * @returns {?module:ubus.channel} 3834 */ 3835 static uc_value_t * 3836 uc_ubus_request_new_channel(uc_vm_t *vm, size_t nargs) 3837 { 3838 #ifdef HAVE_UBUS_CHANNEL_SUPPORT 3839 uc_ubus_request_t *callctx = uc_fn_thisval("ubus.request"); 3840 uc_value_t *cb, *disconnect_cb, *timeout; 3841 uc_ubus_connection_t *c; 3842 int fd; 3843 3844 if (!callctx) 3845 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid call context"); 3846 3847 args_get(vm, nargs, 3848 "cb", UC_CLOSURE, true, &cb, 3849 "disconnect_cb", UC_CLOSURE, true, &disconnect_cb, 3850 "timeout", UC_INTEGER, true, &timeout); 3851 3852 c = uc_ubus_conn_alloc(vm, timeout, "ubus.channel"); 3853 3854 if (!c) 3855 return NULL; 3856 3857 if (ubus_channel_create(&c->ctx, &fd, cb ? uc_ubus_channel_req_cb : NULL)) { 3858 ucv_put(c->res); 3859 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Unable to create ubus channel"); 3860 } 3861 3862 ubus_request_set_fd(callctx->ctx, &callctx->req, fd); 3863 3864 return uc_ubus_channel_add(c, cb, disconnect_cb, NULL); 3865 #else 3866 err_return(UBUS_STATUS_NOT_SUPPORTED, "No ubus channel support"); 3867 #endif 3868 } 3869 3870 3871 /** 3872 * Connect to a ubus channel from a file descriptor. 3873 * 3874 * Creates a channel connection from an existing file descriptor, typically 3875 * received from a method call. The callback will be invoked for incoming 3876 * messages on the channel. 3877 * 3878 * Returns a channel connection resource. 3879 * 3880 * Returns `null` if the channel could not be created. 3881 * 3882 * @function module:ubus#open_channel 3883 * 3884 * @param {number|module:fs.file|module:socket.socket} fd 3885 * The file descriptor or resource of the channel to connect to. When a plain 3886 * integer fd is passed, the ubus channel takes ownership and closes it on 3887 * disconnect. When a resource object with a `fileno()` method is passed, the 3888 * resource retains ownership of the fd; the channel merely detaches from it 3889 * on disconnect without closing. 3890 * 3891 * @param {function} cb 3892 * Callback invoked for incoming messages on the channel. 3893 * 3894 * @param {function} [disconnect_cb] 3895 * Optional callback invoked when the channel is disconnected. 3896 * 3897 * @param {number} [timeout=30] 3898 * The timeout in seconds for subsequent operations. 3899 * 3900 * @returns {?module:ubus.channel} 3901 */ 3902 static uc_value_t * 3903 uc_ubus_channel_connect(uc_vm_t *vm, size_t nargs) 3904 { 3905 #ifdef HAVE_UBUS_CHANNEL_SUPPORT 3906 uc_value_t *fd, *cb, *disconnect_cb, *timeout; 3907 bool handle = false; 3908 uc_ubus_connection_t *c; 3909 int fd_val; 3910 3911 args_get(vm, nargs, 3912 "fd", UC_NULL, false, &fd, 3913 "cb", UC_CLOSURE, true, &cb, 3914 "disconnect_cb", UC_CLOSURE, true, &disconnect_cb, 3915 "timeout", UC_INTEGER, true, &timeout); 3916 3917 fd_val = get_fd(vm, fd, &handle); 3918 3919 if (fd_val < 0) 3920 err_return(UBUS_STATUS_INVALID_ARGUMENT, "Invalid file descriptor argument"); 3921 3922 c = uc_ubus_conn_alloc(vm, timeout, "ubus.channel"); 3923 3924 if (!c) 3925 return NULL; 3926 3927 c->fd_handle = handle; 3928 3929 if (ubus_channel_connect(&c->ctx, fd_val, cb ? uc_ubus_channel_req_cb : NULL)) { 3930 ucv_put(c->res); 3931 err_return(UBUS_STATUS_UNKNOWN_ERROR, "Unable to create ubus channel"); 3932 } 3933 3934 return uc_ubus_channel_add(c, cb, disconnect_cb, fd); 3935 #else 3936 err_return(UBUS_STATUS_NOT_SUPPORTED, "No ubus channel support"); 3937 #endif 3938 } 3939 3940 3941 /** 3942 * Get or set the ubus exception handler. 3943 * 3944 * When called without arguments, returns the currently registered exception 3945 * handler function. When called with a function argument, registers it as 3946 * the exception handler for ubus operations. 3947 * 3948 * Returns the current exception handler when called without arguments. 3949 * 3950 * Returns `true` when a new handler was set. 3951 * 3952 * @function module:ubus#guard 3953 * 3954 * @param {function} [handler] 3955 * The exception handler function to register. 3956 * 3957 * @returns {function|boolean} 3958 */ 3959 static uc_value_t * 3960 uc_ubus_guard(uc_vm_t *vm, size_t nargs) 3961 { 3962 uc_value_t *arg = uc_fn_arg(0); 3963 3964 if (!nargs) 3965 return ucv_get(uc_vm_registry_get(vm, "ubus.ex_handler")); 3966 3967 if (arg && !ucv_is_callable(arg)) 3968 return NULL; 3969 3970 uc_vm_registry_set(vm, "ubus.ex_handler", ucv_get(arg)); 3971 3972 return ucv_boolean_new(true); 3973 } 3974 3975 3976 static const uc_function_list_t global_fns[] = { 3977 { "error", uc_ubus_error }, 3978 { "connect", uc_ubus_connect }, 3979 { "open_channel", uc_ubus_channel_connect }, 3980 { "guard", uc_ubus_guard }, 3981 }; 3982 3983 static const uc_function_list_t conn_fns[] = { 3984 { "list", uc_ubus_list }, 3985 { "call", uc_ubus_call }, 3986 { "defer", uc_ubus_defer }, 3987 { "publish", uc_ubus_publish }, 3988 { "remove", uc_ubus_remove }, 3989 { "listener", uc_ubus_listener }, 3990 { "subscriber", uc_ubus_subscriber }, 3991 { "event", uc_ubus_event }, 3992 { "error", uc_ubus_error }, 3993 { "disconnect", uc_ubus_disconnect }, 3994 }; 3995 3996 static const uc_function_list_t chan_fns[] = { 3997 { "request", uc_ubus_chan_request }, 3998 { "defer", uc_ubus_chan_defer }, 3999 { "error", uc_ubus_error }, 4000 { "disconnect", uc_ubus_disconnect }, 4001 }; 4002 4003 static const uc_function_list_t defer_fns[] = { 4004 { "await", uc_ubus_defer_await }, 4005 { "completed", uc_ubus_defer_completed }, 4006 { "abort", uc_ubus_defer_abort }, 4007 }; 4008 4009 static const uc_function_list_t object_fns[] = { 4010 { "subscribed", uc_ubus_object_subscribed }, 4011 { "notify", uc_ubus_object_notify }, 4012 { "remove", uc_ubus_object_remove }, 4013 }; 4014 4015 static const uc_function_list_t request_fns[] = { 4016 { "reply", uc_ubus_request_reply }, 4017 { "error", uc_ubus_request_error }, 4018 { "defer", uc_ubus_request_defer }, 4019 { "get_fd", uc_ubus_request_get_fd }, 4020 { "set_fd", uc_ubus_request_set_fd }, 4021 { "new_channel", uc_ubus_request_new_channel }, 4022 }; 4023 4024 static const uc_function_list_t notify_fns[] = { 4025 { "completed", uc_ubus_notify_completed }, 4026 { "abort", uc_ubus_notify_abort }, 4027 }; 4028 4029 static const uc_function_list_t listener_fns[] = { 4030 { "remove", uc_ubus_listener_remove }, 4031 }; 4032 4033 static const uc_function_list_t subscriber_fns[] = { 4034 { "subscribe", uc_ubus_subscriber_subscribe }, 4035 { "unsubscribe", uc_ubus_subscriber_unsubscribe }, 4036 { "remove", uc_ubus_subscriber_remove }, 4037 }; 4038 4039 static void free_connection(void *ud) { 4040 uc_ubus_connection_t *conn = ud; 4041 4042 blob_buf_free(&conn->buf); 4043 4044 /* Close the transport if it is still open (e.g. the script dropped its 4045 * reference without calling disconnect()). Guarded and idempotent. */ 4046 uc_ubus_conn_teardown(conn); 4047 } 4048 4049 static void free_deferred(void *ud) { 4050 uc_ubus_deferred_t *defer = ud; 4051 4052 uloop_timeout_cancel(&defer->timeout); 4053 } 4054 4055 static void free_object(void *ud) { 4056 uc_ubus_object_t *uuobj = ud; 4057 struct ubus_object *obj = &uuobj->obj; 4058 int i, j; 4059 4060 for (i = 0; i < obj->n_methods; i++) { 4061 for (j = 0; j < obj->methods[i].n_policy; j++) 4062 free((char *)obj->methods[i].policy[j].name); 4063 4064 free((char *)obj->methods[i].name); 4065 free((char *)obj->methods[i].policy); 4066 } 4067 } 4068 4069 static void free_request(void *ud) { 4070 uc_ubus_request_t *callctx = ud; 4071 4072 uc_ubus_request_finish(callctx, UBUS_STATUS_TIMEOUT); 4073 } 4074 4075 void uc_module_init(uc_vm_t *vm, uc_value_t *scope) 4076 { 4077 uc_function_list_register(scope, global_fns); 4078 uc_function_list_register(scope, conn_fns); 4079 4080 /** 4081 * @typedef 4082 * @name Ubus status codes 4083 * @property {number} STATUS_OK - Operation successful 4084 * @property {number} STATUS_INVALID_COMMAND - Invalid command 4085 * @property {number} STATUS_INVALID_ARGUMENT - Invalid argument 4086 * @property {number} STATUS_METHOD_NOT_FOUND - Method not found 4087 * @property {number} STATUS_NOT_FOUND - Object not found 4088 * @property {number} STATUS_NO_DATA - No data available 4089 * @property {number} STATUS_PERMISSION_DENIED - Permission denied 4090 * @property {number} STATUS_TIMEOUT - Operation timed out 4091 * @property {number} STATUS_NOT_SUPPORTED - Operation not supported 4092 * @property {number} STATUS_UNKNOWN_ERROR - Unknown error 4093 * @property {number} STATUS_CONNECTION_FAILED - Connection failed 4094 * @property {number} STATUS_NO_MEMORY - Out of memory (new) 4095 * @property {number} STATUS_PARSE_ERROR - Parse error (new) 4096 * @property {number} STATUS_SYSTEM_ERROR - System error (new) 4097 * @property {number} STATUS_CONTINUE - Virtual code for continued replies 4098 */ 4099 4100 #define ADD_CONST(x) ucv_object_add(scope, #x, ucv_int64_new(UBUS_##x)) 4101 ADD_CONST(STATUS_OK); 4102 ADD_CONST(STATUS_INVALID_COMMAND); 4103 ADD_CONST(STATUS_INVALID_ARGUMENT); 4104 ADD_CONST(STATUS_METHOD_NOT_FOUND); 4105 ADD_CONST(STATUS_NOT_FOUND); 4106 ADD_CONST(STATUS_NO_DATA); 4107 ADD_CONST(STATUS_PERMISSION_DENIED); 4108 ADD_CONST(STATUS_TIMEOUT); 4109 ADD_CONST(STATUS_NOT_SUPPORTED); 4110 ADD_CONST(STATUS_UNKNOWN_ERROR); 4111 ADD_CONST(STATUS_CONNECTION_FAILED); 4112 4113 #ifdef HAVE_NEW_UBUS_STATUS_CODES 4114 ADD_CONST(STATUS_NO_MEMORY); 4115 ADD_CONST(STATUS_PARSE_ERROR); 4116 ADD_CONST(STATUS_SYSTEM_ERROR); 4117 #endif 4118 4119 /* virtual status code for reply */ 4120 #define UBUS_STATUS_CONTINUE -1 4121 ADD_CONST(STATUS_CONTINUE); 4122 4123 /** 4124 * @typedef 4125 * @name Ubus system object IDs 4126 * @property {number} SYSTEM_OBJECT_ACL - System object ACL identifier, 4127 * used to query ACL data via 4128 * {@link module:ubus#call|call()} with an integer object ID 4129 */ 4130 ADD_CONST(SYSTEM_OBJECT_ACL); 4131 4132 uc_type_declare(vm, "ubus.connection", conn_fns, free_connection); 4133 uc_type_declare(vm, "ubus.channel", chan_fns, free_connection); 4134 uc_type_declare(vm, "ubus.deferred", defer_fns, free_deferred); 4135 uc_type_declare(vm, "ubus.object", object_fns, free_object); 4136 uc_type_declare(vm, "ubus.notify", notify_fns, NULL); 4137 uc_type_declare(vm, "ubus.request", request_fns, free_request); 4138 uc_type_declare(vm, "ubus.listener", listener_fns, NULL); 4139 uc_type_declare(vm, "ubus.subscriber", subscriber_fns, NULL); 4140 } 4141
This page was automatically generated by LXR 0.3.1. • OpenWrt