afb-stub-ws: cosmetic improvements
[src/app-framework-binder.git] / src / afb-stub-ws.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "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
18 #define _GNU_SOURCE
19
20 #define NO_PLUGIN_VERBOSE_MACRO
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <endian.h>
29 #include <netdb.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <pthread.h>
34
35 #include <json-c/json.h>
36
37 #include <afb/afb-event.h>
38
39 #include "afb-session.h"
40 #include "afb-cred.h"
41 #include "afb-api.h"
42 #include "afb-apiset.h"
43 #include "afb-proto-ws.h"
44 #include "afb-stub-ws.h"
45 #include "afb-context.h"
46 #include "afb-evt.h"
47 #include "afb-xreq.h"
48 #include "verbose.h"
49 #include "fdev.h"
50 #include "jobs.h"
51
52 struct afb_stub_ws;
53
54
55 /******************* handling subcalls *****************************/
56
57 /**
58  * Structure on server side for recording pending
59  * subcalls.
60  */
61 struct server_subcall
62 {
63         struct server_subcall *next;    /**< next subcall for the client */
64         uint32_t subcallid;             /**< the subcallid */
65         void (*callback)(void*, int, struct json_object*); /**< callback on completion */
66         void *closure;                  /**< closure of the callback */
67 };
68
69 /**
70  * Structure for sending back replies on client side
71  */
72 struct client_subcall
73 {
74         struct afb_stub_ws *stubws;     /**< stub descriptor */
75         uint32_t subcallid;             /**< subcallid for the reply */
76 };
77
78 /*
79  * structure for recording calls on client side
80  */
81 struct client_call {
82         struct client_call *next;       /* the next call */
83         struct afb_stub_ws *stubws;     /* the stub_ws */
84         struct afb_xreq *xreq;          /* the request handle */
85         uint32_t msgid;                 /* the message identifier */
86 };
87
88 /*
89  * structure for a ws request
90  */
91 struct server_req {
92         struct afb_xreq xreq;           /* the xreq */
93         struct afb_stub_ws *stubws;     /* the client of the request */
94         struct afb_proto_ws_call *call; /* the incoming call */
95 };
96
97 /*
98  * structure for recording events on client side
99  */
100 struct client_event
101 {
102         struct client_event *next;
103         struct afb_eventid *eventid;
104         int id;
105         int refcount;
106 };
107
108 /*
109  * structure for recording describe requests
110  */
111 struct client_describe
112 {
113         struct afb_stub_ws *stubws;
114         struct jobloop *jobloop;
115         struct json_object *result;
116 };
117
118 /*
119  * structure for jobs of describing
120  */
121 struct server_describe
122 {
123         struct afb_stub_ws *stubws;
124         struct afb_proto_ws_describe *describe;
125 };
126
127 /*
128  * structure for recording sessions
129  */
130 struct server_session
131 {
132         struct server_session *next;
133         struct afb_session *session;
134 };
135
136 /******************* stub description for client or servers ******************/
137
138 struct afb_stub_ws
139 {
140         /* count of references */
141         int refcount;
142
143         /* resource control */
144         pthread_mutex_t mutex;
145
146         /* protocol */
147         struct afb_proto_ws *proto;
148
149         /* listener for events (server side) */
150         struct afb_evt_listener *listener;
151
152         /* event replica (client side) */
153         struct client_event *events;
154
155         /* credentials (server side) */
156         struct afb_cred *cred;
157
158         /* sessions (server side) */
159         struct server_session *sessions;
160
161         /* apiset */
162         struct afb_apiset *apiset;
163
164         /* on hangup callback */
165         void (*on_hangup)(struct afb_stub_ws *);
166
167         /* the api name */
168         char apiname[1];
169 };
170
171 /******************* ws request part for server *****************/
172
173 /* decrement the reference count of the request and free/release it on falling to null */
174 static void server_req_destroy_cb(struct afb_xreq *xreq)
175 {
176         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
177
178         afb_context_disconnect(&wreq->xreq.context);
179         afb_cred_unref(wreq->xreq.cred);
180         json_object_put(wreq->xreq.json);
181         afb_proto_ws_call_unref(wreq->call);
182         afb_stub_ws_unref(wreq->stubws);
183         free(wreq);
184 }
185
186 static void server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info)
187 {
188         int rc;
189         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
190
191         rc = afb_proto_ws_call_success(wreq->call, obj, info);
192         if (rc < 0)
193                 ERROR("error while sending success");
194         json_object_put(obj);
195 }
196
197 static void server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info)
198 {
199         int rc;
200         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
201
202         rc = afb_proto_ws_call_fail(wreq->call, status, info);
203         if (rc < 0)
204                 ERROR("error while sending fail");
205 }
206
207 static void server_req_subcall_cb(struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args, void (*callback)(void*, int, struct json_object*), void *cb_closure)
208 {
209         int rc;
210         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
211
212         rc = afb_proto_ws_call_subcall(wreq->call, api, verb, args, callback, cb_closure);
213         if (rc < 0)
214                 ERROR("error while sending subcall");
215 }
216
217 static int server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_eventid *event)
218 {
219         int rc;
220         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
221
222         rc = afb_evt_eventid_add_watch(wreq->stubws->listener, event);
223         if (rc >= 0)
224                 rc = afb_proto_ws_call_subscribe(wreq->call,  afb_evt_eventid_fullname(event), afb_evt_eventid_id(event));
225         if (rc < 0)
226                 ERROR("error while subscribing event");
227         return rc;
228 }
229
230 static int server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_eventid *event)
231 {
232         int rc, rc2;
233         struct server_req *wreq = CONTAINER_OF_XREQ(struct server_req, xreq);
234
235         rc = afb_proto_ws_call_unsubscribe(wreq->call,  afb_evt_eventid_fullname(event), afb_evt_eventid_id(event));
236         rc2 = afb_evt_eventid_remove_watch(wreq->stubws->listener, event);
237         if (rc >= 0 && rc2 < 0)
238                 rc = rc2;
239         if (rc < 0)
240                 ERROR("error while unsubscribing event");
241         return rc;
242 }
243
244 static const struct afb_xreq_query_itf server_req_xreq_itf = {
245         .success = server_req_success_cb,
246         .fail = server_req_fail_cb,
247         .unref = server_req_destroy_cb,
248         .subcall = server_req_subcall_cb,
249         .subscribe = server_req_subscribe_cb,
250         .unsubscribe = server_req_unsubscribe_cb
251 };
252
253 /******************* client part **********************************/
254
255 /* search the event */
256 static struct client_event *client_event_search(struct afb_stub_ws *stubws, uint32_t eventid, const char *name)
257 {
258         struct client_event *ev;
259
260         ev = stubws->events;
261         while (ev != NULL && (ev->id != eventid || 0 != strcmp(afb_evt_eventid_fullname(ev->eventid), name)))
262                 ev = ev->next;
263
264         return ev;
265 }
266
267 /* on call, propagate it to the ws service */
268 static void client_call_cb(void * closure, struct afb_xreq *xreq)
269 {
270         struct afb_stub_ws *stubws = closure;
271
272         afb_proto_ws_client_call(stubws->proto, xreq->request.verb, afb_xreq_json(xreq), afb_session_uuid(xreq->context.session), xreq);
273         afb_xreq_unhooked_addref(xreq);
274 }
275
276 static void client_on_description_cb(void *closure, struct json_object *data)
277 {
278         struct client_describe *desc = closure;
279
280         desc->result = data;
281         jobs_leave(desc->jobloop);
282 }
283
284 static void client_send_describe_cb(int signum, void *closure, struct jobloop *jobloop)
285 {
286         struct client_describe *desc = closure;
287
288         if (signum)
289                 jobs_leave(jobloop);
290         else {
291                 desc->jobloop = jobloop;
292                 afb_proto_ws_client_describe(desc->stubws->proto, client_on_description_cb, desc);
293         }
294 }
295
296 /* get the description */
297 static struct json_object *client_describe_cb(void * closure)
298 {
299         struct client_describe desc;
300
301         /* synchronous job: send the request and wait its result */
302         desc.stubws = closure;
303         desc.result = NULL;
304         jobs_enter(NULL, 0, client_send_describe_cb, &desc);
305         return desc.result;
306 }
307
308 /******************* server part: manage events **********************************/
309
310 static void server_event_add(void *closure, const char *event, int eventid)
311 {
312         struct afb_stub_ws *stubws = closure;
313
314         afb_proto_ws_server_event_create(stubws->proto, event, eventid);
315 }
316
317 static void server_event_remove(void *closure, const char *event, int eventid)
318 {
319         struct afb_stub_ws *stubws = closure;
320
321         afb_proto_ws_server_event_remove(stubws->proto, event, eventid);
322 }
323
324 static void server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
325 {
326         struct afb_stub_ws *stubws = closure;
327
328         afb_proto_ws_server_event_push(stubws->proto, event, eventid, object);
329         json_object_put(object);
330 }
331
332 static void server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
333 {
334         struct afb_stub_ws *stubws = closure;
335
336         afb_proto_ws_server_event_broadcast(stubws->proto, event, object);
337         json_object_put(object);
338 }
339
340 /*****************************************************/
341
342 static void on_reply_success(void *closure, void *request, struct json_object *result, const char *info)
343 {
344         struct afb_xreq *xreq = request;
345
346         afb_xreq_success(xreq, result, *info ? info : NULL);
347         afb_xreq_unhooked_unref(xreq);
348 }
349
350 static void on_reply_fail(void *closure, void *request, const char *status, const char *info)
351 {
352         struct afb_xreq *xreq = request;
353
354         afb_xreq_fail(xreq, status, *info ? info : NULL);
355         afb_xreq_unhooked_unref(xreq);
356 }
357
358 static void on_event_create(void *closure, const char *event_name, int event_id)
359 {
360         struct afb_stub_ws *stubws = closure;
361         struct client_event *ev;
362
363         /* check conflicts */
364         ev = client_event_search(stubws, event_id, event_name);
365         if (ev != NULL) {
366                 ev->refcount++;
367                 return;
368         }
369
370         /* no conflict, try to add it */
371         ev = malloc(sizeof *ev);
372         if (ev != NULL) {
373                 ev->eventid = afb_evt_eventid_create(event_name);
374                 if (ev->eventid != NULL) {
375                         ev->refcount = 1;
376                         ev->id = event_id;
377                         ev->next = stubws->events;
378                         stubws->events = ev;
379                         return;
380                 }
381                 free(ev);
382         }
383         ERROR("can't create event %s, out of memory", event_name);
384 }
385
386 static void on_event_remove(void *closure, const char *event_name, int event_id)
387 {
388         struct afb_stub_ws *stubws = closure;
389         struct client_event *ev, **prv;
390
391         /* check conflicts */
392         ev = client_event_search(stubws, event_id, event_name);
393         if (ev == NULL)
394                 return;
395
396         /* decrease the reference count */
397         if (--ev->refcount)
398                 return;
399
400         /* unlinks the event */
401         prv = &stubws->events;
402         while (*prv != ev)
403                 prv = &(*prv)->next;
404         *prv = ev->next;
405
406         /* destroys the event */
407         afb_evt_eventid_unref(ev->eventid);
408         free(ev);
409 }
410
411 static void on_event_subscribe(void *closure, void *request, const char *event_name, int event_id)
412 {
413         struct afb_stub_ws *stubws = closure;
414         struct afb_xreq *xreq = request;
415         struct client_event *ev;
416
417         /* check conflicts */
418         ev = client_event_search(stubws, event_id, event_name);
419         if (ev == NULL)
420                 return;
421
422         if (afb_xreq_subscribe(xreq, ev->eventid) < 0)
423                 ERROR("can't subscribe: %m");
424 }
425
426 static void on_event_unsubscribe(void *closure, void *request, const char *event_name, int event_id)
427 {
428         struct afb_stub_ws *stubws = closure;
429         struct afb_xreq *xreq = request;
430         struct client_event *ev;
431
432         /* check conflicts */
433         ev = client_event_search(stubws, event_id, event_name);
434         if (ev == NULL)
435                 return;
436
437         if (afb_xreq_unsubscribe(xreq, ev->eventid) < 0)
438                 ERROR("can't unsubscribe: %m");
439 }
440
441 static void on_event_push(void *closure, const char *event_name, int event_id, struct json_object *data)
442 {
443         struct afb_stub_ws *stubws = closure;
444         struct client_event *ev;
445
446         /* check conflicts */
447         ev = client_event_search(stubws, event_id, event_name);
448         if (ev)
449                 afb_evt_eventid_push(ev->eventid, data);
450         else
451                 ERROR("unreadable push event");
452 }
453
454 static void on_event_broadcast(void *closure, const char *event_name, struct json_object *data)
455 {
456         afb_evt_broadcast(event_name, data);
457 }
458
459 static void client_subcall_reply_cb(void *closure, int status, json_object *object, struct afb_request *request)
460 {
461         struct afb_proto_ws_subcall *subcall = closure;
462         afb_proto_ws_subcall_reply(subcall, status, object);
463 }
464
465 static void on_subcall(void *closure, struct afb_proto_ws_subcall *subcall, void *request, const char *api, const char *verb, struct json_object *args)
466 {
467         struct afb_xreq *xreq = request;
468
469         afb_xreq_subcall(xreq, api, verb, args, client_subcall_reply_cb, subcall);
470 }
471
472 /*****************************************************/
473
474 static void record_session(struct afb_stub_ws *stubws, struct afb_session *session)
475 {
476         struct server_session *s, **prv;
477
478         /* search */
479         prv = &stubws->sessions;
480         while ((s = *prv)) {
481                 if (s->session == session)
482                         return;
483                 if (afb_session_is_closed(s->session)) {
484                         *prv = s->next;
485                         afb_session_unref(s->session);
486                         free(s);
487                 }
488                 else
489                         prv = &s->next;
490         }
491
492         /* create */
493         s = malloc(sizeof *s);
494         if (s) {
495                 s->session = afb_session_addref(session);
496                 s->next = stubws->sessions;
497                 stubws->sessions = s;
498         }
499 }
500
501 static void release_all_sessions(struct afb_stub_ws *stubws)
502 {
503         struct server_session *s, *n;
504
505         s = stubws->sessions;
506         stubws->sessions = NULL;
507         while(s) {
508                 n = s->next;
509                 afb_session_unref(s->session);
510                 free(s);
511                 s = n;
512         }
513 }
514
515 /*****************************************************/
516
517 static void on_call(void *closure, struct afb_proto_ws_call *call, const char *verb, struct json_object *args, const char *sessionid)
518 {
519         struct afb_stub_ws *stubws = closure;
520         struct server_req *wreq;
521
522         afb_stub_ws_addref(stubws);
523
524         /* create the request */
525         wreq = malloc(sizeof *wreq);
526         if (wreq == NULL)
527                 goto out_of_memory;
528
529         afb_xreq_init(&wreq->xreq, &server_req_xreq_itf);
530         wreq->stubws = stubws;
531         wreq->call = call;
532
533         /* init the context */
534         if (afb_context_connect(&wreq->xreq.context, sessionid, NULL) < 0)
535                 goto unconnected;
536         wreq->xreq.context.validated = 1;
537         record_session(stubws, wreq->xreq.context.session);
538         if (wreq->xreq.context.created)
539                 afb_session_set_autoclose(wreq->xreq.context.session, 1);
540
541         /* makes the call */
542         wreq->xreq.cred = afb_cred_addref(stubws->cred);
543         wreq->xreq.request.api = stubws->apiname;
544         wreq->xreq.request.verb = verb;
545         wreq->xreq.json = args;
546         afb_xreq_process(&wreq->xreq, stubws->apiset);
547         return;
548
549 unconnected:
550         free(wreq);
551 out_of_memory:
552         json_object_put(args);
553         afb_stub_ws_unref(stubws);
554         afb_proto_ws_call_fail(call, "internal-error", NULL);
555         afb_proto_ws_call_unref(call);
556 }
557
558 static void server_describe_sjob(int signum, void *closure)
559 {
560         struct json_object *obj;
561         struct server_describe *desc = closure;
562
563         /* get the description if possible */
564         obj = !signum ? afb_apiset_describe(desc->stubws->apiset, desc->stubws->apiname) : NULL;
565
566         /* send it */
567         afb_proto_ws_describe_put(desc->describe, obj);
568         json_object_put(obj);
569         afb_stub_ws_unref(desc->stubws);
570 }
571
572 static void server_describe_job(int signum, void *closure)
573 {
574         server_describe_sjob(signum, closure);
575         free(closure);
576 }
577
578 static void on_describe(void *closure, struct afb_proto_ws_describe *describe)
579 {
580         struct server_describe *desc, sdesc;
581         struct afb_stub_ws *stubws = closure;
582
583         /* allocate (if possible) and init */
584         desc = malloc(sizeof *desc);
585         if (desc == NULL)
586                 desc = &sdesc;
587         desc->stubws = stubws;
588         desc->describe = describe;
589         afb_stub_ws_addref(stubws);
590
591         /* process */
592         if (desc == &sdesc)
593                 jobs_call(NULL, 0, server_describe_sjob, desc);
594         else {
595                 if (jobs_queue(NULL, 0, server_describe_job, desc) < 0)
596                         jobs_call(NULL, 0, server_describe_job, desc);
597         }
598 }
599
600 /*****************************************************/
601
602 static const struct afb_proto_ws_client_itf client_itf =
603 {
604         .on_reply_success = on_reply_success,
605         .on_reply_fail = on_reply_fail,
606         .on_event_create = on_event_create,
607         .on_event_remove = on_event_remove,
608         .on_event_subscribe = on_event_subscribe,
609         .on_event_unsubscribe = on_event_unsubscribe,
610         .on_event_push = on_event_push,
611         .on_event_broadcast = on_event_broadcast,
612         .on_subcall = on_subcall
613 };
614
615 static const struct afb_proto_ws_server_itf server_itf =
616 {
617         .on_call = on_call,
618         .on_describe = on_describe
619 };
620
621 static struct afb_api_itf ws_api_itf = {
622         .call = client_call_cb,
623         .describe = client_describe_cb
624 };
625
626 /* the interface for events pushing */
627 static const struct afb_evt_itf server_evt_itf = {
628         .broadcast = server_event_broadcast,
629         .push = server_event_push,
630         .add = server_event_add,
631         .remove = server_event_remove
632 };
633
634 /*****************************************************/
635
636 static void drop_all_events(struct afb_stub_ws *stubws)
637 {
638         struct client_event *ev, *nxt;
639
640         ev = stubws->events;
641         stubws->events = NULL;
642
643         while (ev) {
644                 nxt = ev->next;
645                 afb_evt_eventid_unref(ev->eventid);
646                 free(ev);
647                 ev = nxt;
648         }
649 }
650
651 /* callback when receiving a hangup */
652 static void on_hangup(void *closure)
653 {
654         struct afb_stub_ws *stubws = closure;
655
656         afb_stub_ws_addref(stubws);
657         if (stubws->on_hangup)
658                 stubws->on_hangup(stubws);
659
660         release_all_sessions(stubws);
661         afb_stub_ws_unref(stubws);
662 }
663
664 /*****************************************************/
665
666 static struct afb_stub_ws *afb_stub_ws_create(struct fdev *fdev, const char *apiname, struct afb_apiset *apiset, int client)
667 {
668         struct afb_stub_ws *stubws;
669
670         stubws = calloc(1, sizeof *stubws + strlen(apiname));
671         if (stubws == NULL)
672                 errno = ENOMEM;
673         else {
674                 if (client)
675                         stubws->proto = afb_proto_ws_create_client(fdev, &client_itf, stubws);
676                 else
677                         stubws->proto = afb_proto_ws_create_server(fdev, &server_itf, stubws);
678
679                 if (stubws->proto) {
680                         strcpy(stubws->apiname, apiname);
681                         stubws->apiset = afb_apiset_addref(apiset);
682                         stubws->refcount = 1;
683                         afb_proto_ws_on_hangup(stubws->proto, on_hangup);
684                         return stubws;
685                 }
686                 free(stubws);
687         }
688         fdev_unref(fdev);
689         return NULL;
690 }
691
692 struct afb_stub_ws *afb_stub_ws_create_client(struct fdev *fdev, const char *apiname, struct afb_apiset *apiset)
693 {
694         return afb_stub_ws_create(fdev, apiname, apiset, 1);
695 }
696
697 struct afb_stub_ws *afb_stub_ws_create_server(struct fdev *fdev, const char *apiname, struct afb_apiset *apiset)
698 {
699         struct afb_stub_ws *stubws;
700
701         stubws = afb_stub_ws_create(fdev, apiname, apiset, 0);
702         if (stubws) {
703                 stubws->cred = afb_cred_create_for_socket(fdev_fd(fdev));
704                 stubws->listener = afb_evt_listener_create(&server_evt_itf, stubws);
705                 if (stubws->listener != NULL)
706                         return stubws;
707                 afb_stub_ws_unref(stubws);
708         }
709         return NULL;
710 }
711
712 void afb_stub_ws_unref(struct afb_stub_ws *stubws)
713 {
714         if (!__atomic_sub_fetch(&stubws->refcount, 1, __ATOMIC_RELAXED)) {
715                 drop_all_events(stubws);
716                 if (stubws->listener)
717                         afb_evt_listener_unref(stubws->listener);
718                 release_all_sessions(stubws);
719                 afb_proto_ws_unref(stubws->proto);
720                 afb_cred_unref(stubws->cred);
721                 afb_apiset_unref(stubws->apiset);
722                 free(stubws);
723         }
724 }
725
726 void afb_stub_ws_addref(struct afb_stub_ws *stubws)
727 {
728         __atomic_add_fetch(&stubws->refcount, 1, __ATOMIC_RELAXED);
729 }
730
731 void afb_stub_ws_on_hangup(struct afb_stub_ws *stubws, void (*on_hangup)(struct afb_stub_ws*))
732 {
733         stubws->on_hangup = on_hangup;
734 }
735
736 const char *afb_stub_ws_name(struct afb_stub_ws *stubws)
737 {
738         return stubws->apiname;
739 }
740
741 struct afb_api afb_stub_ws_client_api(struct afb_stub_ws *stubws)
742 {
743         struct afb_api api;
744
745         assert(!stubws->listener); /* check client */
746         api.closure = stubws;
747         api.itf = &ws_api_itf;
748         api.group = NULL;
749         return api;
750 }
751
752 int afb_stub_ws_client_add(struct afb_stub_ws *stubws, struct afb_apiset *apiset)
753 {
754         return afb_apiset_add(apiset, stubws->apiname, afb_stub_ws_client_api(stubws));
755 }
756