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