ef9e65d952ef2998cb8221f96962fac7f7f1f910
[src/app-framework-binder.git] / bindings / samples / hello2.c
1 /*
2  * Copyright (C) 2015-2019 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #define _GNU_SOURCE
18 #include <stdio.h>
19 #include <string.h>
20 #include <pthread.h>
21
22 #include <json-c/json.h>
23
24 #define AFB_BINDING_VERSION 2
25 #include <afb/afb-binding.h>
26
27 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
28
29 struct event
30 {
31         struct event *next;
32         afb_event_t event;
33         char tag[1];
34 };
35
36 static struct event *events = 0;
37
38 /* searchs the event of tag */
39 static struct event *event_get(const char *tag)
40 {
41         struct event *e = events;
42         while(e && strcmp(e->tag, tag))
43                 e = e->next;
44         return e;
45 }
46
47 /* deletes the event of tag */
48 static int event_del(const char *tag)
49 {
50         struct event *e, **p;
51
52         /* check exists */
53         e = event_get(tag);
54         if (!e) return -1;
55
56         /* unlink */
57         p = &events;
58         while(*p != e) p = &(*p)->next;
59         *p = e->next;
60
61         /* destroys */
62         afb_event_unref(e->event);
63         free(e);
64         return 0;
65 }
66
67 /* creates the event of tag */
68 static int event_add(const char *tag, const char *name)
69 {
70         struct event *e;
71
72         /* check valid tag */
73         e = event_get(tag);
74         if (e) return -1;
75
76         /* creation */
77         e = malloc(strlen(tag) + sizeof *e);
78         if (!e) return -1;
79         strcpy(e->tag, tag);
80
81         /* make the event */
82         e->event = afb_daemon_make_event(name);
83         if (!e->event.closure) { free(e); return -1; }
84
85         /* link */
86         e->next = events;
87         events = e;
88         return 0;
89 }
90
91 static int event_subscribe(afb_req_t request, const char *tag)
92 {
93         struct event *e;
94         e = event_get(tag);
95         return e ? afb_req_subscribe(request, e->event) : -1;
96 }
97
98 static int event_unsubscribe(afb_req_t request, const char *tag)
99 {
100         struct event *e;
101         e = event_get(tag);
102         return e ? afb_req_unsubscribe(request, e->event) : -1;
103 }
104
105 static int event_push(struct json_object *args, const char *tag)
106 {
107         struct event *e;
108         e = event_get(tag);
109         return e ? afb_event_push(e->event, json_object_get(args)) : -1;
110 }
111
112 static int event_broadcast(struct json_object *args, const char *tag)
113 {
114         struct event *e;
115         e = event_get(tag);
116         return e ? afb_event_broadcast(e->event, json_object_get(args)) : -1;
117 }
118
119 // Sample Generic Ping Debug API
120 static void ping(afb_req_t request, json_object *jresp, const char *tag)
121 {
122         static int pingcount = 0;
123         json_object *query = afb_req_json(request);
124         afb_req_success_f(request, jresp, "Ping Binder Daemon tag=%s count=%d query=%s", tag, ++pingcount, json_object_to_json_string(query));
125 }
126
127 static void pingSample (afb_req_t request)
128 {
129         ping(request, json_object_new_string ("Some String"), "pingSample");
130 }
131
132 static void pingFail (afb_req_t request)
133 {
134         afb_req_fail(request, "failed", "Ping Binder Daemon fails");
135 }
136
137 static void pingNull (afb_req_t request)
138 {
139         ping(request, NULL, "pingNull");
140 }
141
142 static void pingBug (afb_req_t request)
143 {
144         ping((afb_req_t){NULL,NULL}, NULL, "pingBug");
145 }
146
147 static void pingEvent(afb_req_t request)
148 {
149         json_object *query = afb_req_json(request);
150         afb_daemon_broadcast_event("event", json_object_get(query));
151         ping(request, json_object_get(query), "event");
152 }
153
154
155 // For samples https://linuxprograms.wordpress.com/2010/05/20/json-c-libjson-tutorial/
156 static void pingJson (afb_req_t request) {
157     json_object *jresp, *embed;
158
159     jresp = json_object_new_object();
160     json_object_object_add(jresp, "myString", json_object_new_string ("Some String"));
161     json_object_object_add(jresp, "myInt", json_object_new_int (1234));
162
163     embed  = json_object_new_object();
164     json_object_object_add(embed, "subObjString", json_object_new_string ("Some String"));
165     json_object_object_add(embed, "subObjInt", json_object_new_int (5678));
166
167     json_object_object_add(jresp,"eobj", embed);
168
169     ping(request, jresp, "pingJson");
170 }
171
172 static void subcallcb (void *prequest, int status, json_object *object)
173 {
174         afb_req_t request = afb_req_unstore(prequest);
175         if (status < 0)
176                 afb_req_fail(request, "failed", json_object_to_json_string(object));
177         else
178                 afb_req_success(request, json_object_get(object), NULL);
179         afb_req_unref(request);
180 }
181
182 static void subcall (afb_req_t request)
183 {
184         const char *api = afb_req_value(request, "api");
185         const char *verb = afb_req_value(request, "verb");
186         const char *args = afb_req_value(request, "args");
187         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
188
189         if (object == NULL)
190                 afb_req_fail(request, "failed", "bad arguments");
191         else
192                 afb_req_subcall(request, api, verb, object, subcallcb, afb_req_store(request));
193 }
194
195 static void subcallreqcb (void *prequest, int status, json_object *object, afb_req_t request)
196 {
197         if (status < 0)
198                 afb_req_fail(request, "failed", json_object_to_json_string(object));
199         else
200                 afb_req_success(request, json_object_get(object), NULL);
201 }
202
203 static void subcallreq (afb_req_t request)
204 {
205         const char *api = afb_req_value(request, "api");
206         const char *verb = afb_req_value(request, "verb");
207         const char *args = afb_req_value(request, "args");
208         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
209
210         if (object == NULL)
211                 afb_req_fail(request, "failed", "bad arguments");
212         else
213                 afb_req_subcall_req(request, api, verb, object, subcallreqcb, NULL);
214 }
215
216 static void subcallsync (afb_req_t request)
217 {
218         int rc;
219         const char *api = afb_req_value(request, "api");
220         const char *verb = afb_req_value(request, "verb");
221         const char *args = afb_req_value(request, "args");
222         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
223
224         if (object == NULL)
225                 afb_req_fail(request, "failed", "bad arguments");
226         else {
227                 rc = afb_req_subcall_sync(request, api, verb, object, &result);
228                 if (rc >= 0)
229                         afb_req_success(request, result, NULL);
230                 else {
231                         afb_req_fail(request, "failed", json_object_to_json_string(result));
232                         json_object_put(result);
233                 }
234         }
235 }
236
237 static void eventadd (afb_req_t request)
238 {
239         const char *tag = afb_req_value(request, "tag");
240         const char *name = afb_req_value(request, "name");
241
242         pthread_mutex_lock(&mutex);
243         if (tag == NULL || name == NULL)
244                 afb_req_fail(request, "failed", "bad arguments");
245         else if (0 != event_add(tag, name))
246                 afb_req_fail(request, "failed", "creation error");
247         else
248                 afb_req_success(request, NULL, NULL);
249         pthread_mutex_unlock(&mutex);
250 }
251
252 static void eventdel (afb_req_t request)
253 {
254         const char *tag = afb_req_value(request, "tag");
255
256         pthread_mutex_lock(&mutex);
257         if (tag == NULL)
258                 afb_req_fail(request, "failed", "bad arguments");
259         else if (0 != event_del(tag))
260                 afb_req_fail(request, "failed", "deletion error");
261         else
262                 afb_req_success(request, NULL, NULL);
263         pthread_mutex_unlock(&mutex);
264 }
265
266 static void eventsub (afb_req_t request)
267 {
268         const char *tag = afb_req_value(request, "tag");
269
270         pthread_mutex_lock(&mutex);
271         if (tag == NULL)
272                 afb_req_fail(request, "failed", "bad arguments");
273         else if (0 != event_subscribe(request, tag))
274                 afb_req_fail(request, "failed", "subscription error");
275         else
276                 afb_req_success(request, NULL, NULL);
277         pthread_mutex_unlock(&mutex);
278 }
279
280 static void eventunsub (afb_req_t request)
281 {
282         const char *tag = afb_req_value(request, "tag");
283
284         pthread_mutex_lock(&mutex);
285         if (tag == NULL)
286                 afb_req_fail(request, "failed", "bad arguments");
287         else if (0 != event_unsubscribe(request, tag))
288                 afb_req_fail(request, "failed", "unsubscription error");
289         else
290                 afb_req_success(request, NULL, NULL);
291         pthread_mutex_unlock(&mutex);
292 }
293
294 static void eventpush (afb_req_t request)
295 {
296         const char *tag = afb_req_value(request, "tag");
297         const char *data = afb_req_value(request, "data");
298         json_object *object = data ? json_tokener_parse(data) : NULL;
299
300         pthread_mutex_lock(&mutex);
301         if (tag == NULL)
302                 afb_req_fail(request, "failed", "bad arguments");
303         else if (0 > event_push(object, tag))
304                 afb_req_fail(request, "failed", "push error");
305         else
306                 afb_req_success(request, NULL, NULL);
307         pthread_mutex_unlock(&mutex);
308         json_object_put(object);
309 }
310
311 static void callcb (void *prequest, int status, json_object *object)
312 {
313         afb_req_t request = afb_req_unstore(prequest);
314         if (status < 0)
315                 afb_req_fail(request, "failed", json_object_to_json_string(object));
316         else
317                 afb_req_success(request, json_object_get(object), NULL);
318         afb_req_unref(request);
319 }
320
321 static void call (afb_req_t request)
322 {
323         const char *api = afb_req_value(request, "api");
324         const char *verb = afb_req_value(request, "verb");
325         const char *args = afb_req_value(request, "args");
326         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
327
328         if (object == NULL)
329                 afb_req_fail(request, "failed", "bad arguments");
330         else
331                 afb_service_call(api, verb, object, callcb, afb_req_store(request));
332 }
333
334 static void callsync (afb_req_t request)
335 {
336         int rc;
337         const char *api = afb_req_value(request, "api");
338         const char *verb = afb_req_value(request, "verb");
339         const char *args = afb_req_value(request, "args");
340         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
341
342         if (object == NULL)
343                 afb_req_fail(request, "failed", "bad arguments");
344         else {
345                 rc = afb_service_call_sync(api, verb, object, &result);
346                 if (rc >= 0)
347                         afb_req_success(request, result, NULL);
348                 else {
349                         afb_req_fail(request, "failed", json_object_to_json_string(result));
350                         json_object_put(result);
351                 }
352         }
353 }
354
355 static void verbose (afb_req_t request)
356 {
357         int level = 5;
358         json_object *query = afb_req_json(request), *l;
359
360         if (json_object_is_type(query,json_type_int))
361                 level = json_object_get_int(query);
362         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
363                 level = json_object_get_int(l);
364
365         if (!json_object_object_get_ex(query,"message",&l))
366                 l = query;
367
368         AFB_REQ_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
369         afb_req_success(request, NULL, NULL);
370 }
371
372 static void exitnow (afb_req_t request)
373 {
374         int code = 0;
375         json_object *query = afb_req_json(request), *l;
376
377         if (json_object_is_type(query,json_type_int))
378                 code = json_object_get_int(query);
379         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
380                 code = json_object_get_int(l);
381
382         if (!json_object_object_get_ex(query,"reason",&l))
383                 l = NULL;
384
385         AFB_REQ_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
386         afb_req_success(request, NULL, NULL);
387         exit(code);
388 }
389
390 static void broadcast(afb_req_t request)
391 {
392         const char *tag = afb_req_value(request, "tag");
393         const char *name = afb_req_value(request, "name");
394         const char *data = afb_req_value(request, "data");
395         json_object *object = data ? json_tokener_parse(data) : NULL;
396
397         if (tag != NULL) {
398                 pthread_mutex_lock(&mutex);
399                 if (0 > event_broadcast(object, tag))
400                         afb_req_fail(request, "failed", "broadcast error");
401                 else
402                         afb_req_success(request, NULL, NULL);
403                 pthread_mutex_unlock(&mutex);
404         } else if (name != NULL) {
405                 if (0 > afb_daemon_broadcast_event(name, object))
406                         afb_req_fail(request, "failed", "broadcast error");
407                 else
408                         afb_req_success(request, NULL, NULL);
409         } else {
410                 afb_req_fail(request, "failed", "bad arguments");
411         }
412         json_object_put(object);
413 }
414
415 static void hasperm (afb_req_t request)
416 {
417         const char *perm = afb_req_value(request, "perm");
418         if (afb_req_has_permission(request, perm))
419                 afb_req_success_f(request, NULL, "permission %s granted", perm?:"(null)");
420         else
421                 afb_req_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
422 }
423
424 static void appid (afb_req_t request)
425 {
426         char *aid = afb_req_get_application_id(request);
427         afb_req_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
428         free(aid);
429 }
430
431 static void uid (afb_req_t request)
432 {
433         int uid = afb_req_get_uid(request);
434         afb_req_success_f(request, json_object_new_int(uid), "uid is %d", uid);
435 }
436
437 static void closess (afb_req_t request)
438 {
439         afb_req_session_close(request);
440         afb_req_success(request, NULL, "session closed");
441 }
442
443 static void setloa (afb_req_t request)
444 {
445         int loa = json_object_get_int(afb_req_json(request));
446         afb_req_session_set_LOA(request, loa);
447         afb_req_success_f(request, NULL, "LOA set to %d", loa);
448 }
449
450 static void setctx (afb_req_t request, int force)
451 {
452         struct json_object *x = afb_req_json(request);
453         afb_req_context_make(request, force, (void*)json_object_get, (void*)json_object_put, x);
454         afb_req_success_f(request, json_object_get(x), "context set (force = %d)", force);
455 }
456
457 static void setctxset (afb_req_t request)
458 {
459         setctx(request, 1);
460 }
461
462 static void setctxif (afb_req_t request)
463 {
464         setctx(request, 0);
465 }
466
467 static void getctx (afb_req_t request)
468 {
469         struct json_object *x = afb_req_context_make(request, 0, 0, 0, 0);
470         afb_req_success(request, json_object_get(x), "returning the context");
471 }
472
473 static void info (afb_req_t request)
474 {
475         afb_req_success(request, afb_req_get_client_info(request), NULL);
476 }
477
478 static int preinit()
479 {
480         AFB_NOTICE("hello binding comes to live");
481         return 0;
482 }
483
484 static int init()
485 {
486         AFB_NOTICE("hello binding starting");
487         return 0;
488 }
489
490 static void onevent(const char *event, struct json_object *object)
491 {
492         AFB_NOTICE("received event %s(%s)", event, json_object_to_json_string(object));
493 }
494
495 // NOTE: this sample does not use session to keep test a basic as possible
496 //       in real application most APIs should be protected with AFB_SESSION_CHECK
497 static const afb_verb_v2 verbs[]= {
498   { .verb="ping",        .callback=pingSample },
499   { .verb="pingfail",    .callback=pingFail },
500   { .verb="pingnull",    .callback=pingNull },
501   { .verb="pingbug",     .callback=pingBug },
502   { .verb="pingJson",    .callback=pingJson },
503   { .verb="pingevent",   .callback=pingEvent },
504   { .verb="subcall",     .callback=subcall },
505   { .verb="subcallreq",  .callback=subcallreq },
506   { .verb="subcallsync", .callback=subcallsync },
507   { .verb="eventadd",    .callback=eventadd },
508   { .verb="eventdel",    .callback=eventdel },
509   { .verb="eventsub",    .callback=eventsub },
510   { .verb="eventunsub",  .callback=eventunsub },
511   { .verb="eventpush",   .callback=eventpush },
512   { .verb="call",        .callback=call },
513   { .verb="callsync",    .callback=callsync },
514   { .verb="verbose",     .callback=verbose },
515   { .verb="broadcast",   .callback=broadcast },
516   { .verb="hasperm",     .callback=hasperm },
517   { .verb="appid",       .callback=appid },
518   { .verb="uid",         .callback=uid },
519   { .verb="exit",        .callback=exitnow },
520   { .verb="close",       .callback=closess },
521   { .verb="set-loa",     .callback=setloa },
522   { .verb="setctx",      .callback=setctxset },
523   { .verb="setctxif",    .callback=setctxif },
524   { .verb="getctx",      .callback=getctx },
525   { .verb="info",        .callback=info },
526   { .verb=NULL}
527 };
528
529 #if !defined(APINAME)
530 #define APINAME "hello2"
531 #endif
532
533 const afb_binding_v2 afbBindingV2 = {
534         .api = APINAME,
535         .specification = NULL,
536         .verbs = verbs,
537         .preinit = preinit,
538         .init = init,
539         .onevent = onevent
540 };
541