hello3: Fix a bug
[src/app-framework-binder.git] / bindings / samples / hello3.c
1 /*
2  * Copyright (C) 2015-2018 "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 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(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) { 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_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, afb_req_t request)
173 {
174         if (status < 0)
175                 afb_req_fail(request, "failed", json_object_to_json_string(object));
176         else
177                 afb_req_success(request, json_object_get(object), NULL);
178 }
179
180 static void subcall (afb_req_t request)
181 {
182         const char *api = afb_req_value(request, "api");
183         const char *verb = afb_req_value(request, "verb");
184         const char *args = afb_req_value(request, "args");
185         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
186
187         if (object == NULL)
188                 afb_req_fail(request, "failed", "bad arguments");
189         else
190                 afb_req_subcall_legacy(request, api, verb, object, subcallcb, NULL);
191 }
192
193 static void subcallreqcb (void *prequest, int status, json_object *object, afb_req_t request)
194 {
195         if (status < 0)
196                 afb_req_fail(request, "failed", json_object_to_json_string(object));
197         else
198                 afb_req_success(request, json_object_get(object), NULL);
199 }
200
201 static void subcallreq (afb_req_t request)
202 {
203         const char *api = afb_req_value(request, "api");
204         const char *verb = afb_req_value(request, "verb");
205         const char *args = afb_req_value(request, "args");
206         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
207
208         if (object == NULL)
209                 afb_req_fail(request, "failed", "bad arguments");
210         else
211                 afb_req_subcall_legacy(request, api, verb, object, subcallreqcb, NULL);
212 }
213
214 static void subcallsync (afb_req_t request)
215 {
216         int rc;
217         const char *api = afb_req_value(request, "api");
218         const char *verb = afb_req_value(request, "verb");
219         const char *args = afb_req_value(request, "args");
220         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
221
222         if (object == NULL)
223                 afb_req_fail(request, "failed", "bad arguments");
224         else {
225                 rc = afb_req_subcall_sync_legacy(request, api, verb, object, &result);
226                 if (rc >= 0)
227                         afb_req_success(request, result, NULL);
228                 else {
229                         afb_req_fail(request, "failed", json_object_to_json_string(result));
230                         json_object_put(result);
231                 }
232         }
233 }
234
235 static void eventadd (afb_req_t request)
236 {
237         const char *tag = afb_req_value(request, "tag");
238         const char *name = afb_req_value(request, "name");
239
240         pthread_mutex_lock(&mutex);
241         if (tag == NULL || name == NULL)
242                 afb_req_fail(request, "failed", "bad arguments");
243         else if (0 != event_add(tag, name))
244                 afb_req_fail(request, "failed", "creation error");
245         else
246                 afb_req_success(request, NULL, NULL);
247         pthread_mutex_unlock(&mutex);
248 }
249
250 static void eventdel (afb_req_t request)
251 {
252         const char *tag = afb_req_value(request, "tag");
253
254         pthread_mutex_lock(&mutex);
255         if (tag == NULL)
256                 afb_req_fail(request, "failed", "bad arguments");
257         else if (0 != event_del(tag))
258                 afb_req_fail(request, "failed", "deletion error");
259         else
260                 afb_req_success(request, NULL, NULL);
261         pthread_mutex_unlock(&mutex);
262 }
263
264 static void eventsub (afb_req_t request)
265 {
266         const char *tag = afb_req_value(request, "tag");
267
268         pthread_mutex_lock(&mutex);
269         if (tag == NULL)
270                 afb_req_fail(request, "failed", "bad arguments");
271         else if (0 != event_subscribe(request, tag))
272                 afb_req_fail(request, "failed", "subscription error");
273         else
274                 afb_req_success(request, NULL, NULL);
275         pthread_mutex_unlock(&mutex);
276 }
277
278 static void eventunsub (afb_req_t request)
279 {
280         const char *tag = afb_req_value(request, "tag");
281
282         pthread_mutex_lock(&mutex);
283         if (tag == NULL)
284                 afb_req_fail(request, "failed", "bad arguments");
285         else if (0 != event_unsubscribe(request, tag))
286                 afb_req_fail(request, "failed", "unsubscription error");
287         else
288                 afb_req_success(request, NULL, NULL);
289         pthread_mutex_unlock(&mutex);
290 }
291
292 static void eventpush (afb_req_t request)
293 {
294         const char *tag = afb_req_value(request, "tag");
295         const char *data = afb_req_value(request, "data");
296         json_object *object = data ? json_tokener_parse(data) : NULL;
297
298         pthread_mutex_lock(&mutex);
299         if (tag == NULL)
300                 afb_req_fail(request, "failed", "bad arguments");
301         else if (0 > event_push(object, tag))
302                 afb_req_fail(request, "failed", "push error");
303         else
304                 afb_req_success(request, NULL, NULL);
305         pthread_mutex_unlock(&mutex);
306         json_object_put(object);
307 }
308
309 static void callcb (void *prequest, json_object *object, const char *error, const char *info, afb_api_t api)
310 {
311         afb_req_t request = prequest;
312         afb_req_reply(request, json_object_get(object), error, info);
313         afb_req_unref(request);
314 }
315
316 static void call (afb_req_t request)
317 {
318         const char *api = afb_req_value(request, "api");
319         const char *verb = afb_req_value(request, "verb");
320         const char *args = afb_req_value(request, "args");
321         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
322
323         afb_service_call(api, verb, object, callcb, afb_req_addref(request));
324 }
325
326 static void callsync (afb_req_t request)
327 {
328         const char *api = afb_req_value(request, "api");
329         const char *verb = afb_req_value(request, "verb");
330         const char *args = afb_req_value(request, "args");
331         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
332         json_object *result;
333         char *error, *info;
334
335         afb_service_call_sync(api, verb, object, &result, &error, &info);
336         afb_req_reply(request, result, error, info);
337         free(error);
338         free(info);
339 }
340
341 static void verbose (afb_req_t request)
342 {
343         int level = 5;
344         json_object *query = afb_req_json(request), *l;
345
346         if (json_object_is_type(query,json_type_int))
347                 level = json_object_get_int(query);
348         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
349                 level = json_object_get_int(l);
350
351         if (!json_object_object_get_ex(query,"message",&l))
352                 l = query;
353
354         AFB_REQ_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
355         afb_req_success(request, NULL, NULL);
356 }
357
358 static void exitnow (afb_req_t request)
359 {
360         int code = 0;
361         json_object *query = afb_req_json(request), *l;
362
363         if (json_object_is_type(query,json_type_int))
364                 code = json_object_get_int(query);
365         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
366                 code = json_object_get_int(l);
367
368         if (!json_object_object_get_ex(query,"reason",&l))
369                 l = NULL;
370
371         AFB_REQ_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
372         afb_req_success(request, NULL, NULL);
373         exit(code);
374 }
375
376 static void broadcast(afb_req_t request)
377 {
378         const char *tag = afb_req_value(request, "tag");
379         const char *name = afb_req_value(request, "name");
380         const char *data = afb_req_value(request, "data");
381         json_object *object = data ? json_tokener_parse(data) : NULL;
382
383         if (tag != NULL) {
384                 pthread_mutex_lock(&mutex);
385                 if (0 > event_broadcast(object, tag))
386                         afb_req_fail(request, "failed", "broadcast error");
387                 else
388                         afb_req_success(request, NULL, NULL);
389                 pthread_mutex_unlock(&mutex);
390         } else if (name != NULL) {
391                 if (0 > afb_daemon_broadcast_event(name, object))
392                         afb_req_fail(request, "failed", "broadcast error");
393                 else
394                         afb_req_success(request, NULL, NULL);
395         } else {
396                 afb_req_fail(request, "failed", "bad arguments");
397         }
398         json_object_put(object);
399 }
400
401 static void hasperm (afb_req_t request)
402 {
403         const char *perm = afb_req_value(request, "perm");
404         if (afb_req_has_permission(request, perm))
405                 afb_req_success_f(request, NULL, "permission %s granted", perm?:"(null)");
406         else
407                 afb_req_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
408 }
409
410 static void appid (afb_req_t request)
411 {
412         char *aid = afb_req_get_application_id(request);
413         afb_req_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
414         free(aid);
415 }
416
417 static void uid (afb_req_t request)
418 {
419         int uid = afb_req_get_uid(request);
420         afb_req_success_f(request, json_object_new_int(uid), "uid is %d", uid);
421 }
422
423 static void closess (afb_req_t request)
424 {
425         afb_req_session_close(request);
426         afb_req_reply(request, NULL, NULL, "session closed");
427 }
428
429 static void setloa (afb_req_t request)
430 {
431         int loa = json_object_get_int(afb_req_json(request));
432         afb_req_session_set_LOA(request, loa);
433         afb_req_reply_f(request, NULL, NULL, "LOA set to %d", loa);
434 }
435
436 static void setctx (afb_req_t request)
437 {
438         struct json_object *x = afb_req_json(request);
439         afb_req_context(request, (int)(intptr_t)afb_req_get_vcbdata(request), (void*)json_object_get, (void*)json_object_put, x);
440         afb_req_reply(request, json_object_get(x), NULL, "context set");
441 }
442
443 static void getctx (afb_req_t request)
444 {
445         struct json_object *x = afb_req_context(request, 0, 0, 0, 0);
446         afb_req_reply(request, json_object_get(x), NULL, "returning the context");
447 }
448
449 static void info (afb_req_t request)
450 {
451         afb_req_reply(request, afb_req_get_client_info(request), NULL, NULL);
452 }
453
454 static int preinit(afb_api_t api)
455 {
456         AFB_NOTICE("hello binding comes to live");
457         return 0;
458 }
459
460 static int init(afb_api_t api)
461 {
462         AFB_NOTICE("hello binding starting");
463         return 0;
464 }
465
466 static void onevent(afb_api_t api, const char *event, struct json_object *object)
467 {
468         AFB_NOTICE("received event %s(%s)", event, json_object_to_json_string(object));
469 }
470
471 // NOTE: this sample does not use session to keep test a basic as possible
472 //       in real application most APIs should be protected with AFB_SESSION_CHECK
473 static const struct afb_verb_v3 verbs[]= {
474   { .verb="ping",        .callback=pingSample },
475   { .verb="pingfail",    .callback=pingFail },
476   { .verb="pingnull",    .callback=pingNull },
477   { .verb="pingbug",     .callback=pingBug },
478   { .verb="pingJson",    .callback=pingJson },
479   { .verb="pingevent",   .callback=pingEvent },
480   { .verb="subcall",     .callback=subcall },
481   { .verb="subcallreq",  .callback=subcallreq },
482   { .verb="subcallsync", .callback=subcallsync },
483   { .verb="eventadd",    .callback=eventadd },
484   { .verb="eventdel",    .callback=eventdel },
485   { .verb="eventsub",    .callback=eventsub },
486   { .verb="eventunsub",  .callback=eventunsub },
487   { .verb="eventpush",   .callback=eventpush },
488   { .verb="call",        .callback=call },
489   { .verb="callsync",    .callback=callsync },
490   { .verb="verbose",     .callback=verbose },
491   { .verb="broadcast",   .callback=broadcast },
492   { .verb="hasperm",     .callback=hasperm },
493   { .verb="appid",       .callback=appid },
494   { .verb="uid",         .callback=uid },
495   { .verb="exit",        .callback=exitnow },
496   { .verb="close",       .callback=closess },
497   { .verb="set-loa",     .callback=setloa },
498   { .verb="setctx",      .callback=setctx, .vcbdata = (void*)(intptr_t)1 },
499   { .verb="setctxif",    .callback=setctx, .vcbdata = (void*)(intptr_t)0 },
500   { .verb="getctx",      .callback=getctx },
501   { .verb="info",        .callback=info },
502   { .verb=NULL}
503 };
504
505 #if !defined(APINAME)
506 #define APINAME "hello3"
507 #endif
508
509 const struct afb_binding_v3 afbBindingV3 = {
510         .api = APINAME,
511         .specification = NULL,
512         .verbs = verbs,
513         .preinit = preinit,
514         .init = init,
515         .onevent = onevent
516 };
517