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