cfe9c9b0abde93feb9447f334aced7d1c96d91b1
[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 = calloc(plen, sizeof(struct blobmsg_policy));
414         if (!p)
415                 return 1;
416
417         m->policy = p;
418         lua_pushnil(L);
419         while (lua_next(L, -2) != 0) {
420                 int val = lua_tointeger(L, -1);
421
422                 /* check if the policy is valid */
423                 if ((lua_type(L, -2) != LUA_TSTRING) ||
424                                 (lua_type(L, -1) != LUA_TNUMBER) ||
425                                 (val < 0) ||
426                                 (val > BLOBMSG_TYPE_LAST)) {
427                         lua_pop(L, 1);
428                         continue;
429                 }
430                 p[pidx].name = lua_tostring(L, -2);
431                 p[pidx].type = val;
432                 lua_pop(L, 1);
433                 pidx++;
434         }
435
436         m->n_policy = pidx;
437         lua_pop(L, 2);
438
439         return 0;
440 }
441
442 static void
443 ubus_new_sub_cb(struct ubus_context *ctx, struct ubus_object *obj)
444 {
445         struct ubus_lua_object *luobj;
446
447         luobj = container_of(obj, struct ubus_lua_object, o);
448
449         lua_getglobal(state, "__ubus_cb_publisher");
450         lua_rawgeti(state, -1, luobj->rsubscriber);
451         lua_remove(state, -2);
452
453         if (lua_isfunction(state, -1)) {
454                 lua_pushnumber(state, luobj->o.has_subscribers );
455                 lua_call(state, 1, 0);
456         } else {
457                 lua_pop(state, 1);
458         }
459 }
460
461 static void
462 ubus_lua_load_newsub_cb( lua_State *L, struct ubus_lua_object *obj )
463 {
464         /* keep ref to func */
465         lua_getglobal(L, "__ubus_cb_publisher");
466         lua_pushvalue(L, -2);
467         obj->rsubscriber = luaL_ref(L, -2);
468         lua_pop(L, 1);
469
470         /* real callback */
471         obj->o.subscribe_cb = ubus_new_sub_cb;
472         return;
473 }
474
475 static struct ubus_object* ubus_lua_load_object(lua_State *L)
476 {
477         struct ubus_lua_object *obj = NULL;
478         int mlen = lua_gettablelen(L, -1);
479         struct ubus_method *m;
480         int midx = 0;
481
482         /* setup object pointers */
483         obj = calloc(1, sizeof(struct ubus_lua_object));
484         if (!obj)
485                 return NULL;
486
487         obj->o.name = lua_tostring(L, -2);
488
489         /* setup method pointers */
490         m = calloc(mlen, sizeof(struct ubus_method));
491         obj->o.methods = m;
492
493         /* setup type pointers */
494         obj->o.type = calloc(1, sizeof(struct ubus_object_type));
495         if (!obj->o.type) {
496                 free(obj);
497                 return NULL;
498         }
499
500         obj->o.type->name = lua_tostring(L, -2);
501         obj->o.type->id = 0;
502         obj->o.type->methods = obj->o.methods;
503
504         /* create the callback lookup table */
505         lua_createtable(L, 1, 0);
506         lua_getglobal(L, "__ubus_cb");
507         lua_pushvalue(L, -2);
508         obj->r = luaL_ref(L, -2);
509         lua_pop(L, 1);
510
511         /* scan each method */
512         lua_pushnil(L);
513         while (lua_next(L, -3) != 0) {
514                 /* check if its the subscriber notification callback */
515                 if( lua_type( L, -2 ) == LUA_TSTRING &&
516                                 lua_type( L, -1 ) == LUA_TFUNCTION ){
517                   if( !strcmp( lua_tostring( L, -2 ), "__subscriber_cb" ) )
518                           ubus_lua_load_newsub_cb( L, obj );
519                 }
520
521                 /* check if it looks like a method */
522                 if ((lua_type(L, -2) != LUA_TSTRING) ||
523                                 (lua_type(L, -1) != LUA_TTABLE) ||
524                                 !lua_objlen(L, -1)) {
525                         lua_pop(L, 1);
526                         continue;
527                 }
528
529                 if (!ubus_lua_load_methods(L, &m[midx]))
530                         midx++;
531                 lua_pop(L, 1);
532         }
533
534         obj->o.type->n_methods = obj->o.n_methods = midx;
535
536         /* pop the callback table */
537         lua_pop(L, 1);
538
539         return &obj->o;
540 }
541
542 static int ubus_lua_add(lua_State *L)
543 {
544         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
545
546         /* verify top level object */
547         if (lua_istable(L, 1)) {
548                 lua_pushstring(L, "you need to pass a table");
549                 lua_error(L);
550                 return 0;
551         }
552
553         /* scan each object */
554         lua_pushnil(L);
555         while (lua_next(L, -2) != 0) {
556                 struct ubus_object *obj = NULL;
557
558                 /* check if the object has a table of methods */
559                 if ((lua_type(L, -2) == LUA_TSTRING) && (lua_type(L, -1) == LUA_TTABLE)) {
560                         obj = ubus_lua_load_object(L);
561
562                         if (obj){
563                                 ubus_add_object(c->ctx, obj);
564
565                                 /* allow future reference of ubus obj */
566                                 lua_pushstring(state,"__ubusobj");
567                                 lua_pushlightuserdata(state, obj);
568                                 lua_settable(state,-3);
569                         }
570                 }
571                 lua_pop(L, 1);
572         }
573
574         return 0;
575 }
576
577 static int
578 ubus_lua_notify( lua_State *L )
579 {
580         struct ubus_lua_connection *c;
581         struct ubus_object *obj;
582         const char* method;
583
584         c = luaL_checkudata(L, 1, METANAME);
585         method = luaL_checkstring(L, 3);
586         luaL_checktype(L, 4, LUA_TTABLE);
587
588         if( !lua_islightuserdata( L, 2 ) ){
589                 lua_pushfstring( L, "Invald 2nd parameter, expected ubus obj ref" );
590                 lua_error( L );
591         }
592         obj = lua_touserdata( L, 2 );
593
594         /* create parameters from table */
595         blob_buf_init(&c->buf, 0);
596         if( !ubus_lua_format_blob_array( L, &c->buf, true ) ){
597                 lua_pushfstring( L, "Invalid 4th parameter, expected table of arguments" );
598                 lua_error( L );
599         }
600
601         ubus_notify( c->ctx, obj, method, c->buf.head, -1 );
602         return 0;
603 }
604
605 static void
606 ubus_lua_signatures_cb(struct ubus_context *c, struct ubus_object_data *o, void *p)
607 {
608         lua_State *L = (lua_State *)p;
609
610         if (!o->signature)
611                 return;
612
613         ubus_lua_parse_blob_array(L, blob_data(o->signature), blob_len(o->signature), true);
614 }
615
616 static int
617 ubus_lua_signatures(lua_State *L)
618 {
619         int rv;
620         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
621         const char *path = luaL_checkstring(L, 2);
622
623         rv = ubus_lookup(c->ctx, path, ubus_lua_signatures_cb, L);
624
625         if (rv != UBUS_STATUS_OK)
626         {
627                 lua_pop(L, 1);
628                 lua_pushnil(L);
629                 lua_pushinteger(L, rv);
630                 return 2;
631         }
632
633         return 1;
634 }
635
636
637 static void
638 ubus_lua_call_cb(struct ubus_request *req, int type, struct blob_attr *msg)
639 {
640         lua_State *L = (lua_State *)req->priv;
641
642         if (!msg && L)
643                 lua_pushnil(L);
644
645         if (msg && L)
646                 ubus_lua_parse_blob_array(L, blob_data(msg), blob_len(msg), true);
647 }
648
649 static int
650 ubus_lua_call(lua_State *L)
651 {
652         int rv, top;
653         uint32_t id;
654         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
655         const char *path = luaL_checkstring(L, 2);
656         const char *func = luaL_checkstring(L, 3);
657
658         luaL_checktype(L, 4, LUA_TTABLE);
659         blob_buf_init(&c->buf, 0);
660
661         if (!ubus_lua_format_blob_array(L, &c->buf, true))
662         {
663                 lua_pushnil(L);
664                 lua_pushinteger(L, UBUS_STATUS_INVALID_ARGUMENT);
665                 return 2;
666         }
667
668         rv = ubus_lookup_id(c->ctx, path, &id);
669
670         if (rv)
671         {
672                 lua_pushnil(L);
673                 lua_pushinteger(L, rv);
674                 return 2;
675         }
676
677         top = lua_gettop(L);
678         rv = ubus_invoke(c->ctx, id, func, c->buf.head, ubus_lua_call_cb, L, c->timeout * 1000);
679
680         if (rv != UBUS_STATUS_OK)
681         {
682                 lua_pop(L, 1);
683                 lua_pushnil(L);
684                 lua_pushinteger(L, rv);
685                 return 2;
686         }
687
688         return lua_gettop(L) - top;
689 }
690
691 static void
692 ubus_event_handler(struct ubus_context *ctx, struct ubus_event_handler *ev,
693                         const char *type, struct blob_attr *msg)
694 {
695         struct ubus_lua_event *listener = container_of(ev, struct ubus_lua_event, e);
696
697         lua_getglobal(state, "__ubus_cb_event");
698         lua_rawgeti(state, -1, listener->r);
699         lua_remove(state, -2);
700
701         if (lua_isfunction(state, -1)) {
702                 ubus_lua_parse_blob_array(state, blob_data(msg), blob_len(msg), true);
703                 lua_call(state, 1, 0);
704         } else {
705                 lua_pop(state, 1);
706         }
707 }
708
709 static struct ubus_event_handler*
710 ubus_lua_load_event(lua_State *L)
711 {
712         struct ubus_lua_event* event = NULL;
713
714         event = calloc(1, sizeof(struct ubus_lua_event));
715         if (!event)
716                 return NULL;
717
718         event->e.cb = ubus_event_handler;
719
720         /* update the he callback lookup table */
721         lua_getglobal(L, "__ubus_cb_event");
722         lua_pushvalue(L, -2);
723         event->r = luaL_ref(L, -2);
724         lua_setfield(L, -1, lua_tostring(L, -3));
725
726         return &event->e;
727 }
728
729 static int
730 ubus_lua_listen(lua_State *L) {
731         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
732
733         /* verify top level object */
734         luaL_checktype(L, 2, LUA_TTABLE);
735
736         /* scan each object */
737         lua_pushnil(L);
738         while (lua_next(L, -2) != 0) {
739                 struct ubus_event_handler *listener;
740
741                 /* check if the key is a string and the value is a method */
742                 if ((lua_type(L, -2) == LUA_TSTRING) && (lua_type(L, -1) == LUA_TFUNCTION)) {
743                         listener = ubus_lua_load_event(L);
744                         if(listener != NULL) {
745                                 ubus_register_event_handler(c->ctx, listener, lua_tostring(L, -2));
746                         }
747                 }
748                 lua_pop(L, 1);
749         }
750         return 0;
751 }
752
753 static void
754 ubus_sub_remove_handler(struct ubus_context *ctx, struct ubus_subscriber *s,
755                             uint32_t id)
756 {
757         struct ubus_lua_subscriber *sub;
758
759         sub = container_of(s, struct ubus_lua_subscriber, s);
760
761         lua_getglobal(state, "__ubus_cb_subscribe");
762         lua_rawgeti(state, -1, sub->rremove);
763         lua_remove(state, -2);
764
765         if (lua_isfunction(state, -1)) {
766                 lua_call(state, 0, 0);
767         } else {
768                 lua_pop(state, 1);
769         }
770 }
771
772 static int
773 ubus_sub_notify_handler(struct ubus_context *ctx, struct ubus_object *obj,
774             struct ubus_request_data *req, const char *method,
775             struct blob_attr *msg)
776 {
777         struct ubus_subscriber *s;
778         struct ubus_lua_subscriber *sub;
779
780         s = container_of(obj, struct ubus_subscriber, obj);
781         sub = container_of(s, struct ubus_lua_subscriber, s);
782
783         lua_getglobal(state, "__ubus_cb_subscribe");
784         lua_rawgeti(state, -1, sub->rnotify);
785         lua_remove(state, -2);
786
787         if (lua_isfunction(state, -1)) {
788                 if( msg ){
789                         ubus_lua_parse_blob_array(state, blob_data(msg), blob_len(msg), true);
790                         lua_call(state, 1, 0);
791                 } else {
792                         lua_call(state, 0, 0);
793                 }
794         } else {
795                 lua_pop(state, 1);
796         }
797
798         return 0;
799 }
800
801
802
803 static void
804 ubus_lua_do_subscribe( struct ubus_context *ctx, lua_State *L, const char* target,
805                         int idxnotify, int idxremove )
806 {
807         uint32_t id;
808         int status;
809         struct ubus_lua_subscriber *sub;
810
811         if( ( status = ubus_lookup_id( ctx, target, &id ) ) ){
812                 lua_pushfstring( L, "Unable find target, status=%d", status );
813                 lua_error( L );
814         }
815
816         sub = calloc( 1, sizeof( struct ubus_lua_subscriber ) );
817         if( !sub ){
818                 lua_pushstring( L, "Out of memory" );
819                 lua_error( L );
820         }
821
822         if( idxnotify ){
823                 lua_getglobal(L, "__ubus_cb_subscribe");
824                 lua_pushvalue(L, idxnotify);
825                 sub->rnotify = luaL_ref(L, -2);
826                 lua_pop(L, 1);
827                 sub->s.cb = ubus_sub_notify_handler;
828         }
829
830         if( idxremove ){
831                 lua_getglobal(L, "__ubus_cb_subscribe");
832                 lua_pushvalue(L, idxnotify);
833                 sub->rnotify = luaL_ref(L, -2);
834                 lua_pop(L, 1);
835                 sub->s.remove_cb = ubus_sub_remove_handler;
836         }
837
838         if( ( status = ubus_register_subscriber( ctx, &sub->s ) ) ){
839                 lua_pushfstring( L, "Failed to register subscriber, status=%d", status );
840                 lua_error( L );
841         }
842
843         if( ( status = ubus_subscribe( ctx, &sub->s, id) ) ){
844                 lua_pushfstring( L, "Failed to register subscriber, status=%d", status );
845                 lua_error( L );
846         }
847 }
848
849 static int
850 ubus_lua_subscribe(lua_State *L) {
851         int idxnotify, idxremove, stackstart;
852         struct ubus_lua_connection *c;
853         const char* target;
854
855         idxnotify = idxremove = 0;
856         stackstart = lua_gettop( L );
857
858
859         c = luaL_checkudata(L, 1, METANAME);
860         target = luaL_checkstring(L, 2);
861         luaL_checktype(L, 3, LUA_TTABLE);
862
863
864         lua_pushstring( L, "notify");
865         lua_gettable( L, 3 );
866         if( lua_type( L, -1 ) == LUA_TFUNCTION ){
867                 idxnotify = lua_gettop( L );
868         } else {
869                 lua_pop( L, 1 );
870         }
871
872         lua_pushstring( L, "remove");
873         lua_gettable( L, 3 );
874         if( lua_type( L, -1 ) == LUA_TFUNCTION ){
875                 idxremove = lua_gettop( L );
876         } else {
877                 lua_pop( L, 1 );
878         }
879
880         if( idxnotify )
881                 ubus_lua_do_subscribe( c->ctx, L, target, idxnotify, idxremove );
882
883         if( lua_gettop( L ) > stackstart )
884                 lua_pop( L, lua_gettop( L ) - stackstart );
885
886         return 0;
887 }
888
889 static int
890 ubus_lua_send(lua_State *L)
891 {
892         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
893         const char *event = luaL_checkstring(L, 2);
894
895         if (*event == 0)
896                 return luaL_argerror(L, 2, "no event name");
897
898         // Event content convert to ubus form
899         luaL_checktype(L, 3, LUA_TTABLE);
900         blob_buf_init(&c->buf, 0);
901
902         if (!ubus_lua_format_blob_array(L, &c->buf, true)) {
903                 lua_pushnil(L);
904                 lua_pushinteger(L, UBUS_STATUS_INVALID_ARGUMENT);
905                 return 2;
906         }
907
908         // Send the event
909         ubus_send_event(c->ctx, event, c->buf.head);
910
911         return 0;
912 }
913
914
915
916 static int
917 ubus_lua__gc(lua_State *L)
918 {
919         struct ubus_lua_connection *c = luaL_checkudata(L, 1, METANAME);
920
921         blob_buf_free(&c->buf);
922         if (c->ctx != NULL)
923         {
924                 ubus_free(c->ctx);
925                 memset(c, 0, sizeof(*c));
926         }
927
928         return 0;
929 }
930
931 static const luaL_Reg ubus[] = {
932         { "connect", ubus_lua_connect },
933         { "objects", ubus_lua_objects },
934         { "add", ubus_lua_add },
935         { "notify", ubus_lua_notify },
936         { "reply", ubus_lua_reply },
937         { "defer_request", ubus_lua_defer_request },
938         { "complete_deferred_request", ubus_lua_complete_deferred_request },
939         { "signatures", ubus_lua_signatures },
940         { "call", ubus_lua_call },
941         { "close", ubus_lua__gc },
942         { "listen", ubus_lua_listen },
943         { "send", ubus_lua_send },
944         { "subscribe", ubus_lua_subscribe },
945         { "__gc", ubus_lua__gc },
946         { NULL, NULL },
947 };
948
949 /* avoid missing prototype warning */
950 int luaopen_ubus(lua_State *L);
951
952 int
953 luaopen_ubus(lua_State *L)
954 {
955         /* create metatable */
956         luaL_newmetatable(L, METANAME);
957
958         /* metatable.__index = metatable */
959         lua_pushvalue(L, -1);
960         lua_setfield(L, -2, "__index");
961
962         /* fill metatable */
963         luaL_register(L, NULL, ubus);
964         lua_pop(L, 1);
965
966         /* create module */
967         luaL_register(L, MODNAME, ubus);
968
969         /* set some enum defines */
970         lua_pushinteger(L, BLOBMSG_TYPE_ARRAY);
971         lua_setfield(L, -2, "ARRAY");
972         lua_pushinteger(L, BLOBMSG_TYPE_TABLE);
973         lua_setfield(L, -2, "TABLE");
974         lua_pushinteger(L, BLOBMSG_TYPE_STRING);
975         lua_setfield(L, -2, "STRING");
976         lua_pushinteger(L, BLOBMSG_TYPE_INT64);
977         lua_setfield(L, -2, "INT64");
978         lua_pushinteger(L, BLOBMSG_TYPE_INT32);
979         lua_setfield(L, -2, "INT32");
980         lua_pushinteger(L, BLOBMSG_TYPE_INT16);
981         lua_setfield(L, -2, "INT16");
982         lua_pushinteger(L, BLOBMSG_TYPE_INT8);
983         lua_setfield(L, -2, "INT8");
984         lua_pushinteger(L, BLOBMSG_TYPE_BOOL);
985         lua_setfield(L, -2, "BOOLEAN");
986
987         /* used in our callbacks */
988         state = L;
989
990         /* create the callback table */
991         lua_createtable(L, 1, 0);
992         lua_setglobal(L, "__ubus_cb");
993
994         /* create the event table */
995         lua_createtable(L, 1, 0);
996         lua_setglobal(L, "__ubus_cb_event");
997
998         /* create the subscriber table */
999         lua_createtable(L, 1, 0);
1000         lua_setglobal(L, "__ubus_cb_subscribe");
1001
1002         /* create the publisher table - notifications of new subs */
1003         lua_createtable(L, 1, 0);
1004         lua_setglobal(L, "__ubus_cb_publisher");
1005         return 0;
1006 }