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