afb-proto-ws: fix self locking issue
[src/app-framework-binder.git] / src / afb-proto-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-ws.h"
38 #include "afb-msg-json.h"
39 #include "afb-proto-ws.h"
40
41 struct afb_proto_ws;
42
43 /******** implementation of internal binder protocol per api **************/
44 /*
45
46 This protocol is asymetric: there is a client and a server
47
48 The client can require the following actions:
49
50   - call a verb
51
52   - ask for description
53
54 The server must reply to the previous actions by
55
56   - answering success or failure of the call
57
58   - answering the required description
59
60 The server can also within the context of a call
61
62   - make a subcall
63
64   - subscribe or unsubscribe an event
65
66 For the purpose of handling events the server can:
67
68   - create/destroy an event
69
70   - push or brodcast data as an event
71
72 */
73 /************** constants for protocol definition *************************/
74
75 #define CHAR_FOR_CALL             'C'
76 #define CHAR_FOR_ANSWER_SUCCESS   'T'
77 #define CHAR_FOR_ANSWER_FAIL      'F'
78 #define CHAR_FOR_EVT_BROADCAST    '*'
79 #define CHAR_FOR_EVT_ADD          '+'
80 #define CHAR_FOR_EVT_DEL          '-'
81 #define CHAR_FOR_EVT_PUSH         '!'
82 #define CHAR_FOR_EVT_SUBSCRIBE    'S'
83 #define CHAR_FOR_EVT_UNSUBSCRIBE  'U'
84 #define CHAR_FOR_SUBCALL_CALL     'B'
85 #define CHAR_FOR_SUBCALL_REPLY    'R'
86 #define CHAR_FOR_DESCRIBE         'D'
87 #define CHAR_FOR_DESCRIPTION      'd'
88
89 /******************* handling subcalls *****************************/
90
91 /**
92  * Structure on server side for recording pending
93  * subcalls.
94  */
95 struct server_subcall
96 {
97         struct server_subcall *next;    /**< next subcall for the client */
98         uint32_t subcallid;             /**< the subcallid */
99         void (*callback)(void*, int, struct json_object*); /**< callback on completion */
100         void *closure;                  /**< closure of the callback */
101 };
102
103 /**
104  * Structure for sending back replies on client side
105  */
106 struct afb_proto_ws_subcall
107 {
108         struct afb_proto_ws *protows;   /**< proto descriptor */
109         void *buffer;
110         uint32_t subcallid;             /**< subcallid for the reply */
111 };
112
113 /*
114  * structure for recording calls on client side
115  */
116 struct client_call {
117         struct client_call *next;       /* the next call */
118         struct afb_proto_ws *protows;   /* the proto_ws */
119         void *request;
120         uint32_t callid;                /* the message identifier */
121 };
122
123 /*
124  * structure for a ws request
125  */
126 struct afb_proto_ws_call {
127         struct client_call *next;       /* the next call */
128         struct afb_proto_ws *protows;   /* the client of the request */
129         uint32_t refcount;              /* reference count */
130         uint32_t callid;                /* the incoming request callid */
131         char *buffer;                   /* the incoming buffer */
132 };
133
134 /*
135  * structure for recording describe requests
136  */
137 struct client_describe
138 {
139         struct client_describe *next;
140         struct afb_proto_ws *protows;
141         void (*callback)(void*, struct json_object*);
142         void *closure;
143         uint32_t descid;
144 };
145
146 /*
147  * structure for jobs of describing
148  */
149 struct afb_proto_ws_describe
150 {
151         struct afb_proto_ws *protows;
152         uint32_t descid;
153 };
154
155 /******************* proto description for client or servers ******************/
156
157 struct afb_proto_ws
158 {
159         /* count of references */
160         int refcount;
161
162         /* file descriptor */
163         int fd;
164
165         /* resource control */
166         pthread_mutex_t mutex;
167
168         /* websocket */
169         struct afb_ws *ws;
170
171         /* the client closure */
172         void *closure;
173
174         /* the client side interface */
175         const struct afb_proto_ws_client_itf *client_itf;
176
177         /* the server side interface */
178         const struct afb_proto_ws_server_itf *server_itf;
179
180         /* emitted calls (client side) */
181         struct client_call *calls;
182
183         /* pending subcalls (server side) */
184         struct server_subcall *subcalls;
185
186         /* pending description (client side) */
187         struct client_describe *describes;
188
189         /* on hangup callback */
190         void (*on_hangup)(void *closure);
191 };
192
193 /******************* common useful tools **********************************/
194
195 /**
196  * translate a pointer to some integer
197  * @param ptr the pointer to translate
198  * @return an integer
199  */
200 static inline uint32_t ptr2id(void *ptr)
201 {
202         return (uint32_t)(((intptr_t)ptr) >> 6);
203 }
204
205 /******************* serialisation part **********************************/
206
207 struct readbuf
208 {
209         char *base, *head, *end;
210 };
211
212 #define WRITEBUF_COUNT_MAX  32
213 struct writebuf
214 {
215         struct iovec iovec[WRITEBUF_COUNT_MAX];
216         uint32_t uints[WRITEBUF_COUNT_MAX];
217         int count;
218 };
219
220 static char *readbuf_get(struct readbuf *rb, uint32_t length)
221 {
222         char *before = rb->head;
223         char *after = before + length;
224         if (after > rb->end)
225                 return 0;
226         rb->head = after;
227         return before;
228 }
229
230 static int readbuf_char(struct readbuf *rb, char *value)
231 {
232         if (rb->head >= rb->end)
233                 return 0;
234         *value = *rb->head++;
235         return 1;
236 }
237
238 static int readbuf_uint32(struct readbuf *rb, uint32_t *value)
239 {
240         char *after = rb->head + sizeof *value;
241         if (after > rb->end)
242                 return 0;
243         memcpy(value, rb->head, sizeof *value);
244         rb->head = after;
245         *value = le32toh(*value);
246         return 1;
247 }
248
249 static int readbuf_string(struct readbuf *rb, const char **value, size_t *length)
250 {
251         uint32_t len;
252         if (!readbuf_uint32(rb, &len) || !len)
253                 return 0;
254         if (length)
255                 *length = (size_t)(len - 1);
256         return (*value = readbuf_get(rb, len)) != NULL &&  rb->head[-1] == 0;
257 }
258
259 static int readbuf_object(struct readbuf *rb, struct json_object **object)
260 {
261         const char *string;
262         struct json_object *o;
263         int rc = readbuf_string(rb, &string, NULL);
264         if (rc) {
265                 o = json_tokener_parse(string);
266                 if (o == NULL && strcmp(string, "null"))
267                         o = json_object_new_string(string);
268                 *object = o;
269         }
270         return rc;
271 }
272
273 static int writebuf_put(struct writebuf *wb, const void *value, size_t length)
274 {
275         int i = wb->count;
276         if (i == WRITEBUF_COUNT_MAX)
277                 return 0;
278         wb->iovec[i].iov_base = (void*)value;
279         wb->iovec[i].iov_len = length;
280         wb->count = i + 1;
281         return 1;
282 }
283
284 static int writebuf_char(struct writebuf *wb, char value)
285 {
286         int i = wb->count;
287         if (i == WRITEBUF_COUNT_MAX)
288                 return 0;
289         *(char*)&wb->uints[i] = value;
290         wb->iovec[i].iov_base = &wb->uints[i];
291         wb->iovec[i].iov_len = 1;
292         wb->count = i + 1;
293         return 1;
294 }
295
296 static int writebuf_uint32(struct writebuf *wb, uint32_t value)
297 {
298         int i = wb->count;
299         if (i == WRITEBUF_COUNT_MAX)
300                 return 0;
301         wb->uints[i] = htole32(value);
302         wb->iovec[i].iov_base = &wb->uints[i];
303         wb->iovec[i].iov_len = sizeof wb->uints[i];
304         wb->count = i + 1;
305         return 1;
306 }
307
308 static int writebuf_string_length(struct writebuf *wb, const char *value, size_t length)
309 {
310         uint32_t len = (uint32_t)++length;
311         return (size_t)len == length && len && writebuf_uint32(wb, len) && writebuf_put(wb, value, length);
312 }
313
314 static int writebuf_string(struct writebuf *wb, const char *value)
315 {
316         return writebuf_string_length(wb, value, strlen(value));
317 }
318
319 static int writebuf_object(struct writebuf *wb, struct json_object *object)
320 {
321         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
322         return string != NULL && writebuf_string(wb, string);
323 }
324
325 /******************* ws request part for server *****************/
326
327 void afb_proto_ws_call_addref(struct afb_proto_ws_call *call)
328 {
329         __atomic_add_fetch(&call->refcount, 1, __ATOMIC_RELAXED);
330 }
331
332 void afb_proto_ws_call_unref(struct afb_proto_ws_call *call)
333 {
334         if (__atomic_sub_fetch(&call->refcount, 1, __ATOMIC_RELAXED))
335                 return;
336
337         afb_proto_ws_unref(call->protows);
338         free(call->buffer);
339         free(call);
340 }
341
342 int afb_proto_ws_call_success(struct afb_proto_ws_call *call, struct json_object *obj, const char *info)
343 {
344         int rc = -1;
345         struct writebuf wb = { .count = 0 };
346         struct afb_proto_ws *protows = call->protows;
347
348         if (writebuf_char(&wb, CHAR_FOR_ANSWER_SUCCESS)
349          && writebuf_uint32(&wb, call->callid)
350          && writebuf_string(&wb, info ?: "")
351          && writebuf_object(&wb, obj)) {
352                 pthread_mutex_lock(&protows->mutex);
353                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
354                 pthread_mutex_unlock(&protows->mutex);
355                 if (rc >= 0) {
356                         rc = 0;
357                         goto success;
358                 }
359         }
360 success:
361         return rc;
362 }
363
364 int afb_proto_ws_call_fail(struct afb_proto_ws_call *call, const char *status, const char *info)
365 {
366         int rc = -1;
367         struct writebuf wb = { .count = 0 };
368         struct afb_proto_ws *protows = call->protows;
369
370         if (writebuf_char(&wb, CHAR_FOR_ANSWER_FAIL)
371          && writebuf_uint32(&wb, call->callid)
372          && writebuf_string(&wb, status)
373          && writebuf_string(&wb, info ? : "")) {
374                 pthread_mutex_lock(&protows->mutex);
375                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
376                 pthread_mutex_unlock(&protows->mutex);
377                 if (rc >= 0) {
378                         rc = 0;
379                         goto success;
380                 }
381         }
382 success:
383         return rc;
384 }
385
386 int afb_proto_ws_call_subcall(struct afb_proto_ws_call *call, const char *api, const char *verb, struct json_object *args, void (*callback)(void*, int, struct json_object*), void *cb_closure)
387 {
388         int rc = -1;
389         struct writebuf wb = { .count = 0 };
390         struct server_subcall *sc, *osc;
391         struct afb_proto_ws *protows = call->protows;
392
393         sc = malloc(sizeof *sc);
394         if (!sc)
395                 errno = ENOMEM;
396         else {
397                 sc->callback = callback;
398                 sc->closure = cb_closure;
399
400                 pthread_mutex_lock(&protows->mutex);
401                 sc->subcallid = ptr2id(sc);
402                 do {
403                         sc->subcallid++;
404                         osc = protows->subcalls;
405                         while(osc && osc->subcallid != sc->subcallid)
406                                 osc = osc->next;
407                 } while (osc);
408                 sc->next = protows->subcalls;
409                 protows->subcalls = sc;
410                 pthread_mutex_unlock(&protows->mutex);
411
412                 if (writebuf_char(&wb, CHAR_FOR_SUBCALL_CALL)
413                  && writebuf_uint32(&wb, sc->subcallid)
414                  && writebuf_uint32(&wb, call->callid)
415                  && writebuf_string(&wb, api)
416                  && writebuf_string(&wb, verb)
417                  && writebuf_object(&wb, args)) {
418                         pthread_mutex_lock(&protows->mutex);
419                         rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
420                         pthread_mutex_unlock(&protows->mutex);
421                         if (rc >= 0) {
422                                 rc = 0;
423                                 goto success;
424                         }
425                 }
426         }
427 success:
428         return rc;
429 }
430
431 int afb_proto_ws_call_subscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
432 {
433         int rc = -1;
434         struct writebuf wb = { .count = 0 };
435         struct afb_proto_ws *protows = call->protows;
436
437         if (writebuf_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
438          && writebuf_uint32(&wb, call->callid)
439          && writebuf_uint32(&wb, (uint32_t)event_id)
440          && writebuf_string(&wb, event_name)) {
441                 pthread_mutex_lock(&protows->mutex);
442                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
443                 pthread_mutex_unlock(&protows->mutex);
444                 if (rc >= 0) {
445                         rc = 0;
446                         goto success;
447                 }
448         }
449 success:
450         return rc;
451 }
452
453 int afb_proto_ws_call_unsubscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
454 {
455         int rc = -1;
456         struct writebuf wb = { .count = 0 };
457         struct afb_proto_ws *protows = call->protows;
458
459         if (writebuf_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
460          && writebuf_uint32(&wb, call->callid)
461          && writebuf_uint32(&wb, (uint32_t)event_id)
462          && writebuf_string(&wb, event_name)) {
463                 pthread_mutex_lock(&protows->mutex);
464                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
465                 pthread_mutex_unlock(&protows->mutex);
466                 if (rc >= 0) {
467                         rc = 0;
468                         goto success;
469                 }
470         }
471 success:
472         return rc;
473 }
474
475 /******************* client part **********************************/
476
477 /* search a memorized call */
478 static struct client_call *client_call_search_locked(struct afb_proto_ws *protows, uint32_t callid)
479 {
480         struct client_call *call;
481
482         call = protows->calls;
483         while (call != NULL && call->callid != callid)
484                 call = call->next;
485
486         return call;
487 }
488
489 static struct client_call *client_call_search_unlocked(struct afb_proto_ws *protows, uint32_t callid)
490 {
491         struct client_call *result;
492
493         pthread_mutex_lock(&protows->mutex);
494         result = client_call_search_locked(protows, callid);
495         pthread_mutex_unlock(&protows->mutex);
496         return result;
497 }
498
499 /* free and release the memorizing call */
500 static void client_call_destroy(struct client_call *call)
501 {
502         struct client_call **prv;
503         struct afb_proto_ws *protows = call->protows;
504
505         pthread_mutex_lock(&protows->mutex);
506         prv = &call->protows->calls;
507         while (*prv != NULL) {
508                 if (*prv == call) {
509                         *prv = call->next;
510                         break;
511                 }
512                 prv = &(*prv)->next;
513         }
514         pthread_mutex_unlock(&protows->mutex);
515         free(call);
516 }
517
518 /* get event data from the message */
519 static int client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
520 {
521         return readbuf_uint32(rb, eventid) && readbuf_string(rb, name, NULL);
522 }
523
524 /* get event from the message */
525 static int client_msg_call_get(struct afb_proto_ws *protows, struct readbuf *rb, struct client_call **call)
526 {
527         uint32_t callid;
528
529         /* get event data from the message */
530         if (!readbuf_uint32(rb, &callid)) {
531                 return 0;
532         }
533
534         /* get the call */
535         *call = client_call_search_unlocked(protows, callid);
536         if (*call == NULL) {
537                 return 0;
538         }
539
540         return 1;
541 }
542
543 /* adds an event */
544 static void client_on_event_create(struct afb_proto_ws *protows, struct readbuf *rb)
545 {
546         const char *event_name;
547         uint32_t event_id;
548
549         if (protows->client_itf->on_event_create && client_msg_event_read(rb, &event_id, &event_name))
550                 protows->client_itf->on_event_create(protows->closure, event_name, (int)event_id);
551 }
552
553 /* removes an event */
554 static void client_on_event_remove(struct afb_proto_ws *protows, struct readbuf *rb)
555 {
556         const char *event_name;
557         uint32_t event_id;
558
559         if (protows->client_itf->on_event_remove && client_msg_event_read(rb, &event_id, &event_name))
560                 protows->client_itf->on_event_remove(protows->closure, event_name, (int)event_id);
561 }
562
563 /* subscribes an event */
564 static void client_on_event_subscribe(struct afb_proto_ws *protows, struct readbuf *rb)
565 {
566         const char *event_name;
567         uint32_t event_id;
568         struct client_call *call;
569
570         if (protows->client_itf->on_event_subscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
571                 protows->client_itf->on_event_subscribe(protows->closure, call->request, event_name, (int)event_id);
572 }
573
574 /* unsubscribes an event */
575 static void client_on_event_unsubscribe(struct afb_proto_ws *protows, struct readbuf *rb)
576 {
577         const char *event_name;
578         uint32_t event_id;
579         struct client_call *call;
580
581         if (protows->client_itf->on_event_unsubscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
582                 protows->client_itf->on_event_unsubscribe(protows->closure, call->request, event_name, (int)event_id);
583 }
584
585 /* receives broadcasted events */
586 static void client_on_event_broadcast(struct afb_proto_ws *protows, struct readbuf *rb)
587 {
588         const char *event_name;
589         struct json_object *object;
590
591         if (protows->client_itf->on_event_broadcast && readbuf_string(rb, &event_name, NULL) && readbuf_object(rb, &object))
592                 protows->client_itf->on_event_broadcast(protows->closure, event_name, object);
593 }
594
595 /* pushs an event */
596 static void client_on_event_push(struct afb_proto_ws *protows, struct readbuf *rb)
597 {
598         const char *event_name;
599         uint32_t event_id;
600         struct json_object *object;
601
602         if (protows->client_itf->on_event_push && client_msg_event_read(rb, &event_id, &event_name) && readbuf_object(rb, &object))
603                 protows->client_itf->on_event_push(protows->closure, event_name, (int)event_id, object);
604 }
605
606 static void client_on_reply_success(struct afb_proto_ws *protows, struct readbuf *rb)
607 {
608         struct client_call *call;
609         struct json_object *object;
610         const char *info;
611
612         if (!client_msg_call_get(protows, rb, &call))
613                 return;
614
615         if (readbuf_string(rb, &info, NULL) && readbuf_object(rb, &object)) {
616                 protows->client_itf->on_reply_success(protows->closure, call->request, object, info);
617         } else {
618                 protows->client_itf->on_reply_fail(protows->closure, call->request, "proto-error", "can't process success");
619         }
620         client_call_destroy(call);
621 }
622
623 static void client_on_reply_fail(struct afb_proto_ws *protows, struct readbuf *rb)
624 {
625         struct client_call *call;
626         const char *info, *status;
627
628         if (!client_msg_call_get(protows, rb, &call))
629                 return;
630         
631
632         if (readbuf_string(rb, &status, NULL) && readbuf_string(rb, &info, NULL)) {
633                 protows->client_itf->on_reply_fail(protows->closure, call->request, status, info);
634         } else {
635                 protows->client_itf->on_reply_fail(protows->closure, call->request, "proto-error", "can't process fail");
636         }
637         client_call_destroy(call);
638 }
639
640 /* send a subcall reply */
641 static int client_send_subcall_reply(struct afb_proto_ws *protows, uint32_t subcallid, int status, json_object *object)
642 {
643         struct writebuf wb = { .count = 0 };
644         char ie = status < 0;
645         int rc;
646
647         if (writebuf_char(&wb, CHAR_FOR_SUBCALL_REPLY)
648          && writebuf_uint32(&wb, subcallid)
649          && writebuf_char(&wb, ie)
650          && writebuf_object(&wb, object)) {
651                 pthread_mutex_lock(&protows->mutex);
652                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
653                 pthread_mutex_unlock(&protows->mutex);
654                 if (rc >= 0)
655                         return 0;
656         }
657         return -1;
658 }
659
660 /* callback for subcall reply */
661 int afb_proto_ws_subcall_reply(struct afb_proto_ws_subcall *subcall, int status, struct json_object *result)
662 {
663         int rc = client_send_subcall_reply(subcall->protows, subcall->subcallid, status, result);
664         afb_proto_ws_unref(subcall->protows);
665         free(subcall->buffer);
666         free(subcall);
667         return rc;
668 }
669
670 /* received a subcall request */
671 static void client_on_subcall(struct afb_proto_ws *protows, struct readbuf *rb)
672 {
673         struct afb_proto_ws_subcall *subcall;
674         struct client_call *call;
675         const char *api, *verb;
676         uint32_t subcallid;
677         struct json_object *object;
678
679         /* get the subcallid */
680         if (!readbuf_uint32(rb, &subcallid))
681                 return;
682
683         /* if not expected drop it */
684         if (!protows->client_itf->on_subcall)
685                 goto error;
686
687         /* retrieve the message data */
688         if (!client_msg_call_get(protows, rb, &call))
689                 goto error;
690
691         /* allocation of the subcall */
692         subcall = malloc(sizeof *subcall);
693         if (!subcall)
694                 goto error;
695
696         /* make the call */
697         if (readbuf_string(rb, &api, NULL)
698          && readbuf_string(rb, &verb, NULL)
699          && readbuf_object(rb, &object)) {
700                 afb_proto_ws_addref(protows);
701                 subcall->protows = protows;
702                 subcall->subcallid = subcallid;
703                 subcall->buffer = rb->base;
704                 rb->base = NULL;
705                 protows->client_itf->on_subcall(protows->closure, subcall, call->request, api, verb, object);
706                 return;
707         }
708         free(subcall);
709 error:
710         client_send_subcall_reply(protows, subcallid, 1, NULL);
711 }
712
713 static void client_on_description(struct afb_proto_ws *protows, struct readbuf *rb)
714 {
715         uint32_t descid;
716         struct client_describe *desc, **prv;
717         struct json_object *object;
718
719         if (readbuf_uint32(rb, &descid)) {
720                 pthread_mutex_lock(&protows->mutex);
721                 prv = &protows->describes;
722                 while ((desc = *prv) && desc->descid != descid)
723                         prv = &desc->next;
724                 if (!desc)
725                         pthread_mutex_unlock(&protows->mutex);
726                 else {
727                         *prv = desc->next;
728                         pthread_mutex_unlock(&protows->mutex);
729                         if (!readbuf_object(rb, &object))
730                                 object = NULL;
731                         desc->callback(desc->closure, object);
732                         free(desc);
733                 }
734         }
735 }
736
737 /* callback when receiving binary data */
738 static void client_on_binary(void *closure, char *data, size_t size)
739 {
740         struct afb_proto_ws *protows;
741         struct readbuf rb;
742
743         rb.base = data;
744         if (size > 0) {
745                 rb.head = data;
746                 rb.end = data + size;
747                 protows = closure;
748
749                 switch (*rb.head++) {
750                 case CHAR_FOR_ANSWER_SUCCESS: /* success */
751                         client_on_reply_success(protows, &rb);
752                         break;
753                 case CHAR_FOR_ANSWER_FAIL: /* fail */
754                         client_on_reply_fail(protows, &rb);
755                         break;
756                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
757                         client_on_event_broadcast(protows, &rb);
758                         break;
759                 case CHAR_FOR_EVT_ADD: /* creates the event */
760                         client_on_event_create(protows, &rb);
761                         break;
762                 case CHAR_FOR_EVT_DEL: /* removes the event */
763                         client_on_event_remove(protows, &rb);
764                         break;
765                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
766                         client_on_event_push(protows, &rb);
767                         break;
768                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
769                         client_on_event_subscribe(protows, &rb);
770                         break;
771                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
772                         client_on_event_unsubscribe(protows, &rb);
773                         break;
774                 case CHAR_FOR_SUBCALL_CALL: /* subcall */
775                         client_on_subcall(protows, &rb);
776                         break;
777                 case CHAR_FOR_DESCRIPTION: /* description */
778                         client_on_description(protows, &rb);
779                         break;
780                 default: /* unexpected message */
781                         /* TODO: close the connection */
782                         break;
783                 }
784         }
785         free(rb.base);
786 }
787
788 int afb_proto_ws_client_call(
789                 struct afb_proto_ws *protows,
790                 const char *verb,
791                 struct json_object *args,
792                 const char *sessionid,
793                 void *request
794 )
795 {
796         int rc = -1;
797         struct client_call *call;
798         struct writebuf wb = { .count = 0 };
799
800         /* allocate call data */
801         call = malloc(sizeof *call);
802         if (call == NULL) {
803                 errno = ENOMEM;
804                 return -1;
805         }
806         call->request = request;
807
808         /* init call data */
809         pthread_mutex_lock(&protows->mutex);
810         call->callid = ptr2id(call);
811         while(client_call_search_locked(protows, call->callid) != NULL)
812                 call->callid++;
813         call->protows = protows;
814         call->next = protows->calls;
815         protows->calls = call;
816         pthread_mutex_unlock(&protows->mutex);
817
818         /* creates the call message */
819         if (!writebuf_char(&wb, CHAR_FOR_CALL)
820          || !writebuf_uint32(&wb, call->callid)
821          || !writebuf_string(&wb, verb)
822          || !writebuf_string(&wb, sessionid)
823          || !writebuf_object(&wb, args)) {
824                 errno = EINVAL;
825                 goto clean;
826         }
827
828         /* send */
829         pthread_mutex_lock(&protows->mutex);
830         rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
831         pthread_mutex_unlock(&protows->mutex);
832         if (rc >= 0) {
833                 rc = 0;
834                 goto end;
835         }
836
837 clean:
838         client_call_destroy(call);
839 end:
840         return rc;
841 }
842
843 /* get the description */
844 int afb_proto_ws_client_describe(struct afb_proto_ws *protows, void (*callback)(void*, struct json_object*), void *closure)
845 {
846         struct client_describe *desc, *d;
847         struct writebuf wb = { .count = 0 };
848
849         desc = malloc(sizeof *desc);
850         if (!desc) {
851                 errno = ENOMEM;
852                 goto error;
853         }
854
855         /* fill in stack the description of the task */
856         pthread_mutex_lock(&protows->mutex);
857         desc->descid = ptr2id(desc);
858         d = protows->describes;
859         while (d) {
860                 if (d->descid != desc->descid)
861                         d = d->next;
862                 else {
863                         desc->descid++;
864                         d = protows->describes;
865                 }
866         }
867         desc->callback = callback;
868         desc->closure = closure;
869         desc->protows = protows;
870         desc->next = protows->describes;
871         protows->describes = desc;
872
873         /* send */
874         if (writebuf_char(&wb, CHAR_FOR_DESCRIBE)
875          && writebuf_uint32(&wb, desc->descid)
876          && afb_ws_binary_v(protows->ws, wb.iovec, wb.count) >= 0) {
877                 pthread_mutex_unlock(&protows->mutex);
878                 return 0;
879         }
880
881         d = protows->describes;
882         if (d == desc)
883                 protows->describes = desc->next;
884         else {
885                 while(d && d->next != desc)
886                         d = d->next;
887                 if (d)
888                         d->next = desc->next;
889         }
890         pthread_mutex_unlock(&protows->mutex);
891         free(desc);
892 error:
893         /* TODO? callback(closure, NULL); */
894         return -1;
895 }
896
897 /******************* client description part for server *****************************/
898
899 /* on call, propagate it to the ws service */
900 static void server_on_call(struct afb_proto_ws *protows, struct readbuf *rb)
901 {
902         struct afb_proto_ws_call *call;
903         const char *uuid, *verb;
904         uint32_t callid;
905         size_t lenverb;
906         struct json_object *object;
907
908         afb_proto_ws_addref(protows);
909
910         /* reads the call message data */
911         if (!readbuf_uint32(rb, &callid)
912          || !readbuf_string(rb, &verb, &lenverb)
913          || !readbuf_string(rb, &uuid, NULL)
914          || !readbuf_object(rb, &object))
915                 goto overflow;
916
917         /* create the request */
918         call = malloc(sizeof *call);
919         if (call == NULL)
920                 goto out_of_memory;
921
922         call->protows = protows;
923         call->callid = callid;
924         call->refcount = 1;
925         call->buffer = rb->base;
926         rb->base = NULL; /* don't free the buffer */
927
928         protows->server_itf->on_call(protows->closure, call, verb, object, uuid);
929         return;
930
931 out_of_memory:
932         json_object_put(object);
933
934 overflow:
935         afb_proto_ws_unref(protows);
936 }
937
938 /* on subcall reply */
939 static void server_on_subcall_reply(struct afb_proto_ws *protows, struct readbuf *rb)
940 {
941         char ie;
942         uint32_t subcallid;
943         struct json_object *object;
944         struct server_subcall *sc, **psc;
945
946         /* reads the call message data */
947         if (!readbuf_uint32(rb, &subcallid)
948          || !readbuf_char(rb, &ie)
949          || !readbuf_object(rb, &object)) {
950                 /* TODO bad protocol */
951                 return;
952         }
953
954         /* search the subcall and unlink it */
955         pthread_mutex_lock(&protows->mutex);
956         psc = &protows->subcalls;
957         while ((sc = *psc) && sc->subcallid != subcallid)
958                 psc = &sc->next;
959         if (!sc) {
960                 pthread_mutex_unlock(&protows->mutex);
961                 json_object_put(object);
962                 /* TODO subcall not found */
963         } else {
964                 *psc = sc->next;
965                 pthread_mutex_unlock(&protows->mutex);
966                 sc->callback(sc->closure, -(int)ie, object);
967                 free(sc);
968         }
969 }
970
971 static int server_send_description(struct afb_proto_ws *protows, uint32_t descid, struct json_object *descobj)
972 {
973         int rc;
974         struct writebuf wb = { .count = 0 };
975
976         if (writebuf_char(&wb, CHAR_FOR_DESCRIPTION)
977          && writebuf_uint32(&wb, descid)
978          && writebuf_object(&wb, descobj)) {
979                 pthread_mutex_lock(&protows->mutex);
980                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
981                 pthread_mutex_unlock(&protows->mutex);
982                 if (rc >= 0)
983                         return 0;
984         }
985         return -1;
986 }
987
988 int afb_proto_ws_describe_put(struct afb_proto_ws_describe *describe, struct json_object *description)
989 {
990         int rc = server_send_description(describe->protows, describe->descid, description);
991         afb_proto_ws_unref(describe->protows);
992         free(describe);
993         return rc;
994 }
995
996 /* on describe, propagate it to the ws service */
997 static void server_on_describe(struct afb_proto_ws *protows, struct readbuf *rb)
998 {
999         uint32_t descid;
1000         struct afb_proto_ws_describe *desc;
1001
1002         /* reads the descid */
1003         if (readbuf_uint32(rb, &descid)) {
1004                 if (protows->server_itf->on_describe) {
1005                         /* create asynchronous job */
1006                         desc = malloc(sizeof *desc);
1007                         if (desc) {
1008                                 desc->descid = descid;
1009                                 desc->protows = protows;
1010                                 afb_proto_ws_addref(protows);
1011                                 protows->server_itf->on_describe(protows->closure, desc);
1012                                 return;
1013                         }
1014                 }
1015                 server_send_description(protows, descid, NULL);
1016         }
1017 }
1018
1019 /* callback when receiving binary data */
1020 static void server_on_binary(void *closure, char *data, size_t size)
1021 {
1022         struct afb_proto_ws *protows;
1023         struct readbuf rb;
1024
1025         rb.base = data;
1026         if (size > 0) {
1027                 rb.head = data;
1028                 rb.end = data + size;
1029                 protows = closure;
1030
1031                 switch (*rb.head++) {
1032                 case CHAR_FOR_CALL:
1033                         server_on_call(protows, &rb);
1034                         break;
1035                 case CHAR_FOR_SUBCALL_REPLY:
1036                         server_on_subcall_reply(protows, &rb);
1037                         break;
1038                 case CHAR_FOR_DESCRIBE:
1039                         server_on_describe(protows, &rb);
1040                         break;
1041                 default: /* unexpected message */
1042                         /* TODO: close the connection */
1043                         break;
1044                 }
1045         }
1046         free(rb.base);
1047 }
1048
1049 /******************* server part: manage events **********************************/
1050
1051 static int server_event_send(struct afb_proto_ws *protows, char order, const char *event_name, int event_id, struct json_object *data)
1052 {
1053         struct writebuf wb = { .count = 0 };
1054         int rc;
1055
1056         if (writebuf_char(&wb, order)
1057          && (order == CHAR_FOR_EVT_BROADCAST || writebuf_uint32(&wb, event_id))
1058          && writebuf_string(&wb, event_name)
1059          && (order == CHAR_FOR_EVT_ADD || order == CHAR_FOR_EVT_DEL || writebuf_object(&wb, data))) {
1060                 pthread_mutex_lock(&protows->mutex);
1061                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
1062                 pthread_mutex_unlock(&protows->mutex);
1063                 if (rc >= 0)
1064                         return 0;
1065         }
1066         return -1;
1067 }
1068
1069 int afb_proto_ws_server_event_create(struct afb_proto_ws *protows, const char *event_name, int event_id)
1070 {
1071         return server_event_send(protows, CHAR_FOR_EVT_ADD, event_name, event_id, NULL);
1072 }
1073
1074 int afb_proto_ws_server_event_remove(struct afb_proto_ws *protows, const char *event_name, int event_id)
1075 {
1076         return server_event_send(protows, CHAR_FOR_EVT_DEL, event_name, event_id, NULL);
1077 }
1078
1079 int afb_proto_ws_server_event_push(struct afb_proto_ws *protows, const char *event_name, int event_id, struct json_object *data)
1080 {
1081         return server_event_send(protows, CHAR_FOR_EVT_PUSH, event_name, event_id, data);
1082 }
1083
1084 int afb_proto_ws_server_event_broadcast(struct afb_proto_ws *protows, const char *event_name, struct json_object *data)
1085 {
1086         return server_event_send(protows, CHAR_FOR_EVT_BROADCAST, event_name, 0, data);
1087 }
1088
1089 /*****************************************************/
1090
1091 /* callback when receiving a hangup */
1092 static void on_hangup(void *closure)
1093 {
1094         struct afb_proto_ws *protows = closure;
1095         struct server_subcall *sc, *nsc;
1096         struct client_describe *cd, *ncd;
1097
1098         nsc = protows->subcalls;
1099         while (nsc) {
1100                 sc= nsc;
1101                 nsc = sc->next;
1102                 sc->callback(sc->closure, 1, NULL);
1103                 free(sc);
1104         }
1105
1106         ncd = protows->describes;
1107         while (ncd) {
1108                 cd= ncd;
1109                 ncd = cd->next;
1110                 cd->callback(cd->closure, NULL);
1111                 free(cd);
1112         }
1113
1114         if (protows->fd >= 0) {
1115                 close(protows->fd);
1116                 protows->fd = -1;
1117                 if (protows->on_hangup)
1118                         protows->on_hangup(protows->closure);
1119         }
1120 }
1121
1122 /*****************************************************/
1123
1124 static const struct afb_ws_itf proto_ws_client_ws_itf =
1125 {
1126         .on_close = NULL,
1127         .on_text = NULL,
1128         .on_binary = client_on_binary,
1129         .on_error = NULL,
1130         .on_hangup = on_hangup
1131 };
1132
1133 static const struct afb_ws_itf server_ws_itf =
1134 {
1135         .on_close = NULL,
1136         .on_text = NULL,
1137         .on_binary = server_on_binary,
1138         .on_error = NULL,
1139         .on_hangup = on_hangup
1140 };
1141
1142 /*****************************************************/
1143
1144 static struct afb_proto_ws *afb_proto_ws_create(struct sd_event *eloop, int fd, const struct afb_proto_ws_server_itf *itfs, const struct afb_proto_ws_client_itf *itfc, void *closure, const struct afb_ws_itf *itf)
1145 {
1146         struct afb_proto_ws *protows;
1147
1148         protows = calloc(1, sizeof *protows);
1149         if (protows == NULL)
1150                 errno = ENOMEM;
1151         else {
1152                 fcntl(fd, F_SETFD, FD_CLOEXEC);
1153                 fcntl(fd, F_SETFL, O_NONBLOCK);
1154                 protows->ws = afb_ws_create(eloop, fd, itf, protows);
1155                 if (protows->ws != NULL) {
1156                         protows->fd = fd;
1157                         protows->refcount = 1;
1158                         protows->subcalls = NULL;
1159                         protows->closure = closure;
1160                         protows->server_itf = itfs;
1161                         protows->client_itf = itfc;
1162                         pthread_mutex_init(&protows->mutex, NULL);
1163                         return protows;
1164                 }
1165                 free(protows);
1166         }
1167         return NULL;
1168 }
1169
1170 struct afb_proto_ws *afb_proto_ws_create_client(struct sd_event *eloop, int fd, const struct afb_proto_ws_client_itf *itf, void *closure)
1171 {
1172         return afb_proto_ws_create(eloop, fd, NULL, itf, closure, &proto_ws_client_ws_itf);
1173 }
1174
1175 struct afb_proto_ws *afb_proto_ws_create_server(struct sd_event *eloop, int fd, const struct afb_proto_ws_server_itf *itf, void *closure)
1176 {
1177         return afb_proto_ws_create(eloop, fd, itf, NULL, closure, &server_ws_itf);
1178 }
1179
1180 void afb_proto_ws_unref(struct afb_proto_ws *protows)
1181 {
1182         if (!__atomic_sub_fetch(&protows->refcount, 1, __ATOMIC_RELAXED)) {
1183                 afb_proto_ws_hangup(protows);
1184                 afb_ws_destroy(protows->ws);
1185                 pthread_mutex_destroy(&protows->mutex);
1186                 free(protows);
1187         }
1188 }
1189
1190 void afb_proto_ws_addref(struct afb_proto_ws *protows)
1191 {
1192         __atomic_add_fetch(&protows->refcount, 1, __ATOMIC_RELAXED);
1193 }
1194
1195 int afb_proto_ws_is_client(struct afb_proto_ws *protows)
1196 {
1197         return !!protows->client_itf;
1198 }
1199
1200 int afb_proto_ws_is_server(struct afb_proto_ws *protows)
1201 {
1202         return !!protows->server_itf;
1203 }
1204
1205 void afb_proto_ws_hangup(struct afb_proto_ws *protows)
1206 {
1207         afb_ws_hangup(protows->ws);
1208 }
1209
1210 void afb_proto_ws_on_hangup(struct afb_proto_ws *protows, void (*on_hangup)(void *closure))
1211 {
1212         protows->on_hangup = on_hangup;
1213 }
1214