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