Fix bad memory access at client disconnection
[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 "fdev.h"
39 #include "verbose.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;                  /* the request closure */
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         /* resource control */
136         pthread_mutex_t mutex;
137
138         /* websocket */
139         struct afb_ws *ws;
140
141         /* the client closure */
142         void *closure;
143
144         /* the client side interface */
145         const struct afb_proto_ws_client_itf *client_itf;
146
147         /* the server side interface */
148         const struct afb_proto_ws_server_itf *server_itf;
149
150         /* emitted calls (client side) */
151         struct client_call *calls;
152
153         /* pending description (client side) */
154         struct client_describe *describes;
155
156         /* on hangup callback */
157         void (*on_hangup)(void *closure);
158
159         /* queuing facility for processing messages */
160         int (*queuing)(struct afb_proto_ws *proto, void (*process)(int s, void *c), 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         enum json_tokener_error jerr;
262         int rc = readbuf_string(rb, &string, NULL);
263         if (rc) {
264                 o = json_tokener_parse_verbose(string, &jerr);
265                 if (jerr != json_tokener_success)
266                         o = json_object_new_string(string);
267                 *object = o;
268         }
269         return rc;
270 }
271
272 static int writebuf_put(struct writebuf *wb, const void *value, size_t length)
273 {
274         int i = wb->count;
275         if (i == WRITEBUF_COUNT_MAX)
276                 return 0;
277         wb->iovec[i].iov_base = (void*)value;
278         wb->iovec[i].iov_len = length;
279         wb->count = i + 1;
280         return 1;
281 }
282
283 static int writebuf_char(struct writebuf *wb, char value)
284 {
285         int i = wb->count;
286         if (i == WRITEBUF_COUNT_MAX)
287                 return 0;
288         *(char*)&wb->uints[i] = value;
289         wb->iovec[i].iov_base = &wb->uints[i];
290         wb->iovec[i].iov_len = 1;
291         wb->count = i + 1;
292         return 1;
293 }
294
295 static int writebuf_uint32(struct writebuf *wb, uint32_t value)
296 {
297         int i = wb->count;
298         if (i == WRITEBUF_COUNT_MAX)
299                 return 0;
300         wb->uints[i] = htole32(value);
301         wb->iovec[i].iov_base = &wb->uints[i];
302         wb->iovec[i].iov_len = sizeof wb->uints[i];
303         wb->count = i + 1;
304         return 1;
305 }
306
307 static int writebuf_string_length(struct writebuf *wb, const char *value, size_t length)
308 {
309         uint32_t len = (uint32_t)++length;
310         return (size_t)len == length && len && writebuf_uint32(wb, len) && writebuf_put(wb, value, length);
311 }
312
313 static int writebuf_string(struct writebuf *wb, const char *value)
314 {
315         return writebuf_string_length(wb, value, strlen(value));
316 }
317
318 static int writebuf_nullstring(struct writebuf *wb, const char *value)
319 {
320         return value ? writebuf_string_length(wb, value, strlen(value)) : writebuf_uint32(wb, 0);
321 }
322
323 static int writebuf_object(struct writebuf *wb, struct json_object *object)
324 {
325         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
326         return string != NULL && writebuf_string(wb, string);
327 }
328
329 /******************* queuing of messages *****************/
330
331 /* queue the processing of the received message (except if size=0 cause it's not a valid message) */
332 static void queue_message_processing(struct afb_proto_ws *protows, char *data, size_t size, void (*processing)(int,void*))
333 {
334         struct binary *binary;
335
336         if (size) {
337                 binary = malloc(sizeof *binary);
338                 if (!binary) {
339                         /* TODO process the problem */
340                         errno = ENOMEM;
341                 } else {
342                         binary->protows = protows;
343                         binary->rb.base = data;
344                         binary->rb.head = data;
345                         binary->rb.end = data + size;
346                         if (!protows->queuing
347                          || protows->queuing(protows, processing, binary) < 0)
348                                 processing(0, binary);
349                         return;
350                 }
351         }
352         free(data);
353 }
354
355 /******************* ws request part for server *****************/
356
357 void afb_proto_ws_call_addref(struct afb_proto_ws_call *call)
358 {
359         __atomic_add_fetch(&call->refcount, 1, __ATOMIC_RELAXED);
360 }
361
362 void afb_proto_ws_call_unref(struct afb_proto_ws_call *call)
363 {
364         if (__atomic_sub_fetch(&call->refcount, 1, __ATOMIC_RELAXED))
365                 return;
366
367         afb_proto_ws_unref(call->protows);
368         free(call->buffer);
369         free(call);
370 }
371
372 int afb_proto_ws_call_reply(struct afb_proto_ws_call *call, struct json_object *obj, const char *error, const char *info)
373 {
374         int rc = -1;
375         struct writebuf wb = { .count = 0 };
376         struct afb_proto_ws *protows = call->protows;
377
378         if (writebuf_char(&wb, CHAR_FOR_REPLY)
379          && writebuf_uint32(&wb, call->callid)
380          && writebuf_nullstring(&wb, error)
381          && writebuf_nullstring(&wb, info)
382          && writebuf_object(&wb, obj)) {
383                 pthread_mutex_lock(&protows->mutex);
384                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
385                 pthread_mutex_unlock(&protows->mutex);
386                 if (rc >= 0) {
387                         rc = 0;
388                         goto success;
389                 }
390         }
391 success:
392         return rc;
393 }
394
395 int afb_proto_ws_call_subscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
396 {
397         int rc = -1;
398         struct writebuf wb = { .count = 0 };
399         struct afb_proto_ws *protows = call->protows;
400
401         if (writebuf_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
402          && writebuf_uint32(&wb, call->callid)
403          && writebuf_uint32(&wb, (uint32_t)event_id)
404          && writebuf_string(&wb, event_name)) {
405                 pthread_mutex_lock(&protows->mutex);
406                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
407                 pthread_mutex_unlock(&protows->mutex);
408                 if (rc >= 0) {
409                         rc = 0;
410                         goto success;
411                 }
412         }
413 success:
414         return rc;
415 }
416
417 int afb_proto_ws_call_unsubscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
418 {
419         int rc = -1;
420         struct writebuf wb = { .count = 0 };
421         struct afb_proto_ws *protows = call->protows;
422
423         if (writebuf_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
424          && writebuf_uint32(&wb, call->callid)
425          && writebuf_uint32(&wb, (uint32_t)event_id)
426          && writebuf_string(&wb, event_name)) {
427                 pthread_mutex_lock(&protows->mutex);
428                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
429                 pthread_mutex_unlock(&protows->mutex);
430                 if (rc >= 0) {
431                         rc = 0;
432                         goto success;
433                 }
434         }
435 success:
436         return rc;
437 }
438
439 /******************* client part **********************************/
440
441 /* search a memorized call */
442 static struct client_call *client_call_search_locked(struct afb_proto_ws *protows, uint32_t callid)
443 {
444         struct client_call *call;
445
446         call = protows->calls;
447         while (call != NULL && call->callid != callid)
448                 call = call->next;
449
450         return call;
451 }
452
453 static struct client_call *client_call_search_unlocked(struct afb_proto_ws *protows, uint32_t callid)
454 {
455         struct client_call *result;
456
457         pthread_mutex_lock(&protows->mutex);
458         result = client_call_search_locked(protows, callid);
459         pthread_mutex_unlock(&protows->mutex);
460         return result;
461 }
462
463 /* free and release the memorizing call */
464 static void client_call_destroy(struct client_call *call)
465 {
466         struct client_call **prv;
467         struct afb_proto_ws *protows = call->protows;
468
469         pthread_mutex_lock(&protows->mutex);
470         prv = &call->protows->calls;
471         while (*prv != NULL) {
472                 if (*prv == call) {
473                         *prv = call->next;
474                         break;
475                 }
476                 prv = &(*prv)->next;
477         }
478         pthread_mutex_unlock(&protows->mutex);
479         free(call);
480 }
481
482 /* get event data from the message */
483 static int client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
484 {
485         return readbuf_uint32(rb, eventid) && readbuf_string(rb, name, NULL);
486 }
487
488 /* get event from the message */
489 static int client_msg_call_get(struct afb_proto_ws *protows, struct readbuf *rb, struct client_call **call)
490 {
491         uint32_t callid;
492
493         /* get event data from the message */
494         if (!readbuf_uint32(rb, &callid)) {
495                 return 0;
496         }
497
498         /* get the call */
499         *call = client_call_search_unlocked(protows, callid);
500         if (*call == NULL) {
501                 return 0;
502         }
503
504         return 1;
505 }
506
507 /* adds an event */
508 static void client_on_event_create(struct afb_proto_ws *protows, struct readbuf *rb)
509 {
510         const char *event_name;
511         uint32_t event_id;
512
513         if (protows->client_itf->on_event_create && client_msg_event_read(rb, &event_id, &event_name))
514                 protows->client_itf->on_event_create(protows->closure, event_name, (int)event_id);
515         else
516                 ERROR("Ignoring creation of event");
517 }
518
519 /* removes an event */
520 static void client_on_event_remove(struct afb_proto_ws *protows, struct readbuf *rb)
521 {
522         const char *event_name;
523         uint32_t event_id;
524
525         if (protows->client_itf->on_event_remove && client_msg_event_read(rb, &event_id, &event_name))
526                 protows->client_itf->on_event_remove(protows->closure, event_name, (int)event_id);
527         else
528                 ERROR("Ignoring deletion of event");
529 }
530
531 /* subscribes an event */
532 static void client_on_event_subscribe(struct afb_proto_ws *protows, struct readbuf *rb)
533 {
534         const char *event_name;
535         uint32_t event_id;
536         struct client_call *call;
537
538         if (protows->client_itf->on_event_subscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
539                 protows->client_itf->on_event_subscribe(protows->closure, call->request, event_name, (int)event_id);
540         else
541                 ERROR("Ignoring subscription to event");
542 }
543
544 /* unsubscribes an event */
545 static void client_on_event_unsubscribe(struct afb_proto_ws *protows, struct readbuf *rb)
546 {
547         const char *event_name;
548         uint32_t event_id;
549         struct client_call *call;
550
551         if (protows->client_itf->on_event_unsubscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
552                 protows->client_itf->on_event_unsubscribe(protows->closure, call->request, event_name, (int)event_id);
553         else
554                 ERROR("Ignoring unsubscription to event");
555 }
556
557 /* receives broadcasted events */
558 static void client_on_event_broadcast(struct afb_proto_ws *protows, struct readbuf *rb)
559 {
560         const char *event_name, *uuid;
561         char hop;
562         struct json_object *object;
563
564         if (protows->client_itf->on_event_broadcast && readbuf_string(rb, &event_name, NULL) && readbuf_object(rb, &object) && (uuid = readbuf_get(rb, 16)) && readbuf_char(rb, &hop))
565                 protows->client_itf->on_event_broadcast(protows->closure, event_name, object, (unsigned char*)uuid, (uint8_t)hop);
566         else
567                 ERROR("Ignoring broadcast of event");
568 }
569
570 /* pushs an event */
571 static void client_on_event_push(struct afb_proto_ws *protows, struct readbuf *rb)
572 {
573         const char *event_name;
574         uint32_t event_id;
575         struct json_object *object;
576
577         if (protows->client_itf->on_event_push && client_msg_event_read(rb, &event_id, &event_name) && readbuf_object(rb, &object))
578                 protows->client_itf->on_event_push(protows->closure, event_name, (int)event_id, object);
579         else
580                 ERROR("Ignoring push of event");
581 }
582
583 static void client_on_reply(struct afb_proto_ws *protows, struct readbuf *rb)
584 {
585         struct client_call *call;
586         struct json_object *object;
587         const char *error, *info;
588
589         if (!client_msg_call_get(protows, rb, &call))
590                 return;
591
592         if (readbuf_nullstring(rb, &error, NULL) && readbuf_nullstring(rb, &info, NULL) && readbuf_object(rb, &object)) {
593                 protows->client_itf->on_reply(protows->closure, call->request, object, error, info);
594         } else {
595                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "proto-error", "can't process success");
596         }
597         client_call_destroy(call);
598 }
599
600 static void client_on_description(struct afb_proto_ws *protows, struct readbuf *rb)
601 {
602         uint32_t descid;
603         struct client_describe *desc, **prv;
604         struct json_object *object;
605
606         if (readbuf_uint32(rb, &descid)) {
607                 pthread_mutex_lock(&protows->mutex);
608                 prv = &protows->describes;
609                 while ((desc = *prv) && desc->descid != descid)
610                         prv = &desc->next;
611                 if (!desc)
612                         pthread_mutex_unlock(&protows->mutex);
613                 else {
614                         *prv = desc->next;
615                         pthread_mutex_unlock(&protows->mutex);
616                         if (!readbuf_object(rb, &object))
617                                 object = NULL;
618                         desc->callback(desc->closure, object);
619                         free(desc);
620                 }
621         }
622 }
623
624 /* callback when receiving binary data */
625 static void client_on_binary_job(int sig, void *closure)
626 {
627         struct binary *binary = closure;
628
629         if (!sig) {
630                 switch (*binary->rb.head++) {
631                 case CHAR_FOR_REPLY: /* reply */
632                         client_on_reply(binary->protows, &binary->rb);
633                         break;
634                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
635                         client_on_event_broadcast(binary->protows, &binary->rb);
636                         break;
637                 case CHAR_FOR_EVT_ADD: /* creates the event */
638                         client_on_event_create(binary->protows, &binary->rb);
639                         break;
640                 case CHAR_FOR_EVT_DEL: /* removes the event */
641                         client_on_event_remove(binary->protows, &binary->rb);
642                         break;
643                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
644                         client_on_event_push(binary->protows, &binary->rb);
645                         break;
646                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
647                         client_on_event_subscribe(binary->protows, &binary->rb);
648                         break;
649                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
650                         client_on_event_unsubscribe(binary->protows, &binary->rb);
651                         break;
652                 case CHAR_FOR_DESCRIPTION: /* description */
653                         client_on_description(binary->protows, &binary->rb);
654                         break;
655                 default: /* unexpected message */
656                         /* TODO: close the connection */
657                         break;
658                 }
659         }
660         free(binary->rb.base);
661         free(binary);
662 }
663
664 /* callback when receiving binary data */
665 static void client_on_binary(void *closure, char *data, size_t size)
666 {
667         struct afb_proto_ws *protows = closure;
668
669         queue_message_processing(protows, data, size, client_on_binary_job);
670 }
671
672 int afb_proto_ws_client_call(
673                 struct afb_proto_ws *protows,
674                 const char *verb,
675                 struct json_object *args,
676                 const char *sessionid,
677                 void *request,
678                 const char *user_creds
679 )
680 {
681         int rc = -1;
682         struct client_call *call;
683         struct writebuf wb = { .count = 0 };
684
685         /* allocate call data */
686         call = malloc(sizeof *call);
687         if (call == NULL) {
688                 errno = ENOMEM;
689                 return -1;
690         }
691         call->request = request;
692
693         /* init call data */
694         pthread_mutex_lock(&protows->mutex);
695         call->callid = ptr2id(call);
696         while(client_call_search_locked(protows, call->callid) != NULL)
697                 call->callid++;
698         call->protows = protows;
699         call->next = protows->calls;
700         protows->calls = call;
701         pthread_mutex_unlock(&protows->mutex);
702
703         /* creates the call message */
704         if (!writebuf_char(&wb, CHAR_FOR_CALL)
705          || !writebuf_uint32(&wb, call->callid)
706          || !writebuf_string(&wb, verb)
707          || !writebuf_string(&wb, sessionid)
708          || !writebuf_object(&wb, args)
709          || !writebuf_nullstring(&wb, user_creds)) {
710                 errno = EINVAL;
711                 goto clean;
712         }
713
714         /* send */
715         pthread_mutex_lock(&protows->mutex);
716         rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
717         pthread_mutex_unlock(&protows->mutex);
718         if (rc >= 0) {
719                 rc = 0;
720                 goto end;
721         }
722
723 clean:
724         client_call_destroy(call);
725 end:
726         return rc;
727 }
728
729 /* get the description */
730 int afb_proto_ws_client_describe(struct afb_proto_ws *protows, void (*callback)(void*, struct json_object*), void *closure)
731 {
732         struct client_describe *desc, *d;
733         struct writebuf wb = { .count = 0 };
734
735         desc = malloc(sizeof *desc);
736         if (!desc) {
737                 errno = ENOMEM;
738                 goto error;
739         }
740
741         /* fill in stack the description of the task */
742         pthread_mutex_lock(&protows->mutex);
743         desc->descid = ptr2id(desc);
744         d = protows->describes;
745         while (d) {
746                 if (d->descid != desc->descid)
747                         d = d->next;
748                 else {
749                         desc->descid++;
750                         d = protows->describes;
751                 }
752         }
753         desc->callback = callback;
754         desc->closure = closure;
755         desc->protows = protows;
756         desc->next = protows->describes;
757         protows->describes = desc;
758
759         /* send */
760         if (writebuf_char(&wb, CHAR_FOR_DESCRIBE)
761          && writebuf_uint32(&wb, desc->descid)
762          && afb_ws_binary_v(protows->ws, wb.iovec, wb.count) >= 0) {
763                 pthread_mutex_unlock(&protows->mutex);
764                 return 0;
765         }
766
767         d = protows->describes;
768         if (d == desc)
769                 protows->describes = desc->next;
770         else {
771                 while(d && d->next != desc)
772                         d = d->next;
773                 if (d)
774                         d->next = desc->next;
775         }
776         pthread_mutex_unlock(&protows->mutex);
777         free(desc);
778 error:
779         /* TODO? callback(closure, NULL); */
780         return -1;
781 }
782
783 /******************* client description part for server *****************************/
784
785 /* on call, propagate it to the ws service */
786 static void server_on_call(struct afb_proto_ws *protows, struct readbuf *rb)
787 {
788         struct afb_proto_ws_call *call;
789         const char *uuid, *verb, *user_creds;
790         uint32_t callid;
791         size_t lenverb;
792         struct json_object *object;
793
794         afb_proto_ws_addref(protows);
795
796         /* reads the call message data */
797         if (!readbuf_uint32(rb, &callid)
798          || !readbuf_string(rb, &verb, &lenverb)
799          || !readbuf_string(rb, &uuid, NULL)
800          || !readbuf_object(rb, &object)
801          || !readbuf_nullstring(rb, &user_creds, NULL))
802                 goto overflow;
803
804         /* create the request */
805         call = malloc(sizeof *call);
806         if (call == NULL)
807                 goto out_of_memory;
808
809         call->protows = protows;
810         call->callid = callid;
811         call->refcount = 1;
812         call->buffer = rb->base;
813         rb->base = NULL; /* don't free the buffer */
814
815         protows->server_itf->on_call(protows->closure, call, verb, object, uuid, user_creds);
816         return;
817
818 out_of_memory:
819         json_object_put(object);
820
821 overflow:
822         afb_proto_ws_unref(protows);
823 }
824
825 static int server_send_description(struct afb_proto_ws *protows, uint32_t descid, struct json_object *descobj)
826 {
827         int rc;
828         struct writebuf wb = { .count = 0 };
829
830         if (writebuf_char(&wb, CHAR_FOR_DESCRIPTION)
831          && writebuf_uint32(&wb, descid)
832          && writebuf_object(&wb, descobj)) {
833                 pthread_mutex_lock(&protows->mutex);
834                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
835                 pthread_mutex_unlock(&protows->mutex);
836                 if (rc >= 0)
837                         return 0;
838         }
839         return -1;
840 }
841
842 int afb_proto_ws_describe_put(struct afb_proto_ws_describe *describe, struct json_object *description)
843 {
844         int rc = server_send_description(describe->protows, describe->descid, description);
845         afb_proto_ws_unref(describe->protows);
846         free(describe);
847         return rc;
848 }
849
850 /* on describe, propagate it to the ws service */
851 static void server_on_describe(struct afb_proto_ws *protows, struct readbuf *rb)
852 {
853         uint32_t descid;
854         struct afb_proto_ws_describe *desc;
855
856         /* reads the descid */
857         if (readbuf_uint32(rb, &descid)) {
858                 if (protows->server_itf->on_describe) {
859                         /* create asynchronous job */
860                         desc = malloc(sizeof *desc);
861                         if (desc) {
862                                 desc->descid = descid;
863                                 desc->protows = protows;
864                                 afb_proto_ws_addref(protows);
865                                 protows->server_itf->on_describe(protows->closure, desc);
866                                 return;
867                         }
868                 }
869                 server_send_description(protows, descid, NULL);
870         }
871 }
872
873 /* callback when receiving binary data */
874 static void server_on_binary_job(int sig, void *closure)
875 {
876         struct binary *binary = closure;
877
878         if (!sig) {
879                 switch (*binary->rb.head++) {
880                 case CHAR_FOR_CALL:
881                         server_on_call(binary->protows, &binary->rb);
882                         break;
883                 case CHAR_FOR_DESCRIBE:
884                         server_on_describe(binary->protows, &binary->rb);
885                         break;
886                 default: /* unexpected message */
887                         /* TODO: close the connection */
888                         break;
889                 }
890         }
891         free(binary->rb.base);
892         free(binary);
893 }
894
895 static void server_on_binary(void *closure, char *data, size_t size)
896 {
897         struct afb_proto_ws *protows = closure;
898
899         queue_message_processing(protows, data, size, server_on_binary_job);
900 }
901
902 /******************* server part: manage events **********************************/
903
904 static int server_event_send(struct afb_proto_ws *protows, char order, const char *event_name, int event_id, struct json_object *data)
905 {
906         struct writebuf wb = { .count = 0 };
907         int rc;
908
909         if (writebuf_char(&wb, order)
910          && writebuf_uint32(&wb, event_id)
911          && writebuf_string(&wb, event_name)
912          && (order != CHAR_FOR_EVT_PUSH || writebuf_object(&wb, data))) {
913                 pthread_mutex_lock(&protows->mutex);
914                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
915                 pthread_mutex_unlock(&protows->mutex);
916                 if (rc >= 0)
917                         return 0;
918         }
919         return -1;
920 }
921
922 int afb_proto_ws_server_event_create(struct afb_proto_ws *protows, const char *event_name, int event_id)
923 {
924         return server_event_send(protows, CHAR_FOR_EVT_ADD, event_name, event_id, NULL);
925 }
926
927 int afb_proto_ws_server_event_remove(struct afb_proto_ws *protows, const char *event_name, int event_id)
928 {
929         return server_event_send(protows, CHAR_FOR_EVT_DEL, event_name, event_id, NULL);
930 }
931
932 int afb_proto_ws_server_event_push(struct afb_proto_ws *protows, const char *event_name, int event_id, struct json_object *data)
933 {
934         return server_event_send(protows, CHAR_FOR_EVT_PUSH, event_name, event_id, data);
935 }
936
937 int afb_proto_ws_server_event_broadcast(struct afb_proto_ws *protows, const char *event_name, struct json_object *data, const unsigned char uuid[16], uint8_t hop)
938 {
939         struct writebuf wb = { .count = 0 };
940         int rc;
941
942         if (!hop--)
943                 return 0;
944
945         if (writebuf_char(&wb, CHAR_FOR_EVT_BROADCAST)
946          && writebuf_string(&wb, event_name)
947          && writebuf_object(&wb, data)
948          && writebuf_put(&wb, uuid, 16)
949          && writebuf_char(&wb, (char)hop)) {
950                 pthread_mutex_lock(&protows->mutex);
951                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
952                 pthread_mutex_unlock(&protows->mutex);
953                 if (rc >= 0)
954                         return 0;
955         }
956         return -1;
957 }
958
959 /*****************************************************/
960
961 /* callback when receiving a hangup */
962 static void on_hangup(void *closure)
963 {
964         struct afb_proto_ws *protows = closure;
965         struct client_describe *cd, *ncd;
966         struct client_call *call, *ncall;
967
968         ncd = __atomic_exchange_n(&protows->describes, NULL, __ATOMIC_RELAXED);
969         ncall = __atomic_exchange_n(&protows->calls, NULL, __ATOMIC_RELAXED);
970
971         while (ncall) {
972                 call= ncall;
973                 ncall = call->next;
974                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "disconnected", "server hung up");
975                 free(call);
976         }
977
978         while (ncd) {
979                 cd= ncd;
980                 ncd = cd->next;
981                 cd->callback(cd->closure, NULL);
982                 free(cd);
983         }
984
985         if (protows->ws) {
986                 afb_ws_destroy(protows->ws);
987                 protows->ws = 0;
988                 if (protows->on_hangup)
989                         protows->on_hangup(protows->closure);
990         }
991 }
992
993 /*****************************************************/
994
995 static const struct afb_ws_itf proto_ws_client_ws_itf =
996 {
997         .on_close = NULL,
998         .on_text = NULL,
999         .on_binary = client_on_binary,
1000         .on_error = NULL,
1001         .on_hangup = on_hangup
1002 };
1003
1004 static const struct afb_ws_itf server_ws_itf =
1005 {
1006         .on_close = NULL,
1007         .on_text = NULL,
1008         .on_binary = server_on_binary,
1009         .on_error = NULL,
1010         .on_hangup = on_hangup
1011 };
1012
1013 /*****************************************************/
1014
1015 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)
1016 {
1017         struct afb_proto_ws *protows;
1018
1019         protows = calloc(1, sizeof *protows);
1020         if (protows == NULL)
1021                 errno = ENOMEM;
1022         else {
1023                 fcntl(fdev_fd(fdev), F_SETFD, FD_CLOEXEC);
1024                 fcntl(fdev_fd(fdev), F_SETFL, O_NONBLOCK);
1025                 protows->ws = afb_ws_create(fdev, itf, protows);
1026                 if (protows->ws != NULL) {
1027                         protows->refcount = 1;
1028                         protows->closure = closure;
1029                         protows->server_itf = itfs;
1030                         protows->client_itf = itfc;
1031                         pthread_mutex_init(&protows->mutex, NULL);
1032                         return protows;
1033                 }
1034                 free(protows);
1035         }
1036         return NULL;
1037 }
1038
1039 struct afb_proto_ws *afb_proto_ws_create_client(struct fdev *fdev, const struct afb_proto_ws_client_itf *itf, void *closure)
1040 {
1041         return afb_proto_ws_create(fdev, NULL, itf, closure, &proto_ws_client_ws_itf);
1042 }
1043
1044 struct afb_proto_ws *afb_proto_ws_create_server(struct fdev *fdev, const struct afb_proto_ws_server_itf *itf, void *closure)
1045 {
1046         return afb_proto_ws_create(fdev, itf, NULL, closure, &server_ws_itf);
1047 }
1048
1049 void afb_proto_ws_unref(struct afb_proto_ws *protows)
1050 {
1051         if (protows && !__atomic_sub_fetch(&protows->refcount, 1, __ATOMIC_RELAXED)) {
1052                 afb_proto_ws_hangup(protows);
1053                 pthread_mutex_destroy(&protows->mutex);
1054                 free(protows);
1055         }
1056 }
1057
1058 void afb_proto_ws_addref(struct afb_proto_ws *protows)
1059 {
1060         __atomic_add_fetch(&protows->refcount, 1, __ATOMIC_RELAXED);
1061 }
1062
1063 int afb_proto_ws_is_client(struct afb_proto_ws *protows)
1064 {
1065         return !!protows->client_itf;
1066 }
1067
1068 int afb_proto_ws_is_server(struct afb_proto_ws *protows)
1069 {
1070         return !!protows->server_itf;
1071 }
1072
1073 void afb_proto_ws_hangup(struct afb_proto_ws *protows)
1074 {
1075         if (protows->ws)
1076                 afb_ws_hangup(protows->ws);
1077 }
1078
1079 void afb_proto_ws_on_hangup(struct afb_proto_ws *protows, void (*on_hangup)(void *closure))
1080 {
1081         protows->on_hangup = on_hangup;
1082 }
1083
1084 void afb_proto_ws_set_queuing(struct afb_proto_ws *protows, int (*queuing)(struct afb_proto_ws*, void (*)(int,void*), void*))
1085 {
1086         protows->queuing = queuing;
1087 }