This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ubus_python.c
1404 lines (1218 loc) · 35.1 KB
/
ubus_python.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* python-ubus - python bindings for ubus
*
* Copyright (C) 2017-2018 Stepan Henek <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <Python.h>
#include <dlfcn.h>
#include <libubox/blobmsg_json.h>
#include <libubus.h>
#include <stdio.h>
#ifndef UBUS_UNIX_SOCKET
#define UBUS_UNIX_SOCKET "/var/run/ubus/ubus.sock"
#endif
#define DEFAULT_SOCKET UBUS_UNIX_SOCKET
#define RESPONSE_HANDLER_OBJECT_NAME "ubus.__ResponseHandler"
#define MSG_ALLOCATION_FAILS "Failed to allocate memory!"
#define MSG_LISTEN_TUPLE_EXPECTED "Expected (event, callback) tuple"
#define MSG_ADD_SIGNATURE_INVALID \
"Incorrect method arguments!\n" \
"Expected:\n" \
" (<obj_name>, { " \
"<method_name>: {'signature': <method_signature>, 'method': <callable>}" \
", ...})"
#define MSG_JSON_TO_UBUS_FAILED "Failed to create json for ubus."
#define MSG_JSON_FROM_UBUS_FAILED "Failed to create json from ubus."
#define MSG_NOT_CONNECTED "You are not connected to ubus."
#define MSG_ALREADY_CONNECTED "You are already connected to ubus."
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#define PyStr_Check PyUnicode_Check
#define PyInt_Check PyLong_Check
#else
#define PyStr_Check(x) (PyString_Check(x) || PyUnicode_Check(x))
#define PyUnicode_AsUTF8 PyString_AsString
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
typedef struct {
struct ubus_object object;
PyObject *methods;
} ubus_Object;
typedef struct {
struct ubus_event_handler handler;
PyObject *callback;
}ubus_Listener ;
PyObject *prepare_bool(bool yes)
{
if (yes) {
Py_INCREF(Py_True);
return Py_True;
} else {
Py_INCREF(Py_False);
return Py_False;
}
}
/* ubus module objects */
static PyMethodDef ubus_methods[];
PyObject *python_alloc_list = NULL;
char *socket_path = NULL;
ubus_Listener **listeners = NULL;
size_t listerners_size = 0;
ubus_Object **objects = NULL;
size_t objects_size = 0;
struct blob_buf python_buf;
struct ubus_context *ctx = NULL;
#define CONNECTED (ctx != NULL)
/* json module handlers */
PyObject *json_module = NULL;
enum json_function {
LOADS,
DUMPS,
};
const char *json_function_names[2] = {
[LOADS] = "loads",
[DUMPS] = "dumps",
};
PyObject *perform_json_function(enum json_function json_function, PyObject *input)
{
PyObject *function = PyObject_GetAttrString(json_module, json_function_names[json_function]);
if (!function) {
return NULL;
}
PyObject *arglist = Py_BuildValue("(O)", input);
if (!arglist) {
Py_DECREF(function);
return NULL;
}
PyObject *data_object = PyObject_CallObject(function, arglist);
Py_DECREF(function);
Py_DECREF(arglist);
return data_object; // New reference - should be decreased by the caller
}
/* ResponseHandler */
typedef struct {
PyObject_HEAD
struct ubus_context *ctx;
struct ubus_request_data *req;
struct blob_buf buf;
} ubus_ResponseHandler;
static void ubus_ResponseHandler_dealloc(ubus_ResponseHandler* self)
{
blob_buf_free(&self->buf);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyDoc_STRVAR(
ResponseHandler_reply_doc,
"reply(data)\n"
"\n"
":param data: JSON to be send as a response to a ubus call.\n"
":type data: dict\n"
);
static PyObject *ubus_ResponseHandler_reply(ubus_ResponseHandler *self, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
PyObject *data = NULL;
static char *kwlist[] = {"data", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", kwlist, &data)) {
return NULL;
}
// Call python function json.dumps
PyObject *json_str = perform_json_function(DUMPS, data);
if (!json_str) {
return NULL;
}
// put json string into buffer
blob_buf_init(&self->buf, 0);
bool res = blobmsg_add_json_from_string(&self->buf, PyUnicode_AsUTF8(json_str));
Py_DECREF(json_str);
if (!res) {
PyErr_Format(PyExc_TypeError, MSG_JSON_TO_UBUS_FAILED);
return NULL;
}
// handler is not linked to a call response
if (!self->req || !self->ctx) {
PyErr_Format(PyExc_RuntimeError, "Handler is not linked to a call response.");
return NULL;
}
int retval = ubus_send_reply(self->ctx, self->req, self->buf.head);
return prepare_bool(!retval);
}
PyDoc_STRVAR(
ResponseHandler_doc,
"__ResponseHandler\n"
"\n"
"Object which is used to handle responses to ubus calls.\n"
);
static PyMethodDef ubus_ResponseHandler_methods[] = {
{"reply", (PyCFunction)ubus_ResponseHandler_reply, METH_VARARGS|METH_KEYWORDS, ResponseHandler_reply_doc},
{NULL},
};
static int ubus_ResponseHandler_init(ubus_ResponseHandler *self, PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "", kwlist)){
return -1;
}
memset(&self->buf, 0, sizeof(self->buf));
self->ctx = NULL;
self->req = NULL;
return 0;
}
static PyObject *ubus_ResponseHandler_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
ubus_ResponseHandler *self = (ubus_ResponseHandler *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static PyTypeObject ubus_ResponseHandlerType = {
PyVarObject_HEAD_INIT(NULL, 0)
RESPONSE_HANDLER_OBJECT_NAME, /* tp_name */
sizeof(ubus_ResponseHandler), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)ubus_ResponseHandler_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
ResponseHandler_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
ubus_ResponseHandler_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)ubus_ResponseHandler_init, /* tp_init */
0, /* tp_alloc */
ubus_ResponseHandler_new, /* tp_new */
};
typedef struct {
PyObject_HEAD
PyObject *socket_path;
ubus_Listener **listeners;
size_t listerners_size;
ubus_Object **objects;
size_t objects_size;
PyObject *alloc_list; // Used for easy deallocation
struct blob_buf buf;
struct ubus_context *ctx;
} ubus_Connection;
void free_ubus_object(ubus_Object *obj)
{
if (obj->object.methods) {
for (int i = 0; i < obj->object.n_methods; i++) {
if (&obj->object.methods[i] && obj->object.methods[i].policy) {
free((struct blobmsg_policy *)obj->object.methods[i].policy);
}
}
free((struct ubus_method *)obj->object.methods);
}
if (obj->object.type) {
free(obj->object.type);
}
free(obj);
}
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"ubus",
NULL,
sizeof(struct module_state),
ubus_methods,
NULL,
NULL,
NULL,
NULL
};
#endif
PyObject *ubus_python_module_init(void)
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule3("ubus", ubus_methods, "Ubus bindings");
#endif
return module;
}
PyDoc_STRVAR(
disconnect_doc,
"disconnect(deregister=True)\n"
"\n"
":param deregister: Deregisters object and handlers from ubus as well.\n"
":type deregister: bool\n"
"Disconnects from ubus and disposes all connection structures.\n"
);
void dispose_connection(bool deregister)
{
if (ctx != NULL) {
if (deregister) {
// remove objects
for (int i = 0; i < objects_size; i++) {
ubus_remove_object(ctx, &objects[i]->object);
}
// remove listeners
for (int i = 0; i < listerners_size; i++) {
ubus_unregister_event_handler(ctx, &listeners[i]->handler);
}
}
ubus_free(ctx);
ctx = NULL;
}
uloop_done();
blob_buf_free(&python_buf);
if (python_alloc_list) {
Py_DECREF(python_alloc_list);
python_alloc_list = NULL;
}
// clear event listeners
if (listeners) {
for (int i = 0; i < listerners_size; i++) {
free(listeners[i]);
}
free(listeners);
listerners_size = 0;
listeners = NULL;
}
// clear objects
if (objects) {
for (int i = 0; i < objects_size; i++) {
free_ubus_object(objects[i]);
}
free(objects);
objects_size = 0;
objects = NULL;
}
if (socket_path) {
free(socket_path);
socket_path = NULL;
}
}
static PyObject *ubus_python_disconnect(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
PyObject* deregister = Py_True;
static char *kwlist[] = {"deregister", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O!", kwlist, &PyBool_Type, &deregister)){
return NULL;
}
dispose_connection(PyObject_IsTrue(deregister));
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(
connect_doc,
"connect(socket_path='" DEFAULT_SOCKET "')\n"
"\n"
"Establishes a connection to ubus.\n"
);
static PyObject *ubus_python_connect(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_ALREADY_CONNECTED);
return NULL;
}
static char *kwlist[] = {"socket_path", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s", kwlist, &socket_path)){
return NULL;
}
// Init object list
python_alloc_list = PyList_New(0);
if (!python_alloc_list) {
return NULL;
}
// socket path
if (!socket_path) {
socket_path = strdup(DEFAULT_SOCKET);
if (!socket_path) {
PyErr_Format(PyExc_MemoryError, MSG_ALLOCATION_FAILS);
return NULL;
}
} else {
char *tmp = strdup(socket_path);
if (!tmp) {
PyErr_Format(PyExc_MemoryError, MSG_ALLOCATION_FAILS);
return NULL;
}
socket_path = tmp;
}
// Init event listner array
listeners = NULL;
listerners_size = 0;
// Init objects array
objects = NULL;
objects_size = 0;
// Connect to ubus
ctx = ubus_connect(socket_path);
if (!ctx) {
PyErr_Format(
PyExc_IOError,
"Failed to connect to the ubus socket '%s'\n", socket_path
);
dispose_connection(true);
return NULL;
}
ubus_add_uloop(ctx);
memset(&python_buf, 0, sizeof(python_buf));
return prepare_bool(true);
}
PyDoc_STRVAR(
get_connected_doc,
"get_connected()\n"
"\n"
"Determines whether we are connected to ubus.\n"
":return: True if connected, False otherwise.\n"
":rtype: bool \n"
);
static PyObject *ubus_python_get_connected(PyObject *module, PyObject *args, PyObject *kwargs)
{
return prepare_bool(CONNECTED);
}
PyDoc_STRVAR(
get_socket_path_doc,
"get_socket_path()\n"
"\n"
"Gets socket path for the current connection.\n"
":return: path to socket if connected, None otherwise.\n"
":rtype: bool or str \n"
);
static PyObject *ubus_python_get_socket_path(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (socket_path) {
return PyUnicode_FromString(socket_path);
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
PyDoc_STRVAR(
connect_send_doc,
"send(event, data)\n"
"\n"
"Send an event via ubus.\n"
"\n"
":param event: ubus event which will be used \n"
":type event: str\n"
":param data: python object which can be serialized to json \n"
":type data: dict or list \n"
":return: True on success, False otherwise \n"
":rtype: bool \n"
);
static PyObject *ubus_python_send(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
char *event = NULL;
PyObject *data = NULL;
static char *kwlist[] = {"event", "data", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO", kwlist, &event, &data)){
return NULL;
}
// Call python function json.dumps
PyObject *json_str = perform_json_function(DUMPS, data);
if (!json_str) {
return NULL;
}
// put json string into buffer
blob_buf_init(&python_buf, 0);
bool res = blobmsg_add_json_from_string(&python_buf, PyUnicode_AsUTF8(json_str));
Py_DECREF(json_str);
if (!res) {
PyErr_Format(PyExc_TypeError, MSG_JSON_TO_UBUS_FAILED);
return NULL;
}
int retval = ubus_send_event(ctx, event, python_buf.head);
return prepare_bool(!retval);
}
static void ubus_python_event_handler(struct ubus_context *ctx, struct ubus_event_handler *ev,
const char *type, struct blob_attr *msg)
{
PyGILState_STATE gstate = PyGILState_Ensure();
// Prepare event
PyObject *event = PyUnicode_FromString(type);
if (!event) {
goto event_handler_cleanup0;
}
// Prepare json data
char *str = blobmsg_format_json(msg, true);
if (!str) {
goto event_handler_cleanup1;
}
PyObject *data = PyUnicode_FromString(str);
free(str);
if (!data) {
goto event_handler_cleanup1;
}
// Call python function json.loads
PyObject *data_object = perform_json_function(LOADS, data);
if (!data_object) {
goto event_handler_cleanup2;
}
// Get PyObject callback
ubus_Listener *listener = container_of(ev, ubus_Listener, handler);
// Trigger callback
PyObject *callback_arglist = Py_BuildValue("(O, O)", event, data_object);
if (!callback_arglist) {
goto event_handler_cleanup3;
}
PyObject *result = PyObject_CallObject(listener->callback, callback_arglist);
if (result) {
Py_DECREF(result); // result of the callback is quite useless
} else {
PyErr_Print();
}
Py_DECREF(callback_arglist);
event_handler_cleanup3:
Py_DECREF(data_object);
event_handler_cleanup2:
Py_DECREF(data);
event_handler_cleanup1:
Py_DECREF(event);
event_handler_cleanup0:
// Clear python exceptions
PyErr_Clear();
PyGILState_Release(gstate);
}
PyDoc_STRVAR(
connect_listen_doc,
"listen(event, ...)\n"
"\n"
"Adds a listener on ubus events.\n"
"\n"
":param event: tuple contaning event string and a callback (str, callable) \n"
":type event: tuple\n"
);
static PyObject *ubus_python_listen(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
args = PySequence_Fast(args, "expected a sequence");
int len = PySequence_Size(args);
if (!len) {
PyErr_Format(PyExc_TypeError, "You need to set at least one event.");
goto listen_error1;
}
if (!PyTuple_Check(args)) {
PyErr_Format(PyExc_TypeError, "Tuple of (event, callback) expected.");
goto listen_error1;
}
// Test whether the arguments are valid
for (int i = 0; i < len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(args, i);
// Test tuple
if (!PyTuple_Check(item)) {
PyErr_Format(PyExc_TypeError, MSG_LISTEN_TUPLE_EXPECTED);
goto listen_error1;
}
PyObject *item_tuple = PySequence_Fast(item, MSG_LISTEN_TUPLE_EXPECTED);
if (!item_tuple) {
PyErr_Format(PyExc_MemoryError, "Failed to obtain tuple item");
goto listen_error1;
}
if (!PyTuple_Check(item_tuple) || PySequence_Size(item_tuple) != 2) {
PyErr_Format(PyExc_TypeError, MSG_LISTEN_TUPLE_EXPECTED);
Py_DECREF(item_tuple);
Py_DECREF(args);
goto listen_error1;
}
// Test types
if (!PyStr_Check(PyTuple_GET_ITEM(item_tuple, 0))
|| !PyCallable_Check(PyTuple_GET_ITEM(item_tuple, 1))) {
PyErr_Format(PyExc_TypeError, MSG_LISTEN_TUPLE_EXPECTED);
Py_DECREF(item_tuple);
goto listen_error1;
}
Py_DECREF(item_tuple);
}
// add callbacks
for (int i = 0; i < len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(args, i);
PyObject *item_tuple = PySequence_Fast(item, MSG_LISTEN_TUPLE_EXPECTED);
if (!item_tuple) {
PyErr_Format(PyExc_MemoryError, "Failed to obtain tuple item");
goto listen_error1;
}
PyObject *event = PyTuple_GET_ITEM(item_tuple, 0);
PyObject *callback = PyTuple_GET_ITEM(item_tuple, 1);
// Keep event and callback references
if (PyList_Append(python_alloc_list, event) || PyList_Append(python_alloc_list, callback)) {
Py_DECREF(item_tuple);
goto listen_error1;
}
Py_DECREF(item_tuple);
// prepare event listener
ubus_Listener *listener = calloc(1, sizeof(ubus_Listener));
if (!listener) {
PyErr_Format(PyExc_MemoryError, MSG_ALLOCATION_FAILS);
Py_DECREF(item_tuple);
goto listen_error1;
}
listener->handler.cb = ubus_python_event_handler;
listener->callback = callback;
ubus_Listener **new_listeners = realloc(listeners,
(listerners_size + 1) * sizeof(*listeners));
if (!new_listeners) {
free(listener);
goto listen_error1;
}
listeners = new_listeners;
listeners[listerners_size++] = listener;
// register event handler
int retval = ubus_register_event_handler(ctx, &listener->handler, PyUnicode_AsUTF8(event));
if (retval != UBUS_STATUS_OK) {
listerners_size--;
free(listener);
}
}
Py_DECREF(args);
Py_INCREF(Py_None);
return Py_None;
listen_error1:
Py_DECREF(args);
return NULL;
}
static void ubus_python_timeout_handler(struct uloop_timeout *timeout) {
uloop_end();
}
PyDoc_STRVAR(
connect_loop_doc,
"loop(timeout=-1)\n"
"\n"
"Enters a loop and processes events.\n"
"\n"
":param timeout: loop timeout in ms (if lower than zero then it will run forever) \n"
":type timeout: int\n"
);
static PyObject *ubus_python_loop(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
int timeout = -1;
static char *kwlist[] = {"timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout)){
return NULL;
}
Py_BEGIN_ALLOW_THREADS
if (timeout == 0) {
// process events directly without uloop
ubus_handle_event(ctx);
} else {
uloop_init();
struct uloop_timeout u_timeout;
if (timeout > 0) {
// prepare for timeout
memset(&u_timeout, 0, sizeof(u_timeout));
u_timeout.cb = ubus_python_timeout_handler;
uloop_timeout_set(&u_timeout, timeout); // Timeout to seconds
}
uloop_run();
if (timeout > 0) {
uloop_timeout_cancel(&u_timeout);
}
}
Py_END_ALLOW_THREADS
Py_INCREF(Py_None);
return Py_None;
}
bool test_policies(const struct blobmsg_policy *policies, int n_policies, struct blob_attr *args)
{
struct blob_attr *cur;
int idx = 0, passed_count = 0;
blob_for_each_attr(cur, args, idx) {
const char *name = blobmsg_name(cur);
int type = blobmsg_type(cur);
int pol_idx;
// Iterate through policies
for (pol_idx = 0; pol_idx < n_policies; pol_idx++) {
if (!strcmp(name, policies[pol_idx].name)) {
passed_count += 1;
int pol_type = policies[pol_idx].type;
if (pol_type != BLOBMSG_TYPE_UNSPEC && pol_type != type) {
return false;
}
break;
}
}
// Policy was not found
if (pol_idx >= n_policies) {
return false;
}
}
// All attributes are present and checked
return passed_count == n_policies;
}
static int ubus_python_method_handler(struct ubus_context *ctx, struct ubus_object *obj,
struct ubus_request_data *req, const char *method,
struct blob_attr *msg)
{
// Check whether method signature matches
int method_idx;
for (method_idx = 0; method_idx < obj->n_methods; ++method_idx) {
if (!strcmp(obj->methods[method_idx].name, method)) {
break;
}
}
if (method_idx >= obj->n_methods) {
// Can't find method
return UBUS_STATUS_UNKNOWN_ERROR;
}
if (!test_policies(obj->methods[method_idx].policy, obj->methods[method_idx].n_policy, msg)) {
return UBUS_STATUS_INVALID_ARGUMENT;
}
PyGILState_STATE gstate = PyGILState_Ensure();
int retval = UBUS_STATUS_OK;
// Get python method
PyObject *methods = container_of(obj, ubus_Object, object)->methods;
PyObject *python_method = PyDict_GetItemString(methods, method);
if (!python_method) {
retval = UBUS_STATUS_METHOD_NOT_FOUND;
goto method_handler_exit;
}
// prepare json data
char *str = blobmsg_format_json(msg, true);
if (!str) {
retval = UBUS_STATUS_UNKNOWN_ERROR;
goto method_handler_exit;
}
PyObject *data = PyUnicode_FromString(str);
free(str);
if (!data) {
retval = UBUS_STATUS_UNKNOWN_ERROR;
goto method_handler_exit;
}
// Call python function json.loads
PyObject *data_object = perform_json_function(LOADS, data);
if (!data_object) {
retval = UBUS_STATUS_UNKNOWN_ERROR;
goto method_handler_cleanup1;
}
PyObject *handler = PyObject_CallObject((PyObject *)&ubus_ResponseHandlerType, NULL);
if (!handler) {
PyErr_Print();
goto method_handler_cleanup2;
}
((ubus_ResponseHandler *)handler)->req = req;
((ubus_ResponseHandler *)handler)->ctx = ctx;
// Trigger method
PyObject *callback_arglist = Py_BuildValue("(O, O)", handler, data_object);
if (!callback_arglist) {
retval = UBUS_STATUS_UNKNOWN_ERROR;
goto method_handler_cleanup3;
}
PyObject *callable = PyDict_GetItemString(python_method, "method");
PyObject *result = PyObject_CallObject(callable, callback_arglist);
Py_DECREF(callback_arglist);
if (!result) {
PyErr_Print();
retval = UBUS_STATUS_UNKNOWN_ERROR;
} else {
Py_DECREF(result); // we don't care about the result
}
method_handler_cleanup3:
// NULLify the structures so that using this structure will we useless if a reference
// is left outside the callback code
((ubus_ResponseHandler *)handler)->req = NULL;
((ubus_ResponseHandler *)handler)->ctx = NULL;
Py_DECREF(handler);
method_handler_cleanup2:
Py_DECREF(data_object);
method_handler_cleanup1:
Py_DECREF(data);
method_handler_exit:
// Clear python exceptions
PyErr_Clear();
PyGILState_Release(gstate);
return retval;
}
static bool test_methods_argument(PyObject *methods)
{
if (!methods) {
return false;
}
PyObject *method_name = NULL, *value = NULL;
Py_ssize_t pos = 0;
// Iterate through methods
while(PyDict_Next(methods, &pos, &method_name, &value)) {
// Test name
if (!PyStr_Check(method_name)) {
return false;
}
if (!PyDict_Check(value)) {
return false;
}
// Dict should contain only two elemnts - 'signature' and 'method'
if (PyDict_Size(value) != 2) {
return false;
}
// Test signature
PyObject *signature = PyDict_GetItemString(value, "signature");
if (!signature || !PyDict_Check(signature)) {
return false;
}
Py_ssize_t sig_pos = 0;
PyObject *signature_name = NULL, *signature_type = NULL;
while (PyDict_Next(signature, &sig_pos, &signature_name, &signature_type)) {
if (!PyStr_Check(signature_name)) {
return false;
}
if (!PyInt_Check(signature_type)) {
return false;
}
int type = PyLong_AsLong(signature_type);
if (type < 0 || type > BLOBMSG_TYPE_LAST) { // indexed from 0
return false;
}
}
// Test callable
PyObject *method = PyDict_GetItemString(value, "method");
if (!method || !PyCallable_Check(method)) {
return false;
}
}
return true;
}
PyDoc_STRVAR(
connect_add_doc,
"add(object_name, methods)\n"
"\n"
"Adds an object to ubus.\n"
"methods should look like this: \n"
"{ \n"
" <method_name>: {'signature': <method_signature>, 'method': <callable>} \n"
"} \n"
"\n"
"{ \n"
" test: {'signature': {'argument1': BLOBMSG_TYPE_STRING}, 'method': my_callback} \n"
"} \n"
"\n"
":param object_name: the name of the object which will be present on ubus \n"
":type object_name: str\n"
":param methods: {<method_name>: callable} where callable signature is (request, msg) \n"
":type methods: dict\n"
);
static PyObject *ubus_python_add(PyObject *module, PyObject *args, PyObject *kwargs)
{
if (!CONNECTED) {
PyErr_Format(PyExc_RuntimeError, MSG_NOT_CONNECTED);
return NULL;
}
// arguments
PyObject *object_name = NULL;
PyObject *methods= NULL;
static char *kwlist[] = {"object_name", "methods", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO", kwlist, &object_name, &methods)){
return NULL;
}
// test arguments
if (!PyStr_Check(object_name)) {
PyErr_Format(PyExc_TypeError, MSG_ADD_SIGNATURE_INVALID);
return NULL;
}
if (!test_methods_argument(methods)) {
PyErr_Format(PyExc_TypeError, MSG_ADD_SIGNATURE_INVALID);
return NULL;
}
// allocate the object
ubus_Object *object = calloc(1, sizeof(ubus_Object));
if (!object) {
PyErr_Format(PyExc_MemoryError, MSG_ALLOCATION_FAILS);
return NULL;
}
object->methods = methods;
// set the object
object->object.name = PyUnicode_AsUTF8(object_name);
object->object.n_methods = PyDict_Size(methods);
if (object->object.n_methods > 0) {
struct ubus_method *ubus_methods = calloc(object->object.n_methods, sizeof(struct ubus_method));
if (!ubus_methods) {
free(object);