74a15b058dee1b4df0af8461dafd9bdc6ba4c43c
[project/ubus.git] / lua / ubus.c
1 /*
2  * Copyright (C) 2012 Jo-Philipp Wich <jow@openwrt.org>
3  * Copyright (C) 2012 John Crispin <blogic@openwrt.org>
4  * Copyright (C) 2016 Iain Fraser <iainf@netduma.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License version 2.1
8  * as published by the Free Software Foundation
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include <unistd.h>
17 #include <libubus.h>
18 #include <libubox/blobmsg.h>
19 #include <libubox/blobmsg_json.h>
20 #include <lauxlib.h>
21 #include <lua.h>
22
23 #define MODNAME         "ubus"
24 #define METANAME        MODNAME ".meta"
25
26 static lua_State *state;
27
28 struct ubus_lua_connection {
29         int timeout;
30         struct blob_buf buf;
31         struct ubus_context *ctx;
32 };
33
34 struct ubus_lua_object {
35         struct ubus_object o;
36         int r;
37         int rsubscriber;
38 };
39
40 struct ubus_lua_event {
41         struct ubus_event_handler e;
42         int r;
43 };
44
45 struct ubus_lua_subscriber {
46         struct ubus_subscriber s;
47         int rnotify;
48         int rremove;
49 };
50
51 static int
52 ubus_lua_parse_blob(lua_State *L, struct blob_attr *attr, bool table);
53
54 static int
55 ubus_lua_parse_blob_array(lua_State *L, struct blob_attr *attr, int len, bool table)
56 {
57         int rv;
58         int idx = 1;
59         int rem = len;
60         struct blob_attr *pos;
61
62         lua_newtable(L);
63
64         __blob_for_each_attr(pos, attr, rem)
65         {
66                 rv = ubus_lua_parse_blob(L, pos, table);
67
68                 if (rv > 1)
69                         lua_rawset(L, -3);
70                 else if (rv > 0)
71                         lua_rawseti(L, -2, idx++);
72         }
73
74         return 1;
75 }
76
77 static int
78 ubus_lua_parse_blob(lua_State *L, struct blob_attr *attr, bool table)
79 {
80         int len;
81         int off = 0;
82         void *data;
83
84         if (!blobmsg_check_attr(attr, false))
85                 return 0;
86
87         if (table && blobmsg_name(attr)[0])
88         {
89                 lua_pushstring(L, blobmsg_name(attr));
90                 off++;
91         }
92
93         data = blobmsg_data(attr);
94         len = blobmsg_data_len(attr);
95
96         switch (blob_id(attr))
97         {
98         case BLOBMSG_TYPE_BOOL:
99                 lua_pushboolean(L, *(uint8_t *)data);
100                 break;
101
102         case BLOBMSG_TYPE_INT16:
103                 lua_pushinteger(L, be16_to_cpu(*(uint16_t *)data));
104                 break;
105
106         case BLOBMSG_TYPE_INT32:
107                 lua_pushinteger(L, be32_to_cpu(*(uint32_t *)data));
108                 break;
109
110         case BLOBMSG_TYPE_INT64:
111                 lua_pushnumber(L, (double) be64_to_cpu(*(uint64_t *)data));
112                 break;
113
114         case BLOBMSG_TYPE_STRING:
115                 lua_pushstring(L, data);
116                 break;
117
118         case BLOBMSG_TYPE_ARRAY:
119                 ubus_lua_parse_blob_array(L, data, len, false);
120                 break;
121
122         case BLOBMSG_TYPE_TABLE:
123                 ubus_lua_parse_blob_array(L, data, len, true);
124                 break;
125
126         default:
127                 lua_pushnil(L);
128                 break;
129         }
130
131         return off + 1;
132 }
133
134
135 static bool
136 ubus_lua_format_blob_is_array(lua_State *L)
137 {
138         lua_Integer prv = 0;
139         lua_Integer cur = 0;
140
141         /* Find out whether table is array-like */
142         for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1))
143         {
144 #ifdef LUA_TINT
145                 if (lua_type(L, -2) != LUA_TNUMBER && lua_type(L, -2) != LUA_TINT)
146 #else
147                 if (lua_type(L, -2) != LUA_TNUMBER)
148 #endif
149                 {
150                         lua_pop(L, 2);
151                         return false;
152                 }
153
154                 cur = lua_tointeger(L, -2);
155
156                 if ((cur - 1) != prv)
157                 {
158                         lua_pop(L, 2);
159                         return false;
160                 }
161
162                 prv = cur;
163         }
164
165         return true;
166 }
167
168 static int
169 ubus_lua_format_blob_array(lua_State *L, struct blob_buf *b, bool table);
170
171 static int
172 ubus_lua_format_blob(lua_State *L, struct blob_buf *b, bool table)
173 {
174         void *c;
175         bool rv = true;
176         const char *key = table ? lua_tostring(L, -2) : NULL;
177
178         switch (lua_type(L, -1))
179         {
180         case LUA_TBOOLEAN:
181                 blobmsg_add_u8(b, key, (uint8_t)lua_toboolean(L, -1));
182                 break;
183
184 #ifdef LUA_TINT
185         case LUA_TINT:
186 #endif
187         case LUA_TNUMBER:
188                 blobmsg_add_u32(b, key, (uint32_t)lua_tointeger(L, -1));
189                 break;
190
191         case LUA_TSTRING:
192         case LUA_TUSERDATA:
193         case LUA_TLIGHTUSERDATA:
194                 blobmsg_add_string(b, key, lua_tostring(L, -1));
195                 break;
196
197         case LUA_TTABLE:
198                 if (ubus_lua_format_blob_is_array(L))
199                 {
200                         c = blobmsg_open_array(b, key);
201                         rv = ubus_lua_format_blob_array(L, b, false);
202                         blobmsg_close_array(b, c);
203                 }
204                 else
205                 {
206                         c = blobmsg_open_table(b, key);
207                         rv = ubus_lua_format_blob_array(L, b, true);
208                         blobmsg_close_table(b, c);
209                 }
210                 break;
211
212         default:
213                 rv = false;
214                 break;
215         }
216
217         return rv;
218 }
219
220 static int
221 ubus_lua_format_blob_array(lua_State *L, struct blob_buf *b, bool table)
222 {
223         for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1))
224         {
225                 if (!ubus_lua_format_blob(L, b, table))
226                 {
227                         lua_pop(L, 1);
228                         return false;
229                 }
230         }
231
232         return true;
233 }
234
235
236 static int
237 ubus_lua_connect(lua_State *L)
238 {
239         struct ubus_lua_connection *c;
240         const char *sockpath = luaL_optstring(L, 1, NULL);
241         int timeout = luaL_optint(L, 2, 30);
242
243         if ((c = lua_newuserdata(L, sizeof(*c))) != NULL &&
244                 (c->ctx = ubus_connect(sockpath)) != NULL)
245         {
246                 ubus_add_uloop(c->ctx);
247                 c->timeout = timeout;
248                 memset(&c->buf, 0, sizeof(c->buf));
249                 luaL_getmetatable(L, METANAME);
250                 lua_setmetatable(L, -2);
251                 return 1;
252         }
253
254         /* NB: no errors from ubus_connect() yet */
255         lua_pushnil(L);
256         lua_pushinteger(L, UBUS_STATUS_UNKNOWN_ERROR);
257         return 2;
258 }
259
260
261 static void
262 ubus_lua_objects_cb(struct ubus_context *c, struct ubus_object_data *o, void *p)
263 {
264         lua_State *L = (lua_State *)p;
265
266         lua_pushstring(L, o->path);
267         lua_rawseti(L, -2, lua_objlen(L, -2) + 1);
268 }
269
270 static int
271 ubus_lua_objects(lua_State *L)
272 {
273         int rv;
274         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
275
276         lua_newtable(L);
277         rv = ubus_lookup(c->ctx, NULL, ubus_lua_objects_cb, L);
278
279         if (rv != UBUS_STATUS_OK)
280         {
281                 lua_pop(L, 1);
282                 lua_pushnil(L);
283                 lua_pushinteger(L, rv);
284                 return 2;
285         }
286
287         return 1;
288 }
289
290 static int
291 ubus_method_handler(struct ubus_context *ctx, struct ubus_object *obj,
292                 struct ubus_request_data *req, const char *method,
293                 struct blob_attr *msg)
294 {
295         struct ubus_lua_object *o = container_of(obj, struct ubus_lua_object, o);
296         int rv = 0;
297
298         lua_getglobal(state, "__ubus_cb");
299         lua_rawgeti(state, -1, o->r);
300         lua_getfield(state, -1, method);
301         lua_remove(state, -2);
302         lua_remove(state, -2);
303
304         if (lua_isfunction(state, -1)) {
305                 lua_pushlightuserdata(state, req);
306                 if (!msg)
307                         lua_pushnil(state);
308                 else
309                         ubus_lua_parse_blob_array(state, blob_data(msg), blob_len(msg), true);
310                 lua_call(state, 2, 1);
311                 if (lua_isnumber(state, -1))
312                         rv = lua_tonumber(state, -1);
313         }
314
315         lua_pop(state, 1);
316
317         return rv;
318 }
319
320 static int lua_gettablelen(lua_State *L, int index)
321 {
322         int cnt = 0;
323
324         lua_pushnil(L);
325         index -= 1;
326         while (lua_next(L, index) != 0) {
327                 cnt++;
328                 lua_pop(L, 1);
329         }
330
331         return cnt;
332 }
333
334 static int ubus_lua_reply(lua_State *L)
335 {
336         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
337         struct ubus_request_data *req;
338
339         luaL_checktype(L, 3, LUA_TTABLE);
340         blob_buf_init(&c->buf, 0);
341
342         if (!ubus_lua_format_blob_array(L, &c->buf, true))
343         {
344                 lua_pushnil(L);
345                 lua_pushinteger(L, UBUS_STATUS_INVALID_ARGUMENT);
346                 return 2;
347         }
348
349         req = lua_touserdata(L, 2);
350         ubus_send_reply(c->ctx, req, c->buf.head);
351
352         return 0;
353 }
354
355 static int ubus_lua_defer_request(lua_State *L)
356 {
357         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
358         struct ubus_request_data *req = lua_touserdata(L, 2);
359         struct ubus_request_data *new_req = lua_newuserdata(L, sizeof(struct ubus_request_data));
360         ubus_defer_request(c->ctx, req, new_req);
361
362         return 1;
363 }
364
365 static int ubus_lua_complete_deferred_request(lua_State *L)
366 {
367         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
368         struct ubus_request_data *req = lua_touserdata(L, 2);
369         int ret = luaL_checkinteger(L, 3);
370         ubus_complete_deferred_request(c->ctx, req, ret);
371
372         return 0;
373 }
374
375 static int ubus_lua_load_methods(lua_State *L, struct ubus_method *m)
376 {
377         struct blobmsg_policy *p;
378         int plen;
379         int pidx = 0;
380
381         /* get the function pointer */
382         lua_pushinteger(L, 1);
383         lua_gettable(L, -2);
384
385         /* get the policy table */
386         lua_pushinteger(L, 2);
387         lua_gettable(L, -3);
388
389         /* check if the method table is valid */
390         if ((lua_type(L, -2) != LUA_TFUNCTION) ||
391                         (lua_type(L, -1) != LUA_TTABLE) ||
392                         lua_objlen(L, -1)) {
393                 lua_pop(L, 2);
394                 return 1;
395         }
396
397         /* store function pointer */
398         lua_pushvalue(L, -2);
399         lua_setfield(L, -6, lua_tostring(L, -5));
400
401         m->name = lua_tostring(L, -4);
402         m->handler = ubus_method_handler;
403
404         plen = lua_gettablelen(L, -1);
405
406         /* exit if policy table is empty */
407         if (!plen) {
408                 lua_pop(L, 2);
409                 return 0;
410         }
411
412         /* setup the policy pointers */
413         p = malloc(sizeof(struct blobmsg_policy) * plen);
414         if (!p)
415                 return 1;
416
417         memset(p, 0, sizeof(struct blobmsg_policy) * plen);
418         m->policy = p;
419         lua_pushnil(L);
420         while (lua_next(L, -2) != 0) {
421                 int val = lua_tointeger(L, -1);
422
423                 /* check if the policy is valid */
424                 if ((lua_type(L, -2) != LUA_TSTRING) ||
425                                 (lua_type(L, -1) != LUA_TNUMBER) ||
426                                 (val < 0) ||
427                                 (val > BLOBMSG_TYPE_LAST)) {
428                         lua_pop(L, 1);
429                         continue;
430                 }
431                 p[pidx].name = lua_tostring(L, -2);
432                 p[pidx].type = val;
433                 lua_pop(L, 1);
434                 pidx++;
435         }
436
437         m->n_policy = pidx;
438         lua_pop(L, 2);
439
440         return 0;
441 }
442
443 static void
444 ubus_new_sub_cb(struct ubus_context *ctx, struct ubus_object *obj)
445 {
446         struct ubus_lua_object *luobj;
447
448         luobj = container_of(obj, struct ubus_lua_object, o);
449
450         lua_getglobal(state, "__ubus_cb_publisher");
451         lua_rawgeti(state, -1, luobj->rsubscriber);
452         lua_remove(state, -2);
453
454         if (lua_isfunction(state, -1)) {
455                 lua_pushnumber(state, luobj->o.has_subscribers );
456                 lua_call(state, 1, 0);
457         } else {
458                 lua_pop(state, 1);
459         }
460 }
461
462 static void
463 ubus_lua_load_newsub_cb( lua_State *L, struct ubus_lua_object *obj )
464 {
465         /* keep ref to func */
466         lua_getglobal(L, "__ubus_cb_publisher");
467         lua_pushvalue(L, -2);
468         obj->rsubscriber = luaL_ref(L, -2);
469         lua_pop(L, 1);
470
471         /* real callback */
472         obj->o.subscribe_cb = ubus_new_sub_cb;
473         return;
474 }
475
476 static struct ubus_object* ubus_lua_load_object(lua_State *L)
477 {
478         struct ubus_lua_object *obj = NULL;
479         int mlen = lua_gettablelen(L, -1);
480         struct ubus_method *m;
481         int midx = 0;
482
483         /* setup object pointers */
484         obj = malloc(sizeof(struct ubus_lua_object));
485         if (!obj)
486                 return NULL;
487
488         memset(obj, 0, sizeof(struct ubus_lua_object));
489         obj->o.name = lua_tostring(L, -2);
490
491         /* setup method pointers */
492         m = malloc(sizeof(struct ubus_method) * mlen);
493         memset(m, 0, sizeof(struct ubus_method) * mlen);
494         obj->o.methods = m;
495
496         /* setup type pointers */
497         obj->o.type = malloc(sizeof(struct ubus_object_type));
498         if (!obj->o.type) {
499                 free(obj);
500                 return NULL;
501         }
502
503         memset(obj->o.type, 0, sizeof(struct ubus_object_type));
504         obj->o.type->name = lua_tostring(L, -2);
505         obj->o.type->id = 0;
506         obj->o.type->methods = obj->o.methods;
507
508         /* create the callback lookup table */
509         lua_createtable(L, 1, 0);
510         lua_getglobal(L, "__ubus_cb");
511         lua_pushvalue(L, -2);
512         obj->r = luaL_ref(L, -2);
513         lua_pop(L, 1);
514
515         /* scan each method */
516         lua_pushnil(L);
517         while (lua_next(L, -3) != 0) {
518                 /* check if its the subscriber notification callback */
519                 if( lua_type( L, -2 ) == LUA_TSTRING &&
520                                 lua_type( L, -1 ) == LUA_TFUNCTION ){
521                   if( !strcmp( lua_tostring( L, -2 ), "__subscriber_cb" ) )
522                           ubus_lua_load_newsub_cb( L, obj );
523                 }
524
525                 /* check if it looks like a method */
526                 if ((lua_type(L, -2) != LUA_TSTRING) ||
527                                 (lua_type(L, -1) != LUA_TTABLE) ||
528                                 !lua_objlen(L, -1)) {
529                         lua_pop(L, 1);
530                         continue;
531                 }
532
533                 if (!ubus_lua_load_methods(L, &m[midx]))
534                         midx++;
535                 lua_pop(L, 1);
536         }
537
538         obj->o.type->n_methods = obj->o.n_methods = midx;
539
540         /* pop the callback table */
541         lua_pop(L, 1);
542
543         return &obj->o;
544 }
545
546 static int ubus_lua_add(lua_State *L)
547 {
548         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
549
550         /* verify top level object */
551         if (lua_istable(L, 1)) {
552                 lua_pushstring(L, "you need to pass a table");
553                 lua_error(L);
554                 return 0;
555         }
556
557         /* scan each object */
558         lua_pushnil(L);
559         while (lua_next(L, -2) != 0) {
560                 struct ubus_object *obj = NULL;
561
562                 /* check if the object has a table of methods */
563                 if ((lua_type(L, -2) == LUA_TSTRING) && (lua_type(L, -1) == LUA_TTABLE)) {
564                         obj = ubus_lua_load_object(L);
565
566                         if (obj){
567                                 ubus_add_object(c->ctx, obj);
568
569                                 /* allow future reference of ubus obj */
570                                 lua_pushstring(state,"__ubusobj");
571                                 lua_pushlightuserdata(state, obj);
572                                 lua_settable(state,-3);
573                         }
574                 }
575                 lua_pop(L, 1);
576         }
577
578         return 0;
579 }
580
581 static int
582 ubus_lua_notify( lua_State *L )
583 {
584         struct ubus_lua_connection *c;
585         struct ubus_object *obj;
586         const char* method;
587
588         c = luaL_checkudata(L, 1, METANAME);
589         method = luaL_checkstring(L, 3);
590         luaL_checktype(L, 4, LUA_TTABLE);
591
592         if( !lua_islightuserdata( L, 2 ) ){
593                 lua_pushfstring( L, "Invald 2nd parameter, expected ubus obj ref" );
594                 lua_error( L );
595         }
596         obj = lua_touserdata( L, 2 );
597
598         /* create parameters from table */
599         blob_buf_init(&c->buf, 0);
600         if( !ubus_lua_format_blob_array( L, &c->buf, true ) ){
601                 lua_pushfstring( L, "Invalid 4th parameter, expected table of arguments" );
602                 lua_error( L );
603         }
604
605         ubus_notify( c->ctx, obj, method, c->buf.head, -1 );
606         return 0;
607 }
608
609 static void
610 ubus_lua_signatures_cb(struct ubus_context *c, struct ubus_object_data *o, void *p)
611 {
612         lua_State *L = (lua_State *)p;
613
614         if (!o->signature)
615                 return;
616
617         ubus_lua_parse_blob_array(L, blob_data(o->signature), blob_len(o->signature), true);
618 }
619
620 static int
621 ubus_lua_signatures(lua_State *L)
622 {
623         int rv;
624         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
625         const char *path = luaL_checkstring(L, 2);
626
627         rv = ubus_lookup(c->ctx, path, ubus_lua_signatures_cb, L);
628
629         if (rv != UBUS_STATUS_OK)
630         {
631                 lua_pop(L, 1);
632                 lua_pushnil(L);
633                 lua_pushinteger(L, rv);
634                 return 2;
635         }
636
637         return 1;
638 }
639
640
641 static void
642 ubus_lua_call_cb(struct ubus_request *req, int type, struct blob_attr *msg)
643 {
644         lua_State *L = (lua_State *)req->priv;
645
646         if (!msg && L)
647                 lua_pushnil(L);
648
649         if (msg && L)
650                 ubus_lua_parse_blob_array(L, blob_data(msg), blob_len(msg), true);
651 }
652
653 static int
654 ubus_lua_call(lua_State *L)
655 {
656         int rv, top;
657         uint32_t id;
658         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
659         const char *path = luaL_checkstring(L, 2);
660         const char *func = luaL_checkstring(L, 3);
661
662         luaL_checktype(L, 4, LUA_TTABLE);
663         blob_buf_init(&c->buf, 0);
664
665         if (!ubus_lua_format_blob_array(L, &c->buf, true))
666         {
667                 lua_pushnil(L);
668                 lua_pushinteger(L, UBUS_STATUS_INVALID_ARGUMENT);
669                 return 2;
670         }
671
672         rv = ubus_lookup_id(c->ctx, path, &id);
673
674         if (rv)
675         {
676                 lua_pushnil(L);
677                 lua_pushinteger(L, rv);
678                 return 2;
679         }
680
681         top = lua_gettop(L);
682         rv = ubus_invoke(c->ctx, id, func, c->buf.head, ubus_lua_call_cb, L, c->timeout * 1000);
683
684         if (rv != UBUS_STATUS_OK)
685         {
686                 lua_pop(L, 1);
687                 lua_pushnil(L);
688                 lua_pushinteger(L, rv);
689                 return 2;
690         }
691
692         return lua_gettop(L) - top;
693 }
694
695 static void
696 ubus_event_handler(struct ubus_context *ctx, struct ubus_event_handler *ev,
697                         const char *type, struct blob_attr *msg)
698 {
699         struct ubus_lua_event *listener = container_of(ev, struct ubus_lua_event, e);
700
701         lua_getglobal(state, "__ubus_cb_event");
702         lua_rawgeti(state, -1, listener->r);
703         lua_remove(state, -2);
704
705         if (lua_isfunction(state, -1)) {
706                 ubus_lua_parse_blob_array(state, blob_data(msg), blob_len(msg), true);
707                 lua_call(state, 1, 0);
708         } else {
709                 lua_pop(state, 1);
710         }
711 }
712
713 static struct ubus_event_handler*
714 ubus_lua_load_event(lua_State *L)
715 {
716         struct ubus_lua_event* event = NULL;
717
718         event = malloc(sizeof(struct ubus_lua_event));
719         if (!event)
720                 return NULL;
721
722         memset(event, 0, sizeof(struct ubus_lua_event));
723         event->e.cb = ubus_event_handler;
724
725         /* update the he callback lookup table */
726         lua_getglobal(L, "__ubus_cb_event");
727         lua_pushvalue(L, -2);
728         event->r = luaL_ref(L, -2);
729         lua_setfield(L, -1, lua_tostring(L, -3));
730
731         return &event->e;
732 }
733
734 static int
735 ubus_lua_listen(lua_State *L) {
736         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
737
738         /* verify top level object */
739         luaL_checktype(L, 2, LUA_TTABLE);
740
741         /* scan each object */
742         lua_pushnil(L);
743         while (lua_next(L, -2) != 0) {
744                 struct ubus_event_handler *listener;
745
746                 /* check if the key is a string and the value is a method */
747                 if ((lua_type(L, -2) == LUA_TSTRING) && (lua_type(L, -1) == LUA_TFUNCTION)) {
748                         listener = ubus_lua_load_event(L);
749                         if(listener != NULL) {
750                                 ubus_register_event_handler(c->ctx, listener, lua_tostring(L, -2));
751                         }
752                 }
753                 lua_pop(L, 1);
754         }
755         return 0;
756 }
757
758 static void
759 ubus_sub_remove_handler(struct ubus_context *ctx, struct ubus_subscriber *s,
760                             uint32_t id)
761 {
762         struct ubus_lua_subscriber *sub;
763
764         sub = container_of(s, struct ubus_lua_subscriber, s);
765
766         lua_getglobal(state, "__ubus_cb_subscribe");
767         lua_rawgeti(state, -1, sub->rremove);
768         lua_remove(state, -2);
769
770         if (lua_isfunction(state, -1)) {
771                 lua_call(state, 0, 0);
772         } else {
773                 lua_pop(state, 1);
774         }
775 }
776
777 static int
778 ubus_sub_notify_handler(struct ubus_context *ctx, struct ubus_object *obj,
779             struct ubus_request_data *req, const char *method,
780             struct blob_attr *msg)
781 {
782         struct ubus_subscriber *s;
783         struct ubus_lua_subscriber *sub;
784
785         s = container_of(obj, struct ubus_subscriber, obj);
786         sub = container_of(s, struct ubus_lua_subscriber, s);
787
788         lua_getglobal(state, "__ubus_cb_subscribe");
789         lua_rawgeti(state, -1, sub->rnotify);
790         lua_remove(state, -2);
791
792         if (lua_isfunction(state, -1)) {
793                 if( msg ){
794                         ubus_lua_parse_blob_array(state, blob_data(msg), blob_len(msg), true);
795                         lua_call(state, 1, 0);
796                 } else {
797                         lua_call(state, 0, 0);
798                 }
799         } else {
800                 lua_pop(state, 1);
801         }
802
803         return 0;
804 }
805
806
807
808 static void
809 ubus_lua_do_subscribe( struct ubus_context *ctx, lua_State *L, const char* target,
810                         int idxnotify, int idxremove )
811 {
812         uint32_t id;
813         int status;
814         struct ubus_lua_subscriber *sub;
815
816         if( ( status = ubus_lookup_id( ctx, target, &id ) ) ){
817                 lua_pushfstring( L, "Unable find target, status=%d", status );
818                 lua_error( L );
819         }
820
821         sub = malloc( sizeof( struct ubus_lua_subscriber ) );
822         memset( sub, 0, sizeof( struct ubus_lua_subscriber ) );
823         if( !sub ){
824                 lua_pushstring( L, "Out of memory" );
825                 lua_error( L );
826         }
827
828         if( idxnotify ){
829                 lua_getglobal(L, "__ubus_cb_subscribe");
830                 lua_pushvalue(L, idxnotify);
831                 sub->rnotify = luaL_ref(L, -2);
832                 lua_pop(L, 1);
833                 sub->s.cb = ubus_sub_notify_handler;
834         }
835
836         if( idxremove ){
837                 lua_getglobal(L, "__ubus_cb_subscribe");
838                 lua_pushvalue(L, idxnotify);
839                 sub->rnotify = luaL_ref(L, -2);
840                 lua_pop(L, 1);
841                 sub->s.remove_cb = ubus_sub_remove_handler;
842         }
843
844         if( ( status = ubus_register_subscriber( ctx, &sub->s ) ) ){
845                 lua_pushfstring( L, "Failed to register subscriber, status=%d", status );
846                 lua_error( L );
847         }
848
849         if( ( status = ubus_subscribe( ctx, &sub->s, id) ) ){
850                 lua_pushfstring( L, "Failed to register subscriber, status=%d", status );
851                 lua_error( L );
852         }
853 }
854
855 static int
856 ubus_lua_subscribe(lua_State *L) {
857         int idxnotify, idxremove, stackstart;
858         struct ubus_lua_connection *c;
859         const char* target;
860
861         idxnotify = idxremove = 0;
862         stackstart = lua_gettop( L );
863
864
865         c = luaL_checkudata(L, 1, METANAME);
866         target = luaL_checkstring(L, 2);
867         luaL_checktype(L, 3, LUA_TTABLE);
868
869
870         lua_pushstring( L, "notify");
871         lua_gettable( L, 3 );
872         if( lua_type( L, -1 ) == LUA_TFUNCTION ){
873                 idxnotify = lua_gettop( L );
874         } else {
875                 lua_pop( L, 1 );
876         }
877
878         lua_pushstring( L, "remove");
879         lua_gettable( L, 3 );
880         if( lua_type( L, -1 ) == LUA_TFUNCTION ){
881                 idxremove = lua_gettop( L );
882         } else {
883                 lua_pop( L, 1 );
884         }
885
886         if( idxnotify )
887                 ubus_lua_do_subscribe( c->ctx, L, target, idxnotify, idxremove );
888
889         if( lua_gettop( L ) > stackstart )
890                 lua_pop( L, lua_gettop( L ) - stackstart );
891
892         return 0;
893 }
894
895 static int
896 ubus_lua_send(lua_State *L)
897 {
898         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
899         const char *event = luaL_checkstring(L, 2);
900
901         if (*event == 0)
902                 return luaL_argerror(L, 2, "no event name");
903
904         // Event content convert to ubus form
905         luaL_checktype(L, 3, LUA_TTABLE);
906         blob_buf_init(&c->buf, 0);
907
908         if (!ubus_lua_format_blob_array(L, &c->buf, true)) {
909                 lua_pushnil(L);
910                 lua_pushinteger(L, UBUS_STATUS_INVALID_ARGUMENT);
911                 return 2;
912         }
913
914         // Send the event
915         ubus_send_event(c->ctx, event, c->buf.head);
916
917         return 0;
918 }
919
920
921
922 static int
923 ubus_lua__gc(lua_State *L)
924 {
925         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
926
927         blob_buf_free(&c->buf);
928         if (c->ctx != NULL)
929         {
930                 ubus_free(c->ctx);
931                 memset(c, 0, sizeof(*c));
932         }
933
934         return 0;
935 }
936
937 static const luaL_Reg ubus[] = {
938         { "connect", ubus_lua_connect },
939         { "objects", ubus_lua_objects },
940         { "add", ubus_lua_add },
941         { "notify", ubus_lua_notify },
942         { "reply", ubus_lua_reply },
943         { "defer_request", ubus_lua_defer_request },
944         { "complete_deferred_request", ubus_lua_complete_deferred_request },
945         { "signatures", ubus_lua_signatures },
946         { "call", ubus_lua_call },
947         { "close", ubus_lua__gc },
948         { "listen", ubus_lua_listen },
949         { "send", ubus_lua_send },
950         { "subscribe", ubus_lua_subscribe },
951         { "__gc", ubus_lua__gc },
952         { NULL, NULL },
953 };
954
955 /* avoid missing prototype warning */
956 int luaopen_ubus(lua_State *L);
957
958 int
959 luaopen_ubus(lua_State *L)
960 {
961         /* create metatable */
962         luaL_newmetatable(L, METANAME);
963
964         /* metatable.__index = metatable */
965         lua_pushvalue(L, -1);
966         lua_setfield(L, -2, "__index");
967
968         /* fill metatable */
969         luaL_register(L, NULL, ubus);
970         lua_pop(L, 1);
971
972         /* create module */
973         luaL_register(L, MODNAME, ubus);
974
975         /* set some enum defines */
976         lua_pushinteger(L, BLOBMSG_TYPE_ARRAY);
977         lua_setfield(L, -2, "ARRAY");
978         lua_pushinteger(L, BLOBMSG_TYPE_TABLE);
979         lua_setfield(L, -2, "TABLE");
980         lua_pushinteger(L, BLOBMSG_TYPE_STRING);
981         lua_setfield(L, -2, "STRING");
982         lua_pushinteger(L, BLOBMSG_TYPE_INT64);
983         lua_setfield(L, -2, "INT64");
984         lua_pushinteger(L, BLOBMSG_TYPE_INT32);
985         lua_setfield(L, -2, "INT32");
986         lua_pushinteger(L, BLOBMSG_TYPE_INT16);
987         lua_setfield(L, -2, "INT16");
988         lua_pushinteger(L, BLOBMSG_TYPE_INT8);
989         lua_setfield(L, -2, "INT8");
990         lua_pushinteger(L, BLOBMSG_TYPE_BOOL);
991         lua_setfield(L, -2, "BOOLEAN");
992
993         /* used in our callbacks */
994         state = L;
995
996         /* create the callback table */
997         lua_createtable(L, 1, 0);
998         lua_setglobal(L, "__ubus_cb");
999
1000         /* create the event table */
1001         lua_createtable(L, 1, 0);
1002         lua_setglobal(L, "__ubus_cb_event");
1003
1004         /* create the subscriber table */
1005         lua_createtable(L, 1, 0);
1006         lua_setglobal(L, "__ubus_cb_subscribe");
1007
1008         /* create the publisher table - notifications of new subs */
1009         lua_createtable(L, 1, 0);
1010         lua_setglobal(L, "__ubus_cb_publisher");
1011         return 0;
1012 }