jobs: Fix a lock of call sync
[src/app-framework-binder.git] / bindings / samples / hi3.c
1 /*
2  * Copyright (C) 2015-2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
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 3
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(afb_api_t api, 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_api_make_event(api, name);
83         if (!e->event) { 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(NULL, NULL, "pingBug");
145 }
146
147 static void pingEvent(afb_req_t request)
148 {
149         json_object *query = afb_req_json(request);
150         afb_api_broadcast_event(request->api, "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 *closure, json_object *object, const char *error, const char *info, afb_req_t request)
173 {
174         afb_req_reply(request, json_object_get(object), error, info);
175 }
176
177 static void subcall (afb_req_t request)
178 {
179         const char *api = afb_req_value(request, "api");
180         const char *verb = afb_req_value(request, "verb");
181         const char *args = afb_req_value(request, "args");
182         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
183
184         if (object == NULL)
185                 afb_req_fail(request, "failed", "bad arguments");
186         else
187                 afb_req_subcall(request, api, verb, object, afb_req_subcall_pass_events, subcallcb, NULL);
188 }
189
190 static void subcallsync (afb_req_t request)
191 {
192         int rc;
193         const char *api = afb_req_value(request, "api");
194         const char *verb = afb_req_value(request, "verb");
195         const char *args = afb_req_value(request, "args");
196         json_object *oargs = api && verb && args ? json_tokener_parse(args) : NULL;
197         json_object *object;
198         char *error, *info;
199
200         if (oargs == NULL)
201                 afb_req_fail(request, "failed", "bad arguments");
202         else {
203                 rc = afb_req_subcall_sync(request, api, verb, oargs, afb_req_subcall_pass_events, &object, &error, &info);
204                 afb_req_reply_f(request, object, error, "rc=%d, info=%s", rc, info?:"NULL");
205                 free(error);
206                 free(info);
207         }
208 }
209
210 static void eventadd (afb_req_t request)
211 {
212         const char *tag = afb_req_value(request, "tag");
213         const char *name = afb_req_value(request, "name");
214
215         pthread_mutex_lock(&mutex);
216         if (tag == NULL || name == NULL)
217                 afb_req_fail(request, "failed", "bad arguments");
218         else if (0 != event_add(request->api, tag, name))
219                 afb_req_fail(request, "failed", "creation error");
220         else
221                 afb_req_success(request, NULL, NULL);
222         pthread_mutex_unlock(&mutex);
223 }
224
225 static void eventdel (afb_req_t request)
226 {
227         const char *tag = afb_req_value(request, "tag");
228
229         pthread_mutex_lock(&mutex);
230         if (tag == NULL)
231                 afb_req_fail(request, "failed", "bad arguments");
232         else if (0 != event_del(tag))
233                 afb_req_fail(request, "failed", "deletion error");
234         else
235                 afb_req_success(request, NULL, NULL);
236         pthread_mutex_unlock(&mutex);
237 }
238
239 static void eventsub (afb_req_t request)
240 {
241         const char *tag = afb_req_value(request, "tag");
242
243         pthread_mutex_lock(&mutex);
244         if (tag == NULL)
245                 afb_req_fail(request, "failed", "bad arguments");
246         else if (0 != event_subscribe(request, tag))
247                 afb_req_fail(request, "failed", "subscription error");
248         else
249                 afb_req_success(request, NULL, NULL);
250         pthread_mutex_unlock(&mutex);
251 }
252
253 static void eventunsub (afb_req_t request)
254 {
255         const char *tag = afb_req_value(request, "tag");
256
257         pthread_mutex_lock(&mutex);
258         if (tag == NULL)
259                 afb_req_fail(request, "failed", "bad arguments");
260         else if (0 != event_unsubscribe(request, tag))
261                 afb_req_fail(request, "failed", "unsubscription error");
262         else
263                 afb_req_success(request, NULL, NULL);
264         pthread_mutex_unlock(&mutex);
265 }
266
267 static void eventpush (afb_req_t request)
268 {
269         const char *tag = afb_req_value(request, "tag");
270         const char *data = afb_req_value(request, "data");
271         json_object *object = data ? json_tokener_parse(data) : NULL;
272
273         pthread_mutex_lock(&mutex);
274         if (tag == NULL)
275                 afb_req_fail(request, "failed", "bad arguments");
276         else if (0 > event_push(object, tag))
277                 afb_req_fail(request, "failed", "push error");
278         else
279                 afb_req_success(request, NULL, NULL);
280         pthread_mutex_unlock(&mutex);
281         json_object_put(object);
282 }
283
284 static void callcb (void *prequest, json_object *object, const char *error, const char *info, afb_api_t api)
285 {
286         afb_req_t request = prequest;
287         afb_req_reply(request, json_object_get(object), error, info);
288         afb_req_unref(request);
289 }
290
291 static void call (afb_req_t request)
292 {
293         const char *api = afb_req_value(request, "api");
294         const char *verb = afb_req_value(request, "verb");
295         const char *args = afb_req_value(request, "args");
296         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
297
298         if (object == NULL)
299                 afb_req_fail(request, "failed", "bad arguments");
300         else
301                 afb_api_call(request->api, api, verb, object, callcb, afb_req_addref(request));
302 }
303
304 static void callsync (afb_req_t request)
305 {
306         int rc;
307         const char *api = afb_req_value(request, "api");
308         const char *verb = afb_req_value(request, "verb");
309         const char *args = afb_req_value(request, "args");
310         json_object *oargs = api && verb && args ? json_tokener_parse(args) : NULL;
311         json_object *object;
312         char *error, *info;
313
314         if (oargs == NULL)
315                 afb_req_fail(request, "failed", "bad arguments");
316         else {
317                 rc = afb_api_call_sync(request->api, api, verb, oargs, &object, &error, &info);
318                 afb_req_reply_f(request, object, error, "rc=%d, info=%s", rc, info);
319                 free(error);
320                 free(info);
321         }
322 }
323
324 static void verbose (afb_req_t request)
325 {
326         int level = 5;
327         json_object *query = afb_req_json(request), *l;
328
329         if (json_object_is_type(query,json_type_int))
330                 level = json_object_get_int(query);
331         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
332                 level = json_object_get_int(l);
333
334         if (!json_object_object_get_ex(query,"message",&l))
335                 l = query;
336
337         AFB_REQ_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
338         afb_req_success(request, NULL, NULL);
339 }
340
341 static void exitnow (afb_req_t request)
342 {
343         int code = 0;
344         json_object *query = afb_req_json(request), *l;
345
346         if (json_object_is_type(query,json_type_int))
347                 code = json_object_get_int(query);
348         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
349                 code = json_object_get_int(l);
350
351         if (!json_object_object_get_ex(query,"reason",&l))
352                 l = NULL;
353
354         AFB_REQ_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
355         afb_req_success(request, NULL, NULL);
356         exit(code);
357 }
358
359 static void broadcast(afb_req_t request)
360 {
361         const char *tag = afb_req_value(request, "tag");
362         const char *name = afb_req_value(request, "name");
363         const char *data = afb_req_value(request, "data");
364         json_object *object = data ? json_tokener_parse(data) : NULL;
365
366         if (tag != NULL) {
367                 pthread_mutex_lock(&mutex);
368                 if (0 > event_broadcast(object, tag))
369                         afb_req_fail(request, "failed", "broadcast error");
370                 else
371                         afb_req_success(request, NULL, NULL);
372                 pthread_mutex_unlock(&mutex);
373         } else if (name != NULL) {
374                 if (0 > afb_api_broadcast_event(request->api, name, object))
375                         afb_req_fail(request, "failed", "broadcast error");
376                 else
377                         afb_req_success(request, NULL, NULL);
378         } else {
379                 afb_req_fail(request, "failed", "bad arguments");
380         }
381         json_object_put(object);
382 }
383
384 static void hasperm (afb_req_t request)
385 {
386         const char *perm = afb_req_value(request, "perm");
387         if (afb_req_has_permission(request, perm))
388                 afb_req_success_f(request, NULL, "permission %s granted", perm?:"(null)");
389         else
390                 afb_req_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
391 }
392
393 static void appid (afb_req_t request)
394 {
395         char *aid = afb_req_get_application_id(request);
396         afb_req_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
397         free(aid);
398 }
399
400 static int init(afb_api_t api)
401 {
402         AFB_API_NOTICE(api, "dynamic binding AVE(%s) starting", (const char*)api->userdata);
403         return 0;
404 }
405
406 static void onevent(afb_api_t api, const char *event, struct json_object *object)
407 {
408         AFB_API_NOTICE(api, "received event %s(%s) by AVE(%s)",
409                         event, json_object_to_json_string(object),
410                         (const char*)afb_api_get_userdata(api));
411 }
412
413 // NOTE: this sample does not use session to keep test a basic as possible
414 //       in real application most APIs should be protected with AFB_SESSION_CHECK
415 static const struct {
416         const char *verb;
417         void (*callback)(afb_req_t); } verbs[] =
418 {
419   { .verb="ping",        .callback=pingSample },
420   { .verb="pingfail",    .callback=pingFail },
421   { .verb="pingnull",    .callback=pingNull },
422   { .verb="pingbug",     .callback=pingBug },
423   { .verb="pingJson",    .callback=pingJson },
424   { .verb="pingevent",   .callback=pingEvent },
425   { .verb="subcall",     .callback=subcall },
426   { .verb="subcallsync", .callback=subcallsync },
427   { .verb="eventadd",    .callback=eventadd },
428   { .verb="eventdel",    .callback=eventdel },
429   { .verb="eventsub",    .callback=eventsub },
430   { .verb="eventunsub",  .callback=eventunsub },
431   { .verb="eventpush",   .callback=eventpush },
432   { .verb="call",        .callback=call },
433   { .verb="callsync",    .callback=callsync },
434   { .verb="verbose",     .callback=verbose },
435   { .verb="broadcast",   .callback=broadcast },
436   { .verb="hasperm",     .callback=hasperm },
437   { .verb="appid",       .callback=appid },
438   { .verb="exit",        .callback=exitnow },
439   { .verb=NULL}
440 };
441
442 static void pingoo(struct afb_req_x1 req)
443 {
444         json_object *args = afb_req_x1_json(req);
445         afb_req_x1_reply_f(req, json_object_get(args), NULL, "You reached pingoo \\o/ nice args: %s", json_object_to_json_string(args));
446 }
447
448 static const struct afb_verb_v2 verbsv2[]= {
449   { .verb="pingoo",    .callback=pingoo },
450   { .verb="ping",      .callback=pingoo },
451   { .verb=NULL}
452 };
453
454 static const char *apis[] = { "ave3", "hi3", "salut3", NULL };
455
456 static int build_api(void *closure, afb_api_t api)
457 {
458         int i, rc;
459
460         afb_api_set_userdata(api, closure);
461         AFB_API_NOTICE(api, "dynamic binding AVE(%s) comes to live", (const char*)afb_api_get_userdata(api));
462         afb_api_on_init(api, init);
463         afb_api_on_event(api, onevent);
464
465         rc = afb_api_set_verbs_v2(api, verbsv2);
466         for (i = rc = 0; verbs[i].verb && rc >= 0 ; i++) {
467                 rc = afb_api_add_verb(api, verbs[i].verb, NULL, verbs[i].callback, (void*)(intptr_t)i, NULL, 0, 0);
468         }
469         afb_api_seal(api);
470         return rc;
471 }
472
473 int afbBindingV3entry(afb_api_t api)
474 {
475         int i;
476         afb_api_t napi;
477
478         for (i = 0; apis[i] ; i++) {
479                 napi = afb_api_new_api(api, apis[i], NULL, 0, build_api, (void*)apis[i]);
480                 if (!napi)
481                         AFB_API_ERROR(api, "can't create API %s", apis[i]);
482         }
483         return 0;
484 }
485