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