jobs: Fix a lock of call sync
[src/app-framework-binder.git] / bindings / samples / HelloWorld.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 *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 *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
197
198         if (object == NULL)
199                 afb_req_fail(request, "failed", "bad arguments");
200         else {
201                 rc = afb_req_subcall_sync_legacy(request, api, verb, object, &result);
202                 if (rc >= 0)
203                         afb_req_success(request, result, NULL);
204                 else {
205                         afb_req_fail(request, "failed", json_object_to_json_string(result));
206                         json_object_put(result);
207                 }
208         }
209 }
210
211 static void eventadd (afb_req_t request)
212 {
213         const char *tag = afb_req_value(request, "tag");
214         const char *name = afb_req_value(request, "name");
215
216         pthread_mutex_lock(&mutex);
217         if (tag == NULL || name == NULL)
218                 afb_req_fail(request, "failed", "bad arguments");
219         else if (0 != event_add(tag, name))
220                 afb_req_fail(request, "failed", "creation error");
221         else
222                 afb_req_success(request, NULL, NULL);
223         pthread_mutex_unlock(&mutex);
224 }
225
226 static void eventdel (afb_req_t request)
227 {
228         const char *tag = afb_req_value(request, "tag");
229
230         pthread_mutex_lock(&mutex);
231         if (tag == NULL)
232                 afb_req_fail(request, "failed", "bad arguments");
233         else if (0 != event_del(tag))
234                 afb_req_fail(request, "failed", "deletion error");
235         else
236                 afb_req_success(request, NULL, NULL);
237         pthread_mutex_unlock(&mutex);
238 }
239
240 static void eventsub (afb_req_t request)
241 {
242         const char *tag = afb_req_value(request, "tag");
243
244         pthread_mutex_lock(&mutex);
245         if (tag == NULL)
246                 afb_req_fail(request, "failed", "bad arguments");
247         else if (0 != event_subscribe(request, tag))
248                 afb_req_fail(request, "failed", "subscription error");
249         else
250                 afb_req_success(request, NULL, NULL);
251         pthread_mutex_unlock(&mutex);
252 }
253
254 static void eventunsub (afb_req_t request)
255 {
256         const char *tag = afb_req_value(request, "tag");
257
258         pthread_mutex_lock(&mutex);
259         if (tag == NULL)
260                 afb_req_fail(request, "failed", "bad arguments");
261         else if (0 != event_unsubscribe(request, tag))
262                 afb_req_fail(request, "failed", "unsubscription error");
263         else
264                 afb_req_success(request, NULL, NULL);
265         pthread_mutex_unlock(&mutex);
266 }
267
268 static void eventpush (afb_req_t request)
269 {
270         const char *tag = afb_req_value(request, "tag");
271         const char *data = afb_req_value(request, "data");
272         json_object *object = data ? json_tokener_parse(data) : NULL;
273
274         pthread_mutex_lock(&mutex);
275         if (tag == NULL)
276                 afb_req_fail(request, "failed", "bad arguments");
277         else if (0 > event_push(object, tag))
278                 afb_req_fail(request, "failed", "push error");
279         else
280                 afb_req_success(request, NULL, NULL);
281         pthread_mutex_unlock(&mutex);
282         json_object_put(object);
283 }
284
285 static void callcb (void *prequest, json_object *object, const char *error, const char *info, afb_api_t api)
286 {
287         afb_req_t request = prequest;
288         afb_req_reply(request, json_object_get(object), error, info);
289         afb_req_unref(request);
290 }
291
292 static void call (afb_req_t request)
293 {
294         const char *api = afb_req_value(request, "api");
295         const char *verb = afb_req_value(request, "verb");
296         const char *args = afb_req_value(request, "args");
297         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
298
299         afb_service_call(api, verb, object, callcb, afb_req_addref(request));
300 }
301
302 static void callsync (afb_req_t request)
303 {
304         const char *api = afb_req_value(request, "api");
305         const char *verb = afb_req_value(request, "verb");
306         const char *args = afb_req_value(request, "args");
307         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
308         json_object *result;
309         char *error, *info;
310
311         afb_service_call_sync(api, verb, object, &result, &error, &info);
312         afb_req_reply(request, result, error, info);
313         free(error);
314         free(info);
315 }
316
317 static void verbose (afb_req_t request)
318 {
319         int level = 5;
320         json_object *query = afb_req_json(request), *l;
321
322         if (json_object_is_type(query,json_type_int))
323                 level = json_object_get_int(query);
324         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
325                 level = json_object_get_int(l);
326
327         if (!json_object_object_get_ex(query,"message",&l))
328                 l = query;
329
330         AFB_REQ_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
331         afb_req_success(request, NULL, NULL);
332 }
333
334 static void exitnow (afb_req_t request)
335 {
336         int code = 0;
337         json_object *query = afb_req_json(request), *l;
338
339         if (json_object_is_type(query,json_type_int))
340                 code = json_object_get_int(query);
341         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
342                 code = json_object_get_int(l);
343
344         if (!json_object_object_get_ex(query,"reason",&l))
345                 l = NULL;
346
347         AFB_REQ_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
348         afb_req_success(request, NULL, NULL);
349         exit(code);
350 }
351
352 static void broadcast(afb_req_t request)
353 {
354         const char *tag = afb_req_value(request, "tag");
355         const char *name = afb_req_value(request, "name");
356         const char *data = afb_req_value(request, "data");
357         json_object *object = data ? json_tokener_parse(data) : NULL;
358
359         if (tag != NULL) {
360                 pthread_mutex_lock(&mutex);
361                 if (0 > event_broadcast(object, tag))
362                         afb_req_fail(request, "failed", "broadcast error");
363                 else
364                         afb_req_success(request, NULL, NULL);
365                 pthread_mutex_unlock(&mutex);
366         } else if (name != NULL) {
367                 if (0 > afb_daemon_broadcast_event(name, object))
368                         afb_req_fail(request, "failed", "broadcast error");
369                 else
370                         afb_req_success(request, NULL, NULL);
371         } else {
372                 afb_req_fail(request, "failed", "bad arguments");
373         }
374         json_object_put(object);
375 }
376
377 static void hasperm (afb_req_t request)
378 {
379         const char *perm = afb_req_value(request, "perm");
380         if (afb_req_has_permission(request, perm))
381                 afb_req_success_f(request, NULL, "permission %s granted", perm?:"(null)");
382         else
383                 afb_req_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
384 }
385
386 static void appid (afb_req_t request)
387 {
388         char *aid = afb_req_get_application_id(request);
389         afb_req_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
390         free(aid);
391 }
392
393 static void uid (afb_req_t request)
394 {
395         int uid = afb_req_get_uid(request);
396         afb_req_success_f(request, json_object_new_int(uid), "uid is %d", uid);
397 }
398
399 static int preinit(afb_api_t api)
400 {
401         AFB_API_NOTICE(api, "hello binding comes to live");
402         return 0;
403 }
404
405 static int init(afb_api_t api)
406 {
407         AFB_API_NOTICE(api, "hello binding starting");
408         return 0;
409 }
410
411 static void onevent(afb_api_t api, const char *event, struct json_object *object)
412 {
413         AFB_API_NOTICE(api, "received event %s(%s)", event, json_object_to_json_string(object));
414 }
415
416 // NOTE: this sample does not use session to keep test a basic as possible
417 //       in real application most APIs should be protected with AFB_SESSION_CHECK
418 static const struct afb_verb_v3 verbs[]= {
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="uid",         .callback=uid },
439   { .verb="exit",        .callback=exitnow },
440   { .verb=NULL}
441 };
442
443 const struct afb_binding_v3 afbBindingV3 = {
444         .api = "hello",
445         .specification = NULL,
446         .verbs = verbs,
447         .preinit = preinit,
448         .init = init,
449         .onevent = onevent
450 };
451