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