Update copyright dates
[src/app-framework-binder.git] / src / afb-proto-ws.c
1 /*
2  * Copyright (C) 2015-2020 "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 asymmetric: 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 broadcast data as an event
69
70   - signal unexpected event
71
72 */
73 /************** constants for protocol definition *************************/
74
75 #define CHAR_FOR_CALL             'K'   /* client -> server */
76 #define CHAR_FOR_REPLY            'k'   /* server -> client */
77 #define CHAR_FOR_EVT_BROADCAST    'B'   /* server -> client */
78 #define CHAR_FOR_EVT_ADD          'E'   /* server -> client */
79 #define CHAR_FOR_EVT_DEL          'e'   /* server -> client */
80 #define CHAR_FOR_EVT_PUSH         'P'   /* server -> client */
81 #define CHAR_FOR_EVT_SUBSCRIBE    'X'   /* server -> client */
82 #define CHAR_FOR_EVT_UNSUBSCRIBE  'x'   /* server -> client */
83 #define CHAR_FOR_EVT_UNEXPECTED   'U'   /* client -> server */
84 #define CHAR_FOR_DESCRIBE         'D'   /* client -> server */
85 #define CHAR_FOR_DESCRIPTION      'd'   /* server -> client */
86 #define CHAR_FOR_TOKEN_ADD        'T'   /* client -> server */
87 #define CHAR_FOR_TOKEN_DROP       't'   /* client -> server */
88 #define CHAR_FOR_SESSION_ADD      'S'   /* client -> server */
89 #define CHAR_FOR_SESSION_DROP     's'   /* client -> server */
90 #define CHAR_FOR_VERSION_OFFER    'V'   /* client -> server */
91 #define CHAR_FOR_VERSION_SET      'v'   /* server -> client */
92
93 /******************* manage versions *****************************/
94
95 #define WSAPI_IDENTIFIER        02723012011  /* wsapi: 23.19.1.16.9 */
96
97 #define WSAPI_VERSION_UNSET     0
98 #define WSAPI_VERSION_1         1
99
100 #define WSAPI_VERSION_MIN       WSAPI_VERSION_1
101 #define WSAPI_VERSION_MAX       WSAPI_VERSION_1
102
103 /******************* maximum count of ids ***********************/
104
105 #define ACTIVE_ID_MAX           4095
106
107 /******************* handling calls *****************************/
108
109 /*
110  * structure for recording calls on client side
111  */
112 struct client_call {
113         struct client_call *next;       /* the next call */
114         void *request;                  /* the request closure */
115         uint16_t callid;                /* the message identifier */
116 };
117
118 /*
119  * structure for a ws request
120  */
121 struct afb_proto_ws_call {
122         struct afb_proto_ws *protows;   /* the client of the request */
123         char *buffer;                   /* the incoming buffer */
124         uint16_t refcount;              /* reference count */
125         uint16_t callid;                /* the incoming request callid */
126 };
127
128 /*
129  * structure for recording describe requests
130  */
131 struct client_describe
132 {
133         struct client_describe *next;
134         void (*callback)(void*, struct json_object*);
135         void *closure;
136         uint16_t descid;
137 };
138
139 /*
140  * structure for jobs of describing
141  */
142 struct afb_proto_ws_describe
143 {
144         struct afb_proto_ws *protows;
145         uint16_t descid;
146 };
147
148 /******************* proto description for client or servers ******************/
149
150 struct afb_proto_ws
151 {
152         /* count of references */
153         uint16_t refcount;
154
155         /* id generator */
156         uint16_t genid;
157
158         /* count actives ids */
159         uint16_t idcount;
160
161         /* version */
162         uint8_t version;
163
164         /* resource control */
165         pthread_mutex_t mutex;
166
167         /* websocket */
168         struct afb_ws *ws;
169
170         /* the client closure */
171         void *closure;
172
173         /* the client side interface */
174         const struct afb_proto_ws_client_itf *client_itf;
175
176         /* the server side interface */
177         const struct afb_proto_ws_server_itf *server_itf;
178
179         /* emitted calls (client side) */
180         struct client_call *calls;
181
182         /* pending description (client side) */
183         struct client_describe *describes;
184
185         /* on hangup callback */
186         void (*on_hangup)(void *closure);
187
188         /* queuing facility for processing messages */
189         int (*queuing)(struct afb_proto_ws *proto, void (*process)(int s, void *c), void *closure);
190 };
191
192 /******************* streaming objects **********************************/
193
194 #define WRITEBUF_COUNT_MAX      32
195 #define WRITEBUF_BUFSZ          (WRITEBUF_COUNT_MAX * sizeof(uint32_t))
196
197 struct writebuf
198 {
199         int iovcount, bufcount;
200         struct iovec iovec[WRITEBUF_COUNT_MAX];
201         char buf[WRITEBUF_BUFSZ];
202 };
203
204 struct readbuf
205 {
206         char *base, *head, *end;
207 };
208
209 struct binary
210 {
211         struct afb_proto_ws *protows;
212         struct readbuf rb;
213 };
214
215 /******************* serialization part **********************************/
216
217 static char *readbuf_get(struct readbuf *rb, uint32_t length)
218 {
219         char *before = rb->head;
220         char *after = before + length;
221         if (after > rb->end)
222                 return 0;
223         rb->head = after;
224         return before;
225 }
226
227 static int readbuf_getat(struct readbuf *rb, void *to, uint32_t length)
228 {
229         char *head = readbuf_get(rb, length);
230         if (!head)
231                 return 0;
232         memcpy(to, head, length);
233         return 1;
234 }
235
236 __attribute__((unused))
237 static int readbuf_char(struct readbuf *rb, char *value)
238 {
239         return readbuf_getat(rb, value, sizeof *value);
240 }
241
242 static int readbuf_uint32(struct readbuf *rb, uint32_t *value)
243 {
244         int r = readbuf_getat(rb, value, sizeof *value);
245         if (r)
246                 *value = le32toh(*value);
247         return r;
248 }
249
250 static int readbuf_uint16(struct readbuf *rb, uint16_t *value)
251 {
252         int r = readbuf_getat(rb, value, sizeof *value);
253         if (r)
254                 *value = le16toh(*value);
255         return r;
256 }
257
258 static int readbuf_uint8(struct readbuf *rb, uint8_t *value)
259 {
260         return readbuf_getat(rb, value, sizeof *value);
261 }
262
263 static int _readbuf_string_(struct readbuf *rb, const char **value, size_t *length, int nulok)
264 {
265         uint32_t len;
266         if (!readbuf_uint32(rb, &len))
267                 return 0;
268         if (!len) {
269                 if (!nulok)
270                         return 0;
271                 *value = NULL;
272                 if (length)
273                         *length = 0;
274                 return 1;
275         }
276         if (length)
277                 *length = (size_t)(len - 1);
278         return (*value = readbuf_get(rb, len)) != NULL &&  rb->head[-1] == 0;
279 }
280
281
282 static int readbuf_string(struct readbuf *rb, const char **value, size_t *length)
283 {
284         return _readbuf_string_(rb, value, length, 0);
285 }
286
287 static int readbuf_nullstring(struct readbuf *rb, const char **value, size_t *length)
288 {
289         return _readbuf_string_(rb, value, length, 1);
290 }
291
292 static int readbuf_object(struct readbuf *rb, struct json_object **object)
293 {
294         const char *string;
295         struct json_object *o;
296         enum json_tokener_error jerr;
297         int rc = readbuf_string(rb, &string, NULL);
298         if (rc) {
299                 o = json_tokener_parse_verbose(string, &jerr);
300                 if (jerr != json_tokener_success)
301                         o = json_object_new_string(string);
302                 *object = o;
303         }
304         return rc;
305 }
306
307 static int writebuf_put(struct writebuf *wb, const void *value, size_t length)
308 {
309         int i = wb->iovcount;
310         if (i == WRITEBUF_COUNT_MAX)
311                 return 0;
312         wb->iovec[i].iov_base = (void*)value;
313         wb->iovec[i].iov_len = length;
314         wb->iovcount = i + 1;
315         return 1;
316 }
317
318 static int writebuf_putbuf(struct writebuf *wb, const void *value, int length)
319 {
320         char *p;
321         int i = wb->iovcount, n = wb->bufcount, nafter;
322
323         /* check enough length */
324         nafter = n + length;
325         if (nafter > WRITEBUF_BUFSZ)
326                 return 0;
327
328         /* get where to store */
329         p = &wb->buf[n];
330         if (i && p == (((char*)wb->iovec[i - 1].iov_base) + wb->iovec[i - 1].iov_len))
331                 /* increase previous iovec */
332                 wb->iovec[i - 1].iov_len += (size_t)length;
333         else if (i == WRITEBUF_COUNT_MAX)
334                 /* no more iovec */
335                 return 0;
336         else {
337                 /* new iovec */
338                 wb->iovec[i].iov_base = p;
339                 wb->iovec[i].iov_len = (size_t)length;
340                 wb->iovcount = i + 1;
341         }
342         /* store now */
343         memcpy(p, value, (size_t)length);
344         wb->bufcount = nafter;
345         return 1;
346 }
347
348 __attribute__((unused))
349 static int writebuf_char(struct writebuf *wb, char value)
350 {
351         return writebuf_putbuf(wb, &value, 1);
352 }
353
354 static int writebuf_uint32(struct writebuf *wb, uint32_t value)
355 {
356         value = htole32(value);
357         return writebuf_putbuf(wb, &value, (int)sizeof value);
358 }
359
360 static int writebuf_uint16(struct writebuf *wb, uint16_t value)
361 {
362         value = htole16(value);
363         return writebuf_putbuf(wb, &value, (int)sizeof value);
364 }
365
366 static int writebuf_uint8(struct writebuf *wb, uint8_t value)
367 {
368         return writebuf_putbuf(wb, &value, (int)sizeof value);
369 }
370
371 static int writebuf_string_length(struct writebuf *wb, const char *value, size_t length)
372 {
373         uint32_t len = (uint32_t)++length;
374         return (size_t)len == length && len && writebuf_uint32(wb, len) && writebuf_put(wb, value, length);
375 }
376
377 static int writebuf_string(struct writebuf *wb, const char *value)
378 {
379         return writebuf_string_length(wb, value, strlen(value));
380 }
381
382 static int writebuf_nullstring(struct writebuf *wb, const char *value)
383 {
384         return value ? writebuf_string_length(wb, value, strlen(value)) : writebuf_uint32(wb, 0);
385 }
386
387 static int writebuf_object(struct writebuf *wb, struct json_object *object)
388 {
389         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
390         return string != NULL && writebuf_string(wb, string);
391 }
392
393 /******************* queuing of messages *****************/
394
395 /* queue the processing of the received message (except if size=0 cause it's not a valid message) */
396 static void queue_message_processing(struct afb_proto_ws *protows, char *data, size_t size, void (*processing)(int,void*))
397 {
398         struct binary *binary;
399
400         if (size) {
401                 binary = malloc(sizeof *binary);
402                 if (!binary) {
403                         /* TODO process the problem */
404                         errno = ENOMEM;
405                 } else {
406                         binary->protows = protows;
407                         binary->rb.base = data;
408                         binary->rb.head = data;
409                         binary->rb.end = data + size;
410                         if (!protows->queuing
411                          || protows->queuing(protows, processing, binary) < 0)
412                                 processing(0, binary);
413                         return;
414                 }
415         }
416         free(data);
417 }
418
419 /******************* sending messages *****************/
420
421 static int proto_write(struct afb_proto_ws *protows, struct writebuf *wb)
422 {
423         int rc;
424         struct afb_ws *ws;
425
426         pthread_mutex_lock(&protows->mutex);
427         ws = protows->ws;
428         if (ws == NULL) {
429                 errno = EPIPE;
430                 rc = -1;
431         } else {
432                 rc = afb_ws_binary_v(ws, wb->iovec, wb->iovcount);
433                 if (rc > 0)
434                         rc = 0;
435         }
436         pthread_mutex_unlock(&protows->mutex);
437         return rc;
438 }
439
440 static int send_version_offer_1(struct afb_proto_ws *protows, uint8_t version)
441 {
442         int rc = -1;
443         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
444
445         if (writebuf_char(&wb, CHAR_FOR_VERSION_OFFER)
446          && writebuf_uint32(&wb, WSAPI_IDENTIFIER)
447          && writebuf_uint8(&wb, 1) /* offer one version */
448          && writebuf_uint8(&wb, version))
449                 rc = proto_write(protows, &wb);
450         return rc;
451 }
452
453 static int send_version_set(struct afb_proto_ws *protows, uint8_t version)
454 {
455         int rc = -1;
456         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
457
458         if (writebuf_char(&wb, CHAR_FOR_VERSION_SET)
459          && writebuf_uint8(&wb, version))
460                 rc = proto_write(protows, &wb);
461         return rc;
462 }
463
464 /******************* ws request part for server *****************/
465
466 void afb_proto_ws_call_addref(struct afb_proto_ws_call *call)
467 {
468         __atomic_add_fetch(&call->refcount, 1, __ATOMIC_RELAXED);
469 }
470
471 void afb_proto_ws_call_unref(struct afb_proto_ws_call *call)
472 {
473         if (__atomic_sub_fetch(&call->refcount, 1, __ATOMIC_RELAXED))
474                 return;
475
476         afb_proto_ws_unref(call->protows);
477         free(call->buffer);
478         free(call);
479 }
480
481 int afb_proto_ws_call_reply(struct afb_proto_ws_call *call, struct json_object *obj, const char *error, const char *info)
482 {
483         int rc = -1;
484         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
485         struct afb_proto_ws *protows = call->protows;
486
487         if (writebuf_char(&wb, CHAR_FOR_REPLY)
488          && writebuf_uint16(&wb, call->callid)
489          && writebuf_nullstring(&wb, error)
490          && writebuf_nullstring(&wb, info)
491          && writebuf_object(&wb, obj))
492                 rc = proto_write(protows, &wb);
493         return rc;
494 }
495
496 int afb_proto_ws_call_subscribe(struct afb_proto_ws_call *call, uint16_t event_id)
497 {
498         int rc = -1;
499         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
500         struct afb_proto_ws *protows = call->protows;
501
502         if (writebuf_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
503          && writebuf_uint16(&wb, call->callid)
504          && writebuf_uint16(&wb, event_id))
505                 rc = proto_write(protows, &wb);
506         return rc;
507 }
508
509 int afb_proto_ws_call_unsubscribe(struct afb_proto_ws_call *call, uint16_t event_id)
510 {
511         int rc = -1;
512         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
513         struct afb_proto_ws *protows = call->protows;
514
515         if (writebuf_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
516          && writebuf_uint16(&wb, call->callid)
517          && writebuf_uint16(&wb, event_id))
518                 rc = proto_write(protows, &wb);
519         return rc;
520 }
521
522 /******************* client part **********************************/
523
524 /* search a memorized call */
525 static struct client_call *client_call_search_locked(struct afb_proto_ws *protows, uint16_t callid)
526 {
527         struct client_call *call;
528
529         call = protows->calls;
530         while (call != NULL && call->callid != callid)
531                 call = call->next;
532
533         return call;
534 }
535
536 static struct client_call *client_call_search_unlocked(struct afb_proto_ws *protows, uint16_t callid)
537 {
538         struct client_call *result;
539
540         pthread_mutex_lock(&protows->mutex);
541         result = client_call_search_locked(protows, callid);
542         pthread_mutex_unlock(&protows->mutex);
543         return result;
544 }
545
546 /* free and release the memorizing call */
547 static void client_call_destroy(struct afb_proto_ws *protows, struct client_call *call)
548 {
549         struct client_call **prv;
550
551         pthread_mutex_lock(&protows->mutex);
552         prv = &protows->calls;
553         while (*prv != NULL) {
554                 if (*prv == call) {
555                         protows->idcount--;
556                         *prv = call->next;
557                         pthread_mutex_unlock(&protows->mutex);
558                         free(call);
559                         return;
560                 }
561                 prv = &(*prv)->next;
562         }
563         pthread_mutex_unlock(&protows->mutex);
564 }
565
566 /* get event from the message */
567 static int client_msg_call_get(struct afb_proto_ws *protows, struct readbuf *rb, struct client_call **call)
568 {
569         uint16_t callid;
570
571         /* get event data from the message */
572         if (!readbuf_uint16(rb, &callid))
573                 return 0;
574
575         /* get the call */
576         *call = client_call_search_unlocked(protows, callid);
577         return *call != NULL;
578 }
579
580 /* adds an event */
581 static void client_on_event_create(struct afb_proto_ws *protows, struct readbuf *rb)
582 {
583         const char *event_name;
584         uint16_t event_id;
585
586         if (protows->client_itf->on_event_create 
587                         && readbuf_uint16(rb, &event_id)
588                         && readbuf_string(rb, &event_name, NULL))
589                 protows->client_itf->on_event_create(protows->closure, event_id, event_name);
590         else
591                 ERROR("Ignoring creation of event");
592 }
593
594 /* removes an event */
595 static void client_on_event_remove(struct afb_proto_ws *protows, struct readbuf *rb)
596 {
597         uint16_t event_id;
598
599         if (protows->client_itf->on_event_remove && readbuf_uint16(rb, &event_id))
600                 protows->client_itf->on_event_remove(protows->closure, event_id);
601         else
602                 ERROR("Ignoring deletion of event");
603 }
604
605 /* subscribes an event */
606 static void client_on_event_subscribe(struct afb_proto_ws *protows, struct readbuf *rb)
607 {
608         uint16_t event_id;
609         struct client_call *call;
610
611         if (protows->client_itf->on_event_subscribe && client_msg_call_get(protows, rb, &call) && readbuf_uint16(rb, &event_id))
612                 protows->client_itf->on_event_subscribe(protows->closure, call->request, event_id);
613         else
614                 ERROR("Ignoring subscription to event");
615 }
616
617 /* unsubscribes an event */
618 static void client_on_event_unsubscribe(struct afb_proto_ws *protows, struct readbuf *rb)
619 {
620         uint16_t event_id;
621         struct client_call *call;
622
623         if (protows->client_itf->on_event_unsubscribe && client_msg_call_get(protows, rb, &call) && readbuf_uint16(rb, &event_id))
624                 protows->client_itf->on_event_unsubscribe(protows->closure, call->request, event_id);
625         else
626                 ERROR("Ignoring unsubscription to event");
627 }
628
629 /* receives broadcasted events */
630 static void client_on_event_broadcast(struct afb_proto_ws *protows, struct readbuf *rb)
631 {
632         const char *event_name, *uuid;
633         uint8_t hop;
634         struct json_object *object;
635
636         if (protows->client_itf->on_event_broadcast && readbuf_string(rb, &event_name, NULL) && readbuf_object(rb, &object) && (uuid = readbuf_get(rb, 16)) && readbuf_uint8(rb, &hop))
637                 protows->client_itf->on_event_broadcast(protows->closure, event_name, object, (unsigned char*)uuid, hop);
638         else
639                 ERROR("Ignoring broadcast of event");
640 }
641
642 /* pushs an event */
643 static void client_on_event_push(struct afb_proto_ws *protows, struct readbuf *rb)
644 {
645         uint16_t event_id;
646         struct json_object *object;
647
648         if (protows->client_itf->on_event_push && readbuf_uint16(rb, &event_id) && readbuf_object(rb, &object))
649                 protows->client_itf->on_event_push(protows->closure, event_id, object);
650         else
651                 ERROR("Ignoring push of event");
652 }
653
654 static void client_on_reply(struct afb_proto_ws *protows, struct readbuf *rb)
655 {
656         struct client_call *call;
657         struct json_object *object;
658         const char *error, *info;
659
660         if (!client_msg_call_get(protows, rb, &call))
661                 return;
662
663         if (readbuf_nullstring(rb, &error, NULL) && readbuf_nullstring(rb, &info, NULL) && readbuf_object(rb, &object)) {
664                 protows->client_itf->on_reply(protows->closure, call->request, object, error, info);
665         } else {
666                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "proto-error", "can't process success");
667         }
668         client_call_destroy(protows, call);
669 }
670
671 static void client_on_description(struct afb_proto_ws *protows, struct readbuf *rb)
672 {
673         uint32_t descid;
674         struct client_describe *desc, **prv;
675         struct json_object *object;
676
677         if (readbuf_uint32(rb, &descid)) {
678                 pthread_mutex_lock(&protows->mutex);
679                 prv = &protows->describes;
680                 while ((desc = *prv) && desc->descid != descid)
681                         prv = &desc->next;
682                 if (!desc)
683                         pthread_mutex_unlock(&protows->mutex);
684                 else {
685                         *prv = desc->next;
686                         protows->idcount--;
687                         pthread_mutex_unlock(&protows->mutex);
688                         if (!readbuf_object(rb, &object))
689                                 object = NULL;
690                         desc->callback(desc->closure, object);
691                         free(desc);
692                 }
693         }
694 }
695
696 /* received a version set */
697 static void client_on_version_set(struct afb_proto_ws *protows, struct readbuf *rb)
698 {
699         uint8_t version;
700
701         /* reads the descid */
702         if (readbuf_uint8(rb, &version)
703          && WSAPI_VERSION_MIN <= version
704          && version <= WSAPI_VERSION_MAX) {
705                 protows->version = version;
706                 return;
707         }
708         afb_proto_ws_hangup(protows);
709 }
710
711
712 /* callback when receiving binary data */
713 static void client_on_binary_job(int sig, void *closure)
714 {
715         struct binary *binary = closure;
716
717         if (!sig) {
718                 switch (*binary->rb.head++) {
719                 case CHAR_FOR_REPLY: /* reply */
720                         client_on_reply(binary->protows, &binary->rb);
721                         break;
722                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
723                         client_on_event_broadcast(binary->protows, &binary->rb);
724                         break;
725                 case CHAR_FOR_EVT_ADD: /* creates the event */
726                         client_on_event_create(binary->protows, &binary->rb);
727                         break;
728                 case CHAR_FOR_EVT_DEL: /* removes the event */
729                         client_on_event_remove(binary->protows, &binary->rb);
730                         break;
731                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
732                         client_on_event_push(binary->protows, &binary->rb);
733                         break;
734                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
735                         client_on_event_subscribe(binary->protows, &binary->rb);
736                         break;
737                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
738                         client_on_event_unsubscribe(binary->protows, &binary->rb);
739                         break;
740                 case CHAR_FOR_DESCRIPTION: /* description */
741                         client_on_description(binary->protows, &binary->rb);
742                         break;
743                 case CHAR_FOR_VERSION_SET: /* set the protocol version */
744                         client_on_version_set(binary->protows, &binary->rb);
745                         break;
746                 default: /* unexpected message */
747                         /* TODO: close the connection */
748                         break;
749                 }
750         }
751         free(binary->rb.base);
752         free(binary);
753 }
754
755 /* callback when receiving binary data */
756 static void client_on_binary(void *closure, char *data, size_t size)
757 {
758         struct afb_proto_ws *protows = closure;
759
760         queue_message_processing(protows, data, size, client_on_binary_job);
761 }
762
763 static int client_send_cmd_id16_optstr(struct afb_proto_ws *protows, char order, uint16_t id, const char *value)
764 {
765         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
766         int rc = -1;
767
768         if (writebuf_char(&wb, order)
769          && writebuf_uint16(&wb, id)
770          && (!value || writebuf_string(&wb, value)))
771                 rc = proto_write(protows, &wb);
772         return rc;
773 }
774
775 int afb_proto_ws_client_session_create(struct afb_proto_ws *protows, uint16_t sessionid, const char *sessionstr)
776 {
777         return client_send_cmd_id16_optstr(protows, CHAR_FOR_SESSION_ADD, sessionid, sessionstr);
778 }
779
780 int afb_proto_ws_client_session_remove(struct afb_proto_ws *protows, uint16_t sessionid)
781 {
782         return client_send_cmd_id16_optstr(protows, CHAR_FOR_SESSION_DROP, sessionid, NULL);
783 }
784
785 int afb_proto_ws_client_token_create(struct afb_proto_ws *protows, uint16_t tokenid, const char *tokenstr)
786 {
787         return client_send_cmd_id16_optstr(protows, CHAR_FOR_TOKEN_ADD, tokenid, tokenstr);
788
789 }
790
791 int afb_proto_ws_client_token_remove(struct afb_proto_ws *protows, uint16_t tokenid)
792 {
793         return client_send_cmd_id16_optstr(protows, CHAR_FOR_TOKEN_DROP, tokenid, NULL);
794 }
795
796 int afb_proto_ws_client_event_unexpected(struct afb_proto_ws *protows, uint16_t eventid)
797 {
798         return client_send_cmd_id16_optstr(protows, CHAR_FOR_EVT_UNEXPECTED, eventid, NULL);
799 }
800
801 int afb_proto_ws_client_call(
802                 struct afb_proto_ws *protows,
803                 const char *verb,
804                 struct json_object *args,
805                 uint16_t sessionid,
806                 uint16_t tokenid,
807                 void *request,
808                 const char *user_creds
809 )
810 {
811         int rc = -1;
812         struct client_call *call;
813         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
814         uint16_t id;
815
816         /* allocate call data */
817         call = malloc(sizeof *call);
818         if (call == NULL) {
819                 errno = ENOMEM;
820                 return -1;
821         }
822         call->request = request;
823
824         /* init call data */
825         pthread_mutex_lock(&protows->mutex);
826         if (protows->idcount >= ACTIVE_ID_MAX) {
827                 pthread_mutex_unlock(&protows->mutex);
828                 errno = EBUSY;
829                 goto clean;
830         }
831         protows->idcount++;
832         id = ++protows->genid;
833         while(!id || client_call_search_locked(protows, id) != NULL)
834                 id++;
835         call->callid = protows->genid = id;
836         call->next = protows->calls;
837         protows->calls = call;
838         pthread_mutex_unlock(&protows->mutex);
839
840         /* creates the call message */
841         if (!writebuf_char(&wb, CHAR_FOR_CALL)
842          || !writebuf_uint16(&wb, call->callid)
843          || !writebuf_string(&wb, verb)
844          || !writebuf_uint16(&wb, sessionid)
845          || !writebuf_uint16(&wb, tokenid)
846          || !writebuf_object(&wb, args)
847          || !writebuf_nullstring(&wb, user_creds)) {
848                 errno = EINVAL;
849                 goto clean;
850         }
851
852         /* send */
853         rc = proto_write(protows, &wb);
854         if (!rc)
855                 goto end;
856
857 clean:
858         client_call_destroy(protows, call);
859 end:
860         return rc;
861 }
862
863 /* get the description */
864 int afb_proto_ws_client_describe(struct afb_proto_ws *protows, void (*callback)(void*, struct json_object*), void *closure)
865 {
866         struct client_describe *desc, *d;
867         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
868         uint16_t id;
869
870         desc = malloc(sizeof *desc);
871         if (!desc) {
872                 errno = ENOMEM;
873                 goto error;
874         }
875
876         /* fill in stack the description of the task */
877         pthread_mutex_lock(&protows->mutex);
878         if (protows->idcount >= ACTIVE_ID_MAX) {
879                 errno = EBUSY;
880                 goto busy;
881         }
882         protows->idcount++;
883         id = ++protows->genid;
884         d = protows->describes;
885         while (d) {
886                 if (id && d->descid != id)
887                         d = d->next;
888                 else {
889                         id++;
890                         d = protows->describes;
891                 }
892         }
893         desc->descid = protows->genid = id;
894         desc->callback = callback;
895         desc->closure = closure;
896         desc->next = protows->describes;
897         protows->describes = desc;
898         pthread_mutex_unlock(&protows->mutex);
899
900         /* send */
901         if (!writebuf_char(&wb, CHAR_FOR_DESCRIBE)
902          || !writebuf_uint16(&wb, desc->descid)) {
903                  errno = EINVAL;
904                  goto error2;
905         }
906
907         if (proto_write(protows, &wb) == 0)
908                 return 0;
909
910 error2:
911         pthread_mutex_lock(&protows->mutex);
912         d = protows->describes;
913         if (d == desc)
914                 protows->describes = desc->next;
915         else {
916                 while(d && d->next != desc)
917                         d = d->next;
918                 if (d)
919                         d->next = desc->next;
920         }
921         protows->idcount--;
922 busy:
923         pthread_mutex_unlock(&protows->mutex);
924         free(desc);
925 error:
926         /* TODO? callback(closure, NULL); */
927         return -1;
928 }
929
930 /******************* client description part for server *****************************/
931
932 /* on call, propagate it to the ws service */
933 static void server_on_call(struct afb_proto_ws *protows, struct readbuf *rb)
934 {
935         struct afb_proto_ws_call *call;
936         const char *verb, *user_creds;
937         uint16_t callid, sessionid, tokenid;
938         size_t lenverb;
939         struct json_object *object;
940
941         afb_proto_ws_addref(protows);
942
943         /* reads the call message data */
944         if (!readbuf_uint16(rb, &callid)
945          || !readbuf_string(rb, &verb, &lenverb)
946          || !readbuf_uint16(rb, &sessionid)
947          || !readbuf_uint16(rb, &tokenid)
948          || !readbuf_object(rb, &object)
949          || !readbuf_nullstring(rb, &user_creds, NULL))
950                 goto overflow;
951
952         /* create the request */
953         call = malloc(sizeof *call);
954         if (call == NULL)
955                 goto out_of_memory;
956
957         call->protows = protows;
958         call->callid = callid;
959         call->refcount = 1;
960         call->buffer = rb->base;
961         rb->base = NULL; /* don't free the buffer */
962
963         protows->server_itf->on_call(protows->closure, call, verb, object, sessionid, tokenid, user_creds);
964         return;
965
966 out_of_memory:
967         json_object_put(object);
968
969 overflow:
970         afb_proto_ws_unref(protows);
971 }
972
973 static int server_send_description(struct afb_proto_ws *protows, uint32_t descid, struct json_object *descobj)
974 {
975         int rc = -1;
976         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
977
978         if (writebuf_char(&wb, CHAR_FOR_DESCRIPTION)
979          && writebuf_uint32(&wb, descid)
980          && writebuf_object(&wb, descobj))
981                 rc = proto_write(protows, &wb);
982         return rc;
983 }
984
985 int afb_proto_ws_describe_put(struct afb_proto_ws_describe *describe, struct json_object *description)
986 {
987         int rc = server_send_description(describe->protows, describe->descid, description);
988         afb_proto_ws_unref(describe->protows);
989         free(describe);
990         return rc;
991 }
992
993 /* on describe, propagate it to the ws service */
994 static void server_on_describe(struct afb_proto_ws *protows, struct readbuf *rb)
995 {
996         uint16_t descid;
997         struct afb_proto_ws_describe *desc;
998
999         /* reads the descid */
1000         if (readbuf_uint16(rb, &descid)) {
1001                 if (protows->server_itf->on_describe) {
1002                         /* create asynchronous job */
1003                         desc = malloc(sizeof *desc);
1004                         if (desc) {
1005                                 desc->descid = descid;
1006                                 desc->protows = protows;
1007                                 afb_proto_ws_addref(protows);
1008                                 protows->server_itf->on_describe(protows->closure, desc);
1009                                 return;
1010                         }
1011                 }
1012                 server_send_description(protows, descid, NULL);
1013         }
1014 }
1015
1016 static void server_on_session_add(struct afb_proto_ws *protows, struct readbuf *rb)
1017 {
1018         uint16_t sessionid;
1019         const char *sessionstr;
1020
1021         if (readbuf_uint16(rb, &sessionid) && readbuf_string(rb, &sessionstr, NULL))
1022                 protows->server_itf->on_session_create(protows->closure, sessionid, sessionstr);
1023 }
1024
1025 static void server_on_session_drop(struct afb_proto_ws *protows, struct readbuf *rb)
1026 {
1027         uint16_t sessionid;
1028
1029         if (readbuf_uint16(rb, &sessionid))
1030                 protows->server_itf->on_session_remove(protows->closure, sessionid);
1031 }
1032
1033 static void server_on_token_add(struct afb_proto_ws *protows, struct readbuf *rb)
1034 {
1035         uint16_t tokenid;
1036         const char *tokenstr;
1037
1038         if (readbuf_uint16(rb, &tokenid) && readbuf_string(rb, &tokenstr, NULL))
1039                 protows->server_itf->on_token_create(protows->closure, tokenid, tokenstr);
1040 }
1041
1042 static void server_on_token_drop(struct afb_proto_ws *protows, struct readbuf *rb)
1043 {
1044         uint16_t tokenid;
1045
1046         if (readbuf_uint16(rb, &tokenid))
1047                 protows->server_itf->on_token_remove(protows->closure, tokenid);
1048 }
1049
1050 static void server_on_event_unexpected(struct afb_proto_ws *protows, struct readbuf *rb)
1051 {
1052         uint16_t eventid;
1053
1054         if (readbuf_uint16(rb, &eventid))
1055                 protows->server_itf->on_event_unexpected(protows->closure, eventid);
1056 }
1057
1058 /* on version offer */
1059 static void server_on_version_offer(struct afb_proto_ws *protows, struct readbuf *rb)
1060 {
1061         uint8_t count;
1062         uint8_t *versions;
1063         uint8_t version;
1064         uint8_t v;
1065         uint32_t id;
1066
1067         /* reads the descid */
1068         if (readbuf_uint32(rb, &id)
1069                 && id == WSAPI_IDENTIFIER
1070                 && readbuf_uint8(rb, &count)
1071                 && count > 0
1072                 && (versions = (uint8_t*)readbuf_get(rb, (uint32_t)count))) {
1073                 version = WSAPI_VERSION_UNSET;
1074                 while (count) {
1075                         v = versions[--count];
1076                         if (v >= WSAPI_VERSION_MIN
1077                          && v <= WSAPI_VERSION_MAX
1078                          && (version == WSAPI_VERSION_UNSET || version < v))
1079                                 version = v;
1080                 }
1081                 if (version != WSAPI_VERSION_UNSET) {
1082                         if (send_version_set(protows, version) >= 0) {
1083                                 protows->version = version;
1084                                 return;
1085                         }
1086                 }
1087         }
1088         afb_proto_ws_hangup(protows);
1089 }
1090
1091 /* callback when receiving binary data */
1092 static void server_on_binary_job(int sig, void *closure)
1093 {
1094         struct binary *binary = closure;
1095
1096         if (!sig) {
1097                 switch (*binary->rb.head++) {
1098                 case CHAR_FOR_CALL:
1099                         server_on_call(binary->protows, &binary->rb);
1100                         break;
1101                 case CHAR_FOR_DESCRIBE:
1102                         server_on_describe(binary->protows, &binary->rb);
1103                         break;
1104                 case CHAR_FOR_SESSION_ADD:
1105                         server_on_session_add(binary->protows, &binary->rb);
1106                         break;
1107                 case CHAR_FOR_SESSION_DROP:
1108                         server_on_session_drop(binary->protows, &binary->rb);
1109                         break;
1110                 case CHAR_FOR_TOKEN_ADD:
1111                         server_on_token_add(binary->protows, &binary->rb);
1112                         break;
1113                 case CHAR_FOR_TOKEN_DROP:
1114                         server_on_token_drop(binary->protows, &binary->rb);
1115                         break;
1116                 case CHAR_FOR_EVT_UNEXPECTED:
1117                         server_on_event_unexpected(binary->protows, &binary->rb);
1118                         break;
1119                 case CHAR_FOR_VERSION_OFFER:
1120                         server_on_version_offer(binary->protows, &binary->rb);
1121                         break;
1122                 default: /* unexpected message */
1123                         /* TODO: close the connection */
1124                         break;
1125                 }
1126         }
1127         free(binary->rb.base);
1128         free(binary);
1129 }
1130
1131 static void server_on_binary(void *closure, char *data, size_t size)
1132 {
1133         struct afb_proto_ws *protows = closure;
1134
1135         queue_message_processing(protows, data, size, server_on_binary_job);
1136 }
1137
1138 /******************* server part: manage events **********************************/
1139
1140 static int server_event_send(struct afb_proto_ws *protows, char order, uint16_t event_id, const char *event_name, struct json_object *data)
1141 {
1142         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
1143         int rc = -1;
1144
1145         if (writebuf_char(&wb, order)
1146          && writebuf_uint16(&wb, event_id)
1147          && (order != CHAR_FOR_EVT_ADD || writebuf_string(&wb, event_name))
1148          && (order != CHAR_FOR_EVT_PUSH || writebuf_object(&wb, data)))
1149                 rc = proto_write(protows, &wb);
1150         return rc;
1151 }
1152
1153 int afb_proto_ws_server_event_create(struct afb_proto_ws *protows, uint16_t event_id, const char *event_name)
1154 {
1155         return server_event_send(protows, CHAR_FOR_EVT_ADD, event_id, event_name, NULL);
1156 }
1157
1158 int afb_proto_ws_server_event_remove(struct afb_proto_ws *protows, uint16_t event_id)
1159 {
1160         return server_event_send(protows, CHAR_FOR_EVT_DEL, event_id, NULL, NULL);
1161 }
1162
1163 int afb_proto_ws_server_event_push(struct afb_proto_ws *protows, uint16_t event_id, struct json_object *data)
1164 {
1165         return server_event_send(protows, CHAR_FOR_EVT_PUSH, event_id, NULL, data);
1166 }
1167
1168 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)
1169 {
1170         struct writebuf wb = { .iovcount = 0, .bufcount = 0 };
1171         int rc = -1;
1172
1173         if (!hop)
1174                 return 0;
1175
1176         if (writebuf_char(&wb, CHAR_FOR_EVT_BROADCAST)
1177          && writebuf_string(&wb, event_name)
1178          && writebuf_object(&wb, data)
1179          && writebuf_put(&wb, uuid, 16)
1180          && writebuf_uint8(&wb, (uint8_t)(hop - 1)))
1181                 rc = proto_write(protows, &wb);
1182         return rc;
1183 }
1184
1185 /*****************************************************/
1186
1187 /* callback when receiving a hangup */
1188 static void on_hangup(void *closure)
1189 {
1190         struct afb_proto_ws *protows = closure;
1191         struct client_describe *cd, *ncd;
1192         struct client_call *call, *ncall;
1193         struct afb_ws *ws;
1194
1195         pthread_mutex_lock(&protows->mutex);
1196         ncd = protows->describes;
1197         protows->describes = NULL;
1198         ncall = protows->calls;
1199         protows->calls = NULL;
1200         ws = protows->ws;
1201         protows->ws = NULL;
1202         protows->idcount = 0;
1203         pthread_mutex_unlock(&protows->mutex);
1204
1205         while (ncall) {
1206                 call= ncall;
1207                 ncall = call->next;
1208                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "disconnected", "server hung up");
1209                 free(call);
1210         }
1211
1212         while (ncd) {
1213                 cd= ncd;
1214                 ncd = cd->next;
1215                 cd->callback(cd->closure, NULL);
1216                 free(cd);
1217         }
1218
1219         if (ws) {
1220                 afb_ws_destroy(ws);
1221                 if (protows->on_hangup)
1222                         protows->on_hangup(protows->closure);
1223         }
1224 }
1225
1226 /*****************************************************/
1227
1228 static const struct afb_ws_itf proto_ws_client_ws_itf =
1229 {
1230         .on_close = NULL,
1231         .on_text = NULL,
1232         .on_binary = client_on_binary,
1233         .on_error = NULL,
1234         .on_hangup = on_hangup
1235 };
1236
1237 static const struct afb_ws_itf server_ws_itf =
1238 {
1239         .on_close = NULL,
1240         .on_text = NULL,
1241         .on_binary = server_on_binary,
1242         .on_error = NULL,
1243         .on_hangup = on_hangup
1244 };
1245
1246 /*****************************************************/
1247
1248 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)
1249 {
1250         struct afb_proto_ws *protows;
1251
1252         protows = calloc(1, sizeof *protows);
1253         if (protows == NULL)
1254                 errno = ENOMEM;
1255         else {
1256                 fcntl(fdev_fd(fdev), F_SETFD, FD_CLOEXEC);
1257                 fcntl(fdev_fd(fdev), F_SETFL, O_NONBLOCK);
1258                 protows->ws = afb_ws_create(fdev, itf, protows);
1259                 if (protows->ws != NULL) {
1260                         protows->refcount = 1;
1261                         protows->version = WSAPI_VERSION_UNSET;
1262                         protows->closure = closure;
1263                         protows->server_itf = itfs;
1264                         protows->client_itf = itfc;
1265                         pthread_mutex_init(&protows->mutex, NULL);
1266                         return protows;
1267                 }
1268                 free(protows);
1269         }
1270         return NULL;
1271 }
1272
1273 struct afb_proto_ws *afb_proto_ws_create_client(struct fdev *fdev, const struct afb_proto_ws_client_itf *itf, void *closure)
1274 {
1275         struct afb_proto_ws *protows;
1276
1277         protows = afb_proto_ws_create(fdev, NULL, itf, closure, &proto_ws_client_ws_itf);
1278         if (protows) {
1279                 if (send_version_offer_1(protows, WSAPI_VERSION_1) != 0) {
1280                         afb_proto_ws_unref(protows);
1281                         protows = NULL;
1282                 }
1283         }
1284         return protows;
1285 }
1286
1287 struct afb_proto_ws *afb_proto_ws_create_server(struct fdev *fdev, const struct afb_proto_ws_server_itf *itf, void *closure)
1288 {
1289         return afb_proto_ws_create(fdev, itf, NULL, closure, &server_ws_itf);
1290 }
1291
1292 void afb_proto_ws_unref(struct afb_proto_ws *protows)
1293 {
1294         if (protows && !__atomic_sub_fetch(&protows->refcount, 1, __ATOMIC_RELAXED)) {
1295                 afb_proto_ws_hangup(protows);
1296                 pthread_mutex_destroy(&protows->mutex);
1297                 free(protows);
1298         }
1299 }
1300
1301 void afb_proto_ws_addref(struct afb_proto_ws *protows)
1302 {
1303         __atomic_add_fetch(&protows->refcount, 1, __ATOMIC_RELAXED);
1304 }
1305
1306 int afb_proto_ws_is_client(struct afb_proto_ws *protows)
1307 {
1308         return !!protows->client_itf;
1309 }
1310
1311 int afb_proto_ws_is_server(struct afb_proto_ws *protows)
1312 {
1313         return !!protows->server_itf;
1314 }
1315
1316 void afb_proto_ws_hangup(struct afb_proto_ws *protows)
1317 {
1318         if (protows->ws)
1319                 afb_ws_hangup(protows->ws);
1320 }
1321
1322 void afb_proto_ws_on_hangup(struct afb_proto_ws *protows, void (*on_hangup)(void *closure))
1323 {
1324         protows->on_hangup = on_hangup;
1325 }
1326
1327 void afb_proto_ws_set_queuing(struct afb_proto_ws *protows, int (*queuing)(struct afb_proto_ws*, void (*)(int,void*), void*))
1328 {
1329         protows->queuing = queuing;
1330 }