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