api-v3: First draft
[src/app-framework-binder.git] / src / afb-proto-ws.c
1 /*
2  * Copyright (C) 2015-2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
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 #include "jobs.h"
41 #include "fdev.h"
42
43 struct afb_proto_ws;
44
45 /******** implementation of internal binder protocol per api **************/
46 /*
47
48 This protocol is asymetric: there is a client and a server
49
50 The client can require the following actions:
51
52   - call a verb
53
54   - ask for description
55
56 The server must reply to the previous actions by
57
58   - answering success or failure of the call
59
60   - answering the required description
61
62 The server can also within the context of a call
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_REPLY            'Y'
77 #define CHAR_FOR_EVT_BROADCAST    '*'
78 #define CHAR_FOR_EVT_ADD          '+'
79 #define CHAR_FOR_EVT_DEL          '-'
80 #define CHAR_FOR_EVT_PUSH         '!'
81 #define CHAR_FOR_EVT_SUBSCRIBE    'S'
82 #define CHAR_FOR_EVT_UNSUBSCRIBE  'U'
83 #define CHAR_FOR_DESCRIBE         'D'
84 #define CHAR_FOR_DESCRIPTION      'd'
85
86 /******************* handling calls *****************************/
87
88 /*
89  * structure for recording calls on client side
90  */
91 struct client_call {
92         struct client_call *next;       /* the next call */
93         struct afb_proto_ws *protows;   /* the proto_ws */
94         void *request;
95         uint32_t callid;                /* the message identifier */
96 };
97
98 /*
99  * structure for a ws request
100  */
101 struct afb_proto_ws_call {
102         struct client_call *next;       /* the next call */
103         struct afb_proto_ws *protows;   /* the client of the request */
104         uint32_t refcount;              /* reference count */
105         uint32_t callid;                /* the incoming request callid */
106         char *buffer;                   /* the incoming buffer */
107 };
108
109 /*
110  * structure for recording describe requests
111  */
112 struct client_describe
113 {
114         struct client_describe *next;
115         struct afb_proto_ws *protows;
116         void (*callback)(void*, struct json_object*);
117         void *closure;
118         uint32_t descid;
119 };
120
121 /*
122  * structure for jobs of describing
123  */
124 struct afb_proto_ws_describe
125 {
126         struct afb_proto_ws *protows;
127         uint32_t descid;
128 };
129
130 /******************* proto description for client or servers ******************/
131
132 struct afb_proto_ws
133 {
134         /* count of references */
135         int refcount;
136
137         /* file descriptor */
138         struct fdev *fdev;
139
140         /* resource control */
141         pthread_mutex_t mutex;
142
143         /* websocket */
144         struct afb_ws *ws;
145
146         /* the client closure */
147         void *closure;
148
149         /* the client side interface */
150         const struct afb_proto_ws_client_itf *client_itf;
151
152         /* the server side interface */
153         const struct afb_proto_ws_server_itf *server_itf;
154
155         /* emitted calls (client side) */
156         struct client_call *calls;
157
158         /* pending description (client side) */
159         struct client_describe *describes;
160
161         /* on hangup callback */
162         void (*on_hangup)(void *closure);
163 };
164
165 /******************* streaming objects **********************************/
166
167 #define WRITEBUF_COUNT_MAX  32
168 struct writebuf
169 {
170         struct iovec iovec[WRITEBUF_COUNT_MAX];
171         uint32_t uints[WRITEBUF_COUNT_MAX];
172         int count;
173 };
174
175 struct readbuf
176 {
177         char *base, *head, *end;
178 };
179
180 struct binary
181 {
182         struct afb_proto_ws *protows;
183         struct readbuf rb;
184 };
185
186 /******************* common useful tools **********************************/
187
188 /**
189  * translate a pointer to some integer
190  * @param ptr the pointer to translate
191  * @return an integer
192  */
193 static inline uint32_t ptr2id(void *ptr)
194 {
195         return (uint32_t)(((intptr_t)ptr) >> 6);
196 }
197
198 /******************* serialisation part **********************************/
199
200 static char *readbuf_get(struct readbuf *rb, uint32_t length)
201 {
202         char *before = rb->head;
203         char *after = before + length;
204         if (after > rb->end)
205                 return 0;
206         rb->head = after;
207         return before;
208 }
209
210 __attribute__((unused))
211 static int readbuf_char(struct readbuf *rb, char *value)
212 {
213         if (rb->head >= rb->end)
214                 return 0;
215         *value = *rb->head++;
216         return 1;
217 }
218
219 static int readbuf_uint32(struct readbuf *rb, uint32_t *value)
220 {
221         char *after = rb->head + sizeof *value;
222         if (after > rb->end)
223                 return 0;
224         memcpy(value, rb->head, sizeof *value);
225         rb->head = after;
226         *value = le32toh(*value);
227         return 1;
228 }
229
230 static int _readbuf_string_(struct readbuf *rb, const char **value, size_t *length, int nulok)
231 {
232         uint32_t len;
233         if (!readbuf_uint32(rb, &len))
234                 return 0;
235         if (!len) {
236                 if (!nulok)
237                         return 0;
238                 *value = NULL;
239                 if (length)
240                         *length = 0;
241                 return 1;
242         }
243         if (length)
244                 *length = (size_t)(len - 1);
245         return (*value = readbuf_get(rb, len)) != NULL &&  rb->head[-1] == 0;
246 }
247
248
249 static int readbuf_string(struct readbuf *rb, const char **value, size_t *length)
250 {
251         return _readbuf_string_(rb, value, length, 0);
252 }
253
254 static int readbuf_nullstring(struct readbuf *rb, const char **value, size_t *length)
255 {
256         return _readbuf_string_(rb, value, length, 1);
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_nullstring(struct writebuf *wb, const char *value)
320 {
321         return value ? writebuf_string_length(wb, value, strlen(value)) : writebuf_uint32(wb, 0);
322 }
323
324 static int writebuf_object(struct writebuf *wb, struct json_object *object)
325 {
326         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
327         return string != NULL && writebuf_string(wb, string);
328 }
329
330 /******************* ws request part for server *****************/
331
332 void afb_proto_ws_call_addref(struct afb_proto_ws_call *call)
333 {
334         __atomic_add_fetch(&call->refcount, 1, __ATOMIC_RELAXED);
335 }
336
337 void afb_proto_ws_call_unref(struct afb_proto_ws_call *call)
338 {
339         if (__atomic_sub_fetch(&call->refcount, 1, __ATOMIC_RELAXED))
340                 return;
341
342         afb_proto_ws_unref(call->protows);
343         free(call->buffer);
344         free(call);
345 }
346
347 int afb_proto_ws_call_reply(struct afb_proto_ws_call *call, struct json_object *obj, const char *error, const char *info)
348 {
349         int rc = -1;
350         struct writebuf wb = { .count = 0 };
351         struct afb_proto_ws *protows = call->protows;
352
353         if (writebuf_char(&wb, CHAR_FOR_REPLY)
354          && writebuf_uint32(&wb, call->callid)
355          && writebuf_nullstring(&wb, error)
356          && writebuf_nullstring(&wb, info)
357          && writebuf_object(&wb, obj)) {
358                 pthread_mutex_lock(&protows->mutex);
359                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
360                 pthread_mutex_unlock(&protows->mutex);
361                 if (rc >= 0) {
362                         rc = 0;
363                         goto success;
364                 }
365         }
366 success:
367         return rc;
368 }
369
370 int afb_proto_ws_call_subscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
371 {
372         int rc = -1;
373         struct writebuf wb = { .count = 0 };
374         struct afb_proto_ws *protows = call->protows;
375
376         if (writebuf_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
377          && writebuf_uint32(&wb, call->callid)
378          && writebuf_uint32(&wb, (uint32_t)event_id)
379          && writebuf_string(&wb, event_name)) {
380                 pthread_mutex_lock(&protows->mutex);
381                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
382                 pthread_mutex_unlock(&protows->mutex);
383                 if (rc >= 0) {
384                         rc = 0;
385                         goto success;
386                 }
387         }
388 success:
389         return rc;
390 }
391
392 int afb_proto_ws_call_unsubscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
393 {
394         int rc = -1;
395         struct writebuf wb = { .count = 0 };
396         struct afb_proto_ws *protows = call->protows;
397
398         if (writebuf_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
399          && writebuf_uint32(&wb, call->callid)
400          && writebuf_uint32(&wb, (uint32_t)event_id)
401          && writebuf_string(&wb, event_name)) {
402                 pthread_mutex_lock(&protows->mutex);
403                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
404                 pthread_mutex_unlock(&protows->mutex);
405                 if (rc >= 0) {
406                         rc = 0;
407                         goto success;
408                 }
409         }
410 success:
411         return rc;
412 }
413
414 /******************* client part **********************************/
415
416 /* search a memorized call */
417 static struct client_call *client_call_search_locked(struct afb_proto_ws *protows, uint32_t callid)
418 {
419         struct client_call *call;
420
421         call = protows->calls;
422         while (call != NULL && call->callid != callid)
423                 call = call->next;
424
425         return call;
426 }
427
428 static struct client_call *client_call_search_unlocked(struct afb_proto_ws *protows, uint32_t callid)
429 {
430         struct client_call *result;
431
432         pthread_mutex_lock(&protows->mutex);
433         result = client_call_search_locked(protows, callid);
434         pthread_mutex_unlock(&protows->mutex);
435         return result;
436 }
437
438 /* free and release the memorizing call */
439 static void client_call_destroy(struct client_call *call)
440 {
441         struct client_call **prv;
442         struct afb_proto_ws *protows = call->protows;
443
444         pthread_mutex_lock(&protows->mutex);
445         prv = &call->protows->calls;
446         while (*prv != NULL) {
447                 if (*prv == call) {
448                         *prv = call->next;
449                         break;
450                 }
451                 prv = &(*prv)->next;
452         }
453         pthread_mutex_unlock(&protows->mutex);
454         free(call);
455 }
456
457 /* get event data from the message */
458 static int client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
459 {
460         return readbuf_uint32(rb, eventid) && readbuf_string(rb, name, NULL);
461 }
462
463 /* get event from the message */
464 static int client_msg_call_get(struct afb_proto_ws *protows, struct readbuf *rb, struct client_call **call)
465 {
466         uint32_t callid;
467
468         /* get event data from the message */
469         if (!readbuf_uint32(rb, &callid)) {
470                 return 0;
471         }
472
473         /* get the call */
474         *call = client_call_search_unlocked(protows, callid);
475         if (*call == NULL) {
476                 return 0;
477         }
478
479         return 1;
480 }
481
482 /* adds an event */
483 static void client_on_event_create(struct afb_proto_ws *protows, struct readbuf *rb)
484 {
485         const char *event_name;
486         uint32_t event_id;
487
488         if (protows->client_itf->on_event_create && client_msg_event_read(rb, &event_id, &event_name))
489                 protows->client_itf->on_event_create(protows->closure, event_name, (int)event_id);
490 }
491
492 /* removes an event */
493 static void client_on_event_remove(struct afb_proto_ws *protows, struct readbuf *rb)
494 {
495         const char *event_name;
496         uint32_t event_id;
497
498         if (protows->client_itf->on_event_remove && client_msg_event_read(rb, &event_id, &event_name))
499                 protows->client_itf->on_event_remove(protows->closure, event_name, (int)event_id);
500 }
501
502 /* subscribes an event */
503 static void client_on_event_subscribe(struct afb_proto_ws *protows, struct readbuf *rb)
504 {
505         const char *event_name;
506         uint32_t event_id;
507         struct client_call *call;
508
509         if (protows->client_itf->on_event_subscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
510                 protows->client_itf->on_event_subscribe(protows->closure, call->request, event_name, (int)event_id);
511 }
512
513 /* unsubscribes an event */
514 static void client_on_event_unsubscribe(struct afb_proto_ws *protows, struct readbuf *rb)
515 {
516         const char *event_name;
517         uint32_t event_id;
518         struct client_call *call;
519
520         if (protows->client_itf->on_event_unsubscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
521                 protows->client_itf->on_event_unsubscribe(protows->closure, call->request, event_name, (int)event_id);
522 }
523
524 /* receives broadcasted events */
525 static void client_on_event_broadcast(struct afb_proto_ws *protows, struct readbuf *rb)
526 {
527         const char *event_name;
528         struct json_object *object;
529
530         if (protows->client_itf->on_event_broadcast && readbuf_string(rb, &event_name, NULL) && readbuf_object(rb, &object))
531                 protows->client_itf->on_event_broadcast(protows->closure, event_name, object);
532 }
533
534 /* pushs an event */
535 static void client_on_event_push(struct afb_proto_ws *protows, struct readbuf *rb)
536 {
537         const char *event_name;
538         uint32_t event_id;
539         struct json_object *object;
540
541         if (protows->client_itf->on_event_push && client_msg_event_read(rb, &event_id, &event_name) && readbuf_object(rb, &object))
542                 protows->client_itf->on_event_push(protows->closure, event_name, (int)event_id, object);
543 }
544
545 static void client_on_reply(struct afb_proto_ws *protows, struct readbuf *rb)
546 {
547         struct client_call *call;
548         struct json_object *object;
549         const char *error, *info;
550
551         if (!client_msg_call_get(protows, rb, &call))
552                 return;
553
554         if (readbuf_nullstring(rb, &error, NULL) && readbuf_nullstring(rb, &info, NULL) && readbuf_object(rb, &object)) {
555                 protows->client_itf->on_reply(protows->closure, call->request, object, error, info);
556         } else {
557                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "proto-error", "can't process success");
558         }
559         client_call_destroy(call);
560 }
561
562 static void client_on_description(struct afb_proto_ws *protows, struct readbuf *rb)
563 {
564         uint32_t descid;
565         struct client_describe *desc, **prv;
566         struct json_object *object;
567
568         if (readbuf_uint32(rb, &descid)) {
569                 pthread_mutex_lock(&protows->mutex);
570                 prv = &protows->describes;
571                 while ((desc = *prv) && desc->descid != descid)
572                         prv = &desc->next;
573                 if (!desc)
574                         pthread_mutex_unlock(&protows->mutex);
575                 else {
576                         *prv = desc->next;
577                         pthread_mutex_unlock(&protows->mutex);
578                         if (!readbuf_object(rb, &object))
579                                 object = NULL;
580                         desc->callback(desc->closure, object);
581                         free(desc);
582                 }
583         }
584 }
585
586 /* callback when receiving binary data */
587 static void client_on_binary_job(int sig, void *closure)
588 {
589         struct binary *binary = closure;
590
591         if (!sig) {
592                 switch (*binary->rb.head++) {
593                 case CHAR_FOR_REPLY: /* reply */
594                         client_on_reply(binary->protows, &binary->rb);
595                         break;
596                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
597                         client_on_event_broadcast(binary->protows, &binary->rb);
598                         break;
599                 case CHAR_FOR_EVT_ADD: /* creates the event */
600                         client_on_event_create(binary->protows, &binary->rb);
601                         break;
602                 case CHAR_FOR_EVT_DEL: /* removes the event */
603                         client_on_event_remove(binary->protows, &binary->rb);
604                         break;
605                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
606                         client_on_event_push(binary->protows, &binary->rb);
607                         break;
608                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
609                         client_on_event_subscribe(binary->protows, &binary->rb);
610                         break;
611                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
612                         client_on_event_unsubscribe(binary->protows, &binary->rb);
613                         break;
614                 case CHAR_FOR_DESCRIPTION: /* description */
615                         client_on_description(binary->protows, &binary->rb);
616                         break;
617                 default: /* unexpected message */
618                         /* TODO: close the connection */
619                         break;
620                 }
621         }
622         free(binary->rb.base);
623         free(binary);
624 }
625
626 /* callback when receiving binary data */
627 static void client_on_binary(void *closure, char *data, size_t size)
628 {
629         int rc;
630         struct binary *binary;
631
632         if (size) {
633                 binary = malloc(sizeof *binary);
634                 if (!binary) {
635                         errno = ENOMEM;
636                 } else {
637                         binary->protows = closure;
638                         binary->rb.base = data;
639                         binary->rb.head = data;
640                         binary->rb.end = data + size;
641                         rc = jobs_queue(NULL, 0, client_on_binary_job, binary);
642                         if (rc >= 0)
643                                 return;
644                         free(binary);
645                 }
646         }
647         free(data);
648 }
649
650 int afb_proto_ws_client_call(
651                 struct afb_proto_ws *protows,
652                 const char *verb,
653                 struct json_object *args,
654                 const char *sessionid,
655                 void *request,
656                 const char *user_creds
657 )
658 {
659         int rc = -1;
660         struct client_call *call;
661         struct writebuf wb = { .count = 0 };
662
663         /* allocate call data */
664         call = malloc(sizeof *call);
665         if (call == NULL) {
666                 errno = ENOMEM;
667                 return -1;
668         }
669         call->request = request;
670
671         /* init call data */
672         pthread_mutex_lock(&protows->mutex);
673         call->callid = ptr2id(call);
674         while(client_call_search_locked(protows, call->callid) != NULL)
675                 call->callid++;
676         call->protows = protows;
677         call->next = protows->calls;
678         protows->calls = call;
679         pthread_mutex_unlock(&protows->mutex);
680
681         /* creates the call message */
682         if (!writebuf_char(&wb, CHAR_FOR_CALL)
683          || !writebuf_uint32(&wb, call->callid)
684          || !writebuf_string(&wb, verb)
685          || !writebuf_string(&wb, sessionid)
686          || !writebuf_object(&wb, args)
687          || !writebuf_nullstring(&wb, user_creds)) {
688                 errno = EINVAL;
689                 goto clean;
690         }
691
692         /* send */
693         pthread_mutex_lock(&protows->mutex);
694         rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
695         pthread_mutex_unlock(&protows->mutex);
696         if (rc >= 0) {
697                 rc = 0;
698                 goto end;
699         }
700
701 clean:
702         client_call_destroy(call);
703 end:
704         return rc;
705 }
706
707 /* get the description */
708 int afb_proto_ws_client_describe(struct afb_proto_ws *protows, void (*callback)(void*, struct json_object*), void *closure)
709 {
710         struct client_describe *desc, *d;
711         struct writebuf wb = { .count = 0 };
712
713         desc = malloc(sizeof *desc);
714         if (!desc) {
715                 errno = ENOMEM;
716                 goto error;
717         }
718
719         /* fill in stack the description of the task */
720         pthread_mutex_lock(&protows->mutex);
721         desc->descid = ptr2id(desc);
722         d = protows->describes;
723         while (d) {
724                 if (d->descid != desc->descid)
725                         d = d->next;
726                 else {
727                         desc->descid++;
728                         d = protows->describes;
729                 }
730         }
731         desc->callback = callback;
732         desc->closure = closure;
733         desc->protows = protows;
734         desc->next = protows->describes;
735         protows->describes = desc;
736
737         /* send */
738         if (writebuf_char(&wb, CHAR_FOR_DESCRIBE)
739          && writebuf_uint32(&wb, desc->descid)
740          && afb_ws_binary_v(protows->ws, wb.iovec, wb.count) >= 0) {
741                 pthread_mutex_unlock(&protows->mutex);
742                 return 0;
743         }
744
745         d = protows->describes;
746         if (d == desc)
747                 protows->describes = desc->next;
748         else {
749                 while(d && d->next != desc)
750                         d = d->next;
751                 if (d)
752                         d->next = desc->next;
753         }
754         pthread_mutex_unlock(&protows->mutex);
755         free(desc);
756 error:
757         /* TODO? callback(closure, NULL); */
758         return -1;
759 }
760
761 /******************* client description part for server *****************************/
762
763 /* on call, propagate it to the ws service */
764 static void server_on_call(struct afb_proto_ws *protows, struct readbuf *rb)
765 {
766         struct afb_proto_ws_call *call;
767         const char *uuid, *verb, *user_creds;
768         uint32_t callid;
769         size_t lenverb;
770         struct json_object *object;
771
772         afb_proto_ws_addref(protows);
773
774         /* reads the call message data */
775         if (!readbuf_uint32(rb, &callid)
776          || !readbuf_string(rb, &verb, &lenverb)
777          || !readbuf_string(rb, &uuid, NULL)
778          || !readbuf_object(rb, &object)
779          || !readbuf_nullstring(rb, &user_creds, NULL))
780                 goto overflow;
781
782         /* create the request */
783         call = malloc(sizeof *call);
784         if (call == NULL)
785                 goto out_of_memory;
786
787         call->protows = protows;
788         call->callid = callid;
789         call->refcount = 1;
790         call->buffer = rb->base;
791         rb->base = NULL; /* don't free the buffer */
792
793         protows->server_itf->on_call(protows->closure, call, verb, object, uuid, user_creds);
794         return;
795
796 out_of_memory:
797         json_object_put(object);
798
799 overflow:
800         afb_proto_ws_unref(protows);
801 }
802
803 static int server_send_description(struct afb_proto_ws *protows, uint32_t descid, struct json_object *descobj)
804 {
805         int rc;
806         struct writebuf wb = { .count = 0 };
807
808         if (writebuf_char(&wb, CHAR_FOR_DESCRIPTION)
809          && writebuf_uint32(&wb, descid)
810          && writebuf_object(&wb, descobj)) {
811                 pthread_mutex_lock(&protows->mutex);
812                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
813                 pthread_mutex_unlock(&protows->mutex);
814                 if (rc >= 0)
815                         return 0;
816         }
817         return -1;
818 }
819
820 int afb_proto_ws_describe_put(struct afb_proto_ws_describe *describe, struct json_object *description)
821 {
822         int rc = server_send_description(describe->protows, describe->descid, description);
823         afb_proto_ws_unref(describe->protows);
824         free(describe);
825         return rc;
826 }
827
828 /* on describe, propagate it to the ws service */
829 static void server_on_describe(struct afb_proto_ws *protows, struct readbuf *rb)
830 {
831         uint32_t descid;
832         struct afb_proto_ws_describe *desc;
833
834         /* reads the descid */
835         if (readbuf_uint32(rb, &descid)) {
836                 if (protows->server_itf->on_describe) {
837                         /* create asynchronous job */
838                         desc = malloc(sizeof *desc);
839                         if (desc) {
840                                 desc->descid = descid;
841                                 desc->protows = protows;
842                                 afb_proto_ws_addref(protows);
843                                 protows->server_itf->on_describe(protows->closure, desc);
844                                 return;
845                         }
846                 }
847                 server_send_description(protows, descid, NULL);
848         }
849 }
850
851 /* callback when receiving binary data */
852 static void server_on_binary_job(int sig, void *closure)
853 {
854         struct binary *binary = closure;
855
856         if (!sig) {
857                 switch (*binary->rb.head++) {
858                 case CHAR_FOR_CALL:
859                         server_on_call(binary->protows, &binary->rb);
860                         break;
861                 case CHAR_FOR_DESCRIBE:
862                         server_on_describe(binary->protows, &binary->rb);
863                         break;
864                 default: /* unexpected message */
865                         /* TODO: close the connection */
866                         break;
867                 }
868         }
869         free(binary->rb.base);
870         free(binary);
871 }
872
873 static void server_on_binary(void *closure, char *data, size_t size)
874 {
875         int rc;
876         struct binary *binary;
877
878         if (size) {
879                 binary = malloc(sizeof *binary);
880                 if (!binary) {
881                         errno = ENOMEM;
882                 } else {
883                         binary->protows = closure;
884                         binary->rb.base = data;
885                         binary->rb.head = data;
886                         binary->rb.end = data + size;
887                         rc = jobs_queue(NULL, 0, server_on_binary_job, binary);
888                         if (rc >= 0)
889                                 return;
890                         free(binary);
891                 }
892         }
893         free(data);
894 }
895
896 /******************* server part: manage events **********************************/
897
898 static int server_event_send(struct afb_proto_ws *protows, char order, const char *event_name, int event_id, struct json_object *data)
899 {
900         struct writebuf wb = { .count = 0 };
901         int rc;
902
903         if (writebuf_char(&wb, order)
904          && (order == CHAR_FOR_EVT_BROADCAST || writebuf_uint32(&wb, event_id))
905          && writebuf_string(&wb, event_name)
906          && (order == CHAR_FOR_EVT_ADD || order == CHAR_FOR_EVT_DEL || writebuf_object(&wb, data))) {
907                 pthread_mutex_lock(&protows->mutex);
908                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
909                 pthread_mutex_unlock(&protows->mutex);
910                 if (rc >= 0)
911                         return 0;
912         }
913         return -1;
914 }
915
916 int afb_proto_ws_server_event_create(struct afb_proto_ws *protows, const char *event_name, int event_id)
917 {
918         return server_event_send(protows, CHAR_FOR_EVT_ADD, event_name, event_id, NULL);
919 }
920
921 int afb_proto_ws_server_event_remove(struct afb_proto_ws *protows, const char *event_name, int event_id)
922 {
923         return server_event_send(protows, CHAR_FOR_EVT_DEL, event_name, event_id, NULL);
924 }
925
926 int afb_proto_ws_server_event_push(struct afb_proto_ws *protows, const char *event_name, int event_id, struct json_object *data)
927 {
928         return server_event_send(protows, CHAR_FOR_EVT_PUSH, event_name, event_id, data);
929 }
930
931 int afb_proto_ws_server_event_broadcast(struct afb_proto_ws *protows, const char *event_name, struct json_object *data)
932 {
933         return server_event_send(protows, CHAR_FOR_EVT_BROADCAST, event_name, 0, data);
934 }
935
936 /*****************************************************/
937
938 /* callback when receiving a hangup */
939 static void on_hangup(void *closure)
940 {
941         struct afb_proto_ws *protows = closure;
942         struct client_describe *cd, *ncd;
943
944         ncd = protows->describes;
945         while (ncd) {
946                 cd= ncd;
947                 ncd = cd->next;
948                 cd->callback(cd->closure, NULL);
949                 free(cd);
950         }
951
952         if (protows->fdev) {
953                 fdev_unref(protows->fdev);
954                 protows->fdev = 0;
955                 if (protows->on_hangup)
956                         protows->on_hangup(protows->closure);
957         }
958 }
959
960 /*****************************************************/
961
962 static const struct afb_ws_itf proto_ws_client_ws_itf =
963 {
964         .on_close = NULL,
965         .on_text = NULL,
966         .on_binary = client_on_binary,
967         .on_error = NULL,
968         .on_hangup = on_hangup
969 };
970
971 static const struct afb_ws_itf server_ws_itf =
972 {
973         .on_close = NULL,
974         .on_text = NULL,
975         .on_binary = server_on_binary,
976         .on_error = NULL,
977         .on_hangup = on_hangup
978 };
979
980 /*****************************************************/
981
982 static struct afb_proto_ws *afb_proto_ws_create(struct fdev *fdev, const struct afb_proto_ws_server_itf *itfs, const struct afb_proto_ws_client_itf *itfc, void *closure, const struct afb_ws_itf *itf)
983 {
984         struct afb_proto_ws *protows;
985
986         protows = calloc(1, sizeof *protows);
987         if (protows == NULL)
988                 errno = ENOMEM;
989         else {
990                 fcntl(fdev_fd(fdev), F_SETFD, FD_CLOEXEC);
991                 fcntl(fdev_fd(fdev), F_SETFL, O_NONBLOCK);
992                 protows->ws = afb_ws_create(fdev, itf, protows);
993                 if (protows->ws != NULL) {
994                         protows->fdev = fdev;
995                         protows->refcount = 1;
996                         protows->closure = closure;
997                         protows->server_itf = itfs;
998                         protows->client_itf = itfc;
999                         pthread_mutex_init(&protows->mutex, NULL);
1000                         return protows;
1001                 }
1002                 free(protows);
1003         }
1004         return NULL;
1005 }
1006
1007 struct afb_proto_ws *afb_proto_ws_create_client(struct fdev *fdev, const struct afb_proto_ws_client_itf *itf, void *closure)
1008 {
1009         return afb_proto_ws_create(fdev, NULL, itf, closure, &proto_ws_client_ws_itf);
1010 }
1011
1012 struct afb_proto_ws *afb_proto_ws_create_server(struct fdev *fdev, const struct afb_proto_ws_server_itf *itf, void *closure)
1013 {
1014         return afb_proto_ws_create(fdev, itf, NULL, closure, &server_ws_itf);
1015 }
1016
1017 void afb_proto_ws_unref(struct afb_proto_ws *protows)
1018 {
1019         if (!__atomic_sub_fetch(&protows->refcount, 1, __ATOMIC_RELAXED)) {
1020                 afb_proto_ws_hangup(protows);
1021                 afb_ws_destroy(protows->ws);
1022                 pthread_mutex_destroy(&protows->mutex);
1023                 free(protows);
1024         }
1025 }
1026
1027 void afb_proto_ws_addref(struct afb_proto_ws *protows)
1028 {
1029         __atomic_add_fetch(&protows->refcount, 1, __ATOMIC_RELAXED);
1030 }
1031
1032 int afb_proto_ws_is_client(struct afb_proto_ws *protows)
1033 {
1034         return !!protows->client_itf;
1035 }
1036
1037 int afb_proto_ws_is_server(struct afb_proto_ws *protows)
1038 {
1039         return !!protows->server_itf;
1040 }
1041
1042 void afb_proto_ws_hangup(struct afb_proto_ws *protows)
1043 {
1044         afb_ws_hangup(protows->ws);
1045 }
1046
1047 void afb_proto_ws_on_hangup(struct afb_proto_ws *protows, void (*on_hangup)(void *closure))
1048 {
1049         protows->on_hangup = on_hangup;
1050 }
1051