Send error replies on disconnection
[src/app-framework-binder.git] / bindings / samples / ave.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_WANT_DYNAPI
25 #define AFB_BINDING_VERSION 0
26 #include <afb/afb-binding.h>
27
28 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
29
30 struct event
31 {
32         struct event *next;
33         afb_eventid *eventid;
34         char tag[1];
35 };
36
37 static struct event *events = 0;
38
39 /* searchs the event of tag */
40 static struct event *event_get(const char *tag)
41 {
42         struct event *e = events;
43         while(e && strcmp(e->tag, tag))
44                 e = e->next;
45         return e;
46 }
47
48 /* deletes the event of tag */
49 static int event_del(const char *tag)
50 {
51         struct event *e, **p;
52
53         /* check exists */
54         e = event_get(tag);
55         if (!e) return -1;
56
57         /* unlink */
58         p = &events;
59         while(*p != e) p = &(*p)->next;
60         *p = e->next;
61
62         /* destroys */
63         afb_eventid_unref(e->eventid);
64         free(e);
65         return 0;
66 }
67
68 /* creates the event of tag */
69 static int event_add(afb_dynapi *dynapi, const char *tag, const char *name)
70 {
71         struct event *e;
72
73         /* check valid tag */
74         e = event_get(tag);
75         if (e) return -1;
76
77         /* creation */
78         e = malloc(strlen(tag) + sizeof *e);
79         if (!e) return -1;
80         strcpy(e->tag, tag);
81
82         /* make the event */
83         e->eventid = afb_dynapi_make_eventid(dynapi, name);
84         if (!e->eventid) { free(e); return -1; }
85
86         /* link */
87         e->next = events;
88         events = e;
89         return 0;
90 }
91
92 static int event_subscribe(afb_request *request, const char *tag)
93 {
94         struct event *e;
95         e = event_get(tag);
96         return e ? afb_request_subscribe(request, e->eventid) : -1;
97 }
98
99 static int event_unsubscribe(afb_request *request, const char *tag)
100 {
101         struct event *e;
102         e = event_get(tag);
103         return e ? afb_request_unsubscribe(request, e->eventid) : -1;
104 }
105
106 static int event_push(struct json_object *args, const char *tag)
107 {
108         struct event *e;
109         e = event_get(tag);
110         return e ? afb_eventid_push(e->eventid, json_object_get(args)) : -1;
111 }
112
113 static int event_broadcast(struct json_object *args, const char *tag)
114 {
115         struct event *e;
116         e = event_get(tag);
117         return e ? afb_eventid_broadcast(e->eventid, json_object_get(args)) : -1;
118 }
119
120 // Sample Generic Ping Debug API
121 static void ping(afb_request *request, json_object *jresp, const char *tag)
122 {
123         static int pingcount = 0;
124         json_object *query = afb_request_json(request);
125         afb_request_success_f(request, jresp, "Ping Binder Daemon tag=%s count=%d query=%s", tag, ++pingcount, json_object_to_json_string(query));
126 }
127
128 static void pingSample (afb_request *request)
129 {
130         ping(request, json_object_new_string ("Some String"), "pingSample");
131 }
132
133 static void pingFail (afb_request *request)
134 {
135         afb_request_fail(request, "failed", "Ping Binder Daemon fails");
136 }
137
138 static void pingNull (afb_request *request)
139 {
140         ping(request, NULL, "pingNull");
141 }
142
143 static void pingBug (afb_request *request)
144 {
145         ping(NULL, NULL, "pingBug");
146 }
147
148 static void pingEvent(afb_request *request)
149 {
150         json_object *query = afb_request_json(request);
151         afb_dynapi_broadcast_event(request->api, "event", json_object_get(query));
152         ping(request, json_object_get(query), "event");
153 }
154
155
156 // For samples https://linuxprograms.wordpress.com/2010/05/20/json-c-libjson-tutorial/
157 static void pingJson (afb_request *request) {
158     json_object *jresp, *embed;
159
160     jresp = json_object_new_object();
161     json_object_object_add(jresp, "myString", json_object_new_string ("Some String"));
162     json_object_object_add(jresp, "myInt", json_object_new_int (1234));
163
164     embed  = json_object_new_object();
165     json_object_object_add(embed, "subObjString", json_object_new_string ("Some String"));
166     json_object_object_add(embed, "subObjInt", json_object_new_int (5678));
167
168     json_object_object_add(jresp,"eobj", embed);
169
170     ping(request, jresp, "pingJson");
171 }
172
173 static void subcallcb (void *closure, int status, json_object *object, afb_request *request)
174 {
175         if (status < 0)
176                 afb_request_fail(request, "failed", json_object_to_json_string(object));
177         else
178                 afb_request_success(request, json_object_get(object), NULL);
179 }
180
181 static void subcall (afb_request *request)
182 {
183         const char *api = afb_request_value(request, "api");
184         const char *verb = afb_request_value(request, "verb");
185         const char *args = afb_request_value(request, "args");
186         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
187
188         if (object == NULL)
189                 afb_request_fail(request, "failed", "bad arguments");
190         else
191                 afb_request_subcall(request, api, verb, object, subcallcb, NULL);
192 }
193
194 static void subcallsync (afb_request *request)
195 {
196         int rc;
197         const char *api = afb_request_value(request, "api");
198         const char *verb = afb_request_value(request, "verb");
199         const char *args = afb_request_value(request, "args");
200         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
201
202         if (object == NULL)
203                 afb_request_fail(request, "failed", "bad arguments");
204         else {
205                 rc = afb_request_subcall_sync(request, api, verb, object, &result);
206                 if (rc >= 0)
207                         afb_request_success(request, result, NULL);
208                 else {
209                         afb_request_fail(request, "failed", json_object_to_json_string(result));
210                         json_object_put(result);
211                 }
212         }
213 }
214
215 static void eventadd (afb_request *request)
216 {
217         const char *tag = afb_request_value(request, "tag");
218         const char *name = afb_request_value(request, "name");
219
220         pthread_mutex_lock(&mutex);
221         if (tag == NULL || name == NULL)
222                 afb_request_fail(request, "failed", "bad arguments");
223         else if (0 != event_add(request->api, tag, name))
224                 afb_request_fail(request, "failed", "creation error");
225         else
226                 afb_request_success(request, NULL, NULL);
227         pthread_mutex_unlock(&mutex);
228 }
229
230 static void eventdel (afb_request *request)
231 {
232         const char *tag = afb_request_value(request, "tag");
233
234         pthread_mutex_lock(&mutex);
235         if (tag == NULL)
236                 afb_request_fail(request, "failed", "bad arguments");
237         else if (0 != event_del(tag))
238                 afb_request_fail(request, "failed", "deletion error");
239         else
240                 afb_request_success(request, NULL, NULL);
241         pthread_mutex_unlock(&mutex);
242 }
243
244 static void eventsub (afb_request *request)
245 {
246         const char *tag = afb_request_value(request, "tag");
247
248         pthread_mutex_lock(&mutex);
249         if (tag == NULL)
250                 afb_request_fail(request, "failed", "bad arguments");
251         else if (0 != event_subscribe(request, tag))
252                 afb_request_fail(request, "failed", "subscription error");
253         else
254                 afb_request_success(request, NULL, NULL);
255         pthread_mutex_unlock(&mutex);
256 }
257
258 static void eventunsub (afb_request *request)
259 {
260         const char *tag = afb_request_value(request, "tag");
261
262         pthread_mutex_lock(&mutex);
263         if (tag == NULL)
264                 afb_request_fail(request, "failed", "bad arguments");
265         else if (0 != event_unsubscribe(request, tag))
266                 afb_request_fail(request, "failed", "unsubscription error");
267         else
268                 afb_request_success(request, NULL, NULL);
269         pthread_mutex_unlock(&mutex);
270 }
271
272 static void eventpush (afb_request *request)
273 {
274         const char *tag = afb_request_value(request, "tag");
275         const char *data = afb_request_value(request, "data");
276         json_object *object = data ? json_tokener_parse(data) : NULL;
277
278         pthread_mutex_lock(&mutex);
279         if (tag == NULL)
280                 afb_request_fail(request, "failed", "bad arguments");
281         else if (0 > event_push(object, tag))
282                 afb_request_fail(request, "failed", "push error");
283         else
284                 afb_request_success(request, NULL, NULL);
285         pthread_mutex_unlock(&mutex);
286         json_object_put(object);
287 }
288
289 static void callcb (void *prequest, int status, json_object *object, afb_dynapi *dynapi)
290 {
291         afb_request *request = prequest;
292         if (status < 0)
293                 afb_request_fail(request, "failed", json_object_to_json_string(object));
294         else
295                 afb_request_success(request, json_object_get(object), NULL);
296         afb_request_unref(request);
297 }
298
299 static void call (afb_request *request)
300 {
301         const char *api = afb_request_value(request, "api");
302         const char *verb = afb_request_value(request, "verb");
303         const char *args = afb_request_value(request, "args");
304         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
305
306         if (object == NULL)
307                 afb_request_fail(request, "failed", "bad arguments");
308         else
309                 afb_dynapi_call(request->api, api, verb, object, callcb, afb_request_addref(request));
310 }
311
312 static void callsync (afb_request *request)
313 {
314         int rc;
315         const char *api = afb_request_value(request, "api");
316         const char *verb = afb_request_value(request, "verb");
317         const char *args = afb_request_value(request, "args");
318         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
319
320         if (object == NULL)
321                 afb_request_fail(request, "failed", "bad arguments");
322         else {
323                 rc = afb_dynapi_call_sync(request->api, api, verb, object, &result);
324                 if (rc >= 0)
325                         afb_request_success(request, result, NULL);
326                 else {
327                         afb_request_fail(request, "failed", json_object_to_json_string(result));
328                         json_object_put(result);
329                 }
330         }
331 }
332
333 static void verbose (afb_request *request)
334 {
335         int level = 5;
336         json_object *query = afb_request_json(request), *l;
337
338         if (json_object_is_type(query,json_type_int))
339                 level = json_object_get_int(query);
340         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
341                 level = json_object_get_int(l);
342
343         if (!json_object_object_get_ex(query,"message",&l))
344                 l = query;
345
346         AFB_REQUEST_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
347         afb_request_success(request, NULL, NULL);
348 }
349
350 static void exitnow (afb_request *request)
351 {
352         int code = 0;
353         json_object *query = afb_request_json(request), *l;
354
355         if (json_object_is_type(query,json_type_int))
356                 code = json_object_get_int(query);
357         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
358                 code = json_object_get_int(l);
359
360         if (!json_object_object_get_ex(query,"reason",&l))
361                 l = NULL;
362
363         AFB_REQUEST_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
364         afb_request_success(request, NULL, NULL);
365         exit(code);
366 }
367
368 static void broadcast(afb_request *request)
369 {
370         const char *tag = afb_request_value(request, "tag");
371         const char *name = afb_request_value(request, "name");
372         const char *data = afb_request_value(request, "data");
373         json_object *object = data ? json_tokener_parse(data) : NULL;
374
375         if (tag != NULL) {
376                 pthread_mutex_lock(&mutex);
377                 if (0 > event_broadcast(object, tag))
378                         afb_request_fail(request, "failed", "broadcast error");
379                 else
380                         afb_request_success(request, NULL, NULL);
381                 pthread_mutex_unlock(&mutex);
382         } else if (name != NULL) {
383                 if (0 > afb_dynapi_broadcast_event(request->api, name, object))
384                         afb_request_fail(request, "failed", "broadcast error");
385                 else
386                         afb_request_success(request, NULL, NULL);
387         } else {
388                 afb_request_fail(request, "failed", "bad arguments");
389         }
390         json_object_put(object);
391 }
392
393 static void hasperm (afb_request *request)
394 {
395         const char *perm = afb_request_value(request, "perm");
396         if (afb_request_has_permission(request, perm))
397                 afb_request_success_f(request, NULL, "permission %s granted", perm?:"(null)");
398         else
399                 afb_request_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
400 }
401
402 static void appid (afb_request *request)
403 {
404         char *aid = afb_request_get_application_id(request);
405         afb_request_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
406         free(aid);
407 }
408
409 static int init(afb_dynapi *dynapi)
410 {
411         AFB_DYNAPI_NOTICE(dynapi, "dynamic binding AVE(%s) starting", (const char*)dynapi->userdata);
412         return 0;
413 }
414
415 static void onevent(afb_dynapi *dynapi, const char *event, struct json_object *object)
416 {
417         AFB_DYNAPI_NOTICE(dynapi, "received event %s(%s) by AVE(%s)",
418                         event, json_object_to_json_string(object),
419                         (const char*)afb_dynapi_get_userdata(dynapi));
420 }
421
422 // NOTE: this sample does not use session to keep test a basic as possible
423 //       in real application most APIs should be protected with AFB_SESSION_CHECK
424 static const struct {
425         const char *verb;
426         void (*callback)(afb_request*); } verbs[] =
427 {
428   { .verb="ping",        .callback=pingSample },
429   { .verb="pingfail",    .callback=pingFail },
430   { .verb="pingnull",    .callback=pingNull },
431   { .verb="pingbug",     .callback=pingBug },
432   { .verb="pingJson",    .callback=pingJson },
433   { .verb="pingevent",   .callback=pingEvent },
434   { .verb="subcall",     .callback=subcall },
435   { .verb="subcallsync", .callback=subcallsync },
436   { .verb="eventadd",    .callback=eventadd },
437   { .verb="eventdel",    .callback=eventdel },
438   { .verb="eventsub",    .callback=eventsub },
439   { .verb="eventunsub",  .callback=eventunsub },
440   { .verb="eventpush",   .callback=eventpush },
441   { .verb="call",        .callback=call },
442   { .verb="callsync",    .callback=callsync },
443   { .verb="verbose",     .callback=verbose },
444   { .verb="broadcast",   .callback=broadcast },
445   { .verb="hasperm",     .callback=hasperm },
446   { .verb="appid",       .callback=appid },
447   { .verb="exit",        .callback=exitnow },
448   { .verb=NULL}
449 };
450
451 static void pingoo(struct afb_req_x1 req)
452 {
453         json_object *args = afb_req_x1_json(req);
454         afb_req_x1_reply_f(req, json_object_get(args), NULL, "You reached pingoo \\o/ nice args: %s", json_object_to_json_string(args));
455 }
456
457 static const struct afb_verb_v2 verbsv2[]= {
458   { .verb="pingoo",      .callback=pingoo },
459   { .verb="ping",      .callback=pingoo },
460   { .verb=NULL}
461 };
462
463 static const char *apis[] = { "ave", "hi", "salut", NULL };
464
465 static int build_api(void *closure, afb_dynapi *dynapi)
466 {
467         int i, rc;
468
469         afb_dynapi_set_userdata(dynapi, closure);
470         AFB_DYNAPI_NOTICE(dynapi, "dynamic binding AVE(%s) comes to live", (const char*)afb_dynapi_get_userdata(dynapi));
471         afb_dynapi_on_init(dynapi, init);
472         afb_dynapi_on_event(dynapi, onevent);
473
474         rc = afb_dynapi_set_verbs_v2(dynapi, verbsv2);
475         for (i = rc = 0; verbs[i].verb && rc >= 0 ; i++) {
476                 rc = afb_dynapi_add_verb(dynapi, verbs[i].verb, NULL, verbs[i].callback, (void*)(intptr_t)i, NULL, 0);
477         }
478         afb_dynapi_seal(dynapi);
479         return rc;
480 }
481
482 int afbBindingVdyn(afb_dynapi *dynapi)
483 {
484         int i, rc;
485
486         for (i = 0; apis[i] ; i++) {
487                 rc = afb_dynapi_new_api(dynapi, apis[i], NULL, 0, build_api, (void*)apis[i]);
488                 if (rc < 0)
489                         AFB_DYNAPI_ERROR(dynapi, "can't create API %s", apis[i]);
490         }
491         return 0;
492 }
493